http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/ccdcf329/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/CapitalisingDummySslEngine.java ---------------------------------------------------------------------- diff --git a/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/CapitalisingDummySslEngine.java b/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/CapitalisingDummySslEngine.java deleted file mode 100644 index 10a64d4..0000000 --- a/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/CapitalisingDummySslEngine.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.proton.engine.impl.ssl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.nio.ByteBuffer; - -import javax.net.ssl.SSLEngineResult; -import javax.net.ssl.SSLEngineResult.HandshakeStatus; -import javax.net.ssl.SSLEngineResult.Status; -import javax.net.ssl.SSLException; - - - -/** - * A simpler implementation of an SSLEngine that has predictable human-readable output, and that allows us to - * easily trigger {@link Status#BUFFER_OVERFLOW} and {@link Status#BUFFER_UNDERFLOW}. - * - * Using a true SSLEngine for this would be impractical. - */ -public class CapitalisingDummySslEngine implements ProtonSslEngine -{ - static final int SHORT_ENCODED_CHUNK_SIZE = 2; - static final int MAX_ENCODED_CHUNK_SIZE = 5; - private static final char ENCODED_TEXT_BEGIN = '<'; - private static final char ENCODED_TEXT_END = '>'; - private static final char ENCODED_TEXT_INNER_CHAR = '-'; - - private static final int CLEAR_CHUNK_SIZE = 2; - private static final char CLEARTEXT_PADDING = '_'; - private SSLException _nextException; - private int _applicationBufferSize = CLEAR_CHUNK_SIZE; - private int _packetBufferSize = MAX_ENCODED_CHUNK_SIZE; - private int _unwrapCount; - - /** - * Converts a_ to <-A->. z_ is special and encodes as <> (to give us packets of different lengths). - * If dst is not sufficiently large ({@value #SHORT_ENCODED_CHUNK_SIZE} in our encoding), we return - * {@link Status#BUFFER_OVERFLOW}, and the src and dst ByteBuffers are unchanged. - */ - @Override - public SSLEngineResult wrap(ByteBuffer src, ByteBuffer dst) - throws SSLException - { - int consumed = 0; - int produced = 0; - final Status resultStatus; - - if (src.remaining() >= CLEAR_CHUNK_SIZE) - { - src.mark(); - - char uncapitalisedChar = (char) src.get(); - char underscore = (char) src.get(); - - validateClear(uncapitalisedChar, underscore); - - boolean useShortEncoding = uncapitalisedChar == 'z'; - int encodingLength = useShortEncoding ? SHORT_ENCODED_CHUNK_SIZE : MAX_ENCODED_CHUNK_SIZE; - boolean overflow = dst.remaining() < encodingLength; - - if (overflow) - { - src.reset(); - resultStatus = Status.BUFFER_OVERFLOW; - } - else - { - consumed = CLEAR_CHUNK_SIZE; - - char capitalisedChar = Character.toUpperCase(uncapitalisedChar); - - dst.put((byte)ENCODED_TEXT_BEGIN); - if (!useShortEncoding) - { - dst.put((byte)ENCODED_TEXT_INNER_CHAR); - dst.put((byte)capitalisedChar); - dst.put((byte)ENCODED_TEXT_INNER_CHAR); - } - dst.put((byte)ENCODED_TEXT_END); - produced = encodingLength; - - resultStatus = Status.OK; - } - } - else - { - resultStatus = Status.OK; - } - - return new SSLEngineResult(resultStatus, HandshakeStatus.NOT_HANDSHAKING, consumed, produced); - } - - /** - * Converts <-A-><-B-><-C-> to a_. <> is special and decodes as z_ - * Input such as "<A" will causes a {@link Status#BUFFER_UNDERFLOW} result status. - */ - @Override - public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer dst) - throws SSLException - { - _unwrapCount++; - - if(_nextException != null) - { - throw _nextException; - } - - Status resultStatus; - final int consumed; - final int produced; - - if (src.remaining() >= SHORT_ENCODED_CHUNK_SIZE) - { - src.mark(); - - char begin = (char)src.get(); - char nextChar = (char)src.get(); // Could be - or > - final int readSoFar = 2; - final char capitalisedChar; - - if (nextChar != ENCODED_TEXT_END) - { - int remainingBytesForMaxLengthPacket = MAX_ENCODED_CHUNK_SIZE - readSoFar; - if (src.remaining() < remainingBytesForMaxLengthPacket ) - { - src.reset(); - resultStatus = Status.BUFFER_UNDERFLOW; - return new SSLEngineResult(resultStatus, HandshakeStatus.NOT_HANDSHAKING, 0, 0); - } - else - { - char beginInner = nextChar; - capitalisedChar = (char)src.get(); - char endInner = (char)src.get(); - char end = (char)src.get(); - consumed = MAX_ENCODED_CHUNK_SIZE; - validateEncoded(begin, beginInner, capitalisedChar, endInner, end); - } - } - else - { - assertEquals("Unexpected begin", Character.toString(ENCODED_TEXT_BEGIN), Character.toString(begin)); - capitalisedChar = 'Z'; - consumed = SHORT_ENCODED_CHUNK_SIZE;; - } - - char lowerCaseChar = Character.toLowerCase(capitalisedChar); - dst.put((byte)lowerCaseChar); - dst.put((byte)CLEARTEXT_PADDING); - produced = CLEAR_CHUNK_SIZE; - - resultStatus = Status.OK; - } - else - { - resultStatus = Status.BUFFER_UNDERFLOW; - consumed = 0; - produced = 0; - } - - return new SSLEngineResult(resultStatus, HandshakeStatus.NOT_HANDSHAKING, consumed, produced); - } - - @Override - public int getEffectiveApplicationBufferSize() - { - return getApplicationBufferSize(); - } - - private int getApplicationBufferSize() - { - return _applicationBufferSize; - } - - @Override - public int getPacketBufferSize() - { - return _packetBufferSize; - } - - public void setApplicationBufferSize(int value) - { - _applicationBufferSize = value; - } - - public void setPacketBufferSize(int value) - { - _packetBufferSize = value; - } - - @Override - public String getProtocol() - { - throw new UnsupportedOperationException(); - } - - @Override - public HandshakeStatus getHandshakeStatus() - { - throw new UnsupportedOperationException(); - } - - @Override - public Runnable getDelegatedTask() - { - throw new UnsupportedOperationException(); - } - - @Override - public String getCipherSuite() - { - throw new UnsupportedOperationException(); - } - - - private void validateEncoded(char begin, char beginInner, char capitalisedChar, char endInner, char end) - { - assertEquals("Unexpected begin", Character.toString(ENCODED_TEXT_BEGIN), Character.toString(begin)); - assertEquals("Unexpected begin inner", Character.toString(ENCODED_TEXT_INNER_CHAR), Character.toString(beginInner)); - assertEquals("Unexpected end inner", Character.toString(ENCODED_TEXT_INNER_CHAR), Character.toString(endInner)); - assertEquals("Unexpected end", Character.toString(ENCODED_TEXT_END), Character.toString(end)); - assertTrue("Encoded character " + capitalisedChar + " must be capital", Character.isUpperCase(capitalisedChar)); - } - - private void validateClear(char uncapitalisedChar, char underscore) - { - assertTrue("Clear text character " + uncapitalisedChar + " must be lowercase", Character.isLowerCase(uncapitalisedChar)); - assertEquals("Unexpected clear text pad", Character.toString(CLEARTEXT_PADDING), Character.toString(underscore)); - } - - @Override - public boolean getUseClientMode() - { - return true; - } - - public void rejectNextEncodedPacket(SSLException nextException) - { - _nextException = nextException; - } - - int getUnwrapCount() { - return _unwrapCount; - } -}
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/ccdcf329/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/RememberingTransportInput.java ---------------------------------------------------------------------- diff --git a/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/RememberingTransportInput.java b/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/RememberingTransportInput.java deleted file mode 100644 index 366feb3..0000000 --- a/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/RememberingTransportInput.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.proton.engine.impl.ssl; - -import java.nio.ByteBuffer; - -import org.apache.qpid.proton.engine.TransportException; -import org.apache.qpid.proton.engine.impl.TransportInput; - -class RememberingTransportInput implements TransportInput -{ - private StringBuilder _receivedInput = new StringBuilder(); - private String _nextError; - private int _inputBufferSize = 1024; - private ByteBuffer _buffer; - private int _processCount = 0; - private Integer _zeroCapacityAtCount = null; - private int _capacityCount = 0; - - String getAcceptedInput() - { - return _receivedInput.toString(); - } - - @Override - public String toString() - { - return "[RememberingTransportInput receivedInput (length " + _receivedInput.length() + ") is:" + _receivedInput.toString() + "]"; - } - - @Override - public int capacity() - { - initIntermediateBuffer(); - - _capacityCount++; - if(_zeroCapacityAtCount != null && _capacityCount >= _zeroCapacityAtCount) { - return 0; - } - - return _buffer.remaining(); - } - - @Override - public int position() - { - initIntermediateBuffer(); - return _buffer.position(); - } - - @Override - public ByteBuffer tail() - { - initIntermediateBuffer(); - return _buffer; - } - - @Override - public void process() throws TransportException - { - _processCount++; - - initIntermediateBuffer(); - - if(_nextError != null) - { - throw new TransportException(_nextError); - } - - _buffer.flip(); - byte[] receivedInputBuffer = new byte[_buffer.remaining()]; - _buffer.get(receivedInputBuffer); - _buffer.compact(); - _receivedInput.append(new String(receivedInputBuffer)); - } - - @Override - public void close_tail() - { - // do nothing - } - - public void rejectNextInput(String nextError) - { - _nextError = nextError; - } - - /** - * If called before the object is otherwise used, the intermediate input buffer will be - * initiated to the given size. If called after use, an ISE will be thrown. - * - * @param inputBufferSize size of the intermediate input buffer - * @throws IllegalStateException if the buffer was already initialised - */ - public void setInputBufferSize(int inputBufferSize) throws IllegalStateException - { - if (_buffer != null) - { - throw new IllegalStateException("Intermediate input buffer already initialised"); - } - - _inputBufferSize = inputBufferSize; - } - - private void initIntermediateBuffer() - { - if (_buffer == null) - { - _buffer = ByteBuffer.allocate(_inputBufferSize); - } - } - - int getProcessCount() - { - return _processCount; - } - - int getCapacityCount() - { - return _capacityCount; - } - - /** - * Sets a point at which calls to capacity will return 0 regardless of the actual buffer state. - * - * @param zeroCapacityAtCount number of calls to capacity at which zero starts being returned. - */ - void setZeroCapacityAtCount(Integer zeroCapacityAtCount) - { - if(zeroCapacityAtCount != null && zeroCapacityAtCount < 1) { - throw new IllegalArgumentException("Value must be null, or at least 1"); - } - _zeroCapacityAtCount = zeroCapacityAtCount; - } -} http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/ccdcf329/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/SimpleSslTransportWrapperTest.java ---------------------------------------------------------------------- diff --git a/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/SimpleSslTransportWrapperTest.java b/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/SimpleSslTransportWrapperTest.java deleted file mode 100644 index 6ee1582..0000000 --- a/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/SimpleSslTransportWrapperTest.java +++ /dev/null @@ -1,468 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.proton.engine.impl.ssl; - -import static org.apache.qpid.proton.engine.impl.ByteBufferUtils.pour; -import static org.apache.qpid.proton.engine.impl.TransportTestHelper.assertByteBufferContentEquals; -import static org.apache.qpid.proton.engine.impl.TransportTestHelper.pourBufferToString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; - -import javax.net.ssl.SSLException; - -import org.apache.qpid.proton.engine.Transport; -import org.apache.qpid.proton.engine.TransportException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -/** - * TODO unit test handshaking - * TODO unit test closing - * TODO unit test graceful handling of SSLEngine.wrap throwing an SSLException - */ -public class SimpleSslTransportWrapperTest -{ - private RememberingTransportInput _underlyingInput; - private CannedTransportOutput _underlyingOutput; - private SimpleSslTransportWrapper _sslWrapper; - private CapitalisingDummySslEngine _dummySslEngine; - - @Rule - public ExpectedException _expectedException = ExpectedException.none(); - - @Before - public void setUp() - { - _underlyingInput = new RememberingTransportInput(); - _underlyingOutput = new CannedTransportOutput(); - _dummySslEngine = new CapitalisingDummySslEngine(); - _sslWrapper = new SimpleSslTransportWrapper(_dummySslEngine, _underlyingInput, _underlyingOutput); - } - - @Test - public void testInputDecodesOnePacket() - { - String encodedBytes = "<-A->"; - - putBytesIntoTransport(encodedBytes); - - assertEquals("a_", _underlyingInput.getAcceptedInput()); - assertEquals(CapitalisingDummySslEngine.MAX_ENCODED_CHUNK_SIZE, _sslWrapper.capacity()); - assertEquals(2, _dummySslEngine.getUnwrapCount());// 1 packet, 1 underflow - assertEquals(1, _underlyingInput.getProcessCount()); - } - - /** - * Note that this only feeds 1 encoded packet in at a time due to default settings of the dummy engine, - * See {@link #testUnderlyingInputUsingSmallBuffer_receivesAllDecodedInputRequiringMultipleUnwraps} - * for a related test that passes multiple encoded packets into the ssl wrapper at once. - */ - @Test - public void testInputWithMultiplePackets() - { - String encodedBytes = "<-A-><-B-><-C-><>"; - - putBytesIntoTransport(encodedBytes); - - assertEquals("a_b_c_z_", _underlyingInput.getAcceptedInput()); - assertEquals(CapitalisingDummySslEngine.MAX_ENCODED_CHUNK_SIZE, _sslWrapper.capacity()); - assertEquals(8, _dummySslEngine.getUnwrapCount()); // (1 decode + 1 underflow) * 4 packets - assertEquals(4, _underlyingInput.getProcessCount()); // 1 process per decoded packet - } - - @Test - public void testInputIncompletePacket_isNotPassedToUnderlyingInputUntilCompleted() - { - String incompleteEncodedBytes = "<-A-><-B-><-C"; // missing the trailing '>' to cause the underflow - String remainingEncodedBytes = "-><-D->"; - - putBytesIntoTransport(incompleteEncodedBytes); - assertEquals("a_b_", _underlyingInput.getAcceptedInput()); - assertEquals(5, _dummySslEngine.getUnwrapCount()); // 2 * (1 decode + 1 underflow) + 1 underflow - assertEquals(2, _underlyingInput.getProcessCount()); // 1 process per decoded packet - - putBytesIntoTransport(remainingEncodedBytes); - assertEquals("a_b_c_d_", _underlyingInput.getAcceptedInput()); - assertEquals(4, _underlyingInput.getProcessCount()); // earlier + 2 - assertEquals(9, _dummySslEngine.getUnwrapCount()); // Earlier + 2 * (1 decode + 1 underflow) - // due to way the bytes are fed in across - // boundary of encoded packets - } - - /** - * As per {@link #testInputIncompletePacket_isNotPassedToUnderlyingInputUntilCompleted()} - * but this time it takes TWO chunks to complete the "dangling" packet. - */ - @Test - public void testInputIncompletePacketInThreeParts() - { - String firstEncodedBytes = "<-A-><-B-><-"; - String secondEncodedBytes = "C"; // Sending this causes the impl to have to hold the data without producing more input yet - String thirdEncodedBytes = "-><-D->"; - - putBytesIntoTransport(firstEncodedBytes); - assertEquals("a_b_", _underlyingInput.getAcceptedInput()); - assertEquals(5, _dummySslEngine.getUnwrapCount()); // 2 * (1 decode + 1 underflow) + 1 underflow - assertEquals(2, _underlyingInput.getProcessCount()); // 1 process per decoded packet - - putBytesIntoTransport(secondEncodedBytes); - assertEquals("a_b_", _underlyingInput.getAcceptedInput()); - assertEquals(6, _dummySslEngine.getUnwrapCount()); // earlier + 1 underflow - assertEquals(2, _underlyingInput.getProcessCount()); // as earlier - - putBytesIntoTransport(thirdEncodedBytes); - assertEquals("a_b_c_d_", _underlyingInput.getAcceptedInput()); - assertEquals(4, _underlyingInput.getProcessCount()); // 1 process per decoded packet - assertEquals(10, _dummySslEngine.getUnwrapCount()); // Earlier + (decode + underflow) * 2 - // due to way the bytes are fed in across - // boundary of encoded packets - } - - /** - * Tests that when a small underlying input buffer (1 byte here) is used, all of the encoded - * data packet (5 bytes each here) can be processed despite multiple attempts being required to - * pass the decoded bytes (2 bytes here) to the underlying input layer for processing. - */ - @Test - public void testUnderlyingInputUsingSmallBuffer_receivesAllDecodedInputRequiringMultipleUnderlyingProcesses() - { - int underlyingInputBufferSize = 1; - int encodedPacketSize = 5; - - _underlyingInput.setInputBufferSize(underlyingInputBufferSize); - assertEquals("Unexpected underlying input capacity", underlyingInputBufferSize, _underlyingInput.capacity()); - - assertEquals("Unexpected max encoded chunk size", encodedPacketSize, CapitalisingDummySslEngine.MAX_ENCODED_CHUNK_SIZE); - - byte[] bytes = "<-A-><-B->".getBytes(StandardCharsets.UTF_8); - ByteBuffer encodedByteSource = ByteBuffer.wrap(bytes); - - assertEquals("Unexpected initial capacity", encodedPacketSize, _sslWrapper.capacity()); - - // Process the first 'encoded packet' (<-A->) - int numberPoured = pour(encodedByteSource, _sslWrapper.tail()); - assertEquals("Unexpected number of bytes poured into the wrapper input buffer", encodedPacketSize, numberPoured); - assertEquals("Unexpected position in encoded source byte buffer", encodedPacketSize * 1, encodedByteSource.position()); - assertEquals("Unexpected capacity", 0, _sslWrapper.capacity()); - _sslWrapper.process(); - assertEquals("Unexpected capacity", encodedPacketSize, _sslWrapper.capacity()); - - assertEquals("unexpected underlying output after first wrapper process", "a_", _underlyingInput.getAcceptedInput()); - assertEquals("unexpected underlying process count after first wrapper process", 2 , _underlyingInput.getProcessCount()); - - // Process the second 'encoded packet' (<-B->) - numberPoured = pour(encodedByteSource, _sslWrapper.tail()); - assertEquals("Unexpected number of bytes poured into the wrapper input buffer", encodedPacketSize, numberPoured); - assertEquals("Unexpected position in encoded source byte buffer", encodedPacketSize * 2, encodedByteSource.position()); - assertEquals("Unexpected capacity", 0, _sslWrapper.capacity()); - _sslWrapper.process(); - assertEquals("Unexpected capacity", encodedPacketSize, _sslWrapper.capacity()); - - assertEquals("unexpected underlying output after second wrapper process", "a_b_", _underlyingInput.getAcceptedInput()); - assertEquals("unexpected underlying process count after second wrapper process", 4 , _underlyingInput.getProcessCount()); - } - - /** - * Tests that when a small underlying input buffer (1 byte here) is used, all of the encoded - * data packets (20 bytes total here) can be processed despite multiple unwraps being required - * to process a given set of input (3 packets, 15 bytes here) and then as a result also multiple - * attempts to pass the decoded packet (2 bytes here) to the underlying input layer for processing. - */ - @Test - public void testUnderlyingInputUsingSmallBuffer_receivesAllDecodedInputRequiringMultipleUnwraps() - { - int underlyingInputBufferSize = 1; - int encodedPacketSize = 5; - int sslEngineBufferSize = 15; - - assertEquals("Unexpected max encoded chunk size", encodedPacketSize, CapitalisingDummySslEngine.MAX_ENCODED_CHUNK_SIZE); - - _underlyingOutput = new CannedTransportOutput(); - _underlyingInput = new RememberingTransportInput(); - _underlyingInput.setInputBufferSize(underlyingInputBufferSize); - assertEquals("Unexpected underlying input capacity", underlyingInputBufferSize, _underlyingInput.capacity()); - - // Create a dummy ssl engine that has buffers that holds multiple encoded/decoded - // packets, but still can't fit all of the input - _dummySslEngine = new CapitalisingDummySslEngine(); - _dummySslEngine.setApplicationBufferSize(sslEngineBufferSize); - _dummySslEngine.setPacketBufferSize(sslEngineBufferSize); - - _sslWrapper = new SimpleSslTransportWrapper(_dummySslEngine, _underlyingInput, _underlyingOutput); - - byte[] bytes = "<-A-><-B-><-C-><-D->".getBytes(StandardCharsets.UTF_8); - ByteBuffer encodedByteSource = ByteBuffer.wrap(bytes); - - assertEquals("Unexpected initial capacity", sslEngineBufferSize, _sslWrapper.capacity()); - - // Process the first three 'encoded packets' (<-A-><-B-><-C->). This will require 3 'proper' unwraps, and - // as each decoded packet is 2 bytes, each of those will require 2 underlying input processes. - int numberPoured = pour(encodedByteSource, _sslWrapper.tail()); - assertEquals("Unexpected number of bytes poured into the wrapper input buffer", sslEngineBufferSize, numberPoured); - assertEquals("Unexpected position in encoded source byte buffer", encodedPacketSize * 3, encodedByteSource.position()); - assertEquals("Unexpected capacity", 0, _sslWrapper.capacity()); - - _sslWrapper.process(); - - assertEquals("a_b_c_", _underlyingInput.getAcceptedInput()); - assertEquals("Unexpected capacity", sslEngineBufferSize, _sslWrapper.capacity()); - assertEquals("unexpected underlying process count after wrapper process", 6 , _underlyingInput.getProcessCount()); - assertEquals(4, _dummySslEngine.getUnwrapCount()); // 3 decodes + 1 underflow - - // Process the fourth 'encoded packet' (<-D->) - numberPoured = pour(encodedByteSource, _sslWrapper.tail()); - assertEquals("Unexpected number of bytes poured into the wrapper input buffer", encodedPacketSize, numberPoured); - assertEquals("Unexpected position in encoded source byte buffer", encodedPacketSize * 4, encodedByteSource.position()); - assertEquals("Unexpected capacity", sslEngineBufferSize - encodedPacketSize, _sslWrapper.capacity()); - - _sslWrapper.process(); - - assertEquals("a_b_c_d_", _underlyingInput.getAcceptedInput()); - assertEquals("Unexpected capacity", sslEngineBufferSize, _sslWrapper.capacity()); - assertEquals("unexpected underlying process count after second wrapper process", 8 , _underlyingInput.getProcessCount()); - assertEquals(6, _dummySslEngine.getUnwrapCount()); // earlier + 1 decode + 1 underflow - } - - /** - * Tests that an exception is thrown when the underlying input has zero capacity when the call - * with newly decoded input is initially made. - */ - @Test (timeout = 5000) - public void testUnderlyingInputHasZeroCapacityInitially() - { - int underlyingInputBufferSize = 1; - int encodedPacketSize = 5; - - assertEquals("Unexpected max encoded chunk size", encodedPacketSize, CapitalisingDummySslEngine.MAX_ENCODED_CHUNK_SIZE); - - // Set the input to have a small buffer, but then return 0 from the 2nd capacity call onward. - _underlyingInput.setInputBufferSize(underlyingInputBufferSize); - _underlyingInput.setZeroCapacityAtCount(2); - assertEquals("Unexpected initial underlying input capacity", underlyingInputBufferSize, _underlyingInput.capacity()); - assertEquals("Unexpected underlying input capacity", 0, _underlyingInput.capacity()); - - // Now try decoding the input, should fail - byte[] bytes = "<-A->".getBytes(StandardCharsets.UTF_8); - ByteBuffer encodedByteSource = ByteBuffer.wrap(bytes); - - assertEquals("Unexpected initial wrapper capacity", encodedPacketSize, _sslWrapper.capacity()); - - int numberPoured = pour(encodedByteSource, _sslWrapper.tail()); - assertEquals("Unexpected number of bytes poured into the wrapper input buffer", encodedPacketSize, numberPoured); - assertEquals("Unexpected position in encoded source byte buffer", encodedPacketSize, encodedByteSource.position()); - assertEquals("Unexpected wrapper capacity", 0, _sslWrapper.capacity()); - - try - { - _sslWrapper.process(); - fail("Expected an exception"); - } - catch (TransportException te) - { - // expected. - } - - //Check we got no chars of decoded output. - assertEquals("", _underlyingInput.getAcceptedInput()); - assertEquals("Unexpected wrapper capacity", -1, _sslWrapper.capacity()); - assertEquals("unexpected underlying process count after wrapper process", 0 , _underlyingInput.getProcessCount()); - assertEquals("unexpected underlying capacity count after wrapper process", 3, _underlyingInput.getCapacityCount()); - assertEquals("unexpected underlying capacity after wrapper process", 0 , _underlyingInput.capacity()); - assertEquals(1, _dummySslEngine.getUnwrapCount()); // 1 decode (then exception) - } - - /** - * Tests that an exception is thrown when the underlying input has no capacity (but isn't closed) - * during the process of incrementally passing the decoded bytes to its smaller input buffer - * for processing. - */ - @Test (timeout = 5000) - public void testUnderlyingInputHasZeroCapacityMidProcessing() - { - int underlyingInputBufferSize = 1; - int encodedPacketSize = 5; - - assertEquals("Unexpected max encoded chunk size", encodedPacketSize, CapitalisingDummySslEngine.MAX_ENCODED_CHUNK_SIZE); - - // Set the input to have a small buffer, but then return 0 from the 3rd capacity call onward. - _underlyingInput.setInputBufferSize(underlyingInputBufferSize); - _underlyingInput.setZeroCapacityAtCount(3); - assertEquals("Unexpected initial underlying input capacity", underlyingInputBufferSize, _underlyingInput.capacity()); - - // Now try decoding the input, should fail - byte[] bytes = "<-A->".getBytes(StandardCharsets.UTF_8); - ByteBuffer encodedByteSource = ByteBuffer.wrap(bytes); - - assertEquals("Unexpected initial wrapper capacity", encodedPacketSize, _sslWrapper.capacity()); - - int numberPoured = pour(encodedByteSource, _sslWrapper.tail()); - assertEquals("Unexpected number of bytes poured into the wrapper input buffer", encodedPacketSize, numberPoured); - assertEquals("Unexpected position in encoded source byte buffer", encodedPacketSize, encodedByteSource.position()); - assertEquals("Unexpected wrapper capacity", 0, _sslWrapper.capacity()); - - try - { - _sslWrapper.process(); - fail("Expected an exception"); - } - catch (TransportException te) - { - // expected. - } - - //Check we got the first char (a) of decoded output, but not the second (_). - assertEquals("a", _underlyingInput.getAcceptedInput()); - assertEquals("Unexpected wrapper capacity", -1, _sslWrapper.capacity()); - assertEquals("unexpected underlying process count after wrapper process", 1 , _underlyingInput.getProcessCount()); - assertEquals("unexpected underlying capacity count after wrapper process", 3, _underlyingInput.getCapacityCount()); - assertEquals("unexpected underlying capacity after wrapper process", 0 , _underlyingInput.capacity()); - assertEquals(1, _dummySslEngine.getUnwrapCount()); // 1 decode (then exception) - } - - @Test - public void testSslUnwrapThrowsException_returnsErrorResultAndRefusesFurtherInput() throws Exception - { - SSLException sslException = new SSLException("unwrap exception"); - _dummySslEngine.rejectNextEncodedPacket(sslException); - - _sslWrapper.tail().put("<-A->".getBytes(StandardCharsets.UTF_8)); - _sslWrapper.process(); - assertEquals(_sslWrapper.capacity(), Transport.END_OF_STREAM); - } - - @Test - public void testUnderlyingInputReturnsErrorResult_returnsErrorResultAndRefusesFurtherInput() throws Exception - { - String underlyingErrorDescription = "dummy underlying error"; - _underlyingInput.rejectNextInput(underlyingErrorDescription); - - _sslWrapper.tail().put("<-A->".getBytes(StandardCharsets.UTF_8)); - - try { - _sslWrapper.process(); - fail("no exception"); - } catch (TransportException e) { - assertEquals(underlyingErrorDescription, e.getMessage()); - } - } - - @Test - public void testHeadIsReadOnly() - { - _underlyingOutput.setOutput(""); - assertTrue(_sslWrapper.head().isReadOnly()); - } - - @Test - public void testOutputEncodesOnePacket() - { - _underlyingOutput.setOutput("a_"); - - ByteBuffer outputBuffer = _sslWrapper.head(); - - assertByteBufferContentEquals("<-A->".getBytes(StandardCharsets.UTF_8), outputBuffer); - } - - @Test - public void testOutputEncodesMultiplePackets() - { - _underlyingOutput.setOutput("a_b_c_"); - - assertEquals("<-A-><-B-><-C->", getAllBytesFromTransport()); - } - - @Test - public void testOutputEncodesMultiplePacketsOfVaryingSize() - { - _underlyingOutput.setOutput("z_a_b_"); - - assertEquals("<><-A-><-B->", getAllBytesFromTransport()); - } - - @Test - public void testClientConsumesEncodedOutputInMultipleChunks() - { - _underlyingOutput.setOutput("a_b_"); - - { - ByteBuffer buffer = _sslWrapper.head(); - String output = pourBufferToString(buffer, 2); - assertEquals("<-", output); - _sslWrapper.pop(buffer.position()); - } - - { - ByteBuffer buffer = _sslWrapper.head(); - String output = pourBufferToString(buffer, 3); - assertEquals("A->", output); - _sslWrapper.pop(buffer.position()); - } - - assertEquals("<-B->", getAllBytesFromTransport()); - } - - @Test - public void testNoOutputToEncode() - { - _underlyingOutput.setOutput(""); - - assertFalse(_sslWrapper.head().hasRemaining()); - } - - private void putBytesIntoTransport(String encodedBytes) - { - ByteBuffer byteBuffer = ByteBuffer.wrap(encodedBytes.getBytes(StandardCharsets.UTF_8)); - while(byteBuffer.hasRemaining()) - { - int numberPoured = pour(byteBuffer, _sslWrapper.tail()); - assertTrue("We should be able to pour some bytes into the input buffer", - numberPoured > 0); - _sslWrapper.process(); - } - } - - private String getAllBytesFromTransport() - { - StringBuilder readBytes = new StringBuilder(); - while (true) - { - int pending = _sslWrapper.pending(); - if (pending > 0) { - ByteBuffer buffer = _sslWrapper.head(); - readBytes.append(pourBufferToString(buffer)); - _sslWrapper.pop(pending); - continue; - } else { - break; - } - } - - return readBytes.toString(); - } - -} http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/ccdcf329/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/SslEngineFacadeFactoryTest.java ---------------------------------------------------------------------- diff --git a/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/SslEngineFacadeFactoryTest.java b/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/SslEngineFacadeFactoryTest.java deleted file mode 100644 index 84ba8cb..0000000 --- a/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/SslEngineFacadeFactoryTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.proton.engine.impl.ssl; - -import static org.junit.Assert.assertNotNull; - -import java.net.URL; - -import org.junit.Test; - -public class SslEngineFacadeFactoryTest { - - private static final String PASSWORD = "unittest"; - - @Test - public void testCertifcateLoad() { - String ipFile = resolveFilename("cert.pem.txt"); - SslEngineFacadeFactory factory = new SslEngineFacadeFactory(); - - assertNotNull("Certificate was NULL", factory.readCertificate(ipFile)); - } - - @Test - public void testLoadKey() { - String keyFile = resolveFilename("key.pem.txt"); - SslEngineFacadeFactory factory = new SslEngineFacadeFactory(); - - assertNotNull("Key was NULL", factory.readPrivateKey(keyFile, PASSWORD)); - } - - @Test - public void testLoadUnencryptedPrivateKey(){ - String keyFile = resolveFilename("private-key-clear.pem.txt"); - SslEngineFacadeFactory factory = new SslEngineFacadeFactory(); - - assertNotNull("Key was NULL", factory.readPrivateKey(keyFile, null)); - } - - @Test - public void testLoadUnencryptedPKCS8PrivateKey(){ - String keyFile = resolveFilename("private-key-clear-pkcs8.pem.txt"); - SslEngineFacadeFactory factory = new SslEngineFacadeFactory(); - - assertNotNull("Key was NULL", factory.readPrivateKey(keyFile, null)); - } - - private String resolveFilename(String testFilename) { - URL resourceUri = this.getClass().getResource(testFilename); - - assertNotNull("Failed to load file: " + testFilename, resourceUri); - - String fName = resourceUri.getPath(); - - return fName; - } -} http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/ccdcf329/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/SslHandshakeSniffingTransportWrapperTest.java ---------------------------------------------------------------------- diff --git a/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/SslHandshakeSniffingTransportWrapperTest.java b/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/SslHandshakeSniffingTransportWrapperTest.java deleted file mode 100644 index 3a14837..0000000 --- a/proton-j/src/test/java/org/apache/qpid/proton/engine/impl/ssl/SslHandshakeSniffingTransportWrapperTest.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.proton.engine.impl.ssl; - -import static org.apache.qpid.proton.engine.impl.TransportTestHelper.assertByteBufferContentEquals; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.nio.ByteBuffer; - -import org.apache.qpid.proton.engine.TransportException; -import org.apache.qpid.proton.engine.impl.TransportWrapper; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -public class SslHandshakeSniffingTransportWrapperTest -{ - private static final byte[] EXAMPLE_SSL_V3_HANDSHAKE_BYTES = new byte[] {0x16, 0x03, 0x02, 0x00, 0x31}; - private static final byte[] EXAMPLE_SSL_V2_HANDSHAKE_BYTES = new byte[] {0x00, 0x00, 0x01, 0x03, 0x00}; - - private SslTransportWrapper _secureTransportWrapper = mock(SslTransportWrapper.class); - private TransportWrapper _plainTransportWrapper = mock(TransportWrapper.class); - private SslTransportWrapper _sniffingWrapper = new SslHandshakeSniffingTransportWrapper(_secureTransportWrapper, _plainTransportWrapper); - - @Rule - public ExpectedException _expectedException = ExpectedException.none(); - - @Test - public void testGetInputBufferGetOutputBufferWithNonSsl() - { - testInputAndOutput("INPUT".getBytes(), _plainTransportWrapper); - } - - @Test - public void testWithSSLv2() - { - testInputAndOutput(EXAMPLE_SSL_V2_HANDSHAKE_BYTES, _secureTransportWrapper); - } - - @Test - public void testWithSSLv3TLS() - { - testInputAndOutput(EXAMPLE_SSL_V3_HANDSHAKE_BYTES, _secureTransportWrapper); - } - - private void testInputAndOutput(byte[] input, TransportWrapper transportThatShouldBeUsed) - { - byte[] output = "OUTPUT".getBytes(); - - ByteBuffer underlyingInputBuffer = ByteBuffer.allocate(1024); - ByteBuffer underlyingOutputBuffer = ByteBuffer.wrap(output); - - // set up underlying transport - when(transportThatShouldBeUsed.tail()).thenReturn(underlyingInputBuffer); - when(transportThatShouldBeUsed.head()).thenReturn(underlyingOutputBuffer); - - // do input and verify underlying calls were made - ByteBuffer inputBuffer = _sniffingWrapper.tail(); - inputBuffer.put(input); - _sniffingWrapper.process(); - - verify(transportThatShouldBeUsed).tail(); - verify(transportThatShouldBeUsed).process(); - - // check the wrapped input actually received the expected bytes - underlyingInputBuffer.flip(); - assertByteBufferContentEquals(input, underlyingInputBuffer); - - // do output and check we get the correct transport's output - ByteBuffer outputBuffer = _sniffingWrapper.head(); - verify(transportThatShouldBeUsed).head(); - - assertByteBufferContentEquals(output, outputBuffer); - int consumed = outputBuffer.position(); - _sniffingWrapper.pop(consumed); - verify(transportThatShouldBeUsed).pop(consumed); - - verifyZeroInteractionsWithOtherTransport(transportThatShouldBeUsed); - } - - @Test - public void testTooFewBytesToMakeDetermination() - { - byte[] sourceBuffer = new byte[] {0x00}; - - try - { - _sniffingWrapper.tail().put(sourceBuffer); - _sniffingWrapper.close_tail(); - - _expectedException.expect(TransportException.class); - _sniffingWrapper.process(); - } - finally - { - verifyZeroInteractions(_secureTransportWrapper, _plainTransportWrapper); - } - } - - @Test - public void testGetSslAttributesWhenProtocolIsNotYetDetermined_returnNull() - { - assertEquals("Cipher name should be null", null, _sniffingWrapper.getCipherName()); - assertEquals("Protocol name should be null", null, _sniffingWrapper.getProtocolName()); - verifyZeroInteractions(_secureTransportWrapper, _plainTransportWrapper); - } - - @Test - public void testGetSslAttributesWhenUsingNonSsl_returnNull() - { - testGetSslAttributes("INPUT".getBytes(), _plainTransportWrapper, null, null); - } - - /** - * Tests {@link SslHandshakeSniffingTransportWrapper#getCipherName()} - * and {@link SslHandshakeSniffingTransportWrapper#getProtocolName()}. - */ - @Test - public void testGetSslAttributesWhenUsingSsl() - { - String cipherName = "testCipherName"; - String protocolName = "testProtocolName"; - when(_secureTransportWrapper.getCipherName()).thenReturn(cipherName); - when(_secureTransportWrapper.getProtocolName()).thenReturn(protocolName); - - testGetSslAttributes(EXAMPLE_SSL_V2_HANDSHAKE_BYTES, _secureTransportWrapper, cipherName, protocolName); - } - - private void testGetSslAttributes( - byte[] input, TransportWrapper transportThatShouldBeUsed, - String expectedCipherName, String expectedProtocolName) - { - ByteBuffer underlyingInputBuffer = ByteBuffer.allocate(1024); - when(transportThatShouldBeUsed.tail()).thenReturn(underlyingInputBuffer); - - _sniffingWrapper.tail().put(input); - _sniffingWrapper.process(); - - assertEquals(expectedCipherName, _sniffingWrapper.getCipherName()); - assertEquals(expectedProtocolName, _sniffingWrapper.getProtocolName()); - - verifyZeroInteractionsWithOtherTransport(transportThatShouldBeUsed); - } - - private void verifyZeroInteractionsWithOtherTransport(TransportWrapper transportThatShouldBeUsed) - { - final TransportWrapper transportThatShouldNotBeUsed; - if(transportThatShouldBeUsed == _plainTransportWrapper) - { - transportThatShouldNotBeUsed = _secureTransportWrapper; - } - else - { - transportThatShouldNotBeUsed = _plainTransportWrapper; - } - - verifyZeroInteractions(transportThatShouldNotBeUsed); - } - -} http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/ccdcf329/proton-j/src/test/java/org/apache/qpid/proton/message/impl/MessageImplTest.java ---------------------------------------------------------------------- diff --git a/proton-j/src/test/java/org/apache/qpid/proton/message/impl/MessageImplTest.java b/proton-j/src/test/java/org/apache/qpid/proton/message/impl/MessageImplTest.java deleted file mode 100644 index 6070745..0000000 --- a/proton-j/src/test/java/org/apache/qpid/proton/message/impl/MessageImplTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.proton.message.impl; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.nio.ByteBuffer; - -import org.apache.qpid.proton.amqp.Binary; -import org.apache.qpid.proton.amqp.messaging.Data; -import org.apache.qpid.proton.message.Message; -import org.junit.Test; - -public class MessageImplTest -{ - private static final long DATA_SECTION_ULONG_DESCRIPTOR = 0x0000000000000075L; - - @Test - public void testEncodeOfMessageWithSmallDataBodyOnly() - { - doMessageEncodingWithDataBodySectionTestImpl(5); - } - - @Test - public void testEncodeOfMessageWithLargerDataBodyOnly() - { - doMessageEncodingWithDataBodySectionTestImpl(1024); - } - - void doMessageEncodingWithDataBodySectionTestImpl(int bytesLength) - { - byte[] bytes = generateByteArray(bytesLength); - - byte[] expectedBytes = generateExpectedDataSectionBytes(bytes); - byte[] encodedBytes = new byte[expectedBytes.length]; - - Message msg = Message.Factory.create(); - msg.setBody(new Data(new Binary(bytes))); - - int encodedLength = msg.encode(encodedBytes, 0, encodedBytes.length); - - assertArrayEquals("Encoded bytes do not match expectation", expectedBytes, encodedBytes); - assertEquals("Encoded length different than expected length", encodedLength, encodedBytes.length); - } - - private byte[] generateByteArray(int bytesLength) - { - byte[] bytes = new byte[bytesLength]; - for(int i = 0; i < bytesLength; i++) - { - bytes [i] = (byte) (i % 10); - } - - return bytes; - } - - /* - * http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-data - * http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-types-v1.0-os.html - * - * ulong encodings: - * <encoding code="0x80" category="fixed" width="8" label="64-bit unsigned integer in network byte order"/> - * <encoding name="smallulong" code="0x53" category="fixed" width="1" label="unsigned long value in the range 0 to 255 inclusive"/> - * <encoding name="ulong0" code="0x44" category="fixed" width="0" label="the ulong value 0"/> - * - * binary encodings: - * <encoding name="vbin8" code="0xa0" category="variable" width="1" label="up to 2^8 - 1 octets of binary data"/> - * <encoding name="vbin32" code="0xb0" category="variable" width="4" label="up to 2^32 - 1 octets of binary data"/> - */ - byte[] generateExpectedDataSectionBytes(final byte[] payloadBytes) - { - int dataBytesLength = 1; // 0x00 for described-type constructor start - dataBytesLength += 1; // smallulong encoding format for data section descriptor - dataBytesLength += 1; // smallulong 8bit value - dataBytesLength += 1; // vbin variable-width binary encoding format. - if (payloadBytes.length > 255) - { - dataBytesLength += 4; // 32bit length field. - } - else - { - dataBytesLength += 1; // 8bit length field. - } - dataBytesLength += payloadBytes.length; // section payload length. - - ByteBuffer buffer = ByteBuffer.allocate(dataBytesLength); - - buffer.put((byte) 0x00); // 0x00 for described-type constructor start - buffer.put((byte) 0x53); // smallulong encoding format for data section descriptor - buffer.put((byte) DATA_SECTION_ULONG_DESCRIPTOR); // smallulong 8bit value - if (payloadBytes.length > 255) - { - buffer.put((byte) 0xb0); // vbin32 variable-width binary encoding format. - buffer.putInt(payloadBytes.length); // 32bit length field. - } - else - { - buffer.put((byte) 0xa0); // vbin8 variable-width binary encoding format. - buffer.put((byte) payloadBytes.length); // 8bit length field. - } - buffer.put(payloadBytes); // The actual content of given length. - - assertEquals("Unexpected buffer position", dataBytesLength, buffer.position()); - - return buffer.array(); - } - -} http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/ccdcf329/proton-j/src/test/java/org/apache/qpid/proton/messenger/impl/AddressTest.java ---------------------------------------------------------------------- diff --git a/proton-j/src/test/java/org/apache/qpid/proton/messenger/impl/AddressTest.java b/proton-j/src/test/java/org/apache/qpid/proton/messenger/impl/AddressTest.java deleted file mode 100644 index 77154b6..0000000 --- a/proton-j/src/test/java/org/apache/qpid/proton/messenger/impl/AddressTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.proton.messenger.impl; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class AddressTest { - - @SuppressWarnings("deprecation") - private void testParse(String url, String scheme, String user, String pass, String host, String port, String name) - { - Address address = new Address(url); - assertEquals(scheme, address.getScheme()); - assertEquals(user, address.getUser()); - assertEquals(pass, address.getPass()); - assertEquals(host, address.getHost()); - assertEquals(port, address.getPort()); - assertEquals(url, address.toString()); - } - - @Test - public void addressTests() - { - testParse("host", null, null, null, "host", null, null); - testParse("host:423", null, null, null, "host", "423", null); - testParse("user@host", null, "user", null, "host", null, null); - testParse("user:1243^&^:pw@host:423", null, "user", "1243^&^:pw", "host", "423", null); - testParse("user:1243^&^:pw@host:423/Foo.bar:90087", null, "user", "1243^&^:pw", "host", "423", "Foo.bar:90087"); - testParse("user:1243^&^:pw@host:423/Foo.bar:90087@somewhere", null, "user", "1243^&^:pw", "host", "423", "Foo.bar:90087@somewhere"); - testParse("[::1]", null, null, null, "::1", null, null); - testParse("[::1]:amqp", null, null, null, "::1", "amqp", null); - testParse("user@[::1]", null, "user", null, "::1", null, null); - testParse("user@[::1]:amqp", null, "user", null, "::1", "amqp", null); - testParse("user:1243^&^:pw@[::1]:amqp", null, "user", "1243^&^:pw", "::1", "amqp", null); - testParse("user:1243^&^:pw@[::1]:amqp/Foo.bar:90087", null, "user", "1243^&^:pw", "::1", "amqp", "Foo.bar:90087"); - testParse("user:1243^&^:pw@[::1:amqp/Foo.bar:90087", null, "user", "1243^&^:pw", "[", ":1:amqp", "Foo.bar:90087"); - testParse("user:1243^&^:pw@::1]:amqp/Foo.bar:90087", null, "user", "1243^&^:pw", "", ":1]:amqp", "Foo.bar:90087"); - testParse("amqp://user@[::1]", "amqp", "user", null, "::1", null, null); - testParse("amqp://user@[::1]:amqp", "amqp", "user", null, "::1", "amqp", null); - testParse("amqp://user@[1234:52:0:1260:f2de:f1ff:fe59:8f87]:amqp", "amqp", "user", null, "1234:52:0:1260:f2de:f1ff:fe59:8f87", "amqp", null); - testParse("amqp://user:1243^&^:pw@[::1]:amqp", "amqp", "user", "1243^&^:pw", "::1", "amqp", null); - testParse("amqp://user:1243^&^:pw@[::1]:amqp/Foo.bar:90087", "amqp", "user", "1243^&^:pw", "::1", "amqp", "Foo.bar:90087"); - testParse("amqp://host", "amqp", null, null, "host", null, null); - testParse("amqp://user@host", "amqp", "user", null, "host", null, null); - testParse("amqp://user@host/path:%", "amqp", "user", null, "host", null, "path:%"); - testParse("amqp://user@host:5674/path:%", "amqp", "user", null, "host", "5674", "path:%"); - testParse("amqp://user@host/path:%", "amqp", "user", null, "host", null, "path:%"); - testParse("amqp://bigbird@host/queue@host", "amqp", "bigbird", null, "host", null, "queue@host"); - testParse("amqp://host/queue@host", "amqp", null, null, "host", null, "queue@host"); - testParse("amqp://host:9765/queue@host", "amqp", null, null, "host", "9765", "queue@host"); - } -} http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/ccdcf329/proton-j/src/test/java/org/apache/qpid/proton/reactor/ReactorTest.java ---------------------------------------------------------------------- diff --git a/proton-j/src/test/java/org/apache/qpid/proton/reactor/ReactorTest.java b/proton-j/src/test/java/org/apache/qpid/proton/reactor/ReactorTest.java deleted file mode 100644 index 387446e..0000000 --- a/proton-j/src/test/java/org/apache/qpid/proton/reactor/ReactorTest.java +++ /dev/null @@ -1,692 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.proton.reactor; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.net.ServerSocket; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; - -import junit.framework.AssertionFailedError; - -import org.apache.qpid.proton.Proton; -import org.apache.qpid.proton.engine.BaseHandler; -import org.apache.qpid.proton.engine.Connection; -import org.apache.qpid.proton.engine.Delivery; -import org.apache.qpid.proton.engine.Event; -import org.apache.qpid.proton.engine.Event.Type; -import org.apache.qpid.proton.engine.Handler; -import org.apache.qpid.proton.engine.HandlerException; -import org.apache.qpid.proton.engine.Sender; -import org.apache.qpid.proton.engine.Session; -import org.apache.qpid.proton.reactor.impl.AcceptorImpl; -import org.apache.qpid.proton.reactor.impl.LeakTestReactor; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) -public class ReactorTest { - - public ReactorFactory reactorFactory; - private Reactor reactor; - - private static interface ReactorFactory { - Reactor newReactor() throws IOException; - } - - // Parameterize the tests, and run them once with a reactor obtained by calling - // 'Proton.reactor()' and once with the LeakTestReactor. - @Parameters - public static Collection<ReactorFactory[]> data() throws IOException { - ReactorFactory classicReactor = new ReactorFactory() { - @Override public Reactor newReactor() throws IOException { - return Proton.reactor(); - } - }; - ReactorFactory newLeakDetection = new ReactorFactory() { - @Override public Reactor newReactor() throws IOException { - return new LeakTestReactor(); - } - }; - return Arrays.asList(new ReactorFactory[][]{{classicReactor}, {newLeakDetection}}); - } - - public ReactorTest(ReactorFactory reactorFactory) { - this.reactorFactory = reactorFactory; - } - - @Before - public void before() throws IOException { - reactor = reactorFactory.newReactor(); - } - - private void checkForLeaks() { - if (reactor instanceof LeakTestReactor) { - ((LeakTestReactor)reactor).assertNoLeaks(); - } - } - - @After - public void after() { - checkForLeaks(); - } - - /** - * Tests that creating a reactor and running it: - * <ul> - * <li>Doesn't throw any exceptions.</li> - * <li>Returns immediately from the run method (as there is no more work to do).</li> - * </ul> - * @throws IOException - */ - @Test - public void runEmpty() throws IOException { - assertNotNull(reactor); - reactor.run(); - reactor.free(); - } - - private static class TestHandler extends BaseHandler { - private final ArrayList<Type> actual = new ArrayList<Type>(); - - @Override - public void onUnhandled(Event event) { - assertNotNull(event.getReactor()); - actual.add(event.getType()); - } - - public void assertEvents(Type...expected) { - assertArrayEquals(expected, actual.toArray()); - } - } - - /** - * Tests adding a handler to a reactor and running the reactor. The - * expected behaviour is for the reactor to return, and a number of reactor- - * related events to have been delivered to the handler. - * @throws IOException - */ - @Test - public void handlerRun() throws IOException { - Handler handler = reactor.getHandler(); - assertNotNull(handler); - TestHandler testHandler = new TestHandler(); - handler.add(testHandler); - reactor.run(); - reactor.free(); - testHandler.assertEvents(Type.REACTOR_INIT, Type.SELECTABLE_INIT, Type.SELECTABLE_UPDATED, Type.SELECTABLE_FINAL, Type.REACTOR_FINAL); - } - - /** - * Tests basic operation of the Reactor.connection method by creating a - * connection from a reactor, then running the reactor. The expected behaviour - * is for: - * <ul> - * <li>The reactor to end immediately.</li> - * <li>The handler associated with the connection receives an init event.</li> - * <li>The connection is one of the reactor's children.</li> - * </ul> - * @throws IOException - */ - @Test - public void connection() throws IOException { - TestHandler connectionHandler = new TestHandler(); - Connection connection = reactor.connection(connectionHandler); - assertNotNull(connection); - assertTrue("connection should be one of the reactor's children", reactor.children().contains(connection)); - reactor.setConnectionHost(connection, "127.0.0.1", 5672); - assertEquals("connection address configuration failed", - reactor.getConnectionAddress(connection), "127.0.0.1:5672"); - TestHandler reactorHandler = new TestHandler(); - reactor.getHandler().add(reactorHandler); - reactor.run(); - reactor.free(); - reactorHandler.assertEvents(Type.REACTOR_INIT, Type.SELECTABLE_INIT, Type.SELECTABLE_UPDATED, Type.SELECTABLE_FINAL, Type.REACTOR_FINAL); - connectionHandler.assertEvents(Type.CONNECTION_INIT); - } - - /** - * Tests operation of the Reactor.acceptor method by creating an acceptor - * which is immediately closed by the reactor. The expected behaviour is for: - * <ul> - * <li>The reactor to end immediately (as it has no more work to process).</li> - * <li>The handler, associated with the acceptor, to receive no events.</li> - * <li>For it's lifetime, the acceptor is one of the reactor's children.</li> - * </ul> - * @throws IOException - */ - @Test - public void acceptor() throws IOException { - final Acceptor acceptor = reactor.acceptor("127.0.0.1", 0); - assertNotNull(acceptor); - assertTrue("acceptor should be one of the reactor's children", reactor.children().contains(acceptor)); - TestHandler acceptorHandler = new TestHandler(); - BaseHandler.setHandler(acceptor, acceptorHandler); - reactor.getHandler().add(new BaseHandler() { - @Override - public void onReactorInit(Event event) { - acceptor.close(); - } - }); - reactor.run(); - reactor.free(); - acceptorHandler.assertEvents(); - assertFalse("acceptor should have been removed from the reactor's children", reactor.children().contains(acceptor)); - } - - private static class ServerHandler extends TestHandler { - private Acceptor acceptor; - public void setAcceptor(Acceptor acceptor) { - this.acceptor = acceptor; - } - @Override - public void onConnectionRemoteOpen(Event event) { - super.onConnectionRemoteOpen(event); - event.getConnection().open(); - } - @Override - public void onConnectionRemoteClose(Event event) { - super.onConnectionRemoteClose(event); - acceptor.close(); - event.getConnection().close(); - event.getConnection().free(); - } - } - - /** - * Tests end to end behaviour of the reactor by creating an acceptor and then - * a connection (which connects to the port the acceptor is listening on). - * As soon as the connection is established, both the acceptor and connection - * are closed. The events generated by the acceptor and the connection are - * compared to a set of expected events. - * @throws IOException - */ - @Test - public void connect() throws IOException { - ServerHandler sh = new ServerHandler(); - Acceptor acceptor = reactor.acceptor("127.0.0.1", 0, sh); - final int listeningPort = ((AcceptorImpl)acceptor).getPortNumber(); - sh.setAcceptor(acceptor); - - class ClientHandler extends TestHandler { - @Override - public void onConnectionInit(Event event) { - super.onConnectionInit(event); - event.getReactor().setConnectionHost(event.getConnection(), - "127.0.0.1", - listeningPort); - event.getConnection().open(); - } - @Override - public void onConnectionRemoteOpen(Event event) { - super.onConnectionRemoteOpen(event); - event.getConnection().close(); - } - @Override - public void onConnectionRemoteClose(Event event) { - super.onConnectionRemoteClose(event); - event.getConnection().free(); - } - } - ClientHandler ch = new ClientHandler(); - Connection connection = reactor.connection(ch); - - assertTrue("acceptor should be one of the reactor's children", reactor.children().contains(acceptor)); - assertTrue("connection should be one of the reactor's children", reactor.children().contains(connection)); - - reactor.run(); - reactor.free(); - - assertFalse("acceptor should have been removed from the reactor's children", reactor.children().contains(acceptor)); - assertFalse("connection should have been removed from the reactor's children", reactor.children().contains(connection)); - sh.assertEvents(Type.CONNECTION_INIT, Type.CONNECTION_BOUND, - // XXX: proton-c generates a PN_TRANSPORT event here - Type.CONNECTION_REMOTE_OPEN, Type.CONNECTION_LOCAL_OPEN, - Type.TRANSPORT, Type.CONNECTION_REMOTE_CLOSE, - Type.TRANSPORT_TAIL_CLOSED, Type.CONNECTION_LOCAL_CLOSE, - Type.TRANSPORT, Type.TRANSPORT_HEAD_CLOSED, - Type.TRANSPORT_CLOSED, Type.CONNECTION_UNBOUND, - Type.CONNECTION_FINAL); - - ch.assertEvents(Type.CONNECTION_INIT, Type.CONNECTION_LOCAL_OPEN, - Type.CONNECTION_BOUND, - // XXX: proton-c generates two PN_TRANSPORT events here - Type.CONNECTION_REMOTE_OPEN, Type.CONNECTION_LOCAL_CLOSE, - Type.TRANSPORT, Type.TRANSPORT_HEAD_CLOSED, - Type.CONNECTION_REMOTE_CLOSE, Type.TRANSPORT_TAIL_CLOSED, - Type.TRANSPORT_CLOSED, Type.CONNECTION_UNBOUND, - Type.CONNECTION_FINAL); - - } - - private String checkVhost(String vhost) throws IOException { - - class ServerVhostHandler extends ServerHandler { - public String peerVhost; - - @Override - public void onConnectionRemoteOpen(Event event) { - super.onConnectionRemoteOpen(event); - peerVhost = event.getConnection().getRemoteHostname(); - } - } - - class ClientVhostHandler extends TestHandler { - private int port; - private String vhost; - - ClientVhostHandler(String vhost, int port) { - this.port = port; - this.vhost = vhost; - } - - @Override - public void onConnectionInit(Event event) { - super.onConnectionInit(event); - event.getReactor().setConnectionHost(event.getConnection(), - "127.0.0.1", port); - if (vhost != null) { - event.getConnection().setHostname(vhost); - } - event.getConnection().open(); - } - @Override - public void onConnectionRemoteOpen(Event event) { - super.onConnectionRemoteOpen(event); - event.getConnection().close(); - } - @Override - public void onConnectionRemoteClose(Event event) { - super.onConnectionRemoteClose(event); - event.getConnection().free(); - } - } - ServerVhostHandler sh = new ServerVhostHandler(); - Acceptor acceptor = reactor.acceptor("127.0.0.1", 0, sh); - final int listeningPort = ((AcceptorImpl)acceptor).getPortNumber(); - sh.setAcceptor(acceptor); - - ClientVhostHandler ch = new ClientVhostHandler(vhost, listeningPort); - Connection connection = reactor.connection(ch); - - reactor.run(); - reactor.free(); - checkForLeaks(); - - return sh.peerVhost; - } - - /** - * Tests the virtual host default configuration - should be set to host - * used for the connection. - * @throws IOException - **/ - @Test - public void checkVhostDefault() throws IOException { - String vhost = checkVhost(null); - assertEquals("The default virtual host is not correct", - "127.0.0.1", vhost); - } - - /** - * Tests the virtual host override - should be set to connection's - * hostname. - * @throws IOException - **/ - @Test - public void checkVhostOverride() throws IOException { - String vhost = checkVhost("my.vhost"); - assertEquals("The virtual host is not correct", - "my.vhost", vhost); - } - - /** - * Tests eliminating the virtual host configuration - expects no vhost for - * the connection. - * @throws IOException - **/ - @Test - public void checkNoVhost() throws IOException { - String vhost = checkVhost(""); - assertEquals("The virtual host is present", - null, vhost); - } - - - private static class SinkHandler extends BaseHandler { - protected int received = 0; - - @Override - public void onDelivery(Event event) { - Delivery dlv = event.getDelivery(); - if (!dlv.isPartial()) { - dlv.settle(); - ++received; - } - } - } - - private static class SourceHandler extends BaseHandler { - private int remaining; - - protected SourceHandler(int count) { - remaining = count; - } - - @Override - public void onConnectionInit(Event event) { - Connection conn = event.getConnection(); - Session ssn = conn.session(); - Sender snd = ssn.sender("sender"); - conn.open(); - ssn.open(); - snd.open(); - } - - @Override - public void onLinkFlow(Event event) { - Sender link = (Sender)event.getLink(); - while (link.getCredit() > 0 && remaining > 0) { - Delivery dlv = link.delivery(new byte[0]); - assertNotNull(dlv); - dlv.settle(); - link.advance(); - --remaining; - } - - if (remaining == 0) { - event.getConnection().close(); - } - } - - @Override - public void onConnectionRemoteClose(Event event) { - event.getConnection().free(); - } - } - - private void transfer(int count, int window) throws IOException { - reactor = reactorFactory.newReactor(); - ServerHandler sh = new ServerHandler(); - Acceptor acceptor = reactor.acceptor("127.0.0.1", 0, sh); - sh.setAcceptor(acceptor); - sh.add(new Handshaker()); - // XXX: a window of 1 doesn't work unless the flowcontroller is - // added after the thing that settles the delivery - sh.add(new FlowController(window)); - SinkHandler snk = new SinkHandler(); - sh.add(snk); - - SourceHandler src = new SourceHandler(count); - reactor.connectionToHost("127.0.0.1", ((AcceptorImpl)acceptor).getPortNumber(), - src); - reactor.run(); - reactor.free(); - assertEquals("Did not receive the expected number of messages", count, snk.received); - checkForLeaks(); - } - - @Test - public void transfer_0to64_2() throws IOException { - for (int i = 0; i < 64; ++i) { - transfer(i, 2); - } - } - - @Test - public void transfer_1024_64() throws IOException { - transfer(1024, 64); - } - - @Test - public void transfer_4096_1024() throws IOException { - transfer(4*1024, 1024); - } - - @Test - public void schedule() throws IOException { - TestHandler reactorHandler = new TestHandler(); - reactor.getHandler().add(reactorHandler); - TestHandler taskHandler = new TestHandler(); - reactor.schedule(0, taskHandler); - reactor.run(); - reactor.free(); - reactorHandler.assertEvents(Type.REACTOR_INIT, Type.SELECTABLE_INIT, Type.SELECTABLE_UPDATED, Type.REACTOR_QUIESCED, Type.SELECTABLE_UPDATED, - Type.SELECTABLE_FINAL, Type.REACTOR_FINAL); - taskHandler.assertEvents(Type.TIMER_TASK); - } - - private class BarfException extends RuntimeException { - private static final long serialVersionUID = -5891140258375562884L; - } - - private class BarfOnSomethingHandler extends BaseHandler { - protected final BarfException exception; - - protected BarfOnSomethingHandler(BarfException exception) { - this.exception = exception; - } - } - - private class BarfOnReactorInit extends BarfOnSomethingHandler { - - protected BarfOnReactorInit(BarfException exception) { - super(exception); - } - - @Override - public void onReactorInit(Event e) { - throw exception; - } - } - - private class BarfOnReactorFinal extends BarfOnSomethingHandler { - - protected BarfOnReactorFinal(BarfException exception) { - super(exception); - } - - @Override - public void onReactorFinal(Event event) { - throw exception; - } - } - - private class BarfOnConnectionInit extends BarfOnSomethingHandler { - - protected BarfOnConnectionInit(BarfException exception) { - super(exception); - } - - @Override - public void onConnectionInit(Event e) { - throw exception; - } - } - - private class BarfOnSessionInit extends BarfOnSomethingHandler { - - protected BarfOnSessionInit(BarfException exception) { - super(exception); - } - - @Override - public void onSessionInit(Event e) { - throw exception; - } - } - - private class BarfOnLinkInit extends BarfOnSomethingHandler { - - protected BarfOnLinkInit(BarfException exception) { - super(exception); - } - - @Override - public void onLinkInit(Event e) { - throw exception; - } - } - - private class BarfOnTask extends BarfOnSomethingHandler { - - protected BarfOnTask(BarfException exception) { - super(exception); - } - - @Override - public void onTimerTask(Event e) { - throw exception; - } - } - - private void assertReactorRunBarfsOnHandler(Reactor reactor, BarfException expectedException, Handler expectedHandler) { - try { - reactor.run(); - throw new AssertionFailedError("Reactor.run() should have thrown an exception"); - } catch(HandlerException handlerException) { - assertSame("Linked exception does not match expected exception", expectedException, handlerException.getCause()); - assertSame("Handler in exception does not match expected handler", expectedHandler, handlerException.getHandler()); - } - } - - @Test - public void barfInReactorFinal() throws IOException { - BarfException expectedBarf = new BarfException(); - Handler expectedHandler = new BarfOnReactorFinal(expectedBarf); - reactor.getGlobalHandler().add(expectedHandler); - assertReactorRunBarfsOnHandler(reactor, expectedBarf, expectedHandler); - reactor.free(); - } - - @Test - public void barfOnGlobalSet() throws IOException { - BarfException expectedBarf = new BarfException(); - Handler expectedHandler = new BarfOnReactorInit(expectedBarf); - reactor.setGlobalHandler(expectedHandler); - assertReactorRunBarfsOnHandler(reactor, expectedBarf, expectedHandler); - reactor.free(); - } - - @Test - public void barfOnGlobalAdd() throws IOException { - BarfException expectedBarf = new BarfException(); - Handler expectedHandler = new BarfOnReactorInit(expectedBarf); - reactor.getGlobalHandler().add(expectedHandler); - assertReactorRunBarfsOnHandler(reactor, expectedBarf, expectedHandler); - reactor.free(); - } - - @Test - public void barfOnReactorSet() throws IOException { - BarfException expectedBarf = new BarfException(); - Handler expectedHandler = new BarfOnReactorInit(expectedBarf); - reactor.setHandler(expectedHandler); - assertReactorRunBarfsOnHandler(reactor, expectedBarf, expectedHandler); - reactor.free(); - } - - @Test - public void barfOnReactorAdd() throws IOException { - BarfException expectedBarf = new BarfException(); - Handler expectedHandler = new BarfOnReactorInit(expectedBarf); - reactor.getHandler().add(expectedHandler); - assertReactorRunBarfsOnHandler(reactor, expectedBarf, expectedHandler); - reactor.free(); - } - - @Test - public void barfOnConnection() throws IOException { - BarfException expectedBarf = new BarfException(); - Handler expectedHandler = new BarfOnConnectionInit(expectedBarf); - reactor.connection(expectedHandler); - assertReactorRunBarfsOnHandler(reactor, expectedBarf, expectedHandler); - reactor.free(); - } - - @Test - public void barfOnSession() throws IOException { - BarfException expectedBarf = new BarfException(); - Handler expectedHandler = new BarfOnSessionInit(expectedBarf); - reactor.connection(expectedHandler).session(); - assertReactorRunBarfsOnHandler(reactor, expectedBarf, expectedHandler); - reactor.free(); - } - - @Test - public void barfOnLink() throws IOException { - BarfException expectedBarf = new BarfException(); - Handler expectedHandler = new BarfOnLinkInit(expectedBarf); - reactor.connection(expectedHandler).session().sender("barf"); - assertReactorRunBarfsOnHandler(reactor, expectedBarf, expectedHandler); - reactor.free(); - } - - @Test - public void barfOnSchedule() throws IOException { - BarfException expectedBarf = new BarfException(); - Handler expectedHandler = new BarfOnTask(expectedBarf); - reactor.schedule(0, expectedHandler); - assertReactorRunBarfsOnHandler(reactor, expectedBarf, expectedHandler); - reactor.free(); - } - - @Test - public void connectionRefused() throws IOException { - final ServerSocket serverSocket = new ServerSocket(0, 0); - - class ConnectionHandler extends TestHandler { - @Override - public void onConnectionInit(Event event) { - super.onConnectionInit(event); - Connection connection = event.getConnection(); - connection.open(); - try { - serverSocket.close(); - } catch(IOException e) { - AssertionFailedError afe = new AssertionFailedError(); - afe.initCause(e); - throw afe; - } - } - } - TestHandler connectionHandler = new ConnectionHandler(); - reactor.connectionToHost("127.0.0.1", serverSocket.getLocalPort(), connectionHandler); - reactor.run(); - reactor.free(); - serverSocket.close(); - connectionHandler.assertEvents(Type.CONNECTION_INIT, Type.CONNECTION_LOCAL_OPEN, Type.CONNECTION_BOUND, Type.TRANSPORT_ERROR, Type.TRANSPORT_TAIL_CLOSED, - Type.TRANSPORT_HEAD_CLOSED, Type.TRANSPORT_CLOSED, Type.CONNECTION_UNBOUND, Type.TRANSPORT); - } -} http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/ccdcf329/proton-j/src/test/java/org/apache/qpid/proton/reactor/impl/AcceptorImplTest.java ---------------------------------------------------------------------- diff --git a/proton-j/src/test/java/org/apache/qpid/proton/reactor/impl/AcceptorImplTest.java b/proton-j/src/test/java/org/apache/qpid/proton/reactor/impl/AcceptorImplTest.java deleted file mode 100644 index 9ac0538..0000000 --- a/proton-j/src/test/java/org/apache/qpid/proton/reactor/impl/AcceptorImplTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.proton.reactor.impl; - -import java.io.IOException; -import java.nio.channels.ServerSocketChannel; - -import org.apache.qpid.proton.reactor.ReactorChild; -import org.apache.qpid.proton.reactor.Selectable.Callback; -import org.junit.Test; -import org.mockito.Mockito; - -public class AcceptorImplTest { - - /** - * Tests that if ServerSocketChannel.accept() throws an IOException the Acceptor will - * call Selectable.error() on it's underlying selector. - * @throws IOException - */ - @Test - public void acceptThrowsException() throws IOException { - final Callback mockCallback = Mockito.mock(Callback.class); - final SelectableImpl selectable = new SelectableImpl(); - selectable.onError(mockCallback); - ReactorImpl mockReactor = Mockito.mock(ReactorImpl.class); - class MockIO extends IOImpl { - @Override - public ServerSocketChannel serverSocketChannel() throws IOException { - ServerSocketChannel result = Mockito.mock(ServerSocketChannel.class); - Mockito.when(result.accept()).thenThrow(new IOException()); - return result; - } - } - IO mockIO = new MockIO(); - Mockito.when(mockReactor.getIO()).thenReturn(mockIO); - Mockito.when(mockReactor.selectable(Mockito.any(ReactorChild.class))).thenReturn(selectable); - new AcceptorImpl(mockReactor, "host", 1234, null); - selectable.readable(); - Mockito.verify(mockCallback).run(selectable); - } - - /** - * Tests that if ServerSocketChannel.accept() returns <code>null</code> the Acceptor will - * throw a ReactorInternalException (because the acceptor's underlying selectable should - * not have been marked as readable, if there is no connection to accept). - * @throws IOException - */ - @Test(expected=ReactorInternalException.class) - public void acceptReturnsNull() throws IOException { - final Callback mockCallback = Mockito.mock(Callback.class); - final SelectableImpl selectable = new SelectableImpl(); - selectable.onError(mockCallback); - ReactorImpl mockReactor = Mockito.mock(ReactorImpl.class); - class MockIO extends IOImpl { - @Override - public ServerSocketChannel serverSocketChannel() throws IOException { - ServerSocketChannel result = Mockito.mock(ServerSocketChannel.class); - Mockito.when(result.accept()).thenReturn(null); - return result; - } - } - IO mockIO = new MockIO(); - Mockito.when(mockReactor.getIO()).thenReturn(mockIO); - Mockito.when(mockReactor.selectable(Mockito.any(ReactorChild.class))).thenReturn(selectable); - new AcceptorImpl(mockReactor, "host", 1234, null); - selectable.readable(); - } -} --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
