src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
Configuration { public static void init() { int conNum = getIntProperty(CONNECTIONS_NUMBER_PARAMETER, DEFAULT_CONNECTIONS_NUMBER); if (conNum > 0) { numberOfConnections = conNum; } else { throw new IllegalArgumentException("Negative number of connections value", new IOException()); } int maxPartSize = getIntProperty(MAX_CHUNK_SIZE_PARAMETER, DEFAULT_MAX_CHUNK_SIZE); if (maxPartSize > 0) { maxDownloadPartSize = maxPartSize; } else { throw new IllegalArgumentException("Negative download part size value", new IOException()); } int retryCount = getIntProperty(CUSTOM_RETRY_COUNT_PARAMETER, DEFAULT_CUSTOM_RETRY_COUNT); if (retryCount > 0) { customRetryCount = retryCount; } else { throw new IllegalArgumentException("Negative retry count value", new IOException()); } int minPartSize = getIntProperty(MIN_CHUNK_SIZE_PARAMETER, DEFAULT_MIN_CHUNK_SIZE); if (minPartSize > 0) { minDownloadPartSize = minPartSize; } else { throw new IllegalArgumentException("Negative download part size value", new IOException()); } if (minDownloadPartSize > maxDownloadPartSize){ throw new IllegalArgumentException("min_download_chunk_size > max_download_chunk_size", new IOException()); } String url = System.getProperty(INDEX_URL_PARAMETER, ""); if ("".equals(url)) { indexFileURL = Optional.empty(); } else { try { indexFileURL = Optional.of(new URL(url)); } catch (MalformedURLException e) { throw new IllegalArgumentException("Bad URL parameter received", e); } } } private Configuration(); static int getNumberOfConnections(); static int getMaxDownloadPartSize(); static int getMinDownloadPartSize(); static void init(); static int getCustomRetryCount(); static void resetToDefault(); static final String CONNECTIONS_NUMBER_PARAMETER; static final String MAX_CHUNK_SIZE_PARAMETER; static final String MIN_CHUNK_SIZE_PARAMETER; static final String INDEX_URL_PARAMETER; static final String CUSTOM_RETRY_COUNT_PARAMETER; static final int DEFAULT_CONNECTIONS_NUMBER; static final int DEFAULT_MAX_CHUNK_SIZE; static final int DEFAULT_MIN_CHUNK_SIZE; static final int DEFAULT_CUSTOM_RETRY_COUNT; static final String DEFAULT_INDEX_URL; }
@Test (expected = IllegalArgumentException.class) public void testConfigurationShouldThrowExceptionWhenIllegalNumberOfConnectionsIsSet() { System.setProperty(Configuration.CONNECTIONS_NUMBER_PARAMETER, "-1"); Configuration.init(); } @Test (expected = IllegalArgumentException.class) public void testConfigurationShouldThrowExceptionWhenNumberOfConnectionsIsSetToAString() { System.setProperty(Configuration.CONNECTIONS_NUMBER_PARAMETER, "text"); Configuration.init(); } @Test (expected = IllegalArgumentException.class) public void testConfigurationShouldThrowExceptionWhenNegativeMaxChunkSizeIsSet() { System.setProperty(Configuration.MAX_CHUNK_SIZE_PARAMETER, "-1"); Configuration.init(); } @Test (expected = IllegalArgumentException.class) public void testConfigurationShouldThrowExceptionWhenNegativeMinChunkSizeIsSet() { System.setProperty(Configuration.MIN_CHUNK_SIZE_PARAMETER, "-1"); Configuration.init(); } @Test (expected = IllegalArgumentException.class) public void testConfigurationShouldThrowExceptionWhenMaxChunkSizeIsSetToAString() { System.setProperty(Configuration.MAX_CHUNK_SIZE_PARAMETER, "text"); Configuration.init(); } @Test (expected = IllegalArgumentException.class) public void testConfigurationShouldThrowExceptionWhenMinChunkSizeIsSetToAString() { System.setProperty(Configuration.MAX_CHUNK_SIZE_PARAMETER, "text"); Configuration.init(); } @Test (expected = IllegalArgumentException.class) public void testConfigurationShouldThrowExceptionWhenMaxChunkSizeIsNotAnInteger() { System.setProperty(Configuration.MAX_CHUNK_SIZE_PARAMETER, "524288.6"); Configuration.init(); } @Test (expected = IllegalArgumentException.class) public void testConfigurationShouldThrowExceptionWhenMinChunkSizeIsNotAnInteger() { System.setProperty(Configuration.MIN_CHUNK_SIZE_PARAMETER, "524288.6"); Configuration.init(); } @Test (expected = IllegalArgumentException.class) public void testConfigurationShouldThrowExceptionWhenIndexURLIsInvalid() { System.setProperty(Configuration.INDEX_URL_PARAMETER, "not a URL"); Configuration.init(); } @Test (expected = IllegalArgumentException.class) public void testConfigurationShouldThrowExceptionWhenCustomRetryCountInvalid() { System.setProperty(Configuration.CUSTOM_RETRY_COUNT_PARAMETER, "-1"); Configuration.init(); }
PartReader implements Callable<Optional<byte[]>> { @Override public Optional<byte[]> call() throws InterruptedException { LOG.debug("Launched ", threadName, "on ", uri.toString()); Thread.currentThread().setName(threadName); return getByteArray(Configuration.getCustomRetryCount()); } PartReader(AmazonS3URI uri, long from, long to, AtomicBoolean canceledFlag, S3InputStreamFactory factory); @Override Optional<byte[]> call(); static final int END_BYTE; }
@Test public void testFullLoading() throws InterruptedException { AtomicBoolean canceledFlag = new AtomicBoolean(false); PartReader reader = new PartReader(S3DataLoaderMocker.FAKE_URI, 0, DATA_SIZE, canceledFlag, mockFactory); byte[] buffer = reader.call().orElseThrow(RuntimeException::new); for (int i = 0; i < DATA_SIZE; i++) { Assert.assertEquals(i, buffer[i]); } } @Test public void testPartLoading() throws InterruptedException { AtomicBoolean canceledFlag = new AtomicBoolean(false); final int partSize = 10; PartReader reader = new PartReader(S3DataLoaderMocker.FAKE_URI, DATA_SIZE - partSize, DATA_SIZE, canceledFlag, mockFactory); byte[] bufferStream = reader.call().orElseThrow(RuntimeException::new); for (int i = 0; i < partSize; i++) { Assert.assertEquals(i + DATA_SIZE - partSize, bufferStream[i]); } } @Test public void partReaderShouldReconnect() throws InterruptedException { S3DataLoaderMocker.mockIOException(mockFactory); PartReader reader = new PartReader(S3DataLoaderMocker.FAKE_URI, 0, DATA_SIZE, new AtomicBoolean(false), mockFactory); Assert.assertEquals(Optional.empty(), reader.call()); Assert.assertEquals(Configuration.getCustomRetryCount(), S3DataLoaderMocker.getExceptionsCount()); } @Test(expected = RuntimeIOException.class) public void partReaderThrowExceptionWhenDataStreamEndsAhead() throws InterruptedException { S3DataLoaderMocker.mockPrimitiveLoadFromTo(mockFactory, DATA_SIZE/2); PartReader reader = new PartReader(S3DataLoaderMocker.FAKE_URI, 0, DATA_SIZE, new AtomicBoolean(false), mockFactory); reader.call(); }
S3ParallelStream extends InputStream { @Override public int read() throws IOException { if (chunckEndReached()) { currentDataChunck = taskProducer.fetchNextPart(); chunckIndex = 0; } return getNextByte(); } S3ParallelStream(AmazonS3URI uri, long from, long to, S3InputStreamFactory factory); @Override int read(); @Override void close(); }
@Test public void testLoadingInParallel() throws IOException { System.setProperty(Configuration.CONNECTIONS_NUMBER_PARAMETER, Integer.toString(NUM_OF_THREADS)); System.setProperty(Configuration.MAX_CHUNK_SIZE_PARAMETER, Integer.toString(PART_SIZE)); System.setProperty(Configuration.MIN_CHUNK_SIZE_PARAMETER, Integer.toString(PART_SIZE)); Configuration.init(); S3ParallelStream parallelStream = new S3ParallelStream(S3DataLoaderMocker.FAKE_URI, 0, DATA_SIZE, mockFactory); for (int i = 0; i < DATA_SIZE; i++) { final int read = parallelStream.read(); Assert.assertEquals(i, read); } Assert.assertEquals(-1, parallelStream.read()); }
ParallelPartsLoader implements Runnable { void cancelLoading() { canceledFlag.set(true); tasksQueue.clear(); threadPool.shutdown(); LOG.debug("Thread pool was shut down for ", uri.toString()); } ParallelPartsLoader(AmazonS3URI uri, long from, long to, S3InputStreamFactory factory); ParallelPartsLoader(AmazonS3URI uri, long from, long to, S3InputStreamFactory factory, BlockingQueue<Future<Optional<byte[]>>> tasksQueue); @Override void run(); static final int CAPACITY_BUFFER_COEFFICIENT; static final byte[] EOF; }
@Test public void taskProducerShouldTerminateWhenItIsCanceled() throws InterruptedException { BlockingQueue<Future<Optional<byte[]>>> tasksQueue = new LinkedBlockingQueue<>(); ParallelPartsLoader taskProducer = new ParallelPartsLoader( S3DataLoaderMocker.FAKE_URI, 0, DATA_SIZE, mockFactory, tasksQueue ); CompletableFuture.runAsync(taskProducer) .thenAccept(r -> taskProducer.cancelLoading()) .thenAccept(r -> Assert.assertTrue(tasksQueue.isEmpty())); }
S3SeekableStream extends SeekableStream { @Override public int read() throws IOException { return currentDataStream.read(); } S3SeekableStream(AmazonS3URI source, S3Client client, S3InputStreamFactory streamFactory); @Override long length(); @Override long position(); @Override void seek(long targetPosition); @Override int read(); @Override int read(byte[] buffer, int offset, int length); @Override void close(); @Override boolean eof(); @Override String getSource(); }
@Test public void testRead() throws IOException { SeekableStream fakeSeekable = new S3SeekableStream(S3DataLoaderMocker.FAKE_URI, client, factory); assertEquals(0, fakeSeekable.read()); final int arraySize = 16; byte[] loadArray = new byte[arraySize]; assertEquals(fakeSeekable.read(loadArray), arraySize); final int offset = 8; assertEquals(offset, fakeSeekable.read(loadArray, offset, offset)); assertEquals(fakeSeekable.position(), 1 + arraySize + offset); fakeSeekable.close(); } @Test public void streamShouldReturnEOF() throws IOException { long fileSize = 1042 * 1042; PowerMockito.when(client.getFileSize(Mockito.any(AmazonS3URI.class))).thenReturn(fileSize); S3SeekableStream fakeSeekable = new S3SeekableStream(S3DataLoaderMocker.FAKE_URI, client, factory); for (int i = 0; i < fileSize; i++) { final int expectedByte = i & (0xff); assertEquals(expectedByte, fakeSeekable.read()); } assertEquals(-1, fakeSeekable.read()); }
StateSystemUtils { public static @Nullable StateInterval queryUntilNonNullValue(IStateSystemReader ss, int attributeQuark, long t1, long t2) { long current = t1; if (t1 < ss.getStartTime()) { current = ss.getStartTime(); } long end = t2; if (end < ss.getCurrentEndTime()) { end = ss.getCurrentEndTime(); } if (end < current) { return null; } try { while (current < t2) { StateInterval currentInterval = ss.querySingleState(current, attributeQuark); StateValue value = currentInterval.getStateValue(); if (!value.isNull()) { return currentInterval; } current = currentInterval.getEnd() + 1; } } catch (AttributeNotFoundException | StateSystemDisposedException | TimeRangeException e) { } return null; } private StateSystemUtils(); static @Nullable StateInterval querySingleStackTop(IStateSystemReader ss, long t, int stackAttributeQuark); static List<StateInterval> queryHistoryRange(IStateSystemReader ss, int attributeQuark, long t1, long t2); static List<StateInterval> queryHistoryRange(IStateSystemReader ss, int attributeQuark, long t1, long t2, long resolution, @Nullable FutureTask<?> task); static @Nullable StateInterval queryUntilNonNullValue(IStateSystemReader ss, int attributeQuark, long t1, long t2); }
@Test void testQueryUntilNonNullValue() { IStateSystemReader ss = fStateSystem; assertNotNull(ss); int quark; try { quark = ss.getQuarkAbsolute(DUMMY_STRING); assertNull(StateSystemUtils.queryUntilNonNullValue(ss, quark, 0, 999L)); assertNull(StateSystemUtils.queryUntilNonNullValue(ss, quark, 2001L, 5000L)); assertNull(StateSystemUtils.queryUntilNonNullValue(ss, quark, 1000L, 1199L)); StateInterval interval = StateSystemUtils.queryUntilNonNullValue(ss, quark, 1000L, 1300L); assertNotNull(interval); assertTrue(interval.getStateValue() instanceof IntegerStateValue); assertEquals(10, ((IntegerStateValue) interval.getStateValue()).getValue()); interval = StateSystemUtils.queryUntilNonNullValue(ss, quark, 800L, 2500L); assertNotNull(interval); assertTrue(interval.getStateValue() instanceof IntegerStateValue); assertEquals(10, ((IntegerStateValue) interval.getStateValue()).getValue()); interval = StateSystemUtils.queryUntilNonNullValue(ss, quark, 1300L, 1800L); assertNotNull(interval); assertTrue(interval.getStateValue() instanceof IntegerStateValue); assertEquals(10, ((IntegerStateValue) interval.getStateValue()).getValue()); interval = StateSystemUtils.queryUntilNonNullValue(ss, quark, 1500L, 1800L); assertNotNull(interval); assertTrue(interval.getStateValue() instanceof IntegerStateValue); assertEquals(20, ((IntegerStateValue) interval.getStateValue()).getValue()); interval = StateSystemUtils.queryUntilNonNullValue(ss, quark, 1800L, 2500L); assertNotNull(interval); assertTrue(interval.getStateValue() instanceof IntegerStateValue); assertEquals(20, ((IntegerStateValue) interval.getStateValue()).getValue()); } catch (AttributeNotFoundException e) { fail(e.getMessage()); } }
InMemoryBackend implements IStateHistoryBackend { @Override public long getStartTime() { return startTime; } InMemoryBackend(@NotNull String ssid, long startTime); @Override String getSSID(); @Override long getStartTime(); @Override long getEndTime(); @Override void insertPastState(long stateStartTime, long stateEndTime, int quark, StateValue value); @Override void doQuery(List<StateInterval> currentStateInfo, long t); @Override StateInterval doSingularQuery(long t, int attributeQuark); @Override void finishBuilding(long endTime); @Override FileInputStream supplyAttributeTreeReader(); @Override File supplyAttributeTreeWriterFile(); @Override long supplyAttributeTreeWriterFilePosition(); @Override void removeFiles(); @Override void dispose(); @Override void doPartialQuery(long t, @NotNull Set<Integer> quarks, @NotNull Map<Integer, StateInterval> results); }
@Test void testStartTime() { assertEquals(0, fixture.getStartTime()); }
InMemoryBackend implements IStateHistoryBackend { @Override public long getEndTime() { return latestTime; } InMemoryBackend(@NotNull String ssid, long startTime); @Override String getSSID(); @Override long getStartTime(); @Override long getEndTime(); @Override void insertPastState(long stateStartTime, long stateEndTime, int quark, StateValue value); @Override void doQuery(List<StateInterval> currentStateInfo, long t); @Override StateInterval doSingularQuery(long t, int attributeQuark); @Override void finishBuilding(long endTime); @Override FileInputStream supplyAttributeTreeReader(); @Override File supplyAttributeTreeWriterFile(); @Override long supplyAttributeTreeWriterFilePosition(); @Override void removeFiles(); @Override void dispose(); @Override void doPartialQuery(long t, @NotNull Set<Integer> quarks, @NotNull Map<Integer, StateInterval> results); }
@Test void testEndTime() { assertEquals(99999, fixture.getEndTime()); }
InMemoryBackend implements IStateHistoryBackend { @Override public void doQuery(List<StateInterval> currentStateInfo, long t) throws TimeRangeException { if (!checkValidTime(t)) { throw new TimeRangeException(ssid + " Time:" + t + ", Start:" + startTime + ", End:" + latestTime); } synchronized (intervals) { Iterator<StateInterval> iter = serachforEndTime(intervals, t); for (int modCount = 0; iter.hasNext() && modCount < currentStateInfo.size();) { StateInterval entry = iter.next(); final long entryStartTime = entry.getStart(); if (entryStartTime <= t) { currentStateInfo.set(entry.getAttribute(), entry); modCount++; } } } } InMemoryBackend(@NotNull String ssid, long startTime); @Override String getSSID(); @Override long getStartTime(); @Override long getEndTime(); @Override void insertPastState(long stateStartTime, long stateEndTime, int quark, StateValue value); @Override void doQuery(List<StateInterval> currentStateInfo, long t); @Override StateInterval doSingularQuery(long t, int attributeQuark); @Override void finishBuilding(long endTime); @Override FileInputStream supplyAttributeTreeReader(); @Override File supplyAttributeTreeWriterFile(); @Override long supplyAttributeTreeWriterFilePosition(); @Override void removeFiles(); @Override void dispose(); @Override void doPartialQuery(long t, @NotNull Set<Integer> quarks, @NotNull Map<Integer, StateInterval> results); }
@Test void testDoQuery() { List<StateInterval> interval = new ArrayList<>(NUMBER_OF_ATTRIBUTES); for (int i = 0; i < NUMBER_OF_ATTRIBUTES; i++) { interval.add(null); } try { fixture.doQuery(interval, 950); } catch (TimeRangeException | StateSystemDisposedException e) { fail(e.getMessage()); } assertEquals(NUMBER_OF_ATTRIBUTES, interval.size()); testInterval(interval.get(0), 900, 990, 9); testInterval(interval.get(1), 901, 991, 9); testInterval(interval.get(2), 902, 992, 9); testInterval(interval.get(3), 903, 993, 9); testInterval(interval.get(4), 904, 994, 9); testInterval(interval.get(5), 905, 995, 9); testInterval(interval.get(6), 906, 996, 9); testInterval(interval.get(7), 907, 997, 9); testInterval(interval.get(8), 908, 998, 9); testInterval(interval.get(9), 909, 999, 9); }
InMemoryBackend implements IStateHistoryBackend { @Override public StateInterval doSingularQuery(long t, int attributeQuark) throws TimeRangeException, AttributeNotFoundException { if (!checkValidTime(t)) { throw new TimeRangeException(ssid + " Time:" + t + ", Start:" + startTime + ", End:" + latestTime); } synchronized (intervals) { Iterator<StateInterval> iter = serachforEndTime(intervals, t); while (iter.hasNext()) { StateInterval entry = iter.next(); final boolean attributeMatches = (entry.getAttribute() == attributeQuark); final long entryStartTime = entry.getStart(); if (attributeMatches) { if (entryStartTime <= t) { return entry; } } } } throw new AttributeNotFoundException(ssid + " Quark:" + attributeQuark); } InMemoryBackend(@NotNull String ssid, long startTime); @Override String getSSID(); @Override long getStartTime(); @Override long getEndTime(); @Override void insertPastState(long stateStartTime, long stateEndTime, int quark, StateValue value); @Override void doQuery(List<StateInterval> currentStateInfo, long t); @Override StateInterval doSingularQuery(long t, int attributeQuark); @Override void finishBuilding(long endTime); @Override FileInputStream supplyAttributeTreeReader(); @Override File supplyAttributeTreeWriterFile(); @Override long supplyAttributeTreeWriterFilePosition(); @Override void removeFiles(); @Override void dispose(); @Override void doPartialQuery(long t, @NotNull Set<Integer> quarks, @NotNull Map<Integer, StateInterval> results); }
@Test void testQueryAttributeEmpty() { try { StateInterval interval = fixture.doSingularQuery(999, 0); assertNotNull(interval); assertEquals(StateValue.nullValue(), interval.getStateValue()); } catch (TimeRangeException | AttributeNotFoundException | StateSystemDisposedException e) { fail(e.getMessage()); } } @Test void testBegin() { try { StateInterval interval = fixture.doSingularQuery(0, 0); assertNotNull(interval); assertEquals(0, interval.getStart()); assertEquals(90, interval.getEnd()); assertEquals(0, ((IntegerStateValue) interval.getStateValue()).getValue()); } catch (TimeRangeException | AttributeNotFoundException | StateSystemDisposedException e) { fail(e.getMessage()); } } @Test void testEnd() { try { StateInterval interval = fixture.doSingularQuery(99998, 9); testInterval(interval, 99909, 99999, 99); } catch (TimeRangeException | AttributeNotFoundException | StateSystemDisposedException e) { fail(e.getMessage()); } } @Test void testOutOfRange_1() throws TimeRangeException { assertThrows(TimeRangeException.class, () -> { try { StateInterval interval = fixture.doSingularQuery(-1, 0); assertNull(interval); } catch (AttributeNotFoundException | StateSystemDisposedException e) { fail(e.getMessage()); } }); } @Test void testOutOfRange_2() throws TimeRangeException { assertThrows(TimeRangeException.class, () -> { try { StateInterval interval = fixture.doSingularQuery(100000, 0); assertNull(interval); } catch (AttributeNotFoundException | StateSystemDisposedException e) { fail(e.getMessage()); } }); }
HistoryTree { public int getNodeCount() { return fNodeCount; } HistoryTree(File newStateFile, int blockSize, int maxChildren, int providerVersion, long startTime); HistoryTree(File existingStateFile, int expProviderVersion); void closeTree(long requestedEndTime); long getTreeStart(); long getTreeEnd(); int getNodeCount(); HistoryTreeNode getRootNode(); FileInputStream supplyATReader(); File supplyATWriterFile(); long supplyATWriterFilePos(); HistoryTreeNode readNode(int seqNumber); void writeNode(HistoryTreeNode node); void closeFile(); void deleteFile(); void insertInterval(HTInterval interval); HistoryTreeNode selectNextChild(CoreNode currentNode, long t); long getFileSize(); static final int TREE_HEADER_SIZE; }
@Test void testDepth() { HistoryTree ht = setupSmallTree(); HistoryTreeNode node = getLatestLeaf(ht); int nodeFreeSpace = node.getNodeFreeSpace(); int nbIntervals = nodeFreeSpace / STRING_INTERVAL_SIZE; long start = fillValues(ht, STRING_VALUE, nbIntervals, 1); assertEquals(1, ht.getNodeCount()); assertEquals(1, getDepth(ht)); start = fillValues(ht, STRING_VALUE, 1, start); assertEquals(3, ht.getNodeCount()); assertEquals(2, getDepth(ht)); node = getLatestLeaf(ht); nodeFreeSpace = node.getNodeFreeSpace(); nbIntervals = nodeFreeSpace / STRING_INTERVAL_SIZE; start = fillValues(ht, STRING_VALUE, nbIntervals, start); start = fillValues(ht, STRING_VALUE, 1, start); assertEquals(4, ht.getNodeCount()); assertEquals(2, getDepth(ht)); node = getLatestLeaf(ht); nodeFreeSpace = node.getNodeFreeSpace(); nbIntervals = nodeFreeSpace / STRING_INTERVAL_SIZE; start = fillValues(ht, STRING_VALUE, nbIntervals, start); start = fillValues(ht, STRING_VALUE, 1, start); assertEquals(7, ht.getNodeCount()); assertEquals(3, getDepth(ht)); }
SNSAppender extends AbstractAppender<SNSWriterConfig,SNSWriterStatistics,SNSWriterStatisticsMXBean,LogbackEventType> { public void setSubject(String value) { this.subject = value; if (writer == null) return; Utils.invokeSetterQuietly(writer, "setSubject", String.class, value); } SNSAppender(); void setTopicName(String value); String getTopicName(); void setTopicArn(String value); String getTopicArn(); void setAutoCreate(boolean value); boolean getAutoCreate(); void setSubject(String value); String getSubject(); @Override void setBatchDelay(long value); }
@Test public void testChangeSubject() throws Exception { initialize("testChangeSubject"); logger.debug("this triggers writer creation"); MockSNSWriter writer = appender.getMockWriter(); assertEquals("initial subject", "First Subject", writer.config.subject); appender.setSubject("Second Subject"); assertEquals("updated subject", "Second Subject", writer.config.subject); }
JsonConverter { public String convert(Map<String,Object> map) { StringBuilder builder = new StringBuilder(1024); appendMap(builder, map); return builder.toString(); } String convert(Map<String,Object> map); }
@Test public void testEmptyMap() throws Exception { String json = converter.convert(Collections.<String,Object>emptyMap()); assertEquals("{}", json); } @Test public void testSimpleString() throws Exception { String json = converter.convert(new MapBuilder<String,Object>(new TreeMap<String,Object>()) .put("foo", "bar") .toMap()); assertEquals("{\"foo\":\"bar\"}", json); } @Test public void testTwoStrings() throws Exception { String json = converter.convert(new MapBuilder<String,Object>(new TreeMap<String,Object>()) .put("foo", "bar") .put("argle", "bargle") .toMap()); assertEquals("{\"argle\":\"bargle\",\"foo\":\"bar\"}", json); } @Test public void testEscapedStrings() throws Exception { String json = converter.convert(new MapBuilder<String,Object>(new TreeMap<String,Object>()) .put("f\u00f6\u00f6\u0001", "\"\n\r\t\u0007\u0019\f\\") .toMap()); assertEquals("{\"f\u00f6\u00f6\":\"\\\"\\n\\r\\t\\b\\f\\\\\"}", json); } @Test public void testNumber() throws Exception { String json = converter.convert(new MapBuilder<String,Object>(new TreeMap<String,Object>()) .put("foo", Integer.valueOf(123)) .toMap()); assertEquals("{\"foo\":123}", json); } @Test public void testBoolean() throws Exception { String json = converter.convert(new MapBuilder<String,Object>(new TreeMap<String,Object>()) .put("bar", Boolean.TRUE) .put("baz", Boolean.FALSE) .toMap()); assertEquals("{\"bar\":true,\"baz\":false}", json); } @Test public void testDate() throws Exception { Date d = new Date(1507764490123L); String json = converter.convert(new MapBuilder<String,Object>(new TreeMap<String,Object>()) .put("foo", d) .toMap()); assertEquals("{\"foo\":\"2017-10-11T23:28:10.123Z\"}", json); } @Test public void testNull() throws Exception { String json = converter.convert(new MapBuilder<String,Object>(new TreeMap<String,Object>()) .put("bar", null) .toMap()); assertEquals("{\"bar\":null}", json); } @Test public void testArray() throws Exception { String json = converter.convert(new MapBuilder<String,Object>(new TreeMap<String,Object>()) .put("foo", new String[] {"bar", "123", null}) .toMap()); assertEquals("{\"foo\":[\"bar\",\"123\",null]}", json); } @Test public void testList() throws Exception { String json = converter.convert(new MapBuilder<String,Object>(new TreeMap<String,Object>()) .put("foo", Arrays.asList("bar", 123, null)) .toMap()); assertEquals("{\"foo\":[\"bar\",123,null]}", json); } @Test public void testSet() throws Exception { Set<String> s = new TreeSet<String>(); s.add("argle"); s.add("bargle"); String json = converter.convert(new MapBuilder<String,Object>(new TreeMap<String,Object>()) .put("foo", s) .toMap()); assertEquals("{\"foo\":[\"argle\",\"bargle\"]}", json); } @Test public void testMap() throws Exception { String json = converter.convert(new MapBuilder<String,Object>(new TreeMap<String,Object>()) .put("foo", new MapBuilder<String,Object>(new TreeMap<String,Object>()) .put("bar", "baz") .toMap()) .toMap()); assertEquals("{\"foo\":{\"bar\":\"baz\"}}", json); } @Test public void testBogus() throws Exception { String json = converter.convert(new MapBuilder<String,Object>(new TreeMap<String,Object>()) .put("foo", String.class) .toMap()); assertEquals("{\"foo\":\"" + String.class.toString() + "\"}", json); }
JsonAccessLayout extends AbstractJsonLayout<IAccessEvent> { public void setEnableQueryString(boolean value) { enableQueryString = value; } void setEnableServer(boolean value); boolean getEnableServer(); void setEnableRemoteHost(boolean value); boolean getEnableRemoteHost(); void setEnableRemoteUser(boolean value); boolean getEnableRemoteUser(); void setEnableSessionId(boolean value); boolean getEnableSessionId(); void setEnableRequestHeaders(boolean value); boolean getEnableRequestHeaders(); void setEnableResponseHeaders(boolean value); boolean getEnableResponseHeaders(); void setIncludeHeaders(String value); String getIncludeHeaders(); void setExcludeHeaders(String value); String getExcludeHeaders(); void setEnableParameters(boolean value); boolean getEnableParameters(); void setIncludeParameters(String value); String getIncludeParameters(); void setExcludeParameters(String value); String getExcludeParameters(); void setEnableCookies(boolean value); boolean getEnableCookies(); void setIncludeCookies(String value); String getIncludeCookies(); void setExcludeCookies(String value); String getExcludeCookies(); void setEnableQueryString(boolean value); boolean getEnableQueryString(); @Override String doLayout(IAccessEvent event); }
@Test public void testEnableQueryString() throws Exception { JsonAccessLayout layout = new JsonAccessLayout(); layout.setEnableQueryString(true); constructMocks("/example", "name=value", "success!"); applyLayoutAndParse(layout); DomAsserts.assertEquals("query string", "?name=value", dom, "/data/queryString"); }
LogMessage implements Comparable<LogMessage> { public void truncate(int maxSize) { if (size() <= maxSize) return; int idx = maxSize; int curFlag = 0; while (idx > 0) { curFlag = messageBytes[idx] & 0x00C0; if (curFlag != 0x0080) break; idx--; } if (curFlag == 0x00C0) idx--; int newSize = Math.min(maxSize, idx + 1); byte[] newBytes = new byte[newSize]; System.arraycopy(messageBytes, 0, newBytes, 0, newSize); messageBytes = newBytes; message = new String(messageBytes, StandardCharsets.UTF_8); } LogMessage(long timestamp, String message); long getTimestamp(); int size(); String getMessage(); byte[] getBytes(); void truncate(int maxSize); @Override int compareTo(LogMessage that); }
@Test public void testTruncate() throws Exception { final String ascii = "abcdefg"; final String utf8 = "\u00c1\u00c2\u2440"; final String mixed = "\u00c1\u00c2X\u2440"; LogMessage e1 = new LogMessage(0, ""); e1.truncate(Integer.MAX_VALUE); assertArrayEquals("empty array", new byte[0], e1.getBytes()); LogMessage e2 = new LogMessage(0, "this is a test"); e2.truncate(0); assertArrayEquals("truncate to empty", new byte[0], e1.getBytes()); LogMessage a1 = new LogMessage(0, ascii); a1.truncate(7); assertEquals("truncate size == array size, USASCII", "abcdefg", new String(a1.getBytes(), StandardCharsets.UTF_8)); assertEquals("truncate size == array size, USASCII", "abcdefg", a1.getMessage()); LogMessage a2 = new LogMessage(0, ascii); a2.truncate(Integer.MAX_VALUE); assertEquals("truncate size > array size, USASCII", "abcdefg", new String(a2.getBytes(), StandardCharsets.UTF_8)); assertEquals("truncate size > array size, USASCII", "abcdefg", a2.getMessage()); LogMessage a3 = new LogMessage(0, ascii); a3.truncate(3); assertEquals("truncate size < array size, USASCII", "abc", new String(a3.getBytes(), StandardCharsets.UTF_8)); assertEquals("truncate size < array size, USASCII", "abc", a3.getMessage()); LogMessage a4 = new LogMessage(0, ascii); a4.truncate(6); assertEquals("truncate size == array size - 1, USASCII", "abcdef", new String(a4.getBytes(), StandardCharsets.UTF_8)); assertEquals("truncate size == array size - 1, USASCII", "abcdef", a4.getMessage()); LogMessage u1 = new LogMessage(0, utf8); u1.truncate(7); assertEquals("truncate size == array size, UTF-8", "\u00c1\u00c2\u2440", new String(u1.getBytes(), StandardCharsets.UTF_8)); assertEquals("truncate size == array size, UTF-8", "\u00c1\u00c2\u2440", u1.getMessage()); LogMessage u2 = new LogMessage(0, utf8); u2.truncate(Integer.MAX_VALUE); assertEquals("truncate size > array size, UTF-8", "\u00c1\u00c2\u2440", new String(u2.getBytes(), StandardCharsets.UTF_8)); assertEquals("truncate size > array size, UTF-8", "\u00c1\u00c2\u2440", u2.getMessage()); LogMessage u3 = new LogMessage(0, utf8); u3.truncate(4); assertEquals("truncate size < array size, UTF-8, at boundary", "\u00c1\u00c2", new String(u3.getBytes(), StandardCharsets.UTF_8)); assertEquals("truncate size < array size, UTF-8, at boundary", "\u00c1\u00c2", u3.getMessage()); LogMessage u4 = new LogMessage(0, utf8); u4.truncate(5); assertEquals("truncate size < array size, UTF-8, start-of-sequence", "\u00c1\u00c2", new String(u4.getBytes(), StandardCharsets.UTF_8)); assertEquals("truncate size < array size, UTF-8, start-of-sequence", "\u00c1\u00c2", u4.getMessage()); LogMessage u5 = new LogMessage(0, utf8); u5.truncate(6); assertEquals("truncate size < array size, UTF-8, mid-sequence", "\u00c1\u00c2", new String(u5.getBytes(), StandardCharsets.UTF_8)); assertEquals("truncate size < array size, UTF-8, mid-sequence", "\u00c1\u00c2", u5.getMessage()); LogMessage m1 = new LogMessage(0, mixed); m1.truncate(5); assertEquals("truncate size < array size, mixed, ASCII before boundary", "\u00c1\u00c2X", new String(m1.getBytes(), StandardCharsets.UTF_8)); assertEquals("truncate size < array size, mixed, ASCII before boundary", "\u00c1\u00c2X", m1.getMessage()); LogMessage m2 = new LogMessage(0, mixed); m2.truncate(4); assertEquals("truncate size < array size, mixed, ASCII after boundary", "\u00c1\u00c2", new String(m2.getBytes(), StandardCharsets.UTF_8)); assertEquals("truncate size < array size, mixed, ASCII after boundary", "\u00c1\u00c2", m2.getMessage()); }
DefaultThreadFactory implements ThreadFactory { @Override public void startLoggingThread(final LogWriter writer, boolean useShutdownHook, UncaughtExceptionHandler exceptionHandler) { final Thread writerThread = createThread(writer, exceptionHandler); if (useShutdownHook) { Thread shutdownHook = new Thread(new Runnable() { @Override public void run() { writer.stop(); try { writerThread.join(); } catch (InterruptedException e) { } } }); shutdownHook.setName(writerThread.getName() + "-shutdownHook"); writer.setShutdownHook(shutdownHook); Runtime.getRuntime().addShutdownHook(shutdownHook); } writerThread.start(); } DefaultThreadFactory(String appenderName); @Override void startLoggingThread(final LogWriter writer, boolean useShutdownHook, UncaughtExceptionHandler exceptionHandler); }
@Test public void testBasicOperation() throws Exception { TestableDefaultThreadFactory factory = new TestableDefaultThreadFactory("test"); MockLogWriter<AbstractWriterConfig> writer = new MockLogWriter<>(null); factory.startLoggingThread(writer); assertTrue("writer was started", writer.waitUntilInitialized(1000)); assertTrue("no uncaught exceptions", factory.uncaughtExceptions.isEmpty()); ArrayList<Thread> threads = new ArrayList<>(factory.threads); assertEquals("number of threads created", 1, threads.size()); assertRegex("thread name", ".*logwriter-test-\\d+", threads.get(0).getName()); assertSame("writer was started on thread", threads.get(0), writer.writerThread); } @Test public void testUncaughtExceptions() throws Exception { TestableDefaultThreadFactory factory = new TestableDefaultThreadFactory("test"); LogWriter writer = new ThrowingWriterFactory<>().newLogWriter(null, null, null); factory.startLoggingThread(writer); assertTrue("writer was started", writer.waitUntilInitialized(1000)); writer.addMessage(null); writer.addMessage(null); factory.waitForThreadsToFinish(); Set<Thread> allThreads = new HashSet<>(factory.threads); Set<Thread> exceptionThreads = new HashSet<>(factory.uncaughtExceptions.keySet()); assertEquals("caught exception", 1, exceptionThreads.size()); assertEquals("exception threads", allThreads, exceptionThreads); }
Utils { public static Class<?> loadClass(String fullyQualifiedName) { try { return Class.forName(fullyQualifiedName); } catch (ClassNotFoundException ex) { return null; } } static void sleepQuietly(long time); static Class<?> loadClass(String fullyQualifiedName); static Method findMethodIfExists(Class<?> klass, String methodName, Class<?>... paramTypes); static Method findFullyQualifiedMethod(String name, Class<?>... params); static Object invokeQuietly(Object obj, Method method, Object... params); static Object invokeQuietly(Method method, Object... params); static void invokeSetter(Object obj, String setterName, Class<?> valueKlass, Object value); static boolean invokeSetterQuietly(Object obj, String setterName, Class<?> valueKlass, Object value); static String lookupRegion(String override); }
@Test public void testLoadClass() throws Exception { assertSame("known good class", getClass(), Utils.loadClass("com.kdgregory.logging.aws.internal.TestUtils")); assertNull("known bad class", Utils.loadClass("com.kdgregory.IDoNotExist")); }
Utils { public static Method findMethodIfExists(Class<?> klass, String methodName, Class<?>... paramTypes) { if ((klass == null) || (methodName == null) || methodName.isEmpty()) return null; try { return klass.getDeclaredMethod(methodName, paramTypes); } catch (Exception ex) { } try { return klass.getMethod(methodName, paramTypes); } catch (Exception ex) { return null; } } static void sleepQuietly(long time); static Class<?> loadClass(String fullyQualifiedName); static Method findMethodIfExists(Class<?> klass, String methodName, Class<?>... paramTypes); static Method findFullyQualifiedMethod(String name, Class<?>... params); static Object invokeQuietly(Object obj, Method method, Object... params); static Object invokeQuietly(Method method, Object... params); static void invokeSetter(Object obj, String setterName, Class<?> valueKlass, Object value); static boolean invokeSetterQuietly(Object obj, String setterName, Class<?> valueKlass, Object value); static String lookupRegion(String override); }
@Test public void testGetDeclaredMethodIfExists() throws Exception { Method m0a = Utils.findMethodIfExists(null, "declaredMethod"); assertNull("returned null for null class", m0a); Method m0b = Utils.findMethodIfExists(getClass(), null); assertNull("returned null for null method name", m0b); Method m0c = Utils.findMethodIfExists(getClass(), ""); assertNull("returned null for empty method name", m0c); Method m1 = Utils.findMethodIfExists(getClass(), "declaredMethod"); assertEquals("found no-param method", Integer.valueOf(1), m1.invoke(this)); Method m2 = Utils.findMethodIfExists(getClass(), "declaredMethod", String.class); assertEquals("found one-param method", Integer.valueOf(2), m2.invoke(this, "foo")); Method m3 = Utils.findMethodIfExists(getClass(), "declaredMethod", String.class, Integer.class); assertNull("returned null for incorrect parameters", m3); Method m4 = Utils.findMethodIfExists(getClass(), "bogus"); assertNull("returned null for bogus method name", m4); }
Utils { public static Method findFullyQualifiedMethod(String name, Class<?>... params) throws ClassNotFoundException, NoSuchMethodException { if ((name == null) || (name.isEmpty())) return null; int methodIdx = name.lastIndexOf('.'); if (methodIdx <= 0) throw new IllegalArgumentException("invalid factory method name: " + name); String className = name.substring(0, methodIdx); String methodName = name.substring(methodIdx + 1); Class<?> klass = loadClass(className); if (klass == null) throw new ClassNotFoundException(className); Method method = findMethodIfExists(klass, methodName, params); if (method == null) throw new NoSuchMethodException("invalid factory method: " + name); return method; } static void sleepQuietly(long time); static Class<?> loadClass(String fullyQualifiedName); static Method findMethodIfExists(Class<?> klass, String methodName, Class<?>... paramTypes); static Method findFullyQualifiedMethod(String name, Class<?>... params); static Object invokeQuietly(Object obj, Method method, Object... params); static Object invokeQuietly(Method method, Object... params); static void invokeSetter(Object obj, String setterName, Class<?> valueKlass, Object value); static boolean invokeSetterQuietly(Object obj, String setterName, Class<?> valueKlass, Object value); static String lookupRegion(String override); }
@Test public void testFindFactoryMethod() throws Exception { String unparseable = "bogus"; try { Utils.findFullyQualifiedMethod(unparseable); fail("did not throw for unparseable method name"); } catch (IllegalArgumentException ex) { assertRegex("unparseable method name exception message (was: " + ex.getMessage() + ")", "invalid.*" + unparseable, ex.getMessage()); } String invalidClass = "com.example.Bogus"; try { Utils.findFullyQualifiedMethod(invalidClass + ".doesntMatter"); fail("did not throw for nonexistent class"); } catch (ClassNotFoundException ex) { assertRegex("nonexistent class exception message (was: " + ex.getMessage() + ")", ".*" + invalidClass, ex.getMessage()); } String validClassInvalidMethod = getClass().getName() + ".bogus"; try { Utils.findFullyQualifiedMethod(validClassInvalidMethod); fail("did not throw for nonexistent method"); } catch (NoSuchMethodException ex) { assertRegex("nonexistent method exception message (was: " + ex.getMessage() + ")", ".*" + validClassInvalidMethod, ex.getMessage()); } String validClassValidMethod = getClass().getName() + ".factoryMethod"; Method m1 = Utils.findFullyQualifiedMethod(validClassValidMethod); assertEquals("found no-param method", Integer.valueOf(100), m1.invoke(null)); Method m2 = Utils.findFullyQualifiedMethod(validClassValidMethod, String.class); assertEquals("found one-param method", Integer.valueOf(200), m2.invoke(null, "foo")); try { Utils.findFullyQualifiedMethod(validClassValidMethod, String.class, Integer.class); fail("did not throw for method with invalid parameters"); } catch (NoSuchMethodException ex) { assertRegex("nonexistent method exception message (was: " + ex.getMessage() + ")", ".*" + validClassValidMethod, ex.getMessage()); } }
Utils { public static Object invokeQuietly(Object obj, Method method, Object... params) { if ((obj == null) || (method == null)) return null; try { return method.invoke(obj, params); } catch (Exception ex) { return null; } } static void sleepQuietly(long time); static Class<?> loadClass(String fullyQualifiedName); static Method findMethodIfExists(Class<?> klass, String methodName, Class<?>... paramTypes); static Method findFullyQualifiedMethod(String name, Class<?>... params); static Object invokeQuietly(Object obj, Method method, Object... params); static Object invokeQuietly(Method method, Object... params); static void invokeSetter(Object obj, String setterName, Class<?> valueKlass, Object value); static boolean invokeSetterQuietly(Object obj, String setterName, Class<?> valueKlass, Object value); static String lookupRegion(String override); }
@Test public void testInvokeQuietly() throws Exception { Method m1 = Utils.findFullyQualifiedMethod(getClass().getName() + ".declaredMethod", String.class); assertEquals("valid instance invocation", Integer.valueOf(2), Utils.invokeQuietly(this, m1, "foo")); assertEquals("instance invocation with wrong #/params", null, Utils.invokeQuietly(this, m1, "foo", "bar")); assertEquals("instance invocation with null method", null, Utils.invokeQuietly(this, null, "foo", "bar")); assertEquals("instance invocation with null object", null, Utils.invokeQuietly((Object)null, m1, "foo", "bar")); Method m2 = Utils.findFullyQualifiedMethod(getClass().getName() + ".factoryMethod", String.class); assertEquals("valid static invocation", Integer.valueOf(200), Utils.invokeQuietly(m2, "foo")); assertEquals("static invocation with wrong #/params", null, Utils.invokeQuietly(m2, "foo", "bar")); assertEquals("static invocation with null method", null, Utils.invokeQuietly(null, "foo", "bar")); }
JsonAccessLayout extends AbstractJsonLayout<IAccessEvent> { public void setEnableRemoteUser(boolean value) { enableRemoteUser = value; } void setEnableServer(boolean value); boolean getEnableServer(); void setEnableRemoteHost(boolean value); boolean getEnableRemoteHost(); void setEnableRemoteUser(boolean value); boolean getEnableRemoteUser(); void setEnableSessionId(boolean value); boolean getEnableSessionId(); void setEnableRequestHeaders(boolean value); boolean getEnableRequestHeaders(); void setEnableResponseHeaders(boolean value); boolean getEnableResponseHeaders(); void setIncludeHeaders(String value); String getIncludeHeaders(); void setExcludeHeaders(String value); String getExcludeHeaders(); void setEnableParameters(boolean value); boolean getEnableParameters(); void setIncludeParameters(String value); String getIncludeParameters(); void setExcludeParameters(String value); String getExcludeParameters(); void setEnableCookies(boolean value); boolean getEnableCookies(); void setIncludeCookies(String value); String getIncludeCookies(); void setExcludeCookies(String value); String getExcludeCookies(); void setEnableQueryString(boolean value); boolean getEnableQueryString(); @Override String doLayout(IAccessEvent event); }
@Test public void testEnableRemoteUser() throws Exception { JsonAccessLayout layout = new JsonAccessLayout(); layout.setEnableRemoteUser(true); constructMocks("/example", "name=value", "success!"); request.setRemoteUser("example"); applyLayoutAndParse(layout); DomAsserts.assertEquals("remote user", "example", dom, "/data/user"); }
Utils { public static void invokeSetter(Object obj, String setterName, Class<?> valueKlass, Object value) throws Throwable { if (obj == null) return; Method m = findMethodIfExists(obj.getClass(), setterName, valueKlass); if (m == null) throw new NoSuchMethodException(obj.getClass().getName() + "." + setterName); try { m.invoke(obj, value); } catch (InvocationTargetException ex) { throw ex.getCause(); } } static void sleepQuietly(long time); static Class<?> loadClass(String fullyQualifiedName); static Method findMethodIfExists(Class<?> klass, String methodName, Class<?>... paramTypes); static Method findFullyQualifiedMethod(String name, Class<?>... params); static Object invokeQuietly(Object obj, Method method, Object... params); static Object invokeQuietly(Method method, Object... params); static void invokeSetter(Object obj, String setterName, Class<?> valueKlass, Object value); static boolean invokeSetterQuietly(Object obj, String setterName, Class<?> valueKlass, Object value); static String lookupRegion(String override); }
@Test public void testInvokeSetter() throws Throwable { ObjectWithSetter obj = new ObjectWithSetter(); Utils.invokeSetter(obj, "setValue", String.class, "foo"); assertEquals("happy path", "foo", obj.value); assertTrue(Utils.invokeSetterQuietly(obj, "setValue", String.class, null)); assertNull("can set null value", obj.value); Utils.invokeSetter(null, "setValue", String.class, "foo"); try { Utils.invokeSetter(obj, "setSomething", String.class, "foo"); fail("succeeded with nonexistent method"); } catch (NoSuchMethodException ex) { assertRegex("nonexistent method exception message (was: " + ex.getMessage() + ")", ".*setSomething", ex.getMessage()); } try { Utils.invokeSetter(obj, "setValue", String.class, Integer.valueOf(123)); fail("succeeded with incorrect parameter type"); } catch (IllegalArgumentException ex) { } }
Utils { public static boolean invokeSetterQuietly(Object obj, String setterName, Class<?> valueKlass, Object value) { if (obj == null) return false; try { invokeSetter(obj, setterName, valueKlass, value); return true; } catch (Throwable ex) { return false; } } static void sleepQuietly(long time); static Class<?> loadClass(String fullyQualifiedName); static Method findMethodIfExists(Class<?> klass, String methodName, Class<?>... paramTypes); static Method findFullyQualifiedMethod(String name, Class<?>... params); static Object invokeQuietly(Object obj, Method method, Object... params); static Object invokeQuietly(Method method, Object... params); static void invokeSetter(Object obj, String setterName, Class<?> valueKlass, Object value); static boolean invokeSetterQuietly(Object obj, String setterName, Class<?> valueKlass, Object value); static String lookupRegion(String override); }
@Test public void testInvokeSetterQuietly() throws Throwable { ObjectWithSetter obj = new ObjectWithSetter(); assertTrue(Utils.invokeSetterQuietly(obj, "setValue", String.class, "foo")); assertEquals("happy path", "foo", obj.value); assertTrue(Utils.invokeSetterQuietly(obj, "setValue", String.class, null)); assertNull("can set null value", obj.value); assertFalse(Utils.invokeSetterQuietly(null, "setValue", String.class, "foo")); assertFalse(Utils.invokeSetterQuietly(obj, "setSomething", String.class, "foo")); assertFalse(Utils.invokeSetterQuietly(obj, "setValue", String.class, Integer.valueOf(123))); }
ConstructorClientFactory implements ClientFactory<ClientType> { @Override public ClientType createClient() { logger.debug("creating client via constructor"); ClientType client = invokeConstructor(); if (maybeSetEndpoint(client)) return client; maybeSetRegion(client); return client; } ConstructorClientFactory( Class<ClientType> clientType, String clientClassName, String region, String endpoint, InternalLogger logger); @Override ClientType createClient(); }
@Test public void testConstructor() throws Exception { ConstructorClientFactory<AWSLogs> factory = new ConstructorClientFactory<AWSLogs>(AWSLogs.class, AWSLogsClient.class.getName(), null, null, logger); AWSLogs client = factory.createClient(); assertNotNull("actually created a client", client); if (StringUtil.isBlank(System.getenv("AWS_REGION"))) { assertEndpointRegion(client, "us-east-1"); logger.assertInternalDebugLog("creating client via constructor"); logger.assertInternalErrorLog(); } else { assertEndpointRegion(client, System.getenv("AWS_REGION")); logger.assertInternalDebugLog("creating client via constructor", "setting region.*" + System.getenv("AWS_REGION")); logger.assertInternalErrorLog(); } } @Test public void testConstructorWithExplicitRegion() throws Exception { final String region = "us-west-1"; ConstructorClientFactory<AWSLogs> factory = new ConstructorClientFactory<AWSLogs>(AWSLogs.class, AWSLogsClient.class.getName(), region, null, logger); AWSLogs client = factory.createClient(); assertNotNull("actually created a client", client); assertEndpointRegion(client, region); logger.assertInternalDebugLog("creating client via constructor", "setting region.*" + region); logger.assertInternalErrorLog(); } @Test public void testConstructorWithBogusRegion() throws Exception { final String region = "eu-west-3"; ConstructorClientFactory<AWSLogs> factory = new ConstructorClientFactory<AWSLogs>(AWSLogs.class, AWSLogsClient.class.getName(), region, null, logger); try { factory.createClient(); fail("did not throw when constructing client"); } catch (ClientFactoryException ex) { assertRegex("failed to set region.*" + region, ex.getMessage()); } } @Test public void testConstructorWithExplicitEndpoint() throws Exception { final String region = "eu-west-3"; final String endpoint = "logs." + region + ".amazonaws.com"; ConstructorClientFactory<AWSLogs> factory = new ConstructorClientFactory<AWSLogs>(AWSLogs.class, AWSLogsClient.class.getName(), null, endpoint, logger); AWSLogs client = factory.createClient(); assertNotNull("actually created a client", client); assertEndpointRegion(client, region); logger.assertInternalDebugLog("creating client via constructor", "setting endpoint.*" + endpoint); logger.assertInternalErrorLog(); }
BuilderClientFactory implements ClientFactory<ClientType> { @Override public ClientType createClient() { if (builderClass == null) return null; logger.debug("creating client via SDK builder"); Object builder = createBuilder(); maybeSetRegion(builder); setCredentialsProvider(builder); try { Method clientFactoryMethod = builder.getClass().getMethod("build"); return clientType.cast(clientFactoryMethod.invoke(builder)); } catch (Exception ex) { throw new ClientFactoryException("failed to invoke builder: " + builderClassName, ex); } } BuilderClientFactory(Class<ClientType> clientType, String builderClassName, String assumedRole, String region, InternalLogger logger); @Override ClientType createClient(); }
@Test public void testBasicOperation() throws Exception { BuilderClientFactory<AWSLogs> factory = new BuilderClientFactory<AWSLogs>(AWSLogs.class, MockClientBuilder.class.getName(), null, null, logger) { @Override protected AWSCredentialsProvider createDefaultCredentialsProvider() { return testCredentialsProvider; } @Override protected AWSCredentialsProvider createAssumedRoleCredentialsProvider() { throw new IllegalStateException("should not have asked for assumed-role credentials provider"); } }; AWSLogs client = factory.createClient(); assertSame("created a client using mock", client, createdClient); assertNull("did not set region", actualRegion); assertSame("set credentials provider", actualCredentialsProvider, testCredentialsProvider); logger.assertInternalDebugLog( "creating client via SDK builder", "using default credentials provider"); logger.assertInternalErrorLog(); } @Test public void testBuilderWithRegion() throws Exception { final String region = "us-west-1"; BuilderClientFactory<AWSLogs> factory = new BuilderClientFactory<AWSLogs>(AWSLogs.class, MockClientBuilder.class.getName(), null, region, logger) { @Override protected AWSCredentialsProvider createDefaultCredentialsProvider() { return testCredentialsProvider; } @Override protected AWSCredentialsProvider createAssumedRoleCredentialsProvider() { throw new IllegalStateException("should not have asked for assumed-role credentials provider"); } }; AWSLogs client = factory.createClient(); assertSame("client created by builder", client, createdClient); assertSame("region set on builder", region, actualRegion); logger.assertInternalDebugLog( "creating client via SDK builder", "setting region.*" + region, "using default credentials provider"); logger.assertInternalErrorLog(); } @Test public void testBuilderWithInvalidRegion() throws Exception { final String region = "bogus"; BuilderClientFactory<AWSLogs> factory = new BuilderClientFactory<AWSLogs>(AWSLogs.class, MockClientBuilderForInvalidRegionTest.class.getName(), null, region, logger) { @Override protected AWSCredentialsProvider createDefaultCredentialsProvider() { return testCredentialsProvider; } @Override protected AWSCredentialsProvider createAssumedRoleCredentialsProvider() { throw new IllegalStateException("should not have asked for assumed-role credentials provider"); } }; try { factory.createClient(); fail("was able to create client"); } catch (ClientFactoryException ex) { assertRegex("exception message", "failed to set region: " + region, ex.getMessage()); } logger.assertInternalDebugLog( "creating client via SDK builder", "setting region.*" + region); logger.assertInternalErrorLog(); } @Test public void testBuilderWithAssumedRole() throws Exception { final String assumedRole = "Example"; BuilderClientFactory<AWSLogs> factory = new BuilderClientFactory<AWSLogs>(AWSLogs.class, MockClientBuilderForInvalidRegionTest.class.getName(), assumedRole, null, logger) { @Override protected AWSCredentialsProvider createDefaultCredentialsProvider() { throw new IllegalStateException("should not have asked for default credentials provider"); } @Override protected AWSCredentialsProvider createAssumedRoleCredentialsProvider() { return testCredentialsProvider; } }; AWSLogs client = factory.createClient(); assertSame("client created by builder", client, createdClient); assertSame("set credentials provider", actualCredentialsProvider, testCredentialsProvider); logger.assertInternalDebugLog("creating client via SDK builder", "assuming role.*" + assumedRole); logger.assertInternalErrorLog(); } @Test public void testBuilderExceptionWhileAssumingRole() throws Exception { final String assumedRole = "Example"; BuilderClientFactory<AWSLogs> factory = new BuilderClientFactory<AWSLogs>(AWSLogs.class, MockClientBuilderForInvalidRegionTest.class.getName(), assumedRole, null, logger) { @Override protected AWSCredentialsProvider createDefaultCredentialsProvider() { throw new IllegalStateException("should not have asked for default credentials provider"); } @Override protected AWSCredentialsProvider createAssumedRoleCredentialsProvider() { throw new RuntimeException("denied!"); } }; try { factory.createClient(); fail("able to create client when credentials provider threw"); } catch (ClientFactoryException ex) { assertEquals("exception message", "failed to set credentials provider", ex.getMessage()); assertEquals("wrapped exception", "denied!", ex.getCause().getMessage()); } logger.assertInternalDebugLog("creating client via SDK builder", "assuming role.*" + assumedRole); logger.assertInternalErrorLog(); }
JsonAccessLayout extends AbstractJsonLayout<IAccessEvent> { public void setEnableSessionId(boolean value) { enableSessionId = value; } void setEnableServer(boolean value); boolean getEnableServer(); void setEnableRemoteHost(boolean value); boolean getEnableRemoteHost(); void setEnableRemoteUser(boolean value); boolean getEnableRemoteUser(); void setEnableSessionId(boolean value); boolean getEnableSessionId(); void setEnableRequestHeaders(boolean value); boolean getEnableRequestHeaders(); void setEnableResponseHeaders(boolean value); boolean getEnableResponseHeaders(); void setIncludeHeaders(String value); String getIncludeHeaders(); void setExcludeHeaders(String value); String getExcludeHeaders(); void setEnableParameters(boolean value); boolean getEnableParameters(); void setIncludeParameters(String value); String getIncludeParameters(); void setExcludeParameters(String value); String getExcludeParameters(); void setEnableCookies(boolean value); boolean getEnableCookies(); void setIncludeCookies(String value); String getIncludeCookies(); void setExcludeCookies(String value); String getExcludeCookies(); void setEnableQueryString(boolean value); boolean getEnableQueryString(); @Override String doLayout(IAccessEvent event); }
@Test public void testEnableSessionId() throws Exception { JsonAccessLayout layout = new JsonAccessLayout(); layout.setEnableSessionId(true); constructMocks("/example", "name=value", "success!"); request.getSession(); applyLayoutAndParse(layout); String sessionId = new XPathWrapper("/data/sessionId").evaluateAsString(dom); assertFalse("session ID present and not blank", StringUtil.isBlank(sessionId)); } @Test public void testEnableSessionIdWithNoSession() throws Exception { JsonAccessLayout layout = new JsonAccessLayout(); layout.setEnableSessionId(true); constructMocks("/example", "name=value", "success!"); request = new MockHttpServletRequest() { @Override public HttpSession getSession() { throw new IllegalStateException("Cannot create a session after the response has been committed"); } }; applyLayoutAndParse(layout); DomAsserts.assertCount("session ID present", 1, dom, "/data/sessionId"); DomAsserts.assertEquals("session ID is blank", "", dom, "/data/sessionId"); }
StaticMethodClientFactory implements ClientFactory<ClientType> { @Override public ClientType createClient() { if ((fullyQualifiedMethodName == null) || fullyQualifiedMethodName.isEmpty()) return null; logger.debug("creating client via factory method: " + fullyQualifiedMethodName); Method factoryMethod; try { factoryMethod = Utils.findFullyQualifiedMethod(fullyQualifiedMethodName); } catch (Exception ignored) { try { factoryMethod = Utils.findFullyQualifiedMethod(fullyQualifiedMethodName, String.class, String.class, String.class); } catch (Exception ex) { throw new ClientFactoryException("invalid factory method: " + fullyQualifiedMethodName, ex); } } try { return (factoryMethod.getParameterTypes().length == 0) ? clientType.cast(factoryMethod.invoke(null)) : clientType.cast(factoryMethod.invoke(null, assumedRole, region, endpoint)); } catch (Exception ex) { throw new ClientFactoryException("factory method error: " + fullyQualifiedMethodName, ex); } } StaticMethodClientFactory( Class<ClientType> clientType, String fullyQualifiedMethodName, String assumedRole, String region, String endpoint, InternalLogger logger); @Override ClientType createClient(); }
@Test public void testFactoryMethod() throws Exception { String factoryMethodName = getClass().getName() + ".baseFactoryMethod"; StaticMethodClientFactory<AWSLogs> factory = new StaticMethodClientFactory<>(AWSLogs.class, factoryMethodName, null, null, null, logger); AWSLogs client = factory.createClient(); assertNotNull("created a client", client); assertSame("client created via factory", client, clientFromFactory); logger.assertInternalDebugLog(".*factory.*" + factoryMethodName); logger.assertInternalErrorLog(); } @Test public void testFactoryMethodWithConfig() throws Exception { String factoryMethodName = getClass().getName() + ".parameterizedFactoryMethod"; String assumedRole = "arn:aws:iam::123456789012:role/AssumableRole"; final String region = "eu-west-3"; final String endpoint = "logs." + region + ".amazonaws.com"; StaticMethodClientFactory<AWSLogs> factory = new StaticMethodClientFactory<>(AWSLogs.class, factoryMethodName, assumedRole, region, endpoint, logger); AWSLogs client = factory.createClient(); assertNotNull("created a client", client); assertSame("client created via factory", client, clientFromFactory); assertEquals("role provided", assumedRole, factoryParamAssumedRole); assertEquals("region provided", region, factoryParamRegion); assertEquals("endpoint provided", endpoint, factoryParamEndpoint); logger.assertInternalDebugLog(".*factory.*" + factoryMethodName); logger.assertInternalErrorLog(); } @Test public void testFactoryMethodBogusName() throws Exception { String factoryMethodName = "completelybogus"; StaticMethodClientFactory<AWSLogs> factory = new StaticMethodClientFactory<>(AWSLogs.class, factoryMethodName, null, null, null, logger); try { factory.createClient(); fail("should have thrown"); } catch (ClientFactoryException ex) { assertEquals("exception message", "invalid factory method: " + factoryMethodName, ex.getMessage()); } logger.assertInternalDebugLog(".*factory.*" + factoryMethodName); logger.assertInternalErrorLog(); } @Test public void testFactoryMethodNoSuchClass() throws Exception { String factoryMethodName = "com.example.bogus"; StaticMethodClientFactory<AWSLogs> factory = new StaticMethodClientFactory<>(AWSLogs.class, factoryMethodName, null, null, null, logger); try { factory.createClient(); fail("should have thrown"); } catch (ClientFactoryException ex) { assertEquals("exception message", "invalid factory method: " + factoryMethodName, ex.getMessage()); assertSame("wrapped exception", ClassNotFoundException.class, ex.getCause().getClass()); } logger.assertInternalDebugLog(".*factory.*" + factoryMethodName); logger.assertInternalErrorLog(); } @Test public void testFactoryMethodNoSuchMethod() throws Exception { String factoryMethodName = getClass().getName() + ".bogus"; StaticMethodClientFactory<AWSLogs> factory = new StaticMethodClientFactory<>(AWSLogs.class, factoryMethodName, null, null, null, logger); try { factory.createClient(); fail("should have thrown"); } catch (ClientFactoryException ex) { assertEquals("exception message", "invalid factory method: " + factoryMethodName, ex.getMessage()); } logger.assertInternalDebugLog(".*factory.*" + factoryMethodName); logger.assertInternalErrorLog(); } @Test public void testFactoryMethodException() throws Exception { String factoryMethodName = getClass().getName() + ".throwingFactoryMethod"; StaticMethodClientFactory<AWSLogs> factory = new StaticMethodClientFactory<>(AWSLogs.class, factoryMethodName, null, null, null, logger); try { factory.createClient(); fail("should have thrown"); } catch (ClientFactoryException ex) { assertEquals("exception message", "factory method error: " + factoryMethodName, ex.getMessage()); assertEquals("underlying cause", InvalidOperationException.class, ex.getCause().getClass()); } logger.assertInternalDebugLog(".*factory.*" + factoryMethodName); logger.assertInternalErrorLog(); }
AbstractReflectionBasedRetriever { public Object invokeStatic(Class<?> objKlass, String methodName, Class<?> paramKlass, Object value) { return invokeMethod(objKlass, null, methodName, paramKlass, value); } AbstractReflectionBasedRetriever(String builderClassName, String clientClassName, String requestClassName, String responseClassName); AbstractReflectionBasedRetriever(String clientClassName, String requestClassName, String responseClassName); AbstractReflectionBasedRetriever(String className); AbstractReflectionBasedRetriever(); Class<?> loadClass(String className); Object instantiate(Class<?> klass); Object invokeBuilder(); Object invokeMethod(Class<?> objKlass, Object obj, String methodName, Class<?> paramKlass, Object value); Object invokeStatic(Class<?> objKlass, String methodName, Class<?> paramKlass, Object value); void setRequestValue(Object request, String methodName, Class<?> valueKlass, Object value); Object invokeRequest(Object client, String methodName, Object value); T getResponseValue(Object response, String methodName, Class<T> resultKlass); void shutdown(Object client); public Throwable exception; public Class<?> builderKlass; public Class<?> clientKlass; public Class<?> requestKlass; public Class<?> responseKlass; }
@Test public void testInvokeStatic() throws Exception { AbstractReflectionBasedRetriever invoker = new AbstractReflectionBasedRetriever("java.lang.String"); String result = (String)invoker.invokeStatic(invoker.clientKlass, "valueOf", Object.class, new Integer(123)); assertEquals("result", "123", result); }
AbstractReflectionBasedRetriever { public Object invokeBuilder() { if ((exception != null) || (builderKlass == null) || (clientKlass == null)) return null; return clientKlass.cast(invokeMethod(builderKlass, null, "defaultClient", null, null)); } AbstractReflectionBasedRetriever(String builderClassName, String clientClassName, String requestClassName, String responseClassName); AbstractReflectionBasedRetriever(String clientClassName, String requestClassName, String responseClassName); AbstractReflectionBasedRetriever(String className); AbstractReflectionBasedRetriever(); Class<?> loadClass(String className); Object instantiate(Class<?> klass); Object invokeBuilder(); Object invokeMethod(Class<?> objKlass, Object obj, String methodName, Class<?> paramKlass, Object value); Object invokeStatic(Class<?> objKlass, String methodName, Class<?> paramKlass, Object value); void setRequestValue(Object request, String methodName, Class<?> valueKlass, Object value); Object invokeRequest(Object client, String methodName, Object value); T getResponseValue(Object response, String methodName, Class<T> resultKlass); void shutdown(Object client); public Throwable exception; public Class<?> builderKlass; public Class<?> clientKlass; public Class<?> requestKlass; public Class<?> responseKlass; }
@Test public void testInvokeBuilder() throws Exception { AbstractReflectionBasedRetriever invoker = new AbstractReflectionBasedRetriever( HappyPathBuilder.class.getName(), HappyPathClient.class.getName(), HappyPathRequest.class.getName(), HappyPathResponse.class.getName()); assertNull("no exception reported", invoker.exception); assertSame("builder class", HappyPathBuilder.class, invoker.builderKlass); assertSame("client class", HappyPathClient.class, invoker.clientKlass); assertSame("request class", HappyPathRequest.class, invoker.requestKlass); assertSame("response class", HappyPathResponse.class, invoker.responseKlass); HappyPathClient client = (HappyPathClient)invoker.invokeBuilder(); assertNotNull("builder succeeded", client); assertTrue("client was created by builder", client.createdByBuilder); }
AccountIdRetriever extends AbstractReflectionBasedRetriever { public String invoke() { Object client = instantiate(clientKlass); try { Object request = instantiate(requestKlass); Object response = invokeRequest(client, "getCallerIdentity", request); return getResponseValue(response, "getAccount", String.class); } finally { shutdown(client); } } AccountIdRetriever(); String invoke(); }
@Test public void testAccountIdRetrieverHappyPath() throws Exception { AccountIdRetriever retriever = new AccountIdRetriever(); assertNull("no exception", retriever.exception); assertSame("client class", AWSSecurityTokenServiceClient.class, retriever.clientKlass); assertSame("request class", GetCallerIdentityRequest.class, retriever.requestKlass); assertSame("response class", GetCallerIdentityResult.class, retriever.responseKlass); retriever.clientKlass = TestAccountIdRetrieverHappyPath.class; assertEquals("retrieved value", TestAccountIdRetrieverHappyPath.ACCOUNT_ID, retriever.invoke()); } @Test public void testAccountIdRetrieverException() throws Exception { AccountIdRetriever retriever = new AccountIdRetriever(); assertNull("no exception", retriever.exception); assertSame("client class", AWSSecurityTokenServiceClient.class, retriever.clientKlass); assertSame("request class", GetCallerIdentityRequest.class, retriever.requestKlass); assertSame("response class", GetCallerIdentityResult.class, retriever.responseKlass); retriever.clientKlass = TestAccountIdRetrieverException.class; assertNull("retrieved value", retriever.invoke()); }
RoleArnRetriever extends AbstractReflectionBasedRetriever { public String invoke(String roleName) { if (roleName == null) return null; if (Pattern.matches("arn:.+:iam::\\d{12}:role/.+", roleName)) return roleName; Object client = instantiate(clientKlass); try { Object request = instantiate(requestKlass); Object response; do { response = invokeRequest(client, "listRoles", request); if (response == null) return null; String marker = getResponseValue(response, "getMarker", String.class); setRequestValue(request, "setMarker", String.class, marker); List<Object> roles = getResponseValue(response, "getRoles", List.class); if (roles == null) roles = Collections.emptyList(); for (Object role : roles) { String roleArn = (String)invokeMethod(roleKlass, role, "getArn", null, null); if (roleName.equals(invokeMethod(roleKlass, role, "getRoleName", null, null))) return roleArn; } } while (getResponseValue(response, "isTruncated", Boolean.class)); return null; } finally { shutdown(client); } } RoleArnRetriever(); String invoke(String roleName); }
@Test public void testRoleArnRetrieverShortcuts() throws Exception { RoleArnRetriever retriever = new RoleArnRetriever(); assertNull("no construction exception", retriever.exception); retriever.clientKlass = String.class; String roleArn = "arn:aws:iam::123456789012:role/ThisRoleDoesntExist"; assertEquals("returned ARN", roleArn, retriever.invoke(roleArn)); assertNull("no invocation exception", retriever.exception); assertNull("returned null when passed null", retriever.invoke(null)); assertNull("still no invocation exception", retriever.exception); } @Test public void testRoleArnRetrieverHappyPath() throws Exception { RoleArnRetriever retriever = new RoleArnRetriever(); assertNull("no construction exception", retriever.exception); retriever.clientKlass = TestRoleArnRetrieverHappyPath.class; assertEquals("returned expected result", TestRoleArnRetrieverHappyPath.ROLE_ARN, retriever.invoke(TestRoleArnRetrieverHappyPath.ROLE_NAME)); assertNull("no execution exception", retriever.exception); } @Test public void testRoleArnRetrieverNoResults() throws Exception { RoleArnRetriever retriever = new RoleArnRetriever(); assertNull("no construction exception", retriever.exception); retriever.clientKlass = TestRoleArnRetrieverNoResults.class; assertNull("no result", retriever.invoke("NoSuchRole")); assertNull("no execution exception", retriever.exception); } @Test public void testRoleArnRetrieverException() throws Exception { RoleArnRetriever retriever = new RoleArnRetriever(); assertNull("no construction exception", retriever.exception); retriever.clientKlass = TestRoleArnRetrieverException.class; assertNull("no result", retriever.invoke("NoSuchRole")); assertNotNull("execution exception recorded", retriever.exception); }
CloudWatchAppender extends AbstractAppender<CloudWatchAppenderConfig,CloudWatchWriterStatistics,CloudWatchWriterStatisticsMXBean,CloudWatchWriterConfig> { @Override protected void rotate() { super.rotate(); } protected CloudWatchAppender(String name, CloudWatchAppenderConfig config, InternalLogger internalLogger); @PluginBuilderFactory static CloudWatchAppenderBuilder newBuilder(); }
@Test public void testExplicitRotation() throws Exception { initialize("testExplicitRotation"); MockCloudWatchWriterFactory writerFactory = appender.getWriterFactory(); logger.debug("first message"); MockCloudWatchWriter writer0 = appender.getMockWriter(); assertEquals("pre-rotate, writer factory calls", 1, writerFactory.invocationCount); assertEquals("pre-rotate, logstream name", "bargle-0", writer0.config.logStreamName); appender.rotate(); MockCloudWatchWriter writer1 = appender.getMockWriter(); assertEquals("post-rotate, writer factory calls", 2, writerFactory.invocationCount); assertNotSame("post-rotate, writer has been replaced", writer0, writer1); assertEquals("post-rotate, logstream name", "bargle-1", writer1.config.logStreamName); assertEquals("post-rotate, messages passed to old writer", 1, writer0.messages.size()); assertEquals("post-rotate, messages passed to new writer", 0, writer1.messages.size()); appenderInternalLogger.assertDebugLog(); }
CloudWatchAppender extends AbstractAppender<CloudWatchWriterConfig,CloudWatchWriterStatistics,CloudWatchWriterStatisticsMXBean,LogbackEventType> { @Override public void rotate() { super.rotate(); } CloudWatchAppender(); void setLogGroup(String value); String getLogGroup(); void setLogStream(String value); String getLogStream(); void setRetentionPeriod(int value); Integer getRetentionPeriod(); void setDedicatedWriter(boolean value); boolean getDedicatedWriter(); @Override void setRotationMode(String value); @Override void rotate(); }
@Test public void testExplicitRotation() throws Exception { initialize("testExplicitRotation"); MockCloudWatchWriterFactory writerFactory = appender.getWriterFactory(); logger.debug("first message"); MockCloudWatchWriter writer0 = appender.getMockWriter(); assertEquals("pre-rotate, writer factory calls", 1, writerFactory.invocationCount); assertEquals("pre-rotate, logstream name", "bargle-0", writer0.config.logStreamName); appender.rotate(); MockCloudWatchWriter writer1 = appender.getMockWriter(); assertEquals("post-rotate, writer factory calls", 2, writerFactory.invocationCount); assertNotSame("post-rotate, writer has been replaced", writer0, writer1); assertEquals("post-rotate, logstream name", "bargle-1", writer1.config.logStreamName); assertEquals("post-rotate, messages passed to old writer", 1, writer0.messages.size()); assertEquals("post-rotate, messages passed to new writer", 0, writer1.messages.size()); appenderInternalLogger.assertDebugLog(); }
CloudWatchAppender extends AbstractAppender<CloudWatchWriterConfig,CloudWatchWriterStatistics,CloudWatchWriterStatisticsMXBean,LogbackEventType> { @Override public void setRotationMode(String value) { super.setRotationMode(value); } CloudWatchAppender(); void setLogGroup(String value); String getLogGroup(); void setLogStream(String value); String getLogStream(); void setRetentionPeriod(int value); Integer getRetentionPeriod(); void setDedicatedWriter(boolean value); boolean getDedicatedWriter(); @Override void setRotationMode(String value); @Override void rotate(); }
@Test public void testReconfigureRotation() throws Exception { initialize("testDailyRotation"); logger.debug("first message"); MockCloudWatchWriter writer0 = appender.getMockWriter(); appender.updateLastRotationTimestamp(-7200000); logger.debug("second message"); assertSame("still using original writer", writer0, appender.getMockWriter()); appenderInternalLogger.assertDebugLog(); appender.setRotationMode(RotationMode.hourly.toString()); logger.debug("third message"); appenderInternalLogger.assertDebugLog("rotating.*"); MockCloudWatchWriter writer1 = appender.getMockWriter(); assertNotSame("should be using new writer", writer0, writer1); assertEquals("messages passed to old writer", 2, writer0.messages.size()); assertEquals("messages passed to new writer", 1, writer1.messages.size()); }
SNSAppender extends AbstractAppender<SNSWriterConfig,SNSWriterStatistics,SNSWriterStatisticsMXBean> { public void setSubject(String value) { this.subject = value; if (writer == null) return; Utils.invokeSetterQuietly(writer, "setSubject", String.class, value); } SNSAppender(); void setTopicName(String value); String getTopicName(); void setTopicArn(String value); String getTopicArn(); void setAutoCreate(boolean value); boolean getAutoCreate(); void setSubject(String value); String getSubject(); @Override void setBatchDelay(long value); }
@Test public void testChangeSubject() throws Exception { initialize("testChangeSubject"); logger.debug("this triggers writer creation"); MockSNSWriter writer = appender.getMockWriter(); assertEquals("initial subject", "First Subject", writer.config.subject); appender.setSubject("Second Subject"); assertEquals("updated subject", "Second Subject", writer.config.subject); }
CloudWatchAppender extends AbstractAppender<CloudWatchWriterConfig,CloudWatchWriterStatistics,CloudWatchWriterStatisticsMXBean> { @Override public void rotate() { super.rotate(); } CloudWatchAppender(); void setLogGroup(String value); String getLogGroup(); void setLogStream(String value); String getLogStream(); void setRetentionPeriod(int value); int getRetentionPeriod(); void setDedicatedWriter(boolean value); boolean getDedicatedWriter(); @Override void setRotationMode(String value); @Override void rotate(); }
@Test public void testExplicitRotation() throws Exception { initialize("testExplicitRotation"); MockCloudWatchWriterFactory writerFactory = appender.getWriterFactory(); logger.debug("first message"); MockCloudWatchWriter writer0 = appender.getMockWriter(); assertEquals("pre-rotate, writer factory calls", 1, writerFactory.invocationCount); assertEquals("pre-rotate, logstream name", "bargle-0", writer0.config.logStreamName); appender.rotate(); MockCloudWatchWriter writer1 = appender.getMockWriter(); assertEquals("post-rotate, writer factory calls", 2, writerFactory.invocationCount); assertNotSame("post-rotate, writer has been replaced", writer0, writer1); assertEquals("post-rotate, logstream name", "bargle-1", writer1.config.logStreamName); assertEquals("post-rotate, messages passed to old writer", 1, writer0.messages.size()); assertEquals("post-rotate, messages passed to new writer", 0, writer1.messages.size()); appenderInternalLogger.assertDebugLog(); }
CloudWatchAppender extends AbstractAppender<CloudWatchWriterConfig,CloudWatchWriterStatistics,CloudWatchWriterStatisticsMXBean> { @Override public void setRotationMode(String value) { super.setRotationMode(value); } CloudWatchAppender(); void setLogGroup(String value); String getLogGroup(); void setLogStream(String value); String getLogStream(); void setRetentionPeriod(int value); int getRetentionPeriod(); void setDedicatedWriter(boolean value); boolean getDedicatedWriter(); @Override void setRotationMode(String value); @Override void rotate(); }
@Test public void testReconfigureRotation() throws Exception { initialize("testDailyRotation"); logger.debug("first message"); MockCloudWatchWriter writer0 = appender.getMockWriter(); appender.updateLastRotationTimestamp(-7200000); logger.debug("second message"); assertSame("still using original writer", writer0, appender.getMockWriter()); appenderInternalLogger.assertDebugLog(); appender.setRotationMode(RotationMode.hourly.toString()); logger.debug("third message"); appenderInternalLogger.assertDebugLog("rotating.*"); MockCloudWatchWriter writer1 = appender.getMockWriter(); assertNotSame("should be using new writer", writer0, writer1); assertEquals("messages passed to old writer", 2, writer0.messages.size()); assertEquals("messages passed to new writer", 1, writer1.messages.size()); }
AEMDataLayerInterceptorFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof SlingHttpServletRequest && isApplicable((SlingHttpServletRequest) request)) { SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request; DataLayer dataLayer = DataLayerUtil.getDataLayer(slingRequest); try { updateDataLayer(slingRequest, dataLayer); } catch (Exception e) { log.warn("Exception updating DataLayer for resource " + slingRequest.getResource().getPath(), e); } } chain.doFilter(request, response); } @Override void destroy(); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void init(FilterConfig filterConfig); static final String REQUEST_PROPERTY_AEM_DATALAYER_APPLICABLE; }
@Test public void testAttributesCreated() throws IOException, ServletException { FilterChain filterChain = mock(FilterChain.class); AEMDataLayerInterceptorFilter filter = context.getService(AEMDataLayerInterceptorFilter.class); context.currentPage("/test/page-with-cloud-config"); SlingHttpServletRequest request = spy(context.request()); filter.doFilter(request, context.response(), filterChain); verify(request, atLeastOnce()).setAttribute(eq("AEM_DATALAYER"), any(DataLayer.class)); verify(request, atLeastOnce()).setAttribute(eq("AEM_DATALAYER_APPLICABLE"), eq(Boolean.TRUE)); } @Test public void testAttributesNotCreated() throws IOException, ServletException { FilterChain filterChain = mock(FilterChain.class); AEMDataLayerInterceptorFilter filter = context.getService(AEMDataLayerInterceptorFilter.class); context.currentPage("/test/page-without-cloud-config"); SlingHttpServletRequest request = spy(context.request()); filter.doFilter(request, context.response(), filterChain); verify(request, never()).setAttribute(eq("AEM_DATALAYER"), any(DataLayer.class)); verify(request, atLeastOnce()).setAttribute(eq("AEM_DATALAYER_APPLICABLE"), eq(Boolean.FALSE)); }
AEMDataLayerInterceptorFilter implements Filter { boolean resourceHierarchyHasACycle(Resource resource) { String resourceType = resource.getResourceType(); Set<String> resourceTypeSet = new HashSet<>(); ResourceResolver resolver = resource.getResourceResolver(); while (resourceType != null) { if (resourceTypeSet.contains(resourceType)) { log.trace("Found a cycle in the resource type hierarchy for {}", resourceType); return true; } resourceTypeSet.add(resourceType); resourceType = resolver.getParentResourceType(resource.getResourceType()); } return false; } @Override void destroy(); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void init(FilterConfig filterConfig); static final String REQUEST_PROPERTY_AEM_DATALAYER_APPLICABLE; }
@Test public void testResourceTypeHierarchyWithNoCycle() throws IOException, ServletException { AEMDataLayerInterceptorFilter filter = context.getService(AEMDataLayerInterceptorFilter.class); context.currentPage("/test/page-with-cloud-config"); assertThat(filter.resourceHierarchyHasACycle(context.currentResource())).as("has a cycle should be false") .isFalse(); } @Test public void testResourceTypeHierarchiesWithCycles() throws IOException, ServletException { AEMDataLayerInterceptorFilter filter = context.getService(AEMDataLayerInterceptorFilter.class); context.currentPage("/test/pages-with-cycles/with-a-self-cycle"); assertThat(filter.resourceHierarchyHasACycle(context.currentResource())).as("has a self cycle, should be true") .isTrue(); context.currentPage("/test/pages-with-cycles/with-a-parent-child-cycle"); assertThat(filter.resourceHierarchyHasACycle(context.currentResource())) .as("has a parent/child cycle, should be true").isTrue(); context.currentPage("/test/pages-with-cycles/with-a-grandparent-child-cycle"); assertThat(filter.resourceHierarchyHasACycle(context.currentResource())) .as("has a grandparent/child cycle, should be true").isTrue(); context.currentPage("/test/pages-with-cycles/with-a-grandparent-parent-cycle"); assertThat(filter.resourceHierarchyHasACycle(context.currentResource())) .as("has a grandparent/parent cycle, should be true").isTrue(); }
KubernetesSeedNodeProvider implements SeedNodeProvider, ConfigReportSupport { @Override public List<InetSocketAddress> findSeedNodes(String cluster) throws HekateException { if (log.isDebugEnabled()) { log.debug("Searching for seed node addresses [namespace={}, container-port-name={}]", config.getNamespace(), containerPortName); } try (KubernetesClient client = new DefaultKubernetesClient(config)) { List<InetSocketAddress> seedNodes = new ArrayList<>(); PodList pods = client.pods().list(); nullSafe(pods.getItems()) .filter(pod -> pod.getSpec() != null && pod.getStatus() != null && pod.getStatus().getPodIP() != null) .filter(pod -> ACTIVE_POD_PHASES.contains(pod.getStatus().getPhase())) .forEach(pod -> { String ip = pod.getStatus().getPodIP(); nullSafe(pod.getSpec().getContainers()) .flatMap(container -> nullSafe(container.getPorts())) .filter(port -> containerPortName.equals(port.getName()) && port.getContainerPort() != null) .map(ContainerPort::getContainerPort) .forEach(port -> seedNodes.add(new InetSocketAddress(ip, port)) ); }); return seedNodes; } catch (KubernetesClientException e) { throw new HekateException("Kubernetes seed node discovery failure [" + "namespace=" + config.getNamespace() + ", " + "container-port-name=" + containerPortName + "]", e); } } KubernetesSeedNodeProvider(KubernetesSeedNodeProviderConfig cfg); @Override void report(ConfigReporter report); String containerPortName(); String masterUrl(); String namespace(); Boolean trustCertificates(); @Override List<InetSocketAddress> findSeedNodes(String cluster); @Override void startDiscovery(String cluster, InetSocketAddress node); @Override void suspendDiscovery(); @Override void stopDiscovery(String cluster, InetSocketAddress node); @Override long cleanupInterval(); @Override void registerRemote(String cluster, InetSocketAddress node); @Override void unregisterRemote(String cluster, InetSocketAddress node); @Override String toString(); }
@Test public void testSuccess() throws Exception { String portName1 = KubernetesSeedNodeProviderConfig.DEFAULT_CONTAINER_PORT_NAME; String portName2 = "some-port-name"; KubernetesSeedNodeProvider provider1 = createProvider(portName1); assertTrue(provider1.findSeedNodes(CLUSTER).isEmpty()); for (int i = 0; i < 3; i++) { createPod(portName1, "pod" + i, "127.0.0.1", 10000 + i, i > 0); } for (int i = 0; i < 3; i++) { createPod(portName2, "other-pod" + i, "127.0.0.2", 10000 + i, i > 0); } List<InetSocketAddress> seedNodes = provider1.findSeedNodes(CLUSTER); assertEquals(3, seedNodes.size()); assertTrue(seedNodes.stream().allMatch(address -> address.getHostString().equals("127.0.0.1"))); KubernetesSeedNodeProvider provider2 = createProvider(portName2); seedNodes = provider2.findSeedNodes(CLUSTER); assertEquals(3, seedNodes.size()); assertTrue(seedNodes.stream().allMatch(address -> address.getHostString().equals("127.0.0.2"))); } @Test public void testError() throws Exception { expectExactMessage(HekateException.class, "Kubernetes seed node discovery failure [namespace=test, container-port-name=hekate]", () -> new KubernetesSeedNodeProvider(new KubernetesSeedNodeProviderConfig() .withTrustCertificates(false) .withMasterUrl(server.getClient().getMasterUrl().toExternalForm()) .withNamespace(server.getClient().getNamespace()) ).findSeedNodes(CLUSTER) ); }
NettyNetworkService implements NetworkService, NetworkServiceManager, CoreService, JmxSupport<NetworkServiceJmx> { @Override public <T> NetworkConnector<T> connector(String protocol) throws IllegalArgumentException { ArgAssert.notNull(protocol, "Protocol"); return guard.withReadLockAndStateCheck(() -> { ConnectorRegistration<?> module = connectors.computeIfAbsent(protocol, missing -> { throw new IllegalArgumentException("Unknown protocol [name=" + missing + ']'); }); return module.connector(); }); } NettyNetworkService(NetworkServiceFactory factory); @Override void resolve(DependencyContext ctx); @Override void configure(ConfigurationContext ctx); @Override void report(ConfigReporter report); @Override NetworkServerFuture bind(NetworkBindCallback callback); @Override void initialize(InitializationContext ctx); @Override void postInitialize(InitializationContext ctx); @Override void terminate(); @Override void postTerminate(); @Override NetworkConnector<T> connector(String protocol); @Override boolean hasConnector(String protocol); @Override void ping(InetSocketAddress address, NetworkPingCallback callback); @Override NetworkServiceJmx jmx(); @Override String toString(); }
@Test public void testPreConfiguredConnectorAndServerHandler() throws Exception { String protocol = "pre-configured"; HekateTestNode node = createNode(boot -> boot.withService(NetworkServiceFactory.class, net -> { net.withConnector(new NetworkConnectorConfig<String>() .withProtocol(protocol) .withServerHandler((message, from) -> from.send(message.decode() + "-response") ) ); }) ).join(); NetworkConnector<String> connector = node.network().connector(protocol); NetworkClient<String> client = connector.newClient(); try { NetworkClientCallbackMock<String> callback = new NetworkClientCallbackMock<>(); client.connect(node.localNode().socket(), callback); client.send("test"); callback.awaitForMessages("test-response"); } finally { client.disconnect(); } } @Test public void testClientAfterServiceStop() throws Exception { HekateTestNode serverNode = createNode(boot -> boot.withService(NetworkServiceFactory.class, net -> { net.withConnector(new NetworkConnectorConfig<String>() .withProtocol("test") .withServerHandler((message, from) -> from.send(message.decode() + "-response") ) ); }) ).join(); HekateTestNode clientNode = createNode(boot -> boot.withService(NetworkServiceFactory.class, net -> { net.withConnector(new NetworkConnectorConfig<String>() .withProtocol("test") ); }) ).join(); NetworkClient<Object> client = clientNode.network().connector("test").newClient(); NetworkClientCallbackMock<Object> callback = new NetworkClientCallbackMock<>(); client.connect(serverNode.localNode().socket(), callback).get(); assertSame(NetworkClient.State.CONNECTED, client.state()); clientNode.leave(); assertSame(NetworkClient.State.DISCONNECTED, client.state()); try { client.connect(serverNode.localNode().socket(), callback).get(1, TimeUnit.SECONDS); fail("Error was expected."); } catch (IllegalStateException e) { assertEquals("I/O thread pool terminated.", e.getMessage()); } assertSame(NetworkClient.State.DISCONNECTED, client.state()); callback.assertConnects(1); callback.assertDisconnects(1); callback.assertErrors(0); }
AddressPatternOpts { public String exactAddress() { return exactAddress; } private AddressPatternOpts(String source, String exactAddress, IpVersion ipVersion, String netNotMatch, String netMatch, String ipNotMatch, String ipMatch); static AddressPatternOpts parse(String pattern); String exactAddress(); String interfaceNotMatch(); String interfaceMatch(); String ipNotMatch(); String ipMatch(); IpVersion ipVersion(); @Override String toString(); }
@Test public void testExactAddress() { AddressPatternOpts opts = parse("127.0.0.1"); assertEquals("127.0.0.1", opts.exactAddress()); assertNull(opts.ipVersion()); assertInterfacePattersAreNull(opts); assertIpPatternsAreNull(opts); opts = parse(" 127.0.0.1 "); assertEquals("127.0.0.1", opts.exactAddress()); assertNull(opts.ipVersion()); assertInterfacePattersAreNull(opts); assertIpPatternsAreNull(opts); }
AddressPatternOpts { @Override public String toString() { return source; } private AddressPatternOpts(String source, String exactAddress, IpVersion ipVersion, String netNotMatch, String netMatch, String ipNotMatch, String ipMatch); static AddressPatternOpts parse(String pattern); String exactAddress(); String interfaceNotMatch(); String interfaceMatch(); String ipNotMatch(); String ipMatch(); IpVersion ipVersion(); @Override String toString(); }
@Test public void testToString() { assertEquals("any-ip4", parse(null).toString()); assertEquals("any", parse("any").toString()); assertEquals("ip~.*", parse("ip~.*").toString()); }
AddressPattern implements AddressSelector { public String pattern() { return opts.toString(); } AddressPattern(); AddressPattern(String pattern); String pattern(); @Override InetAddress select(); @Override String toString(); }
@Test public void testPattern() throws Exception { assertEquals("any-ip4", createSelector(null).pattern()); assertEquals("127.0.0.1", createSelector("127.0.0.1").pattern()); }
AddressPattern implements AddressSelector { @Override public InetAddress select() throws HekateException { try { if (opts.exactAddress() != null) { if (DEBUG) { log.debug("Using the exact address [{}]", opts); } return InetAddress.getByName(opts.exactAddress()); } if (DEBUG) { log.debug("Trying to resolve address [{}]", opts); } Pattern niIncludes = regex(opts.interfaceMatch()); Pattern niExcludes = regex(opts.interfaceNotMatch()); Pattern addrIncludes = regex(opts.ipMatch()); Pattern addrExcludes = regex(opts.ipNotMatch()); List<NetworkInterface> nis = networkInterfaces(); InetAddress p2pAddr = null; String p2pNiName = null; for (NetworkInterface ni : nis) { if (!ni.isUp() || ni.isLoopback()) { continue; } String niName = ni.getName(); if (matches(true, niName, niIncludes) && matches(false, niName, niExcludes)) { Enumeration<InetAddress> addresses = ni.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (DEBUG) { log.debug("Trying address {}", address); } if (checkAddress(addrIncludes, addrExcludes, niName, address)) { if (ni.isPointToPoint()) { if (p2pAddr == null) { p2pAddr = address; p2pNiName = niName; } } else { if (DEBUG) { log.debug("Resolved address [interface={}, address={}]", niName, address); } return address; } } } } else { if (DEBUG) { log.debug("Skipped network interface that doesn't match name pattern [name={}]", niName); } } } if (DEBUG) { log.debug("Resolved Point-to-Point address [interface={}, address={}]", p2pNiName, p2pAddr); } return p2pAddr; } catch (IOException e) { throw new HekateException("Failed to resolve node address [" + opts + ']', e); } } AddressPattern(); AddressPattern(String pattern); String pattern(); @Override InetAddress select(); @Override String toString(); }
@Test public void testThrowsError() throws Exception { assertNull(createSelector("net~NO_SUCH_INTERFACE").select()); } @Test public void testNonWildcard() throws Exception { InetSocketAddress address = new InetSocketAddress("192.192.192.192", 0); assertEquals(address.getAddress(), createSelector(address.getHostName()).select()); } @Test public void testUnknownHost() throws Exception { InetSocketAddress address = new InetSocketAddress("some-unknown-host.unknown", 0); AddressPattern selector = createSelector(address.getHostName()); try { selector.select(); fail("Error was expected."); } catch (HekateException e) { assertTrue(e.isCausedBy(UnknownHostException.class)); } }
AddressPattern implements AddressSelector { @Override public String toString() { return opts.toString(); } AddressPattern(); AddressPattern(String pattern); String pattern(); @Override InetAddress select(); @Override String toString(); }
@Test public void testToString() { AddressPattern selector = new AddressPattern(); assertEquals(selector.opts().toString(), selector.toString()); }
UpdatablePartitionMapper extends PartitionMapperBase { @Override public Partition partition(int id) { return snapshot.partition(id); } UpdatablePartitionMapper(int partitions, int backupSize); void update(ClusterTopology topology, Function<Partition, Partition> update); @Override Partition partition(int id); @Override PartitionMapper snapshot(); @Override boolean isSnapshot(); @Override ClusterTopology topology(); @Override PartitionMapper copy(ClusterTopologySupport cluster); @Override String toString(); }
@Test public void testEmpty() { UpdatablePartitionMapper mapper = new UpdatablePartitionMapper(16, 2); for (int i = 0; i < mapper.partitions(); i++) { Partition part = mapper.partition(i); assertEquals(i, part.id()); assertNull(part.primaryNode()); assertTrue(part.backupNodes().isEmpty()); assertTrue(part.nodes().isEmpty()); } }
UpdatablePartitionMapper extends PartitionMapperBase { public void update(ClusterTopology topology, Function<Partition, Partition> update) { ArgAssert.notNull(topology, "Topology"); ArgAssert.notNull(update, "Update function"); Snapshot oldSnapshot = this.snapshot; Partition[] newPartitions = new Partition[partitions()]; for (int i = 0; i < newPartitions.length; i++) { Partition newPartition = update.apply(oldSnapshot.partition(i)); Objects.requireNonNull(newPartition, "Partition mapper function returned null."); newPartitions[i] = newPartition; } this.snapshot = new Snapshot(topology, newPartitions, backupNodes()); } UpdatablePartitionMapper(int partitions, int backupSize); void update(ClusterTopology topology, Function<Partition, Partition> update); @Override Partition partition(int id); @Override PartitionMapper snapshot(); @Override boolean isSnapshot(); @Override ClusterTopology topology(); @Override PartitionMapper copy(ClusterTopologySupport cluster); @Override String toString(); }
@Test public void testUpdate() throws Exception { ClusterNode n1 = newNode(); ClusterNode n2 = newNode(); ClusterNode n3 = newNode(); ClusterTopology topology = ClusterTopology.of(1, toSet(n1, n2, n3)); UpdatablePartitionMapper mapper = new UpdatablePartitionMapper(16, 2); mapper.update(topology, old -> new DefaultPartition(old.id(), n1, asList(n2, n3), topology)); assertEquals(topology, mapper.topology()); for (int i = 0; i < mapper.partitions(); i++) { Partition part = mapper.partition(i); assertEquals(i, part.id()); assertEquals(n1, part.primaryNode()); assertEquals(asList(n2, n3), part.backupNodes()); assertEquals(asList(n1, n2, n3), part.nodes()); assertEquals(topology, part.topology()); } }
AwsCredentialsSupplier extends BasicCredentialsSupplier { @Override public Credentials get() { String identity = getIdentity() != null ? getIdentity().trim() : null; String credential = getCredential() != null ? getCredential().trim() : null; if (identity == null || identity.isEmpty() || credential == null || credential.isEmpty()) { DefaultAWSCredentialsProviderChain chain = new DefaultAWSCredentialsProviderChain(); AWSCredentials cred = chain.getCredentials(); if (cred instanceof BasicSessionCredentials) { BasicSessionCredentials sesCred = (BasicSessionCredentials)cred; return new SessionCredentials.Builder() .identity(sesCred.getAWSAccessKeyId()) .credential(sesCred.getAWSSecretKey()) .sessionToken(sesCred.getSessionToken()) .build(); } else { return new Credentials.Builder<>() .identity(cred.getAWSAccessKeyId()) .credential(cred.getAWSSecretKey()) .build(); } } return super.get(); } @Override Credentials get(); }
@Test public void test() throws Exception { String oldAccessKey = null; String oldSecretKey = null; try { oldAccessKey = System.getProperty(AWS_ACCESS_KEY_ID); oldSecretKey = System.getProperty(AWS_SECRET_KEY); String fakeAccessKey = UUID.randomUUID().toString(); String fakeSecretKey = UUID.randomUUID().toString(); System.setProperty(AWS_ACCESS_KEY_ID, fakeAccessKey); System.setProperty(AWS_SECRET_KEY, fakeSecretKey); AwsCredentialsSupplier supplier = new AwsCredentialsSupplier(); assertEquals(fakeAccessKey, supplier.get().identity); assertEquals(fakeSecretKey, supplier.get().credential); supplier.withCredential("test-secret"); assertEquals(fakeAccessKey, supplier.get().identity); assertEquals(fakeSecretKey, supplier.get().credential); supplier.withIdentity("test-access"); assertEquals("test-access", supplier.get().identity); assertEquals("test-secret", supplier.get().credential); } finally { if (oldAccessKey != null) { System.setProperty(AWS_ACCESS_KEY_ID, oldAccessKey); } if (oldSecretKey != null) { System.setProperty(AWS_SECRET_KEY, oldSecretKey); } } }
MessagingServiceFactory implements ServiceFactory<MessagingService> { @Override public String toString() { return ToString.format(this); } List<MessagingChannelConfig<?>> getChannels(); void setChannels(List<MessagingChannelConfig<?>> channels); MessagingServiceFactory withChannel(MessagingChannelConfig<?> channel); List<MessagingConfigProvider> getConfigProviders(); void setConfigProviders(List<MessagingConfigProvider> configProviders); MessagingServiceFactory withConfigProvider(MessagingConfigProvider configProvider); List<MessageInterceptor> getGlobalInterceptors(); void setGlobalInterceptors(List<MessageInterceptor> globalInterceptors); MessagingServiceFactory withGlobalInterceptor(MessageInterceptor globalInterceptor); @Override MessagingService createService(); @Override String toString(); }
@Test public void testToString() { assertTrue(cfg.toString(), cfg.toString().startsWith(MessagingServiceFactory.class.getSimpleName())); }
MessagingChannelConfig extends MessagingConfigBase<MessagingChannelConfig<T>> { public boolean hasReceiver() { return receiver != null; } @Deprecated MessagingChannelConfig(); MessagingChannelConfig(Class<T> baseType); static MessagingChannelConfig<T> of(Class<T> baseType); static MessagingChannelConfig<Object> unchecked(); Class<T> getBaseType(); String getName(); void setName(String name); MessagingChannelConfig<T> withName(String name); int getPartitions(); void setPartitions(int partitions); MessagingChannelConfig<T> withPartitions(int partitions); int getBackupNodes(); void setBackupNodes(int backupNodes); MessagingChannelConfig<T> withBackupNodes(int backupNodes); CodecFactory<T> getMessageCodec(); void setMessageCodec(CodecFactory<T> messageCodec); MessagingChannelConfig<T> withMessageCodec(CodecFactory<T> codecFactory); int getWorkerThreads(); void setWorkerThreads(int workerThreads); MessagingChannelConfig<T> withWorkerThreads(int workerThreads); MessageReceiver<T> getReceiver(); void setReceiver(MessageReceiver<T> receiver); boolean hasReceiver(); MessagingChannelConfig<T> withReceiver(MessageReceiver<T> messageReceiver); ClusterNodeFilter getClusterFilter(); void setClusterFilter(ClusterNodeFilter clusterFilter); MessagingChannelConfig<T> withClusterFilter(ClusterNodeFilter clusterFilter); GenericRetryConfigurer getRetryPolicy(); void setRetryPolicy(GenericRetryConfigurer retryPolicy); MessagingChannelConfig<T> withRetryPolicy(GenericRetryConfigurer retryPolicy); LoadBalancer<T> getLoadBalancer(); void setLoadBalancer(LoadBalancer<T> loadBalancer); MessagingChannelConfig<T> withLoadBalancer(LoadBalancer<T> loadBalancer); List<MessageInterceptor> getInterceptors(); void setInterceptors(List<MessageInterceptor> interceptors); MessagingChannelConfig<T> withInterceptor(MessageInterceptor interceptor); long getMessagingTimeout(); void setMessagingTimeout(long messagingTimeout); MessagingChannelConfig<T> withMessagingTimeout(long messagingTimeout); String getLogCategory(); void setLogCategory(String logCategory); MessagingChannelConfig<T> withLogCategory(String logCategory); int getWarnOnRetry(); void setWarnOnRetry(int warnOnRetry); MessagingChannelConfig<T> withWarnOnRetry(int warnOnRetry); @Override String toString(); }
@Test public void testHasReceiver() { assertFalse(cfg.hasReceiver()); cfg.setReceiver(msg -> { }); assertTrue(cfg.hasReceiver()); cfg.setReceiver(null); assertFalse(cfg.hasReceiver()); }
MessagingChannelConfig extends MessagingConfigBase<MessagingChannelConfig<T>> { @Override public String toString() { return ToString.format(this); } @Deprecated MessagingChannelConfig(); MessagingChannelConfig(Class<T> baseType); static MessagingChannelConfig<T> of(Class<T> baseType); static MessagingChannelConfig<Object> unchecked(); Class<T> getBaseType(); String getName(); void setName(String name); MessagingChannelConfig<T> withName(String name); int getPartitions(); void setPartitions(int partitions); MessagingChannelConfig<T> withPartitions(int partitions); int getBackupNodes(); void setBackupNodes(int backupNodes); MessagingChannelConfig<T> withBackupNodes(int backupNodes); CodecFactory<T> getMessageCodec(); void setMessageCodec(CodecFactory<T> messageCodec); MessagingChannelConfig<T> withMessageCodec(CodecFactory<T> codecFactory); int getWorkerThreads(); void setWorkerThreads(int workerThreads); MessagingChannelConfig<T> withWorkerThreads(int workerThreads); MessageReceiver<T> getReceiver(); void setReceiver(MessageReceiver<T> receiver); boolean hasReceiver(); MessagingChannelConfig<T> withReceiver(MessageReceiver<T> messageReceiver); ClusterNodeFilter getClusterFilter(); void setClusterFilter(ClusterNodeFilter clusterFilter); MessagingChannelConfig<T> withClusterFilter(ClusterNodeFilter clusterFilter); GenericRetryConfigurer getRetryPolicy(); void setRetryPolicy(GenericRetryConfigurer retryPolicy); MessagingChannelConfig<T> withRetryPolicy(GenericRetryConfigurer retryPolicy); LoadBalancer<T> getLoadBalancer(); void setLoadBalancer(LoadBalancer<T> loadBalancer); MessagingChannelConfig<T> withLoadBalancer(LoadBalancer<T> loadBalancer); List<MessageInterceptor> getInterceptors(); void setInterceptors(List<MessageInterceptor> interceptors); MessagingChannelConfig<T> withInterceptor(MessageInterceptor interceptor); long getMessagingTimeout(); void setMessagingTimeout(long messagingTimeout); MessagingChannelConfig<T> withMessagingTimeout(long messagingTimeout); String getLogCategory(); void setLogCategory(String logCategory); MessagingChannelConfig<T> withLogCategory(String logCategory); int getWarnOnRetry(); void setWarnOnRetry(int warnOnRetry); MessagingChannelConfig<T> withWarnOnRetry(int warnOnRetry); @Override String toString(); }
@Test public void testToString() { assertTrue(cfg.toString(), cfg.toString().startsWith(MessagingChannelConfig.class.getSimpleName())); }
MessageMetaData { @Override public String toString() { return MessageMetaData.class.getSimpleName() + "[size=" + size() + ']'; } MessageMetaData(); private MessageMetaData(int size, byte[][] keyAndValue); static MessageMetaData readFrom(DataReader in); void writeTo(DataWriter out); T get(Key<T> key); void set(Key<T> key, T value); int size(); boolean isEmpty(); @Override String toString(); }
@Test public void testKey() { Key<byte[]> key = Key.of("test", MessageMetaData.MetaDataCodec.BYTES); assertEquals("test", key.name()); assertEquals("test", key.toString()); }
LoadBalancers { @SuppressWarnings("unchecked") public static <T> LoadBalancer<T> random() { return (LoadBalancer<T>)RANDOM; } private LoadBalancers(); @SuppressWarnings("unchecked") static LoadBalancer<T> random(); @SuppressWarnings("unchecked") static LoadBalancer<T> newRoundRobin(); }
@Test public void testRandom() throws Exception { LoadBalancer<Object> lb = LoadBalancers.random(); ClusterNodeId nodeId = lb.route("msg", ctx); assertNotNull(nodeId); assertTrue(ctx.contains(nodeId)); assertEquals("Random", lb.toString()); }
LoadBalancers { @SuppressWarnings("unchecked") public static <T> LoadBalancer<T> newRoundRobin() { return (LoadBalancer<T>)new RoundRobin<>(); } private LoadBalancers(); @SuppressWarnings("unchecked") static LoadBalancer<T> random(); @SuppressWarnings("unchecked") static LoadBalancer<T> newRoundRobin(); }
@Test public void testRoundRobin() throws Exception { LoadBalancer<Object> lb = LoadBalancers.newRoundRobin(); int idx = 0; for (int i = 0; i < 100; i++) { ClusterNodeId nodeId = lb.route("msg", ctx); assertNotNull(nodeId); assertTrue(ctx.contains(nodeId)); assertEquals(ctx.nodes().get(idx).id(), nodeId); if (idx == ctx.size() - 1) { idx = 0; } else { idx++; } } assertEquals("RoundRobin", lb.toString()); assertNotSame(lb, LoadBalancers.newRoundRobin()); assertNotSame(lb, LoadBalancers.newRoundRobin()); assertNotSame(lb, LoadBalancers.newRoundRobin()); runParallel(4, 1000, i -> assertNotNull(lb.route(i, ctx)) ); }
ExponentialBackoffPolicy implements RetryBackoffPolicy { @Override public long delayBeforeRetry(int attempt) { if (attempt == 0) { return 0; } else if (attempt >= attemptOverflow) { return maxDelay; } else { int calcAttempt = attempt - 1; return (long)Math.min(Math.pow(2, calcAttempt) * baseDelay, maxDelay); } } ExponentialBackoffPolicy(); ExponentialBackoffPolicy(long baseDelay, long maxDelay); long baseDelay(); long maxDelay(); @Override long delayBeforeRetry(int attempt); @Override String toString(); static final long DEFAULT_BASE_DELAY; static final long DEFAULT_MAX_DELAY; }
@Test public void testCustom() throws Exception { RetryBackoffPolicy policy = new ExponentialBackoffPolicy(50, 3000); assertEquals(0, policy.delayBeforeRetry(0)); assertEquals(50, policy.delayBeforeRetry(1)); assertEquals(100, policy.delayBeforeRetry(2)); assertEquals(200, policy.delayBeforeRetry(3)); assertEquals(400, policy.delayBeforeRetry(4)); assertEquals(800, policy.delayBeforeRetry(5)); assertEquals(1600, policy.delayBeforeRetry(6)); assertEquals(3000, policy.delayBeforeRetry(7)); assertEquals(3000, policy.delayBeforeRetry(8)); assertEquals(3000, policy.delayBeforeRetry(Integer.MAX_VALUE)); } @Test public void testDefault() throws Exception { RetryBackoffPolicy policy = new ExponentialBackoffPolicy(); assertEquals(0, policy.delayBeforeRetry(0)); assertEquals(50, policy.delayBeforeRetry(1)); assertEquals(100, policy.delayBeforeRetry(2)); assertEquals(200, policy.delayBeforeRetry(3)); assertEquals(400, policy.delayBeforeRetry(4)); assertEquals(800, policy.delayBeforeRetry(5)); assertEquals(1600, policy.delayBeforeRetry(6)); assertEquals(3000, policy.delayBeforeRetry(7)); assertEquals(3000, policy.delayBeforeRetry(8)); assertEquals(3000, policy.delayBeforeRetry(Integer.MAX_VALUE)); }
ReceivePressureGuard implements ConfigReportSupport { @Override public String toString() { return ToString.format(this); } ReceivePressureGuard(int loMark, int hiMark); @Override void report(ConfigReporter report); int loMark(); int hiMark(); void onEnqueue(NetworkEndpoint<?> endpoint); void onDequeue(); int queueSize(); int pausedSize(); @Override String toString(); }
@Test public void testToString() { ReceivePressureGuard backPressure = new ReceivePressureGuard(0, 1); assertTrue(backPressure.toString(), backPressure.toString().startsWith(ReceivePressureGuard.class.getSimpleName())); }
SendPressureGuard implements ConfigReportSupport { private long block(long timeout, Object msg) throws InterruptedException, MessageQueueTimeoutException { assert lock.isHeldByCurrentThread() : "Thread must hold lock."; blockedSize.incrementAndGet(); try { long deadline = timeout > 0 ? TimeUnit.MILLISECONDS.toNanos(timeout) : Long.MAX_VALUE; while (deadline > 0 && !stopped && queueSize.get() - blockedSize.get() > loMark) { deadline = block.awaitNanos(deadline); } if (timeout > 0) { return checkDeadline(TimeUnit.NANOSECONDS.toMillis(deadline), msg); } else { return timeout; } } finally { blockedSize.decrementAndGet(); } } SendPressureGuard(int loMark, int hiMark, MessagingOverflowPolicy policy); @Override void report(ConfigReporter report); int loMark(); int hiMark(); MessagingOverflowPolicy policy(); void onEnqueueIgnorePolicy(); void onEnqueue(); long onEnqueue(long timeout, Object msg); void onDequeue(); void terminate(); int queueSize(); @Override String toString(); }
@Test public void testBlock() throws Exception { SendPressureGuard backPressure = new SendPressureGuard(5, 10, MessagingOverflowPolicy.BLOCK); repeat(3, i -> { for (int j = 0; j < 10; j++) { backPressure.onEnqueue(); assertEquals(j + 1, backPressure.queueSize()); } assertEquals(10, backPressure.queueSize()); Future<?> future = runAsync(() -> { backPressure.onEnqueue(); return null; }); busyWait("tread blocked", () -> backPressure.queueSize() == 11); assertFalse(future.isDone()); for (int j = 0; j < 6; j++) { backPressure.onDequeue(); } get(future); assertEquals(5, backPressure.queueSize()); while (backPressure.queueSize() > 0) { backPressure.onDequeue(); } }); }
RpcServerConfig { @Override public String toString() { return ToString.format(this); } Object getHandler(); void setHandler(Object handler); RpcServerConfig withHandler(Object handler); Set<String> getTags(); void setTags(Set<String> tags); RpcServerConfig withTag(String tag); @Override String toString(); }
@Test public void testToString() { assertEquals(ToString.format(cfg), cfg.toString()); }
SendPressureGuard implements ConfigReportSupport { private long blockUninterruptedly(long timeout, Object msg) throws MessageQueueTimeoutException { assert lock.isHeldByCurrentThread() : "Thread must hold lock."; blockedSize.incrementAndGet(); try { boolean interrupted = false; long deadline = timeout > 0 ? TimeUnit.MILLISECONDS.toNanos(timeout) : Long.MAX_VALUE; while (deadline > 0 && !stopped && queueSize.get() - blockedSize.get() > loMark) { try { deadline = block.awaitNanos(deadline); } catch (InterruptedException err) { interrupted = true; } } if (interrupted) { Thread.currentThread().interrupt(); } if (timeout > 0) { return checkDeadline(TimeUnit.NANOSECONDS.toMillis(deadline), msg); } else { return timeout; } } finally { blockedSize.decrementAndGet(); } } SendPressureGuard(int loMark, int hiMark, MessagingOverflowPolicy policy); @Override void report(ConfigReporter report); int loMark(); int hiMark(); MessagingOverflowPolicy policy(); void onEnqueueIgnorePolicy(); void onEnqueue(); long onEnqueue(long timeout, Object msg); void onDequeue(); void terminate(); int queueSize(); @Override String toString(); }
@Test public void testBlockUninterruptedly() throws Exception { SendPressureGuard backPressure = new SendPressureGuard(5, 10, MessagingOverflowPolicy.BLOCK_UNINTERRUPTEDLY); repeat(3, i -> { for (int j = 0; j < 10; j++) { backPressure.onEnqueue(); assertEquals(j + 1, backPressure.queueSize()); } assertEquals(10, backPressure.queueSize()); Future<?> future = runAsync(() -> { Thread.currentThread().interrupt(); backPressure.onEnqueue(); return null; }); busyWait("tread blocked", () -> backPressure.queueSize() == 11); assertFalse(future.isDone()); for (int j = 0; j < 6; j++) { backPressure.onDequeue(); } get(future); assertEquals(5, backPressure.queueSize()); while (backPressure.queueSize() > 0) { backPressure.onDequeue(); } }); }
SendPressureGuard implements ConfigReportSupport { @Override public String toString() { return ToString.format(this); } SendPressureGuard(int loMark, int hiMark, MessagingOverflowPolicy policy); @Override void report(ConfigReporter report); int loMark(); int hiMark(); MessagingOverflowPolicy policy(); void onEnqueueIgnorePolicy(); void onEnqueue(); long onEnqueue(long timeout, Object msg); void onDequeue(); void terminate(); int queueSize(); @Override String toString(); }
@Test public void testToString() { SendPressureGuard backPressure = new SendPressureGuard(0, 1, MessagingOverflowPolicy.FAIL); assertTrue(backPressure.toString(), backPressure.toString().startsWith(SendPressureGuard.class.getSimpleName())); }
BroadcastContext implements BroadcastResult<T> { @Override public String toString() { return ToString.format(BroadcastResult.class, this); } BroadcastContext(T message, List<ClusterNode> nodes, BroadcastFuture<T> future); @Override T message(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); boolean forgetNode(ClusterNode node); BroadcastFuture<T> future(); @Override String toString(); }
@Test public void testToString() { BroadcastContext<String> ctx = ctx(allNodes()); assertEquals(ToString.format(BroadcastResult.class, ctx), ctx.toString()); }
BroadcastContext implements BroadcastResult<T> { @Override public T message() { return message; } BroadcastContext(T message, List<ClusterNode> nodes, BroadcastFuture<T> future); @Override T message(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); boolean forgetNode(ClusterNode node); BroadcastFuture<T> future(); @Override String toString(); }
@Test public void testMessage() { BroadcastContext<String> ctx = ctx(allNodes()); assertEquals(TEST_MESSAGE, ctx.message()); }
BroadcastContext implements BroadcastResult<T> { @Override public List<ClusterNode> nodes() { synchronized (this) { return nodes; } } BroadcastContext(T message, List<ClusterNode> nodes, BroadcastFuture<T> future); @Override T message(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); boolean forgetNode(ClusterNode node); BroadcastFuture<T> future(); @Override String toString(); }
@Test public void testNodes() { assertEquals(allNodes(), ctx(allNodes()).nodes()); assertEquals(singletonList(n1), ctx(singletonList(n1)).nodes()); BroadcastContext<String> ctx = ctx(allNodes()); assertFalse(ctx.forgetNode(n1)); assertEquals(asList(n2, n3), ctx.nodes()); assertFalse(ctx.forgetNode(n2)); assertEquals(singletonList(n3), ctx.nodes()); assertTrue(ctx.forgetNode(n3)); assertTrue(ctx.nodes().isEmpty()); }
BroadcastContext implements BroadcastResult<T> { boolean onSendSuccess() { synchronized (this) { remaining--; return remaining == 0; } } BroadcastContext(T message, List<ClusterNode> nodes, BroadcastFuture<T> future); @Override T message(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); boolean forgetNode(ClusterNode node); BroadcastFuture<T> future(); @Override String toString(); }
@Test public void testOnSendSuccess() { BroadcastContext<String> ctx = ctx(allNodes()); assertFalse(ctx.onSendSuccess()); assertFalse(ctx.onSendSuccess()); assertTrue(ctx.onSendSuccess()); assertTrue(ctx.isSuccess()); allNodes().forEach(n -> assertTrue(ctx.isSuccess(n)) ); assertTrue(ctx.errors().isEmpty()); }
BroadcastContext implements BroadcastResult<T> { boolean onSendFailure(ClusterNode node, Throwable error) { synchronized (this) { if (errors == null) { errors = new HashMap<>(remaining, 1.0f); } errors.put(node, error); remaining--; return remaining == 0; } } BroadcastContext(T message, List<ClusterNode> nodes, BroadcastFuture<T> future); @Override T message(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); boolean forgetNode(ClusterNode node); BroadcastFuture<T> future(); @Override String toString(); }
@Test public void testOnSendFailure() { BroadcastContext<String> ctx = ctx(allNodes()); Exception err1 = new Exception(); Exception err2 = new Exception(); Exception err3 = new Exception(); assertFalse(ctx.onSendFailure(n1, err1)); assertFalse(ctx.onSendFailure(n2, err2)); assertTrue(ctx.onSendFailure(n3, err3)); assertEquals(new HashSet<>(allNodes()), ctx.errors().keySet()); assertSame(err1, ctx.errorOf(n1)); assertSame(err2, ctx.errorOf(n2)); assertSame(err3, ctx.errorOf(n3)); assertFalse(ctx.isSuccess()); assertFalse(ctx.isSuccess(n1)); assertFalse(ctx.isSuccess(n2)); assertFalse(ctx.isSuccess(n3)); }
BroadcastContext implements BroadcastResult<T> { void complete() { future.complete(this); } BroadcastContext(T message, List<ClusterNode> nodes, BroadcastFuture<T> future); @Override T message(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); boolean forgetNode(ClusterNode node); BroadcastFuture<T> future(); @Override String toString(); }
@Test public void testComplete() { BroadcastContext<String> ctx = ctx(allNodes()); ctx.complete(); assertTrue(ctx.isSuccess()); assertFalse(ctx.nodes().isEmpty()); assertTrue(ctx.errors().isEmpty()); BroadcastContext<String> errCtx = ctx(allNodes()); errCtx.future().whenComplete((stringBroadcastResult, throwable) -> { throw TEST_ERROR; }); errCtx.complete(); }
AggregateContext implements AggregateResult<T> { @Override public String toString() { return ToString.format(AggregateResult.class, this); } AggregateContext(T request, List<ClusterNode> nodes, AggregateFuture<T> future); @Override T request(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); @Override Map<ClusterNode, T> resultsByNode(); @Override String toString(); }
@Test public void testToString() { AggregateContext<String> ctx = ctx(allNodes()); assertEquals(ToString.format(AggregateResult.class, ctx), ctx.toString()); }
AggregateContext implements AggregateResult<T> { @Override public T request() { return request; } AggregateContext(T request, List<ClusterNode> nodes, AggregateFuture<T> future); @Override T request(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); @Override Map<ClusterNode, T> resultsByNode(); @Override String toString(); }
@Test public void testRequest() { AggregateContext<String> ctx = ctx(allNodes()); assertEquals(TEST_REQUEST, ctx.request()); }
RpcClientConfig { @Override public String toString() { return ToString.format(this); } Class<?> getRpcInterface(); void setRpcInterface(Class<?> rpcInterface); RpcClientConfig withRpcInterface(Class<?> rpcInterface); String getTag(); void setTag(String tag); RpcClientConfig withTag(String tag); RpcLoadBalancer getLoadBalancer(); void setLoadBalancer(RpcLoadBalancer loadBalancer); RpcClientConfig withLoadBalancer(RpcLoadBalancer loadBalancer); int getPartitions(); void setPartitions(int partitions); RpcClientConfig withPartitions(int partitions); int getBackupNodes(); void setBackupNodes(int backupNodes); RpcClientConfig withBackupNodes(int backupNodes); long getTimeout(); void setTimeout(long timeout); RpcClientConfig withTimeout(long timeout); GenericRetryConfigurer getRetryPolicy(); void setRetryPolicy(GenericRetryConfigurer retryPolicy); RpcClientConfig withRetryPolicy(GenericRetryConfigurer retryPolicy); @Override String toString(); }
@Test public void testToString() { assertEquals(ToString.format(cfg), cfg.toString()); }
AggregateContext implements AggregateResult<T> { @Override public List<ClusterNode> nodes() { synchronized (this) { return nodes; } } AggregateContext(T request, List<ClusterNode> nodes, AggregateFuture<T> future); @Override T request(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); @Override Map<ClusterNode, T> resultsByNode(); @Override String toString(); }
@Test public void testNodes() { assertEquals(allNodes(), ctx(allNodes()).nodes()); assertEquals(singletonList(n1), ctx(singletonList(n1)).nodes()); AggregateContext<String> ctx = ctx(allNodes()); assertFalse(ctx.forgetNode(n1)); assertEquals(asList(n2, n3), ctx.nodes()); assertFalse(ctx.forgetNode(n2)); assertEquals(singletonList(n3), ctx.nodes()); assertTrue(ctx.forgetNode(n3)); assertTrue(ctx.nodes().isEmpty()); }
AggregateContext implements AggregateResult<T> { boolean onReplySuccess(ClusterNode node, Response<T> rsp) { synchronized (this) { results.put(node, rsp.payload()); return isReady(); } } AggregateContext(T request, List<ClusterNode> nodes, AggregateFuture<T> future); @Override T request(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); @Override Map<ClusterNode, T> resultsByNode(); @Override String toString(); }
@Test public void testOnReplySuccess() { AggregateContext<String> ctx = ctx(allNodes()); assertFalse(ctx.onReplySuccess(n1, responseMock("r1"))); assertFalse(ctx.onReplySuccess(n2, responseMock("r2"))); assertTrue(ctx.onReplySuccess(n3, responseMock("r3"))); assertTrue(ctx.isSuccess()); assertTrue(ctx.isSuccess(n1)); assertTrue(ctx.isSuccess(n2)); assertTrue(ctx.isSuccess(n3)); assertTrue(ctx.errors().isEmpty()); assertEquals("r1", ctx.resultOf(n1)); assertEquals("r2", ctx.resultOf(n2)); assertEquals("r3", ctx.resultOf(n3)); Set<String> results = new HashSet<>(asList("r1", "r2", "r3")); for (String r : ctx) { assertTrue(results.contains(r)); } ctx.stream().forEach(r -> assertTrue(results.contains(r)) ); assertEquals(results, new HashSet<>(ctx.results())); }
AggregateContext implements AggregateResult<T> { boolean onReplyFailure(ClusterNode node, Throwable error) { synchronized (this) { if (errors == null) { errors = new HashMap<>(nodes.size(), 1.0f); } errors.put(node, error); return isReady(); } } AggregateContext(T request, List<ClusterNode> nodes, AggregateFuture<T> future); @Override T request(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); @Override Map<ClusterNode, T> resultsByNode(); @Override String toString(); }
@Test public void testOnReplyFailure() { AggregateContext<String> ctx = ctx(allNodes()); Exception err1 = new Exception(); Exception err2 = new Exception(); Exception err3 = new Exception(); assertFalse(ctx.onReplyFailure(n1, err1)); assertFalse(ctx.onReplyFailure(n2, err2)); assertTrue(ctx.onReplyFailure(n3, err3)); assertEquals(new HashSet<>(allNodes()), ctx.errors().keySet()); assertSame(err1, ctx.errorOf(n1)); assertSame(err2, ctx.errorOf(n2)); assertSame(err3, ctx.errorOf(n3)); assertFalse(ctx.isSuccess()); assertFalse(ctx.isSuccess(n1)); assertFalse(ctx.isSuccess(n2)); assertFalse(ctx.isSuccess(n3)); }
AggregateContext implements AggregateResult<T> { void complete() { future.complete(this); } AggregateContext(T request, List<ClusterNode> nodes, AggregateFuture<T> future); @Override T request(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); @Override Map<ClusterNode, T> resultsByNode(); @Override String toString(); }
@Test public void testComplete() throws Exception { AggregateContext<String> ctx = ctx(allNodes()); ctx.complete(); assertTrue(ctx.future().get().isSuccess()); assertFalse(ctx.future().get().nodes().isEmpty()); assertTrue(ctx.future().get().errors().isEmpty()); AggregateContext<String> errCtx = ctx(allNodes()); errCtx.future().whenComplete((rslt, err) -> { throw TEST_ERROR; }); errCtx.complete(); }
DefaultLoadBalancerContext implements LoadBalancerContext { @Override public Optional<FailedAttempt> failure() { return failure; } DefaultLoadBalancerContext( int affinity, Object affinityKey, ClusterTopology topology, PartitionMapper partitions, Optional<FailedAttempt> failure, TopologyContextCache topologyCtx ); @Override ClusterTopology topology(); @Override PartitionMapper partitions(); @Override boolean hasAffinity(); @Override int affinity(); @Override Object affinityKey(); @Override Optional<FailedAttempt> failure(); @Override T topologyContext(Function<ClusterTopology, T> supplier); @Override long version(); @Override ClusterHash hash(); @Override ClusterNode localNode(); @Override List<ClusterNode> nodes(); @Override ClusterNode first(); @Override ClusterNode last(); @Override Set<ClusterNode> nodeSet(); @Override List<ClusterNode> remoteNodes(); @Override NavigableSet<ClusterNode> joinOrder(); @Override Stream<ClusterNode> stream(); @Override boolean contains(ClusterNode node); @Override boolean contains(ClusterNodeId node); @Override ClusterNode get(ClusterNodeId id); @Override int size(); @Override boolean isEmpty(); @Override ClusterNode oldest(); @Override ClusterNode youngest(); @Override ClusterNode random(); @Override ClusterTopology filterAll(ClusterFilter filter); @Override ClusterTopology filter(ClusterNodeFilter filter); @Override Iterator<ClusterNode> iterator(); @Override String toString(); }
@Test public void testFailure() throws Exception { FailedAttempt details = mock(FailedAttempt.class); ClusterNode n1 = newNode(); LoadBalancerContext ctx = newContext(100, "test", 1, toSet(n1, newNode()), details); assertNotNull(ctx.failure()); assertEquals(100, ctx.affinity()); assertEquals("test", ctx.affinityKey()); assertTrue(ctx.hasAffinity()); assertSame(details, ctx.failure().get()); }
MessagingBackPressureConfig { @Override public String toString() { return ToString.format(this); } MessagingBackPressureConfig(); MessagingBackPressureConfig(MessagingBackPressureConfig src); int getInLowWatermark(); void setInLowWatermark(int inLowWatermark); MessagingBackPressureConfig withInLowWatermark(int inLowWatermark); int getInHighWatermark(); void setInHighWatermark(int inHighWatermark); MessagingBackPressureConfig withInHighWatermark(int inHighWatermark); int getOutLowWatermark(); void setOutLowWatermark(int outLowWatermark); MessagingBackPressureConfig withOutLowWatermark(int outLowWatermark); int getOutHighWatermark(); void setOutHighWatermark(int outHighWatermark); MessagingBackPressureConfig withOutHighWatermark(int outHighWatermark); MessagingOverflowPolicy getOutOverflowPolicy(); void setOutOverflowPolicy(MessagingOverflowPolicy outOverflowPolicy); MessagingBackPressureConfig withOutOverflowPolicy(MessagingOverflowPolicy outOverflow); @Override String toString(); }
@Test public void testToString() { assertTrue(cfg.toString(), cfg.toString().startsWith(MessagingBackPressureConfig.class.getSimpleName())); }
JmxUtils { public static ObjectName jmxName(String domain, Class<?> type) throws MalformedObjectNameException { return jmxName(domain, type, null); } private JmxUtils(); static ObjectName jmxName(String domain, Class<?> type); static ObjectName jmxName(String domain, Class<?> type, String name); }
@Test public void testClusterAndNodeName() throws Exception { ObjectName name = new ObjectName("foo.bar", "type", getClass().getSimpleName()); assertEquals(name, JmxUtils.jmxName("foo.bar", getClass())); } @Test public void testClusterNameOnly() throws Exception { ObjectName name = new ObjectName("foo.bar", "type", getClass().getSimpleName()); assertEquals(name, JmxUtils.jmxName("foo.bar", getClass())); } @Test public void testNameAttribute() throws Exception { Hashtable<String, String> attrs = new Hashtable<>(); attrs.put("name", "test-name"); attrs.put("type", getClass().getSimpleName()); ObjectName name = new ObjectName("foo.bar", attrs); assertEquals(name, JmxUtils.jmxName("foo.bar", getClass(), "test-name")); }
JmxServiceFactory implements ServiceFactory<JmxService> { @Override public String toString() { return ToString.format(this); } @Override JmxService createService(); String getDomain(); void setDomain(String domain); JmxServiceFactory withDomain(String domain); MBeanServer getServer(); void setServer(MBeanServer server); JmxServiceFactory withServer(MBeanServer server); @Override String toString(); static final String DEFAULT_DOMAIN; }
@Test public void testToString() { assertEquals(ToString.format(factory), factory.toString()); }
RpcTypeAnalyzer { public List<RpcInterface<?>> analyze(Object target) { Class<?> type = target.getClass(); List<RpcInterfaceInfo<?>> rpcInterfaces = cached(type); return rpcInterfaces.stream() .map(info -> new RpcInterface<>(info, target)) .collect(Collectors.toList()); } RpcTypeAnalyzer(PlaceholderResolver resolver); RpcInterfaceInfo<T> analyzeType(Class<T> type); List<RpcInterface<?>> analyze(Object target); }
@Test public void testAnalyzeWithoutRpcAnnotation() { assertTrue(analyzer.analyze(mock(NotAnRpc.class)).isEmpty()); } @Test public void testAnalyzeNonPublic() { assertTrue(analyzer.analyze(mock(NonPublic.class)).isEmpty()); } @Test public void testAnalyzeA() throws Exception { List<RpcInterface<?>> rpcs = analyzer.analyze(mock(TypeA.class)); assertEquals(1, rpcs.size()); @SuppressWarnings("unchecked") RpcInterface<TypeA> rpc = (RpcInterface<TypeA>)rpcs.get(0); verifyRpcA(rpc); } @Test public void testAnalyzeB() throws Exception { List<RpcInterface<?>> rpcs = analyzer.analyze(mock(TypeB.class)); assertEquals(1, rpcs.size()); @SuppressWarnings("unchecked") RpcInterface<TypeB> rpc = (RpcInterface<TypeB>)rpcs.get(0); verifyRpcB(rpc); } @Test public void testAnalyzeC() throws Exception { List<RpcInterface<?>> rpcs = analyzer.analyze(mock(TypeC.class)); assertEquals(3, rpcs.size()); @SuppressWarnings("unchecked") RpcInterface<TypeA> rpcA = (RpcInterface<TypeA>)rpcs.stream() .filter(f -> f.type().javaType() == TypeA.class) .findFirst() .orElseThrow(AssertionError::new); @SuppressWarnings("unchecked") RpcInterface<TypeB> rpcB = (RpcInterface<TypeB>)rpcs.stream() .filter(f -> f.type().javaType() == TypeB.class) .findFirst() .orElseThrow(AssertionError::new); @SuppressWarnings("unchecked") RpcInterface<TypeC> rpcC = (RpcInterface<TypeC>)rpcs.stream() .filter(f -> f.type().javaType() == TypeC.class) .findFirst() .orElseThrow(AssertionError::new); verifyRpcA(rpcA); verifyRpcB(rpcB); RpcInterfaceInfo<TypeC> typeC = rpcC.type(); assertSame(TypeC.class, typeC.javaType()); assertEquals(2, typeC.version()); assertEquals(1, typeC.minClientVersion()); assertEquals(TypeC.class.getName(), typeC.name()); assertEquals(TypeC.class.getName() + ":2", typeC.versionedName()); assertEquals(5, typeC.methods().size()); assertTrue(typeC.methods().stream().anyMatch(m -> m.javaMethod().getName().equals("methA1"))); assertTrue(typeC.methods().stream().anyMatch(m -> m.javaMethod().getName().equals("methB1"))); assertTrue(typeC.methods().stream().anyMatch(m -> m.javaMethod().getName().equals("methB2"))); assertTrue(typeC.methods().stream().anyMatch(m -> m.javaMethod().getName().equals("methC1"))); assertTrue(typeC.methods().stream().anyMatch(m -> m.javaMethod().getName().equals("methC2"))); }
ResourceServiceFactory implements ServiceFactory<ResourceService> { @Override public ResourceService createService() { return new DefaultResourceService(); } @Override ResourceService createService(); @Override String toString(); }
@Test public void testCreate() { assertNotNull(factory.createService()); }
ResourceServiceFactory implements ServiceFactory<ResourceService> { @Override public String toString() { return ToString.format(this); } @Override ResourceService createService(); @Override String toString(); }
@Test public void testToString() { assertEquals(ToString.format(factory), factory.toString()); }
DefaultResourceService implements ResourceService { @Override public InputStream load(String path) throws ResourceLoadingException { ArgAssert.notNull(path, "Resource path"); ArgAssert.isFalse(path.isEmpty(), "Resource path is empty."); try { URL url = new URL(path); try (InputStream in = url.openStream()) { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[4 * 1024]; for (int read = in.read(buf); read > 0; read = in.read(buf)) { out.write(buf, 0, read); } return new ByteArrayInputStream(out.toByteArray()); } } catch (IOException e) { throw new ResourceLoadingException("Failed to load resource [path=" + path + ']', e); } } @Override InputStream load(String path); @Override String toString(); }
@Test public void testSuccess() throws Exception { File[] files = new File("./").listFiles(); assertNotNull(files); int checked = 0; for (File file : files) { if (file.isFile()) { String path = "file: say("Testing path: " + path); try (InputStream stream = service.load(path)) { assertNotNull(stream); assertEquals(file.length(), stream.available()); checked++; } } } assertTrue(checked > 0); } @Test(expected = IllegalArgumentException.class) public void testNullPath() throws Exception { service.load(null); } @Test(expected = IllegalArgumentException.class) public void testEmptyPath() throws Exception { service.load(""); } @Test(expected = ResourceLoadingException.class) public void testInvalidUrl() throws Exception { service.load("invalid-url"); } @Test(expected = ResourceLoadingException.class) public void testInvalidPath() throws Exception { service.load("file: }
DefaultResourceService implements ResourceService { @Override public String toString() { return getClass().getSimpleName(); } @Override InputStream load(String path); @Override String toString(); }
@Test public void testToString() { assertEquals(DefaultResourceService.class.getSimpleName(), service.toString()); }
Murmur3 { public static int hash(int n1, int n2) { int k1 = mixK1(n1); int h1 = mixH1(0, k1); k1 = mixK1(n2); h1 = mixH1(h1, k1); return mix(h1, Integer.BYTES); } private Murmur3(); static int hash(int n1, int n2); }
@Test public void test() throws Exception { assertValidUtilityClass(Murmur3.class); Set<Integer> hashes = new HashSet<>(10000, 1.0f); for (int i = 0; i < 10000; i++) { hashes.add(Murmur3.hash(1, i)); } assertEquals(10000, hashes.size()); }
ErrorUtils { public static boolean isCausedBy(Class<? extends Throwable> type, Throwable error) { return findCause(type, error) != null; } private ErrorUtils(); static String stackTrace(Throwable error); static boolean isCausedBy(Class<? extends Throwable> type, Throwable error); static T findCause(Class<T> type, Throwable error); }
@Test public void testIsCausedBy() { assertFalse(ErrorUtils.isCausedBy(Exception.class, null)); assertFalse(ErrorUtils.isCausedBy(IOException.class, new Exception())); assertTrue(ErrorUtils.isCausedBy(IOException.class, new IOException())); assertTrue(ErrorUtils.isCausedBy(IOException.class, new Exception(new IOException()))); assertTrue(ErrorUtils.isCausedBy(IOException.class, new Exception(new Exception(new IOException())))); }
ErrorUtils { public static String stackTrace(Throwable error) { ArgAssert.notNull(error, "error"); StringWriter out = new StringWriter(); error.printStackTrace(new PrintWriter(out)); return out.toString(); } private ErrorUtils(); static String stackTrace(Throwable error); static boolean isCausedBy(Class<? extends Throwable> type, Throwable error); static T findCause(Class<T> type, Throwable error); }
@Test public void testStackTrace() { assertTrue(ErrorUtils.stackTrace(new Exception()).contains(ErrorUtilsTest.class.getName())); assertTrue(ErrorUtils.stackTrace(new Exception()).contains(ErrorUtilsTest.class.getName() + ".testStackTrace(")); }
StreamUtils { public static <T> Stream<T> nullSafe(Collection<T> collection) { if (collection == null || collection.isEmpty()) { return Stream.empty(); } return collection.stream().filter(Objects::nonNull); } private StreamUtils(); static Stream<T> nullSafe(Collection<T> collection); }
@Test public void testNullSafe() { assertNotNull(nullSafe(null)); assertNotNull(nullSafe(emptyList())); assertEquals(singletonList("non null"), nullSafe(asList(null, "non null", null)).collect(toList())); }
ConfigCheck { public void that(boolean check, String msg) throws HekateConfigurationException { if (!check) { throw new HekateConfigurationException(component + ": " + msg); } } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }
@Test public void testThatSuccess() { check.that(true, "Success"); } @Test public void testThatFailure() { expectExactMessage(HCE, PREFIX + "Test message", () -> check.that(Boolean.valueOf("false"), "Test message") ); check.that(true, "Success"); }
ConfigCheck { public HekateConfigurationException fail(Throwable cause) { throw new HekateConfigurationException(component + ": " + cause.toString(), cause); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }
@Test public void testFail() { expectExactMessage(HCE, PREFIX + "java.lang.Exception: test error message", () -> check.fail(new Exception("test error message")) ); }
ConfigCheck { public void isPowerOfTwo(int n, String component) throws HekateConfigurationException { that(Utils.isPowerOfTwo(n), component + " must be a power of two [value=" + n + ']'); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }
@Test public void testIsPowerOfTwo() { expectExactMessage(HCE, PREFIX + "Ten must be a power of two [value=10]", () -> check.isPowerOfTwo(10, "Ten") ); check.isPowerOfTwo(8, "Success"); }
ConfigCheck { public void range(int value, int from, int to, String component) { that(value >= from && value <= to, component + " must be within the " + from + ".." + to + " range."); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }
@Test public void testRange() { expectExactMessage(HCE, PREFIX + "Ten must be within the 1..5 range.", () -> check.range(10, 1, 5, "Ten") ); check.range(0, 0, 0, "0-0-0"); check.range(1, 0, 1, "1-0-1"); check.range(1, 1, 1, "1-1-1"); check.range(5, 1, 8, "5-1-8"); }
ConfigCheck { public void positive(int value, String component) { greater(value, 0, component); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }
@Test public void testPositiveInt() { expectExactMessage(HCE, PREFIX + "Zero must be greater than 0 [value=0]", () -> check.positive(0, "Zero") ); expectExactMessage(HCE, PREFIX + "Negative must be greater than 0 [value=-1]", () -> check.positive(-1, "Negative") ); check.positive(1, "Success"); } @Test public void testPositiveLong() { expectExactMessage(HCE, PREFIX + "Zero must be greater than 0 [value=0]", () -> check.positive(0L, "Zero") ); expectExactMessage(HCE, PREFIX + "Negative must be greater than 0 [value=-1]", () -> check.positive(-1L, "Negative") ); check.positive(1L, "Success"); }
ConfigCheck { public void nonNegative(int value, String component) { greaterOrEquals(value, 0, component); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }
@Test public void testNonNegativeInt() { expectExactMessage(HCE, PREFIX + "Negative must be greater than or equals to 0 [value=-1]", () -> check.nonNegative(-1, "Negative") ); check.nonNegative(0, "Success"); check.nonNegative(1, "Success"); }
ConfigCheck { public void unique(Object what, Set<?> where, String component) { that(!where.contains(what), "duplicated " + component + " [value=" + what + ']'); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }
@Test public void testUnique() { expectExactMessage(HCE, PREFIX + "duplicated One [value=one]", () -> check.unique("one", singleton("one"), "One") ); check.unique("one", emptySet(), "Success"); check.unique("one", singleton("two"), "Success"); check.unique("one", new HashSet<>(asList("two", "three")), "Success"); }
ConfigCheck { public void isTrue(boolean value, String msg) throws HekateConfigurationException { that(value, msg); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }
@Test public void testIsTrue() { expectExactMessage(HCE, PREFIX + "True Epic fail", () -> check.isTrue(Boolean.valueOf("false"), "True Epic fail") ); check.isTrue(true, "Success"); }
ConfigCheck { public void isFalse(boolean value, String msg) throws HekateConfigurationException { that(!value, msg); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }
@Test public void testIsFalse() { check.isFalse(false, "Success"); expectExactMessage(HCE, PREFIX + "Epic fail", () -> check.isFalse(true, "Epic fail") ); }
ConfigCheck { public void notNull(Object value, String component) throws HekateConfigurationException { notNull(value, component, "must be not null"); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }
@Test public void testNotNull() { expectExactMessage(HCE, PREFIX + "Epic fail must be not null.", () -> check.notNull(null, "Epic fail") ); check.notNull("777", "Success"); }
ConfigCheck { public void notEmpty(String value, String component) throws HekateConfigurationException { notNull(value, component); that(!value.trim().isEmpty(), component + " must be a non-empty string."); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }
@Test public void testNotEmptyString() { expectExactMessage(HCE, PREFIX + "Epic fail must be not null.", () -> check.notEmpty((String)null, "Epic fail") ); expectExactMessage(HCE, PREFIX + "Epic fail must be a non-empty string.", () -> check.notEmpty("", "Epic fail") ); expectExactMessage(HCE, PREFIX + "Epic fail must be a non-empty string.", () -> check.notEmpty(" ", "Epic fail") ); expectExactMessage(HCE, PREFIX + "Epic fail must be a non-empty string.", () -> check.notEmpty("\n", "Epic fail") ); check.notEmpty("777", "Success"); } @Test public void testNotEmptyStream() { expectExactMessage(HCE, PREFIX + "Epic fail must be not null.", () -> check.notEmpty((Stream<?>)null, "Epic fail") ); expectExactMessage(HCE, PREFIX + "Epic fail must be not empty.", () -> check.notEmpty(Stream.empty(), "Epic fail") ); check.notEmpty(Stream.of("777"), "Success"); check.notEmpty(Stream.of((String)null), "Success"); }
ConfigCheck { public void validSysName(String value, String component) { if (value != null) { String trimmed = value.trim(); if (!trimmed.isEmpty() && !SYS_NAME.matcher(trimmed).matches()) { throw fail(component + " can contain only alpha-numeric characters and non-repeatable dots/hyphens " + "[value=" + trimmed + ']'); } } } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }
@Test public void testSysName() { expectExactMessage(HCE, PREFIX + "Epic fail can contain only alpha-numeric characters and non-repeatable dots/hyphens " + "[value=-not-valid-]", () -> check.validSysName("-not-valid-", "Epic fail") ); check.validSysName(null, "ignore"); check.validSysName("", "ignore"); check.validSysName(" ", "ignore"); check.validSysName("X", "ignore"); check.validSysName("XXX", "ignore"); check.validSysName("x", "ignore"); check.validSysName("xxx", "ignore"); check.validSysName("xxx-x", "ignore"); check.validSysName("xxx-xxx", "ignore"); check.validSysName("x-xxx", "ignore"); check.validSysName("xxx.x", "ignore"); check.validSysName("xxx.xxx", "ignore"); check.validSysName("x.xxx", "ignore"); check.validSysName("x.xxx-x", "ignore"); check.validSysName("x-xxx.x", "ignore"); check.validSysName("x-xxx.x-x.x.x", "ignore"); check.validSysName("x-xxx.x-x.x.x", "ignore"); check.validSysName(" x-xxx.x-x.x.x ", "ignore"); expect(HCE, () -> check.validSysName("-", "ignore")); expect(HCE, () -> check.validSysName(".", "ignore")); expect(HCE, () -> check.validSysName("x..x", "ignore")); expect(HCE, () -> check.validSysName("x--x", "ignore")); expect(HCE, () -> check.validSysName("-xxx", "ignore")); expect(HCE, () -> check.validSysName("xxx-", "ignore")); expect(HCE, () -> check.validSysName(".xxx-", "ignore")); expect(HCE, () -> check.validSysName("xxx.", "ignore")); expect(HCE, () -> check.validSysName("xxx-.-xxx", "ignore")); }
ArgAssert { public static void check(boolean that, String msg) throws IllegalArgumentException { doCheck(that, null, msg); } private ArgAssert(); static void check(boolean that, String msg); static T notNull(T obj, String argName); static String notEmpty(String str, String argName); static void isFalse(boolean condition, String msg); static void isTrue(boolean condition, String msg); static void positive(long val, String argName); static void powerOfTwo(int val, String argName); }
@Test public void testCheck() throws Exception { expectExactMessage(IAE, "test message", () -> ArgAssert.check(false, "test message") ); ArgAssert.check(true, "Success"); }