focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { try { // Copies file // If segmented file, copies manifest (creating a link between new object and original segments) // Use with caution. session.getClient().copyObject(regionService.lookup(source), containerService.getContainer(source).getName(), containerService.getKey(source), containerService.getContainer(target).getName(), containerService.getKey(target)); listener.sent(status.getLength()); // Copy original file attributes return target.withAttributes(source.attributes()); } catch(GenericException e) { throw new SwiftExceptionMappingService().map("Cannot copy {0}", e, source); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map("Cannot copy {0}", e, source); } }
@Test public void testCopy() throws Exception { final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("IAD"); final Path test = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new SwiftTouchFeature(session, new SwiftRegionService(session)).touch(test, new TransferStatus()); final Path copy = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new SwiftDefaultCopyFeature(session).copy(test, copy, new TransferStatus(), new DisabledConnectionCallback(), new DisabledStreamListener()); assertTrue(new SwiftFindFeature(session).find(test)); assertTrue(new SwiftFindFeature(session).find(copy)); new SwiftDeleteFeature(session).delete(Arrays.asList(test, copy), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
public ChannelUriStringBuilder nakDelay(final String nakDelay) { this.nakDelay = null != nakDelay ? parseDuration(NAK_DELAY_PARAM_NAME, nakDelay) : null; return this; }
@Test void shouldHandleNakDelayWithUnits() { assertEquals(1000L, new ChannelUriStringBuilder().nakDelay("1us").nakDelay()); assertEquals(1L, new ChannelUriStringBuilder().nakDelay("1ns").nakDelay()); assertEquals(1000000L, new ChannelUriStringBuilder().nakDelay("1ms").nakDelay()); }
@VisibleForTesting URI getDefaultHttpUri() { return getDefaultHttpUri("/"); }
@Test public void testHttpPublishUriLocalhost() throws RepositoryException, ValidationException { jadConfig.setRepository(new InMemoryRepository(ImmutableMap.of("http_bind_address", "127.0.0.1:9000"))).addConfigurationBean(configuration).process(); assertThat(configuration.getDefaultHttpUri()).isEqualTo(URI.create("http://127.0.0.1:9000/")); }
@Udf public String rpad( @UdfParameter(description = "String to be padded") final String input, @UdfParameter(description = "Target length") final Integer targetLen, @UdfParameter(description = "Padding string") final String padding) { if (input == null) { return null; } if (padding == null || padding.isEmpty() || targetLen == null || targetLen < 0) { return null; } final StringBuilder sb = new StringBuilder(targetLen + padding.length()); sb.append(input); final int padChars = Math.max(targetLen - input.length(), 0); for (int i = 0; i < padChars; i += padding.length()) { sb.append(padding); } sb.setLength(targetLen); return sb.toString(); }
@Test public void shouldAppendPartialPaddingBytes() { final ByteBuffer result = udf.rpad(BYTES_123, 4, BYTES_45); assertThat(BytesUtils.getByteArray(result), is(new byte[]{1,2,3,4})); }
@Finder("search") @SuccessResponse(statuses = { HttpStatus.S_200_OK }) @ParamError(code = INVALID_ID, parameterNames = { "albumId", "photoId" }) @ParamError(code = UNSEARCHABLE_ALBUM_ID, parameterNames = { "albumId" }) public List<AlbumEntry> search(@Optional @QueryParam("albumId") Long albumId, @Optional @QueryParam("photoId") Long photoId) { List<AlbumEntry> result = new ArrayList<>(); for (Map.Entry<CompoundKey, AlbumEntry> entry : _db.getData().entrySet()) { CompoundKey key = entry.getKey(); // if the id is null, don't do any filtering by that id // (treat all values as a match) if (albumId != null && !key.getPart("albumId").equals(albumId)) continue; if (photoId != null && !key.getPart("photoId").equals(photoId)) continue; result.add(entry.getValue()); } return result; }
@Test public void testSearch() { // we previously put the first 3 entries in album 1 Set<AlbumEntry> result = new HashSet<>(_entryRes.search(Long.valueOf(1), null)); Set<AlbumEntry> expected = new HashSet<>(); for (int i = 0; i < 3; i++) { expected.add(_entries[i]); } Assert.assertEquals(result, expected); }
@Override public FsCheckpointStateOutputStream createCheckpointStateOutputStream( CheckpointedStateScope scope) throws IOException { Path target = getTargetPath(scope); int bufferSize = Math.max(writeBufferSize, fileStateThreshold); // Whether the file system dynamically injects entropy into the file paths. final boolean entropyInjecting = EntropyInjector.isEntropyInjecting(filesystem, target); final boolean absolutePath = entropyInjecting || scope == CheckpointedStateScope.SHARED; return new FsCheckpointStateOutputStream( target, filesystem, bufferSize, fileStateThreshold, !absolutePath); }
@Test void testExclusiveStateHasRelativePathHandles() throws IOException { final FsCheckpointStreamFactory factory = createFactory(FileSystem.getLocalFileSystem(), 0); final FsCheckpointStreamFactory.FsCheckpointStateOutputStream stream = factory.createCheckpointStateOutputStream(CheckpointedStateScope.EXCLUSIVE); stream.write(1657); final StreamStateHandle handle = stream.closeAndGetHandle(); assertThat(handle).isInstanceOf(RelativeFileStateHandle.class); assertPathsEqual( exclusiveStateDir, ((RelativeFileStateHandle) handle).getFilePath().getParent()); }
public static byte[] parseHex(String string) { return hexFormat.parseHex(string); }
@Test(expected = IllegalArgumentException.class) @Parameters(method = "invalidHexStrings") public void parseHexInvalid(String hexString) { byte[] actual = ByteUtils.parseHex(hexString); }
public static Request.Builder buildRequestBuilder(final String url, final Map<String, ?> form, final HTTPMethod method) { switch (method) { case GET: return new Request.Builder() .url(buildHttpUrl(url, form)) .get(); case HEAD: return new Request.Builder() .url(buildHttpUrl(url, form)) .head(); case PUT: return new Request.Builder() .url(buildHttpUrl(url)) .put(buildFormBody(form)); case DELETE: return new Request.Builder() .url(buildHttpUrl(url)) .delete(buildFormBody(form)); default: return new Request.Builder() .url(buildHttpUrl(url)) .post(buildFormBody(form)); } }
@Test public void buildRequestBuilderForHEADTest() { Request.Builder builder = HttpUtils.buildRequestBuilder(TEST_URL, formMap, HttpUtils.HTTPMethod.HEAD); Assert.assertNotNull(builder); Assert.assertEquals(builder.build().method(), HttpUtils.HTTPMethod.HEAD.value()); Assert.assertEquals(builder.build().url().toString(), ACTUAL_PARAM_URL); }
@SuppressWarnings("unchecked") public <T extends Expression> T rewrite(final T expression, final C context) { return (T) rewriter.process(expression, context); }
@Test public void shouldRewriteLiteral() { for (final Expression expression : LITERALS) { // When: final Expression rewritten = expressionRewriter.rewrite(expression, context); // Then: assertThat(rewritten, is(expression)); } }
@Nullable public synchronized Beacon track(@NonNull Beacon beacon) { Beacon trackedBeacon = null; if (beacon.isMultiFrameBeacon() || beacon.getServiceUuid() != -1) { trackedBeacon = trackGattBeacon(beacon); } else { trackedBeacon = beacon; } return trackedBeacon; }
@Test public void multiFrameBeaconDifferentServiceUUIDFieldsNotUpdated() { Beacon beacon = getMultiFrameBeacon(); Beacon beaconUpdate = getMultiFrameBeaconUpdateDifferentServiceUUID(); ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker(); tracker.track(beacon); tracker.track(beaconUpdate); Beacon trackedBeacon = tracker.track(beacon); assertNotEquals("rssi should NOT be updated", beaconUpdate.getRssi(), trackedBeacon.getRssi()); assertNotEquals("data fields should NOT be updated", beaconUpdate.getDataFields(), trackedBeacon.getExtraDataFields()); }
@Nullable public Map<String, Object> getScopedObjects() { return null; }
@Test void testScopedObjects() { assertThat(migrationsBundleWithScopedObjects.getScopedObjects()).isNotNull().isEmpty(); }
public static Read read() { return new Read(null, "", new Scan()); }
@Test public void testReadingKeyRangeSuffix() throws Exception { final String table = tmpTable.getName(); final int numRows = 1001; final ByteKey startKey = ByteKey.copyFrom("2".getBytes(StandardCharsets.UTF_8)); createAndWriteData(table, numRows); // Test suffix: [startKey, end). final ByteKeyRange suffixRange = ByteKeyRange.ALL_KEYS.withStartKey(startKey); runReadTestLength( HBaseIO.read().withConfiguration(conf).withTableId(table).withKeyRange(suffixRange), false, 875); }
@SuppressWarnings("unchecked") @Override public void set(Object value) { if (lazyMetric == null) { wakeMetric(value); } else { lazyMetric.set(value); } }
@Test public void set() { //Long LazyDelegatingGauge gauge = new LazyDelegatingGauge("bar"); gauge.set(99l); assertThat(gauge.getValue()).isEqualTo(99l); gauge.set(199l); assertThat(gauge.getValue()).isEqualTo(199l); assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_NUMBER); //Integer gauge = new LazyDelegatingGauge("bar"); gauge.set(99); assertThat(gauge.getValue()).isEqualTo(99); gauge.set(199); assertThat(gauge.getValue()).isEqualTo(199); assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_NUMBER); //Double gauge = new LazyDelegatingGauge("bar"); gauge.set(99.0); assertThat(gauge.getValue()).isEqualTo(99.0); gauge.set(199.01); assertThat(gauge.getValue()).isEqualTo(199.01); assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_NUMBER); //Boolean gauge = new LazyDelegatingGauge("bar"); gauge.set(true); assertThat(gauge.getValue()).isEqualTo(true); gauge.set(false); assertThat(gauge.getValue()).isEqualTo(false); assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_BOOLEAN); //Text gauge = new LazyDelegatingGauge("bar"); gauge.set("something"); assertThat(gauge.getValue()).isEqualTo("something"); gauge.set("something else"); assertThat(gauge.getValue()).isEqualTo("something else"); assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_TEXT); //Ruby Hash gauge = new LazyDelegatingGauge("bar"); gauge.set(RUBY_HASH); assertThat(gauge.getValue().toString()).isEqualTo(RUBY_HASH_AS_STRING); assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_RUBYHASH); //Ruby Timestamp gauge = new LazyDelegatingGauge("bar"); gauge.set(RUBY_TIMESTAMP); assertThat(gauge.getValue()).isEqualTo(TIMESTAMP); assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_RUBYTIMESTAMP); //Unknown gauge = new LazyDelegatingGauge("bar"); gauge.set(Collections.singleton("value")); assertThat(gauge.getValue()).isEqualTo(Collections.singleton("value")); gauge.set(URI.create("foo")); //please don't change the type of gauge after already set assertThat(gauge.getValue()).isEqualTo(URI.create("foo")); assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_UNKNOWN); //Null gauge = new LazyDelegatingGauge("bar"); gauge.set(null); assertThat(gauge.getValue()).isNull(); assertThat(gauge.getType()).isNull(); //Valid, then Null gauge = new LazyDelegatingGauge("bar"); gauge.set("something"); assertThat(gauge.getValue()).isEqualTo("something"); gauge.set(null); assertThat(gauge.getValue()).isNull(); assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_TEXT); }
public int size() { return m.size(); }
@Test public void testBasic() { FeatureMap fm = buildMap(); FeatureMap otherFm = buildMap(); assertEquals(fm, otherFm); int catCount = 0; int realCount = 0; for (VariableInfo i : fm) { if (i instanceof CategoricalInfo) { catCount++; } else if (i instanceof RealInfo) { realCount++; } } assertEquals(5,catCount); assertEquals(3,realCount); assertEquals(8,fm.size()); ImmutableFeatureMap ifm = new ImmutableFeatureMap(fm); assertNotEquals(fm,ifm); assertEquals(8,ifm.size()); }
@Override protected boolean isNewMigration(NoSqlMigration noSqlMigration) { return isNewMigration(noSqlMigration, 0); }
@Test void testMigrations() throws IOException { ElasticSearchDBCreator elasticSearchDBCreator = new ElasticSearchDBCreator(elasticSearchStorageProviderMock, elasticSearchClient(), null); assertThat(elasticSearchDBCreator.isNewMigration(new NoSqlMigrationByClass(M001_CreateJobsIndex.class))).isTrue(); assertThat(elasticSearchDBCreator.isNewMigration(new NoSqlMigrationByClass(M002_CreateRecurringJobsIndex.class))).isTrue(); assertThatCode(elasticSearchDBCreator::runMigrations).doesNotThrowAnyException(); assertThatCode(elasticSearchDBCreator::runMigrations).doesNotThrowAnyException(); assertThat(elasticSearchDBCreator.isNewMigration(new NoSqlMigrationByClass(M001_CreateJobsIndex.class))).isFalse(); assertThat(elasticSearchDBCreator.isNewMigration(new NoSqlMigrationByClass(M002_CreateRecurringJobsIndex.class))).isFalse(); assertThat(elasticSearchClient().indices().get(g -> g.index("*")).result()).hasSize(5); }
@Override public T deserialize(final String topic, final byte[] bytes) { return tryDeserialize(topic, bytes).get(); }
@Test public void shouldLogOnException() { // Given: when(delegate.deserialize(any(), any())).thenThrow(ERROR); // When: assertThrows( RuntimeException.class, () -> deserializer.deserialize("t", SOME_BYTES) ); // Then: verify(processingLogger).error(new DeserializationError(ERROR, Optional.of(SOME_BYTES), "t", false)); }
@Override public boolean isWarnEnabled() { return logger.isWarnEnabled(); }
@Test public void testIsWarnEnabled() { Log mockLog = mock(Log.class); when(mockLog.isWarnEnabled()).thenReturn(true); InternalLogger logger = new CommonsLogger(mockLog, "foo"); assertTrue(logger.isWarnEnabled()); verify(mockLog).isWarnEnabled(); }
public static String normalize(String str) { return new VersionNumber(str).getCanonical(); }
@Test public void testCanonical() { assertEquals("3.2", normalize("3.2.0.0")); assertEquals("3.2-5", normalize("3.2.0.0-5")); assertEquals("3.2", normalize("3.2.0.0-0")); assertEquals("3.2", normalize("3.2--------")); assertEquals("3.2", normalize("3.0002")); assertEquals("1.7.2$%%^@&snapshot-3.1.1", normalize("1.7.2$%%^@&snapshot-3.1.1")); assertEquals("1.99999999999999999999", normalize("1.99999999999999999999")); assertEquals("1.99999999999999999999", normalize("1.0099999999999999999999")); assertEquals("1.99999999999999999999", normalize("1.99999999999999999999.0")); assertEquals("1.99999999999999999999", normalize("1.99999999999999999999--------")); }
@Override public CucumberOptionsAnnotationParser.CucumberOptions getOptions(Class<?> clazz) { CucumberOptions annotation = clazz.getAnnotation(CucumberOptions.class); if (annotation != null) { return new JunitCucumberOptions(annotation); } warnWhenTestNGCucumberOptionsAreUsed(clazz); return null; }
@Test void testUuidGenerator() { io.cucumber.core.options.CucumberOptionsAnnotationParser.CucumberOptions options = this.optionsProvider .getOptions(ClassWithCustomUuidGenerator.class); assertNotNull(options); assertEquals(IncrementingUuidGenerator.class, options.uuidGenerator()); }
void addPeerClusterWatches(@Nonnull Set<String> newPeerClusters, @Nonnull FailoutConfig failoutConfig) { final Set<String> existingPeerClusters = _peerWatches.keySet(); if (newPeerClusters.isEmpty()) { removePeerClusterWatches(); return; } final Set<String> peerClustersToAdd = new HashSet<>(newPeerClusters); peerClustersToAdd.removeAll(existingPeerClusters); if (!peerClustersToAdd.isEmpty()) { addClusterWatches(peerClustersToAdd, failoutConfig); } final Set<String> peerClustersToRemove = new HashSet<>(existingPeerClusters); peerClustersToRemove.removeAll(newPeerClusters); if (!peerClustersToRemove.isEmpty()) { removeClusterWatches(peerClustersToRemove); } }
@Test public void testAddPeerClusterWatchesWithPeerClusterRemoved() { _manager.addPeerClusterWatches(new HashSet<>(Arrays.asList(PEER_CLUSTER_NAME1, PEER_CLUSTER_NAME2)), mock(FailoutConfig.class)); _manager.addPeerClusterWatches(new HashSet<>(Arrays.asList(PEER_CLUSTER_NAME1)), mock(FailoutConfig.class)); verify(_loadBalancerState, times(1)).listenToCluster(eq(PEER_CLUSTER_NAME1), any()); verify(_loadBalancerState, times(1)).listenToCluster(eq(PEER_CLUSTER_NAME2), any()); verify(_warmUpHandler, times(1)).cancelPendingRequests(eq(PEER_CLUSTER_NAME2)); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); verify(_scheduledExecutorService, times(1)).schedule(captor.capture(), eq(PEER_WATCH_TEAR_DOWN_DELAY_MS), eq(TimeUnit.MILLISECONDS)); captor.getValue().run(); verify(_loadBalancerState, times(1)).stopListenToCluster(eq(PEER_CLUSTER_NAME2), any()); }
@Override public <R> R query(TemporalQuery<R> query) { if (query == TemporalQueries.zoneId() || query == TemporalQueries.zone()) { return (R) zoneId; } else if (query.toString().contains(DateTimeFormatterBuilder.class.getCanonicalName())) { return (R) zoneId; } else { return offsetTime.query(query); } }
@Test void query() { assertEquals(zoneId, zoneTime.query(TemporalQueries.zoneId())); assertEquals(zoneId, zoneTime.query(TemporalQueries.zone())); assertEquals(offsetTime.query(TemporalQueries.localTime()), zoneTime.query(TemporalQueries.localTime())); assertEquals(offsetTime.query(TemporalQueries.offset()), zoneTime.query(TemporalQueries.offset())); }
@Override @MethodNotAvailable public CompletionStage<V> removeAsync(K key) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testRemoveAsync() { adapter.removeAsync(23); }
public static void main(String[] args) { var server = new Server("localhost", 8080); var session1 = server.getSession("Session1"); var session2 = server.getSession("Session2"); var request1 = new Request("Data1", session1); var request2 = new Request("Data2", session2); server.process(request1); server.process(request2); }
@Test void appStartsWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
@Override public void preAction(WebService.Action action, Request request) { Level logLevel = getLogLevel(); String deprecatedSinceEndpoint = action.deprecatedSince(); if (deprecatedSinceEndpoint != null) { logWebServiceMessage(logLevel, deprecatedSinceEndpoint); } action.params().forEach(param -> logParamMessage(request, logLevel, param)); }
@Test public void preAction_whenParamAndEndpointAreNotDeprecated_shouldLogNothing() { WebService.Action action = mock(WebService.Action.class); when(action.deprecatedSince()).thenReturn(null); WebService.Param mockParam = mock(WebService.Param.class); when(mockParam.deprecatedKeySince()).thenReturn(null); when(action.params()).thenReturn(List.of(mockParam)); Request request = mock(Request.class); underTest.preAction(action, request); verifyNoDeprecatedMsgInLogs(Level.DEBUG); verifyNoDeprecatedMsgInLogs(Level.WARN); }
@Override public V getAndDelete() { return get(getAndDeleteAsync()); }
@Test public void testGetAndDelete() { RBucket<Integer> al = redisson.getBucket("test"); al.set(10); assertThat(al.getAndDelete()).isEqualTo(10); assertThat(al.isExists()).isFalse(); assertThat(al.getAndDelete()).isNull(); }
public double totalMessageConsumption() { return aggregateStat(ConsumerCollector.CONSUMER_TOTAL_MESSAGES, false); }
@Test public void shouldAggregateTotalMessageConsumptionAcrossAllConsumers() { final MetricCollectors metricCollectors = new MetricCollectors(); final ConsumerCollector collector1 = new ConsumerCollector(); collector1.configure( ImmutableMap.of( ConsumerConfig.CLIENT_ID_CONFIG, "client1", KsqlConfig.KSQL_INTERNAL_METRIC_COLLECTORS_CONFIG, metricCollectors ) ); final ConsumerCollector collector2 = new ConsumerCollector(); collector2.configure( ImmutableMap.of( ConsumerConfig.CLIENT_ID_CONFIG, "client2", KsqlConfig.KSQL_INTERNAL_METRIC_COLLECTORS_CONFIG, metricCollectors ) ); final Map<TopicPartition, List<ConsumerRecord<Object, Object>>> records = new HashMap<>(); final List<ConsumerRecord<Object, Object>> recordList = new ArrayList<>(); for (int i = 0; i < 10; i++) { recordList.add( new ConsumerRecord<>( TEST_TOPIC, 1, 1, 1L, TimestampType .CREATE_TIME, 10, 10, "key", "1234567890", new RecordHeaders(), Optional.empty() ) ); } records.put(new TopicPartition(TEST_TOPIC, 1), recordList); final ConsumerRecords<Object, Object> consumerRecords = new ConsumerRecords<>(records); collector1.onConsume(consumerRecords); collector2.onConsume(consumerRecords); assertEquals(20, metricCollectors.totalMessageConsumption(), 0); }
public static TimeInterval timer() { return new TimeInterval(); }
@Test public void timerTest() { final TimeInterval timer = DateUtil.timer(); // --------------------------------- // -------这是执行过程 // --------------------------------- timer.interval();// 花费毫秒数 timer.intervalRestart();// 返回花费时间,并重置开始时间 timer.intervalMinute();// 花费分钟数 }
public static boolean overlapsOrdered(IndexIterationPointer left, IndexIterationPointer right, Comparator comparator) { assert left.isDescending() == right.isDescending() : "Cannot compare pointer with different directions"; assert left.lastEntryKeyData == null && right.lastEntryKeyData == null : "Can merge only initial pointers"; // fast path for the same instance if (left == right) { return true; } assert comparator.compare(left.from, right.from) <= 0 : "Pointers must be ordered"; // if one of the ends is +/-inf respectively -> overlap if (left.to == null || right.from == null) { return true; } // if given end is equal the ranges overlap (or at least are adjacent) // if at least one of the ranges is inclusive boolean eqOverlaps = left.isToInclusive() || right.isFromInclusive(); // Check non-inf values, do not need to check the other way around because pointers are ordered // Thanks to order we do not have to check `right.to`, we only need to check // if `right.from` belongs to `left` pointer range. // we must take into account inclusiveness, so we do not merge < X and > X ranges int rfCmpLt = comparator.compare(right.from, left.to); return eqOverlaps ? rfCmpLt <= 0 : rfCmpLt < 0; }
@Test void overlapsOrderedSingletonValidation() { assertThatThrownBy(() -> overlapsOrdered(pointer(singleton(6)), pointer(singleton(5)), OrderedIndexStore.SPECIAL_AWARE_COMPARATOR)) .isInstanceOf(AssertionError.class).hasMessageContaining("Pointers must be ordered"); assertThatThrownBy(() -> overlapsOrdered(pointer(singleton(6), true), pointer(singleton(5), true), OrderedIndexStore.SPECIAL_AWARE_COMPARATOR)) .isInstanceOf(AssertionError.class).hasMessageContaining("Pointers must be ordered"); }
@Override protected void handleCloseProducer(CommandCloseProducer closeProducer) { final long producerId = closeProducer.getProducerId(); log.info("[{}] Broker notification of closed producer: {}, assignedBrokerUrl: {}, assignedBrokerUrlTls: {}", remoteAddress, producerId, closeProducer.hasAssignedBrokerServiceUrl() ? closeProducer.getAssignedBrokerServiceUrl() : null, closeProducer.hasAssignedBrokerServiceUrlTls() ? closeProducer.getAssignedBrokerServiceUrlTls() : null); ProducerImpl<?> producer = producers.remove(producerId); if (producer != null) { String brokerServiceUrl = getBrokerServiceUrl(closeProducer, producer); Optional<URI> hostUri = parseUri(brokerServiceUrl, closeProducer.hasRequestId() ? closeProducer.getRequestId() : null); Optional<Long> initialConnectionDelayMs = hostUri.map(__ -> 0L); producer.connectionClosed(this, initialConnectionDelayMs, hostUri); } else { log.warn("[{}] Producer with id {} not found while closing producer", remoteAddress, producerId); } }
@Test public void testHandleCloseProducer() { ThreadFactory threadFactory = new DefaultThreadFactory("testHandleCloseProducer"); EventLoopGroup eventLoop = EventLoopUtil.newEventLoopGroup(1, false, threadFactory); ClientConfigurationData conf = new ClientConfigurationData(); ClientCnx cnx = new ClientCnx(InstrumentProvider.NOOP, conf, eventLoop); long producerId = 1; PulsarClientImpl pulsarClient = mock(PulsarClientImpl.class); when(pulsarClient.getConfiguration()).thenReturn(conf); ProducerImpl producer = mock(ProducerImpl.class); when(producer.getClient()).thenReturn(pulsarClient); cnx.registerProducer(producerId, producer); assertEquals(cnx.producers.size(), 1); CommandCloseProducer closeProducerCmd = new CommandCloseProducer().setProducerId(producerId).setRequestId(1); cnx.handleCloseProducer(closeProducerCmd); assertEquals(cnx.producers.size(), 0); verify(producer).connectionClosed(cnx, Optional.empty(), Optional.empty()); eventLoop.shutdownGracefully(); }
public <T> T convert(String property, Class<T> targetClass) { final AbstractPropertyConverter<?> converter = converterRegistry.get(targetClass); if (converter == null) { throw new MissingFormatArgumentException("converter not found, can't convert from String to " + targetClass.getCanonicalName()); } return (T) converter.convert(property); }
@Test void testConvertIntegerForEmptyProperty() { assertNull(compositeConverter.convert(null, Integer.class)); }
@Override // Camel calls this method if the endpoint isSynchronous(), as the // KafkaEndpoint creates a SynchronousDelegateProducer for it public void process(Exchange exchange) throws Exception { // is the message body a list or something that contains multiple values Message message = exchange.getIn(); if (transactionId != null) { startKafkaTransaction(exchange); } if (endpoint.getConfiguration().isUseIterator() && isIterable(message.getBody())) { processIterableSync(exchange, message); } else { processSingleMessageSync(exchange, message); } }
@Test public void processSendsMessageWithMessageTimestampHeader() throws Exception { endpoint.getConfiguration().setTopic("someTopic"); Mockito.when(exchange.getIn()).thenReturn(in); Mockito.when(exchange.getMessage()).thenReturn(in); in.setHeader(KafkaConstants.KEY, "someKey"); in.setHeader(KafkaConstants.OVERRIDE_TIMESTAMP, LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); producer.process(exchange); verifySendMessage("someTopic", "someKey"); assertRecordMetadataTimestampExists(); }
public static String generateJvmOptsString( org.apache.flink.configuration.Configuration conf, List<ConfigOption<String>> jvmOptions, boolean hasKrb5) { StringBuilder javaOptsSb = new StringBuilder(); for (ConfigOption<String> option : jvmOptions) { concatWithSpace(javaOptsSb, conf.get(option)); } concatWithSpace(javaOptsSb, IGNORE_UNRECOGNIZED_VM_OPTIONS); // krb5.conf file will be available as local resource in JM/TM container if (hasKrb5) { concatWithSpace(javaOptsSb, "-Djava.security.krb5.conf=krb5.conf"); } return javaOptsSb.toString().trim(); }
@Test void testGenerateJvmOptsString() { final String defaultJvmOpts = "-DdefaultJvm"; final String jvmOpts = "-Djvm"; final String krb5 = "-Djava.security.krb5.conf=krb5.conf"; final Configuration conf = new Configuration(); conf.set(CoreOptions.FLINK_DEFAULT_JVM_OPTIONS, defaultJvmOpts); conf.set(CoreOptions.FLINK_JVM_OPTIONS, jvmOpts); final List<ConfigOption<String>> jvmOptions = Arrays.asList(CoreOptions.FLINK_DEFAULT_JVM_OPTIONS, CoreOptions.FLINK_JVM_OPTIONS); // With Krb5 assertThat(Utils.generateJvmOptsString(conf, jvmOptions, true)) .isEqualTo( String.join( " ", defaultJvmOpts, jvmOpts, Utils.IGNORE_UNRECOGNIZED_VM_OPTIONS, krb5)); // Without Krb5 assertThat(Utils.generateJvmOptsString(conf, jvmOptions, false)) .isEqualTo( String.join( " ", defaultJvmOpts, jvmOpts, Utils.IGNORE_UNRECOGNIZED_VM_OPTIONS)); }
@Override public ConnectorPageSource createPageSource( ConnectorTransactionHandle transaction, ConnectorSession session, ConnectorSplit split, ConnectorTableLayoutHandle layout, List<ColumnHandle> columns, SplitContext splitContext, RuntimeStats runtimeStats) { HiveTableLayoutHandle hiveLayout = (HiveTableLayoutHandle) layout; List<HiveColumnHandle> selectedColumns = columns.stream() .map(HiveColumnHandle.class::cast) .collect(toList()); HiveSplit hiveSplit = (HiveSplit) split; Path path = new Path(hiveSplit.getFileSplit().getPath()); Configuration configuration = hdfsEnvironment.getConfiguration( new HdfsContext( session, hiveSplit.getDatabase(), hiveSplit.getTable(), hiveLayout.getTablePath(), false), path); Optional<EncryptionInformation> encryptionInformation = hiveSplit.getEncryptionInformation(); CacheQuota cacheQuota = generateCacheQuota(hiveSplit); HiveFileContext fileContext = new HiveFileContext( splitContext.isCacheable(), cacheQuota, hiveSplit.getFileSplit().getExtraFileInfo().map(BinaryExtraHiveFileInfo::new), OptionalLong.of(hiveSplit.getFileSplit().getFileSize()), OptionalLong.of(hiveSplit.getFileSplit().getStart()), OptionalLong.of(hiveSplit.getFileSplit().getLength()), hiveSplit.getFileSplit().getFileModifiedTime(), HiveSessionProperties.isVerboseRuntimeStatsEnabled(session), runtimeStats); if (columns.stream().anyMatch(columnHandle -> ((HiveColumnHandle) columnHandle).getColumnType().equals(AGGREGATED))) { checkArgument(columns.stream().allMatch(columnHandle -> ((HiveColumnHandle) columnHandle).getColumnType().equals(AGGREGATED)), "Not all columns are of 'AGGREGATED' type"); if (hiveLayout.isFooterStatsUnreliable()) { throw new PrestoException(HIVE_UNSUPPORTED_FORMAT, format("Partial aggregation pushdown is not supported when footer stats are unreliable. " + "Table %s has file %s with unreliable footer stats. " + "Set session property [catalog-name].pushdown_partial_aggregations_into_scan=false and execute query again.", hiveLayout.getSchemaTableName(), hiveSplit.getFileSplit().getPath())); } return createAggregatedPageSource(aggregatedPageSourceFactories, configuration, session, hiveSplit, hiveLayout, selectedColumns, fileContext, encryptionInformation); } if (hiveLayout.isPushdownFilterEnabled()) { Optional<ConnectorPageSource> selectivePageSource = createSelectivePageSource( selectivePageSourceFactories, configuration, session, hiveSplit, hiveLayout, selectedColumns, hiveStorageTimeZone, typeManager, optimizedRowExpressionCache, splitContext, fileContext, encryptionInformation); if (selectivePageSource.isPresent()) { return selectivePageSource.get(); } } TupleDomain<HiveColumnHandle> effectivePredicate = hiveLayout.getDomainPredicate() .transform(Subfield::getRootName) .transform(hiveLayout.getPredicateColumns()::get); if (shouldSkipBucket(hiveLayout, hiveSplit, splitContext, isLegacyTimestampBucketing(session))) { return new HiveEmptySplitPageSource(); } if (shouldSkipPartition(typeManager, hiveLayout, hiveStorageTimeZone, hiveSplit, splitContext)) { return new HiveEmptySplitPageSource(); } Optional<ConnectorPageSource> pageSource = createHivePageSource( cursorProviders, pageSourceFactories, configuration, session, hiveSplit.getFileSplit(), hiveSplit.getTableBucketNumber(), hiveSplit.getStorage(), splitContext.getDynamicFilterPredicate().map(filter -> filter.transform(handle -> (HiveColumnHandle) handle).intersect(effectivePredicate)).orElse(effectivePredicate), selectedColumns, hiveLayout.getPredicateColumns(), hiveSplit.getPartitionKeys(), hiveStorageTimeZone, typeManager, hiveLayout.getSchemaTableName(), hiveLayout.getPartitionColumns().stream().map(HiveColumnHandle.class::cast).collect(toList()), hiveLayout.getDataColumns(), hiveLayout.getTableParameters(), hiveSplit.getPartitionDataColumnCount(), hiveSplit.getTableToPartitionMapping(), hiveSplit.getBucketConversion(), hiveSplit.isS3SelectPushdownEnabled(), fileContext, hiveLayout.getRemainingPredicate(), hiveLayout.isPushdownFilterEnabled(), rowExpressionService, encryptionInformation, hiveSplit.getRowIdPartitionComponent()); if (pageSource.isPresent()) { return pageSource.get(); } throw new IllegalStateException("Could not find a file reader for split " + hiveSplit); }
@Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "Table testdb.table has file of format org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe that does not support partial aggregation pushdown. " + "Set session property \\[catalog\\-name\\].pushdown_partial_aggregations_into_scan=false and execute query again.") public void testFailsWhenNoAggregatedPageSourceAvailable() { HivePageSourceProvider pageSourceProvider = createPageSourceProvider(); ConnectorPageSource pageSource = pageSourceProvider.createPageSource( new HiveTransactionHandle(), SESSION, getHiveSplit(RCBINARY), getHiveTableLayout(false, true, false), ImmutableList.of(LONG_AGGREGATED_COLUMN), new SplitContext(false), new RuntimeStats()); }
@Override public String toString(final RouteUnit routeUnit) { if (null != ownerName && !Strings.isNullOrEmpty(ownerName.getValue()) && tableName.getValue().equals(ownerName.getValue())) { Set<String> actualTableNames = routeUnit.getActualTableNames(tableName.getValue()); String actualTableName = actualTableNames.isEmpty() ? tableName.getValue().toLowerCase() : actualTableNames.iterator().next(); return tableName.getQuoteCharacter().wrap(actualTableName) + "."; } return toString(); }
@Test void assertOwnerTokenWithNoRouteUnitAndOwnerNameValueIsEmpty() { OwnerToken ownerToken = new OwnerToken(0, 1, new IdentifierValue(""), new IdentifierValue("t_user_detail")); assertThat(ownerToken.toString(), is("")); assertTokenGrid(ownerToken); }
@SuppressWarnings("ReferenceEquality") @Override public void setKeyboardTheme(@NonNull KeyboardTheme theme) { if (theme == mLastSetTheme) return; clearKeyIconsCache(true); mKeysIconBuilders.clear(); mTextWidthCache.clear(); mLastSetTheme = theme; if (mKeyboard != null) setWillNotDraw(false); // the new theme might be of a different size requestLayout(); // Hint to reallocate the buffer if the size changed mKeyboardChanged = true; invalidateAllKeys(); final int keyboardThemeStyleResId = getKeyboardStyleResId(theme); final int[] remoteKeyboardThemeStyleable = theme .getResourceMapping() .getRemoteStyleableArrayFromLocal(R.styleable.AnyKeyboardViewTheme); final int[] remoteKeyboardIconsThemeStyleable = theme .getResourceMapping() .getRemoteStyleableArrayFromLocal(R.styleable.AnyKeyboardViewIconsTheme); final int[] padding = new int[] {0, 0, 0, 0}; int keyTypeFunctionAttrId = R.attr.key_type_function; int keyActionAttrId = R.attr.key_type_action; int keyActionTypeDoneAttrId = R.attr.action_done; int keyActionTypeSearchAttrId = R.attr.action_search; int keyActionTypeGoAttrId = R.attr.action_go; HashSet<Integer> doneLocalAttributeIds = new HashSet<>(); TypedArray a = theme .getPackageContext() .obtainStyledAttributes(keyboardThemeStyleResId, remoteKeyboardThemeStyleable); final int n = a.getIndexCount(); for (int i = 0; i < n; i++) { final int remoteIndex = a.getIndex(i); final int localAttrId = theme.getResourceMapping().getLocalAttrId(remoteKeyboardThemeStyleable[remoteIndex]); if (setValueFromThemeInternal(a, padding, localAttrId, remoteIndex)) { doneLocalAttributeIds.add(localAttrId); if (localAttrId == R.attr.keyBackground) { // keyTypeFunctionAttrId and keyActionAttrId are remote final int[] keyStateAttributes = theme.getResourceMapping().getRemoteStyleableArrayFromLocal(KEY_TYPES); keyTypeFunctionAttrId = keyStateAttributes[0]; keyActionAttrId = keyStateAttributes[1]; } } } a.recycle(); // taking icons int iconSetStyleRes = getKeyboardIconsStyleResId(theme); if (iconSetStyleRes != 0) { a = theme .getPackageContext() .obtainStyledAttributes(iconSetStyleRes, remoteKeyboardIconsThemeStyleable); final int iconsCount = a.getIndexCount(); for (int i = 0; i < iconsCount; i++) { final int remoteIndex = a.getIndex(i); final int localAttrId = theme .getResourceMapping() .getLocalAttrId(remoteKeyboardIconsThemeStyleable[remoteIndex]); if (setKeyIconValueFromTheme(theme, a, localAttrId, remoteIndex)) { doneLocalAttributeIds.add(localAttrId); if (localAttrId == R.attr.iconKeyAction) { // keyActionTypeDoneAttrId and keyActionTypeSearchAttrId and // keyActionTypeGoAttrId are remote final int[] keyStateAttributes = theme.getResourceMapping().getRemoteStyleableArrayFromLocal(ACTION_KEY_TYPES); keyActionTypeDoneAttrId = keyStateAttributes[0]; keyActionTypeSearchAttrId = keyStateAttributes[1]; keyActionTypeGoAttrId = keyStateAttributes[2]; } } } a.recycle(); } // filling what's missing KeyboardTheme fallbackTheme = getKeyboardThemeFactory(getContext()).getFallbackTheme(); final int keyboardFallbackThemeStyleResId = getKeyboardStyleResId(fallbackTheme); a = fallbackTheme .getPackageContext() .obtainStyledAttributes( keyboardFallbackThemeStyleResId, R.styleable.AnyKeyboardViewTheme); final int fallbackCount = a.getIndexCount(); for (int i = 0; i < fallbackCount; i++) { final int index = a.getIndex(i); final int attrId = R.styleable.AnyKeyboardViewTheme[index]; if (doneLocalAttributeIds.contains(attrId)) { continue; } setValueFromThemeInternal(a, padding, attrId, index); } a.recycle(); // taking missing icons int fallbackIconSetStyleId = fallbackTheme.getIconsThemeResId(); a = fallbackTheme .getPackageContext() .obtainStyledAttributes(fallbackIconSetStyleId, R.styleable.AnyKeyboardViewIconsTheme); final int fallbackIconsCount = a.getIndexCount(); for (int i = 0; i < fallbackIconsCount; i++) { final int index = a.getIndex(i); final int attrId = R.styleable.AnyKeyboardViewIconsTheme[index]; if (doneLocalAttributeIds.contains(attrId)) { continue; } setKeyIconValueFromTheme(fallbackTheme, a, attrId, index); } a.recycle(); // creating the key-drawable state provider, as we suppose to have the entire data now mDrawableStatesProvider = new KeyDrawableStateProvider( keyTypeFunctionAttrId, keyActionAttrId, keyActionTypeDoneAttrId, keyActionTypeSearchAttrId, keyActionTypeGoAttrId); // settings. // don't forget that there are THREE padding, // the theme's and the // background image's padding and the // View Drawable keyboardBackground = super.getBackground(); if (keyboardBackground != null) { Rect backgroundPadding = new Rect(); keyboardBackground.getPadding(backgroundPadding); padding[0] += backgroundPadding.left; padding[1] += backgroundPadding.top; padding[2] += backgroundPadding.right; padding[3] += backgroundPadding.bottom; } setPadding(padding[0], padding[1], padding[2], padding[3]); final Resources res = getResources(); final int viewWidth = (getWidth() > 0) ? getWidth() : res.getDisplayMetrics().widthPixels; mKeyboardDimens.setKeyboardMaxWidth(viewWidth - padding[0] - padding[2]); mPaint.setTextSize(mKeyTextSize); }
@Test public void testDoesNotCrashWhenSettingTheme() { final KeyboardThemeFactory keyboardThemeFactory = AnyApplication.getKeyboardThemeFactory(getApplicationContext()); mUnderTest.setKeyboardTheme(keyboardThemeFactory.getAllAddOns().get(2)); mUnderTest.setKeyboardTheme(keyboardThemeFactory.getAllAddOns().get(5)); mUnderTest.setKeyboardTheme(keyboardThemeFactory.getAllAddOns().get(1)); }
@Override public X509Certificate[] getAcceptedIssuers() { return trustManager.getAcceptedIssuers(); }
@Test(dataProvider = "caDataProvider") public void testLoadCA(String path, int count) { String caPath = Resources.getResource(path).getPath(); @Cleanup("shutdownNow") ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); TrustManagerProxy trustManagerProxy = new TrustManagerProxy(caPath, 120, scheduledExecutor); X509Certificate[] x509Certificates = trustManagerProxy.getAcceptedIssuers(); assertNotNull(x509Certificates); assertEquals(Arrays.stream(x509Certificates).count(), count); }
public static String buildErrorMessage(final Throwable throwable) { if (throwable == null) { return ""; } final List<String> messages = dedup(getErrorMessages(throwable)); final String msg = messages.remove(0); final String causeMsg = messages.stream() .filter(s -> !s.isEmpty()) .map(cause -> WordUtils.wrap(PREFIX + cause, 80, "\n\t", true)) .collect(Collectors.joining(System.lineSeparator())); return causeMsg.isEmpty() ? msg : msg + System.lineSeparator() + causeMsg; }
@Test public void shouldDeduplicateMessage() { final Throwable cause = new TestException("Something went wrong"); final Throwable subLevel3 = new TestException("Something went wrong", cause); final Throwable subLevel2 = new TestException("Msg that matches", subLevel3); final Throwable subLevel1 = new TestException("Msg that matches", subLevel2); final Throwable e = new TestException("Msg that matches", subLevel1); assertThat( buildErrorMessage(e), is("Msg that matches" + System.lineSeparator() + "Caused by: Something went wrong") ); }
@Override public void setMonochrome(boolean monochrome) { formats = monochrome ? monochrome() : ansi(); }
@Test void should_print_output_from_after_hooks() { Feature feature = TestFeatureParser.parse("path/test.feature", "" + "Feature: feature name\n" + " Scenario: scenario name\n" + " Given first step\n"); ByteArrayOutputStream out = new ByteArrayOutputStream(); Runtime.builder() .withFeatureSupplier(new StubFeatureSupplier(feature)) .withAdditionalPlugins(new PrettyFormatter(out)) .withRuntimeOptions(new RuntimeOptionsBuilder().setMonochrome().build()) .withBackendSupplier(new StubBackendSupplier( emptyList(), singletonList(new StubStepDefinition("first step", "path/step_definitions.java:3")), singletonList(new StubHookDefinition(testCaseState -> testCaseState.log("printed from hook"))))) .build() .run(); assertThat(out, bytes(equalToCompressingWhiteSpace("" + "Scenario: scenario name # path/test.feature:2\n" + " Given first step # path/step_definitions.java:3\n" + "\n" + " printed from hook\n"))); }
public void fetch(DownloadAction downloadAction, URLService urlService) throws Exception { downloadChecksumFile(downloadAction, urlService.baseRemoteURL()); downloadArtifact(downloadAction, urlService.baseRemoteURL()); }
@Test public void shouldValidateChecksumOnArtifact() throws Exception { when(urlService.baseRemoteURL()).thenReturn("http://10.10.1.1/go/files"); when(checksumFileHandler.url("http://10.10.1.1/go/files", "cruise/10/dev/1/windows")).thenReturn("http://10.10.1.1/go/files/cruise/10/dev/1/windows/cruise-output/md5.checksum"); FetchArtifactBuilder builder = getBuilder(new JobIdentifier("cruise", 10, "1", "dev", "1", "windows", 1L), "log", dest.getPath(), mock(FetchHandler.class), checksumFileHandler); builder.fetch(downloadAction, urlService); verify(downloadAction).perform("http://10.10.1.1/go/files/cruise/10/dev/1/windows/cruise-output/md5.checksum", checksumFileHandler); }
@Override public void deleteBrand(Long id) { // 校验存在 validateBrandExists(id); // 删除 brandMapper.deleteById(id); }
@Test public void testDeleteBrand_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> brandService.deleteBrand(id), BRAND_NOT_EXISTS); }
public Preference<Boolean> getBoolean(@StringRes int prefKey, @BoolRes int defaultValue) { return mRxSharedPreferences.getBoolean( mResources.getString(prefKey), mResources.getBoolean(defaultValue)); }
@Test public void testConvertTopGenericRow() { SharedPrefsHelper.setPrefsValue( "settings_key_ext_kbd_top_row_key", "1fae0220-ded6-11e0-9572-0800200c9a66"); SharedPrefsHelper.setPrefsValue(RxSharedPrefs.CONFIGURATION_VERSION, 10); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); Assert.assertFalse( preferences.contains("ext_kbd_enabled_2_1fae0220-ded6-11e0-9572-0800200c9a66")); new RxSharedPrefs(getApplicationContext(), this::testRestoreFunction); Assert.assertTrue( preferences.contains("ext_kbd_enabled_2_1fae0220-ded6-11e0-9572-0800200c9a66")); Assert.assertTrue( preferences.getBoolean("ext_kbd_enabled_2_1fae0220-ded6-11e0-9572-0800200c9a66", false)); }
public static void extractToken(HttpURLConnection conn, Token token) throws IOException, AuthenticationException { int respCode = conn.getResponseCode(); if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_CREATED || respCode == HttpURLConnection.HTTP_ACCEPTED) { // cookie handler should have already extracted the token. try again // for backwards compatibility if this method is called on a connection // not opened via this instance. token.cookieHandler.put(null, conn.getHeaderFields()); } else if (respCode == HttpURLConnection.HTTP_NOT_FOUND) { LOG.trace("Setting token value to null ({}), resp={}", token, respCode); token.set(null); throw new FileNotFoundException(conn.getURL().toString()); } else { LOG.trace("Setting token value to null ({}), resp={}", token, respCode); token.set(null); throw new AuthenticationException("Authentication failed" + ", URL: " + conn.getURL() + ", status: " + conn.getResponseCode() + ", message: " + conn.getResponseMessage()); } }
@Test public void testExtractTokenCookieHeader() throws Exception { HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); String tokenStr = "foo"; Map<String, List<String>> headers = new HashMap<>(); List<String> cookies = new ArrayList<>(); cookies.add(AuthenticatedURL.AUTH_COOKIE + "=" + tokenStr); headers.put("Set-Cookie", cookies); Mockito.when(conn.getHeaderFields()).thenReturn(headers); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); AuthenticatedURL.extractToken(conn, token); Assert.assertTrue(token.isSet()); }
@Override public boolean match(final String rule) { return rule.matches("^array\\|.+\\|\\d+$"); }
@Test public void testMatch() { assertTrue(arrayGenerator.match("array|111|2")); assertTrue(arrayGenerator.match("array|${int|10-20}|2")); assertFalse(arrayGenerator.match("array|10|a")); assertFalse(arrayGenerator.match("array|10|")); }
public QueryConfiguration applyOverrides(QueryConfigurationOverrides overrides) { Map<String, String> sessionProperties; if (overrides.getSessionPropertiesOverrideStrategy() == OVERRIDE) { sessionProperties = new HashMap<>(overrides.getSessionPropertiesOverride()); } else { sessionProperties = new HashMap<>(this.sessionProperties); if (overrides.getSessionPropertiesOverrideStrategy() == SUBSTITUTE) { sessionProperties.putAll(overrides.getSessionPropertiesOverride()); } } overrides.getSessionPropertiesToRemove().forEach(sessionProperties::remove); return new QueryConfiguration( overrides.getCatalogOverride().orElse(catalog), overrides.getSchemaOverride().orElse(schema), Optional.ofNullable(overrides.getUsernameOverride().orElse(username.orElse(null))), Optional.ofNullable(overrides.getPasswordOverride().orElse(password.orElse(null))), Optional.of(sessionProperties), isReusableTable, Optional.of(partitions)); }
@Test public void testOverrides() { assertEquals( CONFIGURATION_1.applyOverrides(overrides), new QueryConfiguration( CATALOG_OVERRIDE, SCHEMA_OVERRIDE, Optional.of(USERNAME_OVERRIDE), Optional.of(PASSWORD_OVERRIDE), Optional.of(SESSION_PROPERTIES), Optional.of(CLIENT_TAGS), Optional.empty())); assertEquals(CONFIGURATION_2.applyOverrides(overrides), new QueryConfiguration( CATALOG_OVERRIDE, SCHEMA_OVERRIDE, Optional.of(USERNAME_OVERRIDE), Optional.of(PASSWORD_OVERRIDE), Optional.empty(), Optional.empty(), Optional.empty())); }
public StepExpression createExpression(StepDefinition stepDefinition) { List<ParameterInfo> parameterInfos = stepDefinition.parameterInfos(); if (parameterInfos.isEmpty()) { return createExpression( stepDefinition.getPattern(), stepDefinitionDoesNotTakeAnyParameter(stepDefinition), false); } ParameterInfo parameterInfo = parameterInfos.get(parameterInfos.size() - 1); return createExpression( stepDefinition.getPattern(), parameterInfo.getTypeResolver()::resolve, parameterInfo.isTransposed()); }
@Test void docstring_expression_transform_doc_string_to_json_node() { String docString = "{\"hello\": \"world\"}"; String contentType = "json"; registry.defineDocStringType(new DocStringType( JsonNode.class, contentType, (String s) -> objectMapper.convertValue(docString, JsonNode.class))); StepDefinition stepDefinition = new StubStepDefinition("Given some stuff:", JsonNode.class); StepExpression expression = stepExpressionFactory.createExpression(stepDefinition); List<Argument> match = expression.match("Given some stuff:", docString, contentType); JsonNode node = (JsonNode) match.get(0).getValue(); assertThat(node.asText(), equalTo(docString)); }
public static String createTravelDocumentSeed(MrzInfo info) { if (info.getDocumentNumber().length() != 9) { throw new VerificationException("Document number should have length of 9"); } checkMrzDate(info.getDateOfBirth()); checkMrzDate(info.getDateOfExpiry()); StringBuilder sb = new StringBuilder(24); sb.append(info.getDocumentNumber()).append(calculateCheckDigit(info.getDocumentNumber())); sb.append(info.getDateOfBirth()).append(calculateCheckDigit(info.getDateOfBirth())); sb.append(info.getDateOfExpiry()).append(calculateCheckDigit(info.getDateOfExpiry())); return sb.toString(); }
@Test public void createTravelDocumentSeedMrzPositive() { MrzUtils.createTravelDocumentSeed(new MrzInfo("SPECI2014", "SSSSSS", "SSSSSS")); }
@Override @NonNull public Flux<Object> decode(@NonNull Publisher<DataBuffer> input, @NonNull ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { ObjectMapper mapper = getObjectMapper(); Flux<TokenBuffer> tokens = Jackson2Tokenizer.tokenize( Flux.from(input), mapper.getFactory(), mapper, true); ObjectReader reader = getObjectReader(elementType, hints); return tokens .as(LocaleUtils::transform) .handle((tokenBuffer, sink) -> { try { Object value = reader.readValue(tokenBuffer.asParser(getObjectMapper())); logValue(value, hints); if (value != null) { sink.next(value); } } catch (IOException ex) { sink.error(processException(ex)); } }); }
@Test @SneakyThrows public void testDecodeCustomType() { MapperEntityFactory entityFactory = new MapperEntityFactory(); entityFactory.addMapping(QueryParamEntity.class, MapperEntityFactory.defaultMapper(CustomQueryParamEntity.class)); ObjectMapper mapper = new ObjectMapper(); CustomJackson2JsonDecoder decoder = new CustomJackson2JsonDecoder(entityFactory, mapper); ResolvableType type = ResolvableType.forMethodParameter( ReactiveQueryController.class.getMethod("query", QueryParamEntity.class), 0 ); DataBuffer buffer = new DefaultDataBufferFactory().wrap("{}".getBytes()); Object object = decoder.decode(buffer, type, MediaType.APPLICATION_JSON, Collections.emptyMap()); assertTrue(object instanceof CustomQueryParamEntity); }
public static boolean isFalse(Boolean value) { return value != null && !value; }
@SuppressWarnings({"ConstantConditions", "SimplifiableJUnitAssertion"}) @Test public void testIsFalse() { assertEquals(true, TernaryLogic.isFalse(false)); assertEquals(false, TernaryLogic.isFalse(true)); assertEquals(false, TernaryLogic.isFalse(null)); }
public static void checkNotNullAndNotEmpty(String arg, String argName) { checkNotNull(arg, argName); checkArgument( !arg.isEmpty(), "'%s' must not be empty.", argName); }
@Test public void testCheckListNotNullAndNotEmpty() throws Exception { // Should not throw. Validate.checkNotNullAndNotEmpty(VALID_LIST, "list"); // Verify it throws. ExceptionAsserts.assertThrows( IllegalArgumentException.class, "'list' must not be null", () -> Validate.checkNotNullAndNotEmpty(NULL_LIST, "list")); ExceptionAsserts.assertThrows( IllegalArgumentException.class, "'list' must have at least one element", () -> Validate.checkNotNullAndNotEmpty(EMPTY_LIST, "list")); }
@Override public List<Catalogue> sort(List<Catalogue> catalogueTree, SortTypeEnum sortTypeEnum) { log.debug("sort catalogue tree based on id. catalogueTree: {}, sortTypeEnum: {}", catalogueTree, sortTypeEnum); return recursionSortCatalogues(catalogueTree, sortTypeEnum); }
@Test public void sortEmptyTest2() { List<Catalogue> catalogueTree = null; SortTypeEnum sortTypeEnum = SortTypeEnum.ASC; List<Catalogue> resultList = catalogueTreeSortDefaultStrategyTest.sort(catalogueTree, sortTypeEnum); assertEquals(Lists.newArrayList(), resultList); }
@Override public Map<K, V> loadAll(Iterable<? extends K> iterable) throws CacheLoaderException { long startNanos = Timer.nanos(); try { return delegate.get().loadAll(iterable); } finally { loadAllProbe.recordValue(Timer.nanosElapsed(startNanos)); } }
@Test public void loadAll() { Collection<String> keys = asList("key1", "key2"); Map<String, String> values = new HashMap<>(); values.put("key1", "value1"); values.put("key2", "value2"); when(delegate.loadAll(keys)).thenReturn(values); Map<String, String> result = cacheLoader.loadAll(keys); assertSame(values, result); assertProbeCalledOnce("loadAll"); }
@Override public Object decorate(RequestedField field, Object value, SearchUser searchUser) { final List<String> ids = parseIDs(value); final EntityTitleRequest req = ids.stream() .map(id -> new EntityIdentifier(id, FIELD_ENTITY_MAPPER.get(field.name()))) .collect(Collectors.collectingAndThen(Collectors.toList(), EntityTitleRequest::new)); final EntitiesTitleResponse response = entityTitleService.getTitles(req, searchUser); return extractTitles(ids, response.entities()).stream() .collect(Collectors.collectingAndThen(Collectors.toList(), titles -> value instanceof Collection<?> ? titles : unwrapIfSingleResult(titles))); }
@Test void testDecorate() { final EntitiesTitleResponse response = new EntitiesTitleResponse(Collections.singleton(new EntityTitleResponse("123", "streams", "My stream")), Collections.emptySet()); final FieldDecorator decorator = new TitleDecorator((request, permissions) -> response); Assertions.assertThat(decorator.decorate(RequestedField.parse("streams"), "123", TestSearchUser.builder().build())) .isEqualTo("My stream"); }
public static int max(int a, int b, int c) { return Math.max(Math.max(a, b), c); }
@Test public void testMax_doubleArrArr() { System.out.println("max"); double[][] A = { {0.7220180, 0.07121225, 0.6881997}, {-0.2648886, -0.89044952, 0.3700456}, {-0.6391588, 0.44947578, 0.6240573} }; assertEquals(0.7220180, MathEx.max(A), 1E-7); }
@Override public String toString() { return String.valueOf(this.bps); }
@Test public void testToString() { String expected = "1000"; assertEquals(small.toString(), expected); }
public void contains(@Nullable Object rowKey, @Nullable Object columnKey) { if (!checkNotNull(actual).contains(rowKey, columnKey)) { /* * TODO(cpovirk): Consider including information about whether any cell with the given row * *or* column was present. */ failWithActual( simpleFact("expected to contain mapping for row-column key pair"), fact("row key", rowKey), fact("column key", columnKey)); } }
@Test public void containsFailure() { ImmutableTable<String, String, String> table = ImmutableTable.of("row", "col", "val"); expectFailureWhenTestingThat(table).contains("row", "otherCol"); assertThat(expectFailure.getFailure()) .factKeys() .containsExactly( "expected to contain mapping for row-column key pair", "row key", "column key", "but was"); assertThat(expectFailure.getFailure()).factValue("row key").isEqualTo("row"); assertThat(expectFailure.getFailure()).factValue("column key").isEqualTo("otherCol"); }
@Override public Object getKey() { if (key == null) { key = serializationService.toObject(dataKey); } return key; }
@Test public void test_getKey() { assertEquals(key, view.getKey()); }
@Override protected void analyzeDependency(final Dependency dependency, final Engine engine) throws AnalysisException { // batch request component-reports for all dependencies synchronized (FETCH_MUTIX) { if (reports == null) { try { requestDelay(); reports = requestReports(engine.getDependencies()); } catch (TransportException ex) { final String message = ex.getMessage(); final boolean warnOnly = getSettings().getBoolean(Settings.KEYS.ANALYZER_OSSINDEX_WARN_ONLY_ON_REMOTE_ERRORS, false); this.setEnabled(false); if (StringUtils.endsWith(message, "401")) { LOG.error("Invalid credentials for the OSS Index, disabling the analyzer"); throw new AnalysisException("Invalid credentials provided for OSS Index", ex); } else if (StringUtils.endsWith(message, "403")) { LOG.error("OSS Index access forbidden, disabling the analyzer"); throw new AnalysisException("OSS Index access forbidden", ex); } else if (StringUtils.endsWith(message, "429")) { if (warnOnly) { LOG.warn("OSS Index rate limit exceeded, disabling the analyzer", ex); } else { throw new AnalysisException("OSS Index rate limit exceeded, disabling the analyzer", ex); } } else if (warnOnly) { LOG.warn("Error requesting component reports, disabling the analyzer", ex); } else { LOG.debug("Error requesting component reports, disabling the analyzer", ex); throw new AnalysisException("Failed to request component-reports", ex); } } catch (SocketTimeoutException e) { final boolean warnOnly = getSettings().getBoolean(Settings.KEYS.ANALYZER_OSSINDEX_WARN_ONLY_ON_REMOTE_ERRORS, false); this.setEnabled(false); if (warnOnly) { LOG.warn("OSS Index socket timeout, disabling the analyzer", e); } else { LOG.debug("OSS Index socket timeout", e); throw new AnalysisException("Failed to establish socket to OSS Index", e); } } catch (Exception e) { LOG.debug("Error requesting component reports", e); throw new AnalysisException("Failed to request component-reports", e); } } // skip enrichment if we failed to fetch reports if (reports != null) { enrich(dependency); } } }
@Test public void should_analyzeDependency_return_a_dedicated_error_message_when_403_response_from_sonatype() throws Exception { // Given OssIndexAnalyzer analyzer = new OssIndexAnalyzerThrowing403(); analyzer.initialize(getSettings()); Identifier identifier = new PurlIdentifier("maven", "test", "test", "1.0", Confidence.HIGHEST); Dependency dependency = new Dependency(); dependency.addSoftwareIdentifier(identifier); Settings settings = getSettings(); Engine engine = new Engine(settings); engine.setDependencies(Collections.singletonList(dependency)); // When AnalysisException output = new AnalysisException(); try { analyzer.analyzeDependency(dependency, engine); } catch (AnalysisException e) { output = e; } // Then assertEquals("OSS Index access forbidden", output.getMessage()); analyzer.close(); }
@Override public double score(double[] truth, double[] prediction) { return of(truth, prediction); }
@Test public void test() { System.out.println("MSE"); double[] truth = { 83.0, 88.5, 88.2, 89.5, 96.2, 98.1, 99.0, 100.0, 101.2, 104.6, 108.4, 110.8, 112.6, 114.2, 115.7, 116.9 }; double[] prediction = { 83.60082, 86.94973, 88.09677, 90.73065, 96.53551, 97.83067, 98.12232, 99.87776, 103.20861, 105.08598, 107.33369, 109.57251, 112.98358, 113.92898, 115.50214, 117.54028, }; MSE instance = new MSE(); double expResult = 0.80275; double result = instance.score(truth, prediction); assertEquals(expResult, result, 1E-5); }
@Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { Class<?> loadedClass = findLoadedClass(name); if (loadedClass != null) { return loadedClass; } if (isClosed) { throw new ClassNotFoundException("This ClassLoader is closed"); } if (config.shouldAcquire(name)) { loadedClass = PerfStatsCollector.getInstance() .measure("load sandboxed class", () -> maybeInstrumentClass(name)); } else { loadedClass = getParent().loadClass(name); } if (resolve) { resolveClass(loadedClass); } return loadedClass; } }
@Test public void shouldDumpClassesWhenConfigured() throws Exception { Path tempDir = Files.createTempDirectory("SandboxClassLoaderTest"); System.setProperty("robolectric.dumpClassesDirectory", tempDir.toAbsolutePath().toString()); ClassLoader classLoader = new SandboxClassLoader(configureBuilder().build()); classLoader.loadClass(AnExampleClass.class.getName()); try (Stream<Path> stream = Files.list(tempDir)) { List<Path> files = stream.collect(Collectors.toList()); assertThat(files).hasSize(1); assertThat(files.get(0).toAbsolutePath().toString()) .containsMatch("org.robolectric.testing.AnExampleClass-robo-instrumented-\\d+.class"); Files.delete(files.get(0)); } finally { Files.delete(tempDir); System.clearProperty("robolectric.dumpClassesDirectory"); } }
public Object getImplementation() { return implementation; }
@Test public void getImplementation() { assertNull(new MapStoreConfig().getImplementation()); }
Future<Boolean> canRollController(int nodeId) { LOGGER.debugCr(reconciliation, "Determining whether controller pod {} can be rolled", nodeId); return describeMetadataQuorum().map(info -> { boolean canRoll = isQuorumHealthyWithoutNode(nodeId, info); if (!canRoll) { LOGGER.debugCr(reconciliation, "Not restarting controller pod {}. Restart would affect the quorum health", nodeId); } return canRoll; }).recover(error -> { LOGGER.warnCr(reconciliation, "Error determining whether it is safe to restart controller pod {}", nodeId, error); return Future.failedFuture(error); }); }
@Test public void cannotRollControllerWhenTimestampInvalid(VertxTestContext context) { Map<Integer, OptionalLong> controllers = new HashMap<>(); controllers.put(1, OptionalLong.of(10000L)); controllers.put(2, OptionalLong.of(-1)); controllers.put(3, OptionalLong.of(-1)); Admin admin = setUpMocks(1, controllers); KafkaQuorumCheck quorumCheck = new KafkaQuorumCheck(Reconciliation.DUMMY_RECONCILIATION, admin, vertx, CONTROLLER_QUORUM_FETCH_TIMEOUT_MS); quorumCheck.canRollController(3).onComplete(context.succeeding(result -> { context.verify(() -> assertFalse(result)); context.completeNow(); })); }
@SuppressWarnings("unchecked") public static String encode(Type parameter) { if (parameter instanceof NumericType) { return encodeNumeric(((NumericType) parameter)); } else if (parameter instanceof Address) { return encodeAddress((Address) parameter); } else if (parameter instanceof Bool) { return encodeBool((Bool) parameter); } else if (parameter instanceof Bytes) { return encodeBytes((Bytes) parameter); } else if (parameter instanceof DynamicBytes) { return encodeDynamicBytes((DynamicBytes) parameter); } else if (parameter instanceof Utf8String) { return encodeString((Utf8String) parameter); } else if (parameter instanceof StaticArray) { if (DynamicStruct.class.isAssignableFrom( ((StaticArray) parameter).getComponentType())) { return encodeStaticArrayWithDynamicStruct((StaticArray) parameter); } else { return encodeArrayValues((StaticArray) parameter); } } else if (parameter instanceof DynamicStruct) { return encodeDynamicStruct((DynamicStruct) parameter); } else if (parameter instanceof DynamicArray) { return encodeDynamicArray((DynamicArray) parameter); } else if (parameter instanceof PrimitiveType) { return encode(((PrimitiveType) parameter).toSolidityType()); } else { throw new UnsupportedOperationException( "Type cannot be encoded: " + parameter.getClass()); } }
@Test public void testPrimitiveLong() { assertEquals( encode(new Long(0)), ("0000000000000000000000000000000000000000000000000000000000000000")); assertEquals( encode(new Long(java.lang.Long.MIN_VALUE)), ("ffffffffffffffffffffffffffffffffffffffffffffffff8000000000000000")); assertEquals( encode(new Long(java.lang.Long.MAX_VALUE)), ("0000000000000000000000000000000000000000000000007fffffffffffffff")); }
@Override public short getShort(int index) { checkIndex(index, 2); return _getShort(index); }
@Test public void testGetShortAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().getShort(0); } }); }
public static <V> DeferredValue<V> withValue(V value) { if (value == null) { return NULL_VALUE; } DeferredValue<V> deferredValue = new DeferredValue<>(); deferredValue.value = value; deferredValue.valueExists = true; return deferredValue; }
@Test public void test_setOfValues() { assertTrue(deferredSet.contains(DeferredValue.withValue("1"))); assertTrue(deferredSet.contains(DeferredValue.withValue("2"))); assertTrue(deferredSet.contains(DeferredValue.withValue("3"))); assertFalse(deferredSet.contains(DeferredValue.withValue("4"))); }
@Override protected Object createBody() { if (command instanceof MessageRequest) { MessageRequest msgRequest = (MessageRequest) command; byte[] shortMessage = msgRequest.getShortMessage(); if (shortMessage == null || shortMessage.length == 0) { return null; } Alphabet alphabet = Alphabet.parseDataCoding(msgRequest.getDataCoding()); if (SmppUtils.is8Bit(alphabet)) { return shortMessage; } String encoding = ExchangeHelper.getCharsetName(getExchange(), false); if (ObjectHelper.isEmpty(encoding) || !Charset.isSupported(encoding)) { encoding = configuration.getEncoding(); } try { return new String(shortMessage, encoding); } catch (UnsupportedEncodingException e) { LOG.info("Unsupported encoding \"{}\". Using system default encoding.", encoding); } return new String(shortMessage); } return null; }
@Test public void createBodyShouldReturnTheShortMessageIfTheCommandIsAMessageRequest() { DeliverSm command = new DeliverSm(); command.setShortMessage("Hello SMPP world!".getBytes()); message = new SmppMessage(camelContext, command, new SmppConfiguration()); assertEquals("Hello SMPP world!", message.createBody()); }
public CompletableFuture<Void> close() { return close(true, false); }
@Test public void testCompatibilityWithPartitionKeyword() throws PulsarAdminException, PulsarClientException { final String topicName = "persistent://prop/ns-abc/testCompatibilityWithPartitionKeyword"; TopicName topicNameEntity = TopicName.get(topicName); String partition2 = topicNameEntity.getPartition(2).toString(); // Create a non-partitioned topic with -partition- keyword Producer<byte[]> producer = pulsarClient.newProducer() .topic(partition2) .create(); List<String> topics = admin.topics().getList("prop/ns-abc"); // Close previous producer to simulate reconnect producer.close(); // Disable auto topic creation conf.setAllowAutoTopicCreation(false); // Check the topic exist in the list. Assert.assertTrue(topics.contains(partition2)); // Check this topic has no partition metadata. Assert.assertThrows(PulsarAdminException.NotFoundException.class, () -> admin.topics().getPartitionedTopicMetadata(topicName)); // Reconnect to the broker and expect successful because the topic has existed in the broker. producer = pulsarClient.newProducer() .topic(partition2) .create(); producer.close(); // Check the topic exist in the list again. Assert.assertTrue(topics.contains(partition2)); // Check this topic has no partition metadata again. Assert.assertThrows(PulsarAdminException.NotFoundException.class, () -> admin.topics().getPartitionedTopicMetadata(topicName)); }
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) { return decoder.decodeFunctionResult(rawInput, outputParameters); }
@Test public void testDecodeStructMultipleDynamicStaticArray3() { String rawInput = "0x00000000000000000000000000000000000000000000000000000000000000a0" + "00000000000000000000000000000000000000000000000000000000000003c0" + "00000000000000000000000000000000000000000000000000000000000004a0" + "00000000000000000000000000000000000000000000000000000000000005a0" + "00000000000000000000000000000000000000000000000000000000000008e0" + "0000000000000000000000000000000000000000000000000000000000000060" + "0000000000000000000000000000000000000000000000000000000000000160" + "0000000000000000000000000000000000000000000000000000000000000220" + "0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000040" + "0000000000000000000000000000000000000000000000000000000000000080" + "0000000000000000000000000000000000000000000000000000000000000001" + "3400000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000009" + "6e6573746564466f6f0000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000040" + "0000000000000000000000000000000000000000000000000000000000000060" + "0000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000040" + "0000000000000000000000000000000000000000000000000000000000000080" + "0000000000000000000000000000000000000000000000000000000000000001" + "3400000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000009" + "6e6573746564466f6f0000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000003" + "000000000000000000000000000000000000000000000000000000000000007b" + "000000000000000000000000000000000000000000000000000000000000007b" + "000000000000000000000000000000000000000000000000000000000000000c" + "0000000000000000000000000000000000000000000000000000000000000021" + "0000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000001" + "0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000040" + "0000000000000000000000000000000000000000000000000000000000000080" + "0000000000000000000000000000000000000000000000000000000000000002" + "6964000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000004" + "6e616d6500000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000003" + "0000000000000000000000000000000000000000000000000000000000000060" + "0000000000000000000000000000000000000000000000000000000000000160" + "0000000000000000000000000000000000000000000000000000000000000260" + "0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000040" + "0000000000000000000000000000000000000000000000000000000000000080" + "0000000000000000000000000000000000000000000000000000000000000001" + "3400000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000009" + "6e6573746564466f6f0000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000040" + "0000000000000000000000000000000000000000000000000000000000000080" + "0000000000000000000000000000000000000000000000000000000000000001" + "3400000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000009" + "6e6573746564466f6f0000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000040" + "0000000000000000000000000000000000000000000000000000000000000060" + "0000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000060" + "0000000000000000000000000000000000000000000000000000000000000120" + "00000000000000000000000000000000000000000000000000000000000001e0" + "0000000000000000000000000000000000000000000000000000000000000040" + "0000000000000000000000000000000000000000000000000000000000000080" + "0000000000000000000000000000000000000000000000000000000000000002" + "6964000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000004" + "6e616d6500000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000040" + "0000000000000000000000000000000000000000000000000000000000000080" + "0000000000000000000000000000000000000000000000000000000000000002" + "6964000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000004" + "6e616d6500000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000040" + "0000000000000000000000000000000000000000000000000000000000000080" + "0000000000000000000000000000000000000000000000000000000000000002" + "6964000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000004" + "6e616d6500000000000000000000000000000000000000000000000000000000"; assertEquals( FunctionReturnDecoder.decode( rawInput, AbiV2TestFixture.idNarBarFooNarFooArraysFunction2.getOutputParameters()), Arrays.asList( new StaticArray3<>( AbiV2TestFixture.Nar.class, new AbiV2TestFixture.Nar( new AbiV2TestFixture.Nuu( new AbiV2TestFixture.Foo("4", "nestedFoo"))), new AbiV2TestFixture.Nar( new AbiV2TestFixture.Nuu(new AbiV2TestFixture.Foo("", ""))), new AbiV2TestFixture.Nar( new AbiV2TestFixture.Nuu( new AbiV2TestFixture.Foo("4", "nestedFoo")))), new DynamicArray<>( AbiV2TestFixture.Bar.class, new AbiV2TestFixture.Bar( BigInteger.valueOf(123), BigInteger.valueOf(123)), new AbiV2TestFixture.Bar( BigInteger.valueOf(12), BigInteger.valueOf(33)), new AbiV2TestFixture.Bar(BigInteger.ZERO, BigInteger.ZERO)), new DynamicArray<>( AbiV2TestFixture.Foo.class, new AbiV2TestFixture.Foo("id", "name")), new DynamicArray<>( AbiV2TestFixture.Nar.class, new AbiV2TestFixture.Nar( new AbiV2TestFixture.Nuu( new AbiV2TestFixture.Foo("4", "nestedFoo"))), new AbiV2TestFixture.Nar( new AbiV2TestFixture.Nuu( new AbiV2TestFixture.Foo("4", "nestedFoo"))), new AbiV2TestFixture.Nar( new AbiV2TestFixture.Nuu( new AbiV2TestFixture.Foo("", "")))), new StaticArray3<>( AbiV2TestFixture.Foo.class, new AbiV2TestFixture.Foo("id", "name"), new AbiV2TestFixture.Foo("id", "name"), new AbiV2TestFixture.Foo("id", "name")))); }
void activate(long newNextWriteOffset) { if (active()) { throw new RuntimeException("Can't activate already active OffsetControlManager."); } if (newNextWriteOffset < 0) { throw new RuntimeException("Invalid negative newNextWriteOffset " + newNextWriteOffset + "."); } // Before switching to active, create an in-memory snapshot at the last committed // offset. This is required because the active controller assumes that there is always // an in-memory snapshot at the last committed offset. snapshotRegistry.idempotentCreateSnapshot(lastStableOffset); this.nextWriteOffset = newNextWriteOffset; metrics.setActive(true); }
@Test public void testActivateFailsIfAlreadyActive() { OffsetControlManager offsetControl = new OffsetControlManager.Builder().build(); offsetControl.activate(1000L); assertEquals("Can't activate already active OffsetControlManager.", assertThrows(RuntimeException.class, () -> offsetControl.activate(2000L)). getMessage()); }
public static <InputT, OutputT> OnTimerInvoker<InputT, OutputT> forTimer( DoFn<InputT, OutputT> fn, String timerId) { return ByteBuddyOnTimerInvokerFactory.only().forTimer(fn, timerId); }
@Test public void testStableName() { OnTimerInvoker<Void, Void> invoker = OnTimerInvokers.forTimer( new StableNameTestDoFn(), TimerDeclaration.PREFIX + StableNameTestDoFn.TIMER_ID); assertThat( invoker.getClass().getName(), equalTo( String.format( "%s$%s$%s$%s", StableNameTestDoFn.class.getName(), OnTimerInvoker.class.getSimpleName(), "tstimeridwithspecialChars" /* alphanum only; human readable but not unique */, "dHMtdGltZXItaWQud2l0aCBzcGVjaWFsQ2hhcnN7fQ" /* base64 encoding of UTF-8 timerId */))); }
@Override public CompletableFuture<List<DescribedGroup>> shareGroupDescribe( RequestContext context, List<String> groupIds) { if (!isActive.get()) { return CompletableFuture.completedFuture(ShareGroupDescribeRequest.getErrorDescribedGroupList( groupIds, Errors.COORDINATOR_NOT_AVAILABLE )); } final List<CompletableFuture<List<ShareGroupDescribeResponseData.DescribedGroup>>> futures = new ArrayList<>(groupIds.size()); final Map<TopicPartition, List<String>> groupsByTopicPartition = new HashMap<>(); groupIds.forEach(groupId -> { if (isGroupIdNotEmpty(groupId)) { groupsByTopicPartition .computeIfAbsent(topicPartitionFor(groupId), __ -> new ArrayList<>()) .add(groupId); } else { futures.add(CompletableFuture.completedFuture(Collections.singletonList( new ShareGroupDescribeResponseData.DescribedGroup() .setGroupId(null) .setErrorCode(Errors.INVALID_GROUP_ID.code()) ))); } }); groupsByTopicPartition.forEach((topicPartition, groupList) -> { CompletableFuture<List<ShareGroupDescribeResponseData.DescribedGroup>> future = runtime.scheduleReadOperation( "share-group-describe", topicPartition, (coordinator, lastCommittedOffset) -> coordinator.shareGroupDescribe(groupIds, lastCommittedOffset) ).exceptionally(exception -> handleOperationException( "share-group-describe", groupList, exception, (error, __) -> ShareGroupDescribeRequest.getErrorDescribedGroupList(groupList, error) )); futures.add(future); }); return FutureUtils.combineFutures(futures, ArrayList::new, List::addAll); }
@Test public void testShareGroupDescribe() throws InterruptedException, ExecutionException { CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime(); GroupCoordinatorService service = new GroupCoordinatorService( new LogContext(), createConfig(), runtime, new GroupCoordinatorMetrics(), createConfigManager() ); int partitionCount = 2; service.startup(() -> partitionCount); ShareGroupDescribeResponseData.DescribedGroup describedGroup1 = new ShareGroupDescribeResponseData.DescribedGroup() .setGroupId("share-group-id-1"); ShareGroupDescribeResponseData.DescribedGroup describedGroup2 = new ShareGroupDescribeResponseData.DescribedGroup() .setGroupId("share-group-id-2"); List<ShareGroupDescribeResponseData.DescribedGroup> expectedDescribedGroups = Arrays.asList( describedGroup1, describedGroup2 ); when(runtime.scheduleReadOperation( ArgumentMatchers.eq("share-group-describe"), ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 0)), ArgumentMatchers.any() )).thenReturn(CompletableFuture.completedFuture(Collections.singletonList(describedGroup1))); CompletableFuture<Object> describedGroupFuture = new CompletableFuture<>(); when(runtime.scheduleReadOperation( ArgumentMatchers.eq("share-group-describe"), ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 1)), ArgumentMatchers.any() )).thenReturn(describedGroupFuture); CompletableFuture<List<ShareGroupDescribeResponseData.DescribedGroup>> future = service.shareGroupDescribe(requestContext(ApiKeys.SHARE_GROUP_DESCRIBE), Arrays.asList("share-group-id-1", "share-group-id-2")); assertFalse(future.isDone()); describedGroupFuture.complete(Collections.singletonList(describedGroup2)); assertEquals(expectedDescribedGroups, future.get()); }
public static Builder start() { return new Builder(); }
@Test public void testRegisterOnlyOnceAllowed() { DecimalEncodedValueImpl speedEnc = new DecimalEncodedValueImpl("speed", 5, 5, false); EncodingManager.start().add(speedEnc).build(); assertThrows(IllegalStateException.class, () -> EncodingManager.start().add(speedEnc).build()); }
@SuppressWarnings("unchecked") RestartRequest recordToRestartRequest(ConsumerRecord<String, byte[]> record, SchemaAndValue value) { String connectorName = record.key().substring(RESTART_PREFIX.length()); if (!(value.value() instanceof Map)) { log.error("Ignoring restart request because the value is not a Map but is {}", className(value.value())); return null; } Map<String, Object> valueAsMap = (Map<String, Object>) value.value(); Object failed = valueAsMap.get(ONLY_FAILED_FIELD_NAME); boolean onlyFailed; if (!(failed instanceof Boolean)) { log.warn("Invalid data for restart request '{}' field should be a Boolean but is {}, defaulting to {}", ONLY_FAILED_FIELD_NAME, className(failed), ONLY_FAILED_DEFAULT); onlyFailed = ONLY_FAILED_DEFAULT; } else { onlyFailed = (Boolean) failed; } Object withTasks = valueAsMap.get(INCLUDE_TASKS_FIELD_NAME); boolean includeTasks; if (!(withTasks instanceof Boolean)) { log.warn("Invalid data for restart request '{}' field should be a Boolean but is {}, defaulting to {}", INCLUDE_TASKS_FIELD_NAME, className(withTasks), INCLUDE_TASKS_DEFAULT); includeTasks = INCLUDE_TASKS_DEFAULT; } else { includeTasks = (Boolean) withTasks; } return new RestartRequest(connectorName, onlyFailed, includeTasks); }
@Test public void testRecordToRestartRequest() { ConsumerRecord<String, byte[]> record = new ConsumerRecord<>(TOPIC, 0, 0, 0L, TimestampType.CREATE_TIME, 0, 0, RESTART_CONNECTOR_KEYS.get(0), CONFIGS_SERIALIZED.get(0), new RecordHeaders(), Optional.empty()); Struct struct = RESTART_REQUEST_STRUCTS.get(0); SchemaAndValue schemaAndValue = new SchemaAndValue(struct.schema(), structToMap(struct)); RestartRequest restartRequest = configStorage.recordToRestartRequest(record, schemaAndValue); assertEquals(CONNECTOR_1_NAME, restartRequest.connectorName()); assertEquals(struct.getBoolean(INCLUDE_TASKS_FIELD_NAME), restartRequest.includeTasks()); assertEquals(struct.getBoolean(ONLY_FAILED_FIELD_NAME), restartRequest.onlyFailed()); }
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers); if (filteredOpenAPI == null) { return filteredOpenAPI; } OpenAPI clone = new OpenAPI(); clone.info(filteredOpenAPI.getInfo()); clone.openapi(filteredOpenAPI.getOpenapi()); clone.jsonSchemaDialect(filteredOpenAPI.getJsonSchemaDialect()); clone.setSpecVersion(filteredOpenAPI.getSpecVersion()); clone.setExtensions(filteredOpenAPI.getExtensions()); clone.setExternalDocs(filteredOpenAPI.getExternalDocs()); clone.setSecurity(filteredOpenAPI.getSecurity()); clone.setServers(filteredOpenAPI.getServers()); clone.tags(filteredOpenAPI.getTags() == null ? null : new ArrayList<>(openAPI.getTags())); final Set<String> allowedTags = new HashSet<>(); final Set<String> filteredTags = new HashSet<>(); Paths clonedPaths = new Paths(); if (filteredOpenAPI.getPaths() != null) { for (String resourcePath : filteredOpenAPI.getPaths().keySet()) { PathItem pathItem = filteredOpenAPI.getPaths().get(resourcePath); PathItem filteredPathItem = filterPathItem(filter, pathItem, resourcePath, params, cookies, headers); PathItem clonedPathItem = cloneFilteredPathItem(filter,filteredPathItem, resourcePath, params, cookies, headers, allowedTags, filteredTags); if (clonedPathItem != null) { if (!clonedPathItem.readOperations().isEmpty()) { clonedPaths.addPathItem(resourcePath, clonedPathItem); } } } clone.paths(clonedPaths); } filteredTags.removeAll(allowedTags); final List<Tag> tags = clone.getTags(); if (tags != null && !filteredTags.isEmpty()) { tags.removeIf(tag -> filteredTags.contains(tag.getName())); if (clone.getTags().isEmpty()) { clone.setTags(null); } } if (filteredOpenAPI.getWebhooks() != null) { for (String resourcePath : filteredOpenAPI.getWebhooks().keySet()) { PathItem pathItem = filteredOpenAPI.getPaths().get(resourcePath); PathItem filteredPathItem = filterPathItem(filter, pathItem, resourcePath, params, cookies, headers); PathItem clonedPathItem = cloneFilteredPathItem(filter,filteredPathItem, resourcePath, params, cookies, headers, allowedTags, filteredTags); if (clonedPathItem != null) { if (!clonedPathItem.readOperations().isEmpty()) { clone.addWebhooks(resourcePath, clonedPathItem); } } } } if (filteredOpenAPI.getComponents() != null) { clone.components(new Components()); clone.getComponents().setSchemas(filterComponentsSchema(filter, filteredOpenAPI.getComponents().getSchemas(), params, cookies, headers)); clone.getComponents().setSecuritySchemes(filteredOpenAPI.getComponents().getSecuritySchemes()); clone.getComponents().setCallbacks(filteredOpenAPI.getComponents().getCallbacks()); clone.getComponents().setExamples(filteredOpenAPI.getComponents().getExamples()); clone.getComponents().setExtensions(filteredOpenAPI.getComponents().getExtensions()); clone.getComponents().setHeaders(filteredOpenAPI.getComponents().getHeaders()); clone.getComponents().setLinks(filteredOpenAPI.getComponents().getLinks()); clone.getComponents().setParameters(filteredOpenAPI.getComponents().getParameters()); clone.getComponents().setRequestBodies(filteredOpenAPI.getComponents().getRequestBodies()); clone.getComponents().setResponses(filteredOpenAPI.getComponents().getResponses()); clone.getComponents().setPathItems(filteredOpenAPI.getComponents().getPathItems()); } if (filter.isRemovingUnreferencedDefinitions()) { clone = removeBrokenReferenceDefinitions(clone); } return clone; }
@Test(description = "Clone should retain any 'deperecated' flags present on operations") public void cloneRetainDeperecatedFlags() throws IOException { final OpenAPI openAPI = getOpenAPI(RESOURCE_DEPRECATED_OPERATIONS); final RemoveUnreferencedDefinitionsFilter remover = new RemoveUnreferencedDefinitionsFilter(); final OpenAPI filtered = new SpecFilter().filter(openAPI, remover, null, null, null); Operation operation = filtered.getPaths().get("/test").getGet(); Boolean deprectedFlag = operation.getDeprecated(); assertNotNull(deprectedFlag); assertEquals(deprectedFlag, Boolean.TRUE); }
@Override public Double getNumber( Object object ) throws KettleValueException { try { if ( isNull( object ) ) { return null; } switch ( type ) { case TYPE_NUMBER: switch ( storageType ) { case STORAGE_TYPE_NORMAL: return (Double) object; case STORAGE_TYPE_BINARY_STRING: return (Double) convertBinaryStringToNativeType( (byte[]) object ); case STORAGE_TYPE_INDEXED: return (Double) index[( (Integer) object ).intValue()]; default: throw new KettleValueException( toString() + " : Unknown storage type " + storageType + " specified." ); } case TYPE_STRING: switch ( storageType ) { case STORAGE_TYPE_NORMAL: return convertStringToNumber( (String) object ); case STORAGE_TYPE_BINARY_STRING: return convertStringToNumber( (String) convertBinaryStringToNativeType( (byte[]) object ) ); case STORAGE_TYPE_INDEXED: return convertStringToNumber( (String) index[( (Integer) object ).intValue()] ); default: throw new KettleValueException( toString() + " : Unknown storage type " + storageType + " specified." ); } case TYPE_DATE: switch ( storageType ) { case STORAGE_TYPE_NORMAL: return convertDateToNumber( (Date) object ); case STORAGE_TYPE_BINARY_STRING: return convertDateToNumber( (Date) convertBinaryStringToNativeType( (byte[]) object ) ); case STORAGE_TYPE_INDEXED: return new Double( ( (Date) index[( (Integer) object ).intValue()] ).getTime() ); default: throw new KettleValueException( toString() + " : Unknown storage type " + storageType + " specified." ); } case TYPE_INTEGER: switch ( storageType ) { case STORAGE_TYPE_NORMAL: return new Double( ( (Long) object ).doubleValue() ); case STORAGE_TYPE_BINARY_STRING: return new Double( ( (Long) convertBinaryStringToNativeType( (byte[]) object ) ).doubleValue() ); case STORAGE_TYPE_INDEXED: return new Double( ( (Long) index[( (Integer) object ).intValue()] ).doubleValue() ); default: throw new KettleValueException( toString() + " : Unknown storage type " + storageType + " specified." ); } case TYPE_BIGNUMBER: switch ( storageType ) { case STORAGE_TYPE_NORMAL: return new Double( ( (BigDecimal) object ).doubleValue() ); case STORAGE_TYPE_BINARY_STRING: return new Double( ( (BigDecimal) convertBinaryStringToNativeType( (byte[]) object ) ).doubleValue() ); case STORAGE_TYPE_INDEXED: return new Double( ( (BigDecimal) index[( (Integer) object ).intValue()] ).doubleValue() ); default: throw new KettleValueException( toString() + " : Unknown storage type " + storageType + " specified." ); } case TYPE_BOOLEAN: switch ( storageType ) { case STORAGE_TYPE_NORMAL: return convertBooleanToNumber( (Boolean) object ); case STORAGE_TYPE_BINARY_STRING: return convertBooleanToNumber( (Boolean) convertBinaryStringToNativeType( (byte[]) object ) ); case STORAGE_TYPE_INDEXED: return convertBooleanToNumber( (Boolean) index[( (Integer) object ).intValue()] ); default: throw new KettleValueException( toString() + " : Unknown storage type " + storageType + " specified." ); } case TYPE_BINARY: throw new KettleValueException( toString() + " : I don't know how to convert binary values to numbers." ); case TYPE_SERIALIZABLE: throw new KettleValueException( toString() + " : I don't know how to convert serializable values to numbers." ); default: throw new KettleValueException( toString() + " : Unknown type " + type + " specified." ); } } catch ( Exception e ) { throw new KettleValueException( "Unexpected conversion error while converting value [" + toString() + "] to a Number", e ); } }
@Test( expected = KettleValueException.class ) public void testGetNumberThrowsKettleValueException() throws KettleValueException { ValueMetaBase valueMeta = new ValueMetaNumber(); valueMeta.getNumber( "1234567890" ); }
public static long acquireMinutesBetween(final LocalDateTime start, final LocalDateTime end) { return start.until(end, ChronoUnit.MINUTES); }
@Test public void testAcquireMinutesBetween() { LocalDateTime start = LocalDateTime.now(); LocalDateTime end = start.plusMinutes(3); assertEquals(3, DateUtils.acquireMinutesBetween(start, end)); }
public InetSocketAddress getListenerAddress() { return checkNotNull(httpServer, "httpServer").getConnectorAddress(0); }
@Test void testPortRanges() throws Exception { WebApp app = WebApps.$for("test", this).start(); String baseUrl = baseUrl(app); WebApp app1 = null; WebApp app2 = null; WebApp app3 = null; WebApp app4 = null; WebApp app5 = null; try { int port = ServerSocketUtil.waitForPort(48000, 60); assertEquals("foo", getContent(baseUrl + "test/foo").trim()); app1 = WebApps.$for("test", this).at(port).start(); assertEquals(port, app1.getListenerAddress().getPort()); app2 = WebApps.$for("test", this).at("0.0.0.0", port, true).start(); assertTrue(app2.getListenerAddress().getPort() > port); Configuration conf = new Configuration(); port = ServerSocketUtil.waitForPort(47000, 60); app3 = WebApps.$for("test", this).at(port).withPortRange(conf, "abc"). start(); assertEquals(port, app3.getListenerAddress().getPort()); ServerSocketUtil.waitForPort(46000, 60); conf.set("abc", "46000-46500"); app4 = WebApps.$for("test", this).at(port).withPortRange(conf, "abc"). start(); assertEquals(46000, app4.getListenerAddress().getPort()); app5 = WebApps.$for("test", this).withPortRange(conf, "abc").start(); assertTrue(app5.getListenerAddress().getPort() > 46000); } finally { stopWebApp(app); stopWebApp(app1); stopWebApp(app2); stopWebApp(app3); stopWebApp(app4); stopWebApp(app5); } }
@Override public double getSmallestNonZeroValue() { if (minStorableValue != 0 || negateReverseDirection) throw new IllegalStateException("getting the smallest non-zero value is not possible if minValue!=0 or negateReverseDirection"); return factor; }
@Test public void smallestNonZeroValue() { assertSmallestNonZeroValue(new DecimalEncodedValueImpl("test", 5, 10, true), 10); assertSmallestNonZeroValue(new DecimalEncodedValueImpl("test", 10, 10, true), 10); assertSmallestNonZeroValue(new DecimalEncodedValueImpl("test", 5, 5, true), 5); assertSmallestNonZeroValue(new DecimalEncodedValueImpl("test", 5, 1, true), 1); assertSmallestNonZeroValue(new DecimalEncodedValueImpl("test", 5, 0.5, true), 0.5); assertSmallestNonZeroValue(new DecimalEncodedValueImpl("test", 5, 0.1, true), 0.1); assertTrue(assertThrows(IllegalStateException.class, () -> new DecimalEncodedValueImpl("test", 5, 0, 5, true, false, false).getSmallestNonZeroValue()) .getMessage().contains("getting the smallest non-zero value is not possible")); }
@Override public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException { final AttributedList<Path> children = new AttributedList<Path>(); // At least one entry successfully parsed boolean success = false; // Call hook for those implementors which need to perform some action upon the list after it has been created // from the server stream, but before any clients see the list parser.preParse(replies); for(String line : replies) { final FTPFile f = parser.parseFTPEntry(line); if(null == f) { continue; } final String name = f.getName(); if(!success) { if(lenient) { // Workaround for #2410. STAT only returns ls of directory itself // Workaround for #2434. STAT of symbolic link directory only lists the directory itself. if(directory.getName().equals(name)) { log.warn(String.format("Skip %s matching parent directory name", f.getName())); continue; } if(name.contains(String.valueOf(Path.DELIMITER))) { if(!name.startsWith(directory.getAbsolute() + Path.DELIMITER)) { // Workaround for #2434. log.warn(String.format("Skip %s with delimiter in name", name)); continue; } } } } success = true; if(name.equals(".") || name.equals("..")) { if(log.isDebugEnabled()) { log.debug(String.format("Skip %s", f.getName())); } continue; } final Path parsed = new Path(directory, PathNormalizer.name(name), f.getType() == FTPFile.DIRECTORY_TYPE ? EnumSet.of(Path.Type.directory) : EnumSet.of(Path.Type.file)); switch(f.getType()) { case FTPFile.SYMBOLIC_LINK_TYPE: parsed.setType(EnumSet.of(Path.Type.file, Path.Type.symboliclink)); // Symbolic link target may be an absolute or relative path final String target = f.getLink(); if(StringUtils.isBlank(target)) { log.warn(String.format("Missing symbolic link target for %s", parsed)); final EnumSet<Path.Type> type = parsed.getType(); type.remove(Path.Type.symboliclink); } else if(StringUtils.startsWith(target, String.valueOf(Path.DELIMITER))) { parsed.setSymlinkTarget(new Path(PathNormalizer.normalize(target), EnumSet.of(Path.Type.file))); } else if(StringUtils.equals("..", target)) { parsed.setSymlinkTarget(directory); } else if(StringUtils.equals(".", target)) { parsed.setSymlinkTarget(parsed); } else { parsed.setSymlinkTarget(new Path(directory, target, EnumSet.of(Path.Type.file))); } break; } if(parsed.isFile()) { parsed.attributes().setSize(f.getSize()); } parsed.attributes().setOwner(f.getUser()); parsed.attributes().setGroup(f.getGroup()); Permission.Action u = Permission.Action.none; if(f.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION)) { u = u.or(Permission.Action.read); } if(f.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION)) { u = u.or(Permission.Action.write); } if(f.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION)) { u = u.or(Permission.Action.execute); } Permission.Action g = Permission.Action.none; if(f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION)) { g = g.or(Permission.Action.read); } if(f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION)) { g = g.or(Permission.Action.write); } if(f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION)) { g = g.or(Permission.Action.execute); } Permission.Action o = Permission.Action.none; if(f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION)) { o = o.or(Permission.Action.read); } if(f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION)) { o = o.or(Permission.Action.write); } if(f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION)) { o = o.or(Permission.Action.execute); } final Permission permission = new Permission(u, g, o); if(f instanceof FTPExtendedFile) { permission.setSetuid(((FTPExtendedFile) f).isSetuid()); permission.setSetgid(((FTPExtendedFile) f).isSetgid()); permission.setSticky(((FTPExtendedFile) f).isSticky()); } if(!Permission.EMPTY.equals(permission)) { parsed.attributes().setPermission(permission); } final Calendar timestamp = f.getTimestamp(); if(timestamp != null) { parsed.attributes().setModificationDate(timestamp.getTimeInMillis()); } children.add(parsed); } if(!success) { throw new FTPInvalidListException(children); } return children; }
@Test public void testStickyBit() throws Exception { final AttributedList<Path> list = new FTPListResponseReader(new FTPParserSelector().getParser("UNIX")) .read(new Path("/", EnumSet.of(Path.Type.directory)), Collections.singletonList("-rwsrwSr-T 1 dkocher dkocher 0 Sep 6 22:27 t") ); final Path parsed = list.get(new Path("/t", EnumSet.of(Path.Type.file))); assertNotNull(parsed); assertTrue(parsed.attributes().getPermission().isSticky()); assertTrue(parsed.attributes().getPermission().isSetuid()); assertTrue(parsed.attributes().getPermission().isSetgid()); assertEquals(new Permission("rwsrwSr-T"), parsed.attributes().getPermission()); }
@JsonCreator public static ModelId of(String id) { Preconditions.checkArgument(StringUtils.isNotBlank(id), "ID must not be blank"); return new AutoValue_ModelId(id); }
@Test public void ensureIdIsNotBlank() { assertThatThrownBy(() -> ModelId.of(null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("ID must not be blank"); assertThatThrownBy(() -> ModelId.of("")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("ID must not be blank"); assertThatThrownBy(() -> ModelId.of(" \n\r\t")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("ID must not be blank"); }
Schema getAvroCompatibleSchema() { return avroCompatibleSchema; }
@Test public void shouldDropOptionalFromRootArraySchema() { // Given: final Schema schema = SchemaBuilder .array(Schema.OPTIONAL_INT64_SCHEMA) .optional() .build(); // When: final AvroDataTranslator translator = new AvroDataTranslator(schema, AvroProperties.DEFAULT_AVRO_SCHEMA_FULL_NAME); // Then: assertThat("Root required", translator.getAvroCompatibleSchema().isOptional(), is(false)); }
public StepDataInterface getStepData() { return new ElasticSearchBulkData(); }
@Test public void testGetStepData() { ElasticSearchBulkMeta esbm = new ElasticSearchBulkMeta(); StepDataInterface sdi = esbm.getStepData(); assertTrue( sdi instanceof ElasticSearchBulkData ); }
@Override public String pluginNamed() { return PluginEnum.LOGGING_KAFKA.getName(); }
@Test public void testPluginNamed() { Assertions.assertEquals(loggingKafkaPluginDataHandler.pluginNamed(), "loggingKafka"); }
void fetchAndRunCommands() { lastPollTime.set(clock.instant()); final List<QueuedCommand> commands = commandStore.getNewCommands(NEW_CMDS_TIMEOUT); if (commands.isEmpty()) { if (!commandTopicExists.get()) { commandTopicDeleted = true; } return; } final List<QueuedCommand> compatibleCommands = checkForIncompatibleCommands(commands); final Optional<QueuedCommand> terminateCmd = findTerminateCommand(compatibleCommands, commandDeserializer); if (terminateCmd.isPresent()) { terminateCluster(terminateCmd.get().getAndDeserializeCommand(commandDeserializer)); return; } LOG.debug("Found {} new writes to command topic", compatibleCommands.size()); for (final QueuedCommand command : compatibleCommands) { if (closed) { return; } executeStatement(command); } }
@Test public void shouldEarlyOutIfNewCommandsContainsTerminate() { // Given: givenQueuedCommands(queuedCommand1, queuedCommand2, queuedCommand3); when(queuedCommand2.getAndDeserializeCommand(commandDeserializer)).thenReturn(clusterTerminate); // When: commandRunner.fetchAndRunCommands(); // Then: verify(statementExecutor, never()).handleRestore(queuedCommand1); verify(statementExecutor, never()).handleRestore(queuedCommand2); verify(statementExecutor, never()).handleRestore(queuedCommand3); }
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception { CruiseConfig configForEdit; CruiseConfig config; LOGGER.debug("[Config Save] Loading config holder"); configForEdit = deserializeConfig(content); if (callback != null) callback.call(configForEdit); config = preprocessAndValidate(configForEdit); return new GoConfigHolder(config, configForEdit); }
@Test void shouldSupportEmptyPipelineGroup() throws Exception { PipelineConfigs group = new BasicPipelineConfigs("defaultGroup", new Authorization()); CruiseConfig config = new BasicCruiseConfig(group); ByteArrayOutputStream stream = new ByteArrayOutputStream(); new MagicalGoConfigXmlWriter(configCache, ConfigElementImplementationRegistryMother.withNoPlugins()).write(config, stream, true); GoConfigHolder configHolder = new MagicalGoConfigXmlLoader(new ConfigCache(), ConfigElementImplementationRegistryMother.withNoPlugins()) .loadConfigHolder(stream.toString()); assertThat(configHolder.config.findGroup("defaultGroup")).isEqualTo(group); }
public void removeBroker(final String addr, String clusterName, String brokerName, long brokerId, final long timeoutMillis) throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQBrokerException { RemoveBrokerRequestHeader requestHeader = new RemoveBrokerRequestHeader(); requestHeader.setBrokerClusterName(clusterName); requestHeader.setBrokerName(brokerName); requestHeader.setBrokerId(brokerId); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.REMOVE_BROKER, requestHeader); RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis); assert response != null; switch (response.getCode()) { case ResponseCode.SUCCESS: return; default: break; } throw new MQBrokerException(response.getCode(), response.getRemark()); }
@Test public void testRemoveBroker() throws RemotingException, InterruptedException, MQBrokerException { mockInvokeSync(); mqClientAPI.removeBroker(defaultBrokerAddr, clusterName, brokerName, MixAll.MASTER_ID, defaultTimeout); }
static Properties resolveConsumerProperties(Map<String, String> options, Object keySchema, Object valueSchema) { Properties properties = from(options); withSerdeConsumerProperties(true, options, keySchema, properties); withSerdeConsumerProperties(false, options, valueSchema, properties); return properties; }
@Test @Parameters(method = "classes") public void when_consumerProperties_javaPropertyIsDefined_then_itsNotOverwritten(String clazz) { // key Map<String, String> keyOptions = Map.of( OPTION_KEY_FORMAT, JAVA_FORMAT, OPTION_KEY_CLASS, clazz, KEY_DESERIALIZER, "deserializer" ); assertThat(resolveConsumerProperties(keyOptions)) .containsExactlyEntriesOf(Map.of(KEY_DESERIALIZER, "deserializer")); // value Map<String, String> valueOptions = Map.of( OPTION_KEY_FORMAT, UNKNOWN_FORMAT, OPTION_VALUE_FORMAT, JAVA_FORMAT, OPTION_VALUE_CLASS, clazz, VALUE_DESERIALIZER, "deserializer" ); assertThat(resolveConsumerProperties(valueOptions)) .containsExactlyEntriesOf(Map.of(VALUE_DESERIALIZER, "deserializer")); }
@Override public RefreshUserToGroupsMappingsResponse refreshUserToGroupsMappings( RefreshUserToGroupsMappingsRequest request) throws StandbyException, YarnException, IOException { // parameter verification. if (request == null) { routerMetrics.incrRefreshUserToGroupsMappingsFailedRetrieved(); RouterServerUtil.logAndThrowException("Missing RefreshUserToGroupsMappings request.", null); } // call refreshUserToGroupsMappings of activeSubClusters. try { long startTime = clock.getTime(); RMAdminProtocolMethod remoteMethod = new RMAdminProtocolMethod( new Class[] {RefreshUserToGroupsMappingsRequest.class}, new Object[] {request}); String subClusterId = request.getSubClusterId(); Collection<RefreshUserToGroupsMappingsResponse> refreshUserToGroupsMappingsResps = remoteMethod.invokeConcurrent(this, RefreshUserToGroupsMappingsResponse.class, subClusterId); if (CollectionUtils.isNotEmpty(refreshUserToGroupsMappingsResps)) { long stopTime = clock.getTime(); routerMetrics.succeededRefreshUserToGroupsMappingsRetrieved(stopTime - startTime); return RefreshUserToGroupsMappingsResponse.newInstance(); } } catch (YarnException e) { routerMetrics.incrRefreshUserToGroupsMappingsFailedRetrieved(); RouterServerUtil.logAndThrowException(e, "Unable to refreshUserToGroupsMappings due to exception. " + e.getMessage()); } routerMetrics.incrRefreshUserToGroupsMappingsFailedRetrieved(); throw new YarnException("Unable to refreshUserToGroupsMappings."); }
@Test public void testRefreshUserToGroupsMappings() throws Exception { // null request. LambdaTestUtils.intercept(YarnException.class, "Missing RefreshUserToGroupsMappings request.", () -> interceptor.refreshUserToGroupsMappings(null)); // normal request. RefreshUserToGroupsMappingsRequest request = RefreshUserToGroupsMappingsRequest.newInstance(); RefreshUserToGroupsMappingsResponse response = interceptor.refreshUserToGroupsMappings(request); assertNotNull(response); }
@Description("Array of smallest and largest IP address in the subnet of the given IP prefix") @ScalarFunction("ip_subnet_range") @SqlType("array(IPADDRESS)") public static Block ipSubnetRange(@SqlType(StandardTypes.IPPREFIX) Slice value) { BlockBuilder blockBuilder = IPADDRESS.createBlockBuilder(null, 2); IPADDRESS.writeSlice(blockBuilder, ipSubnetMin(value)); IPADDRESS.writeSlice(blockBuilder, ipSubnetMax(value)); return blockBuilder.build(); }
@Test public void testIpSubnetRange() { assertFunction("IP_SUBNET_RANGE(IPPREFIX '1.2.3.160/24')", new ArrayType(IPADDRESS), ImmutableList.of("1.2.3.0", "1.2.3.255")); assertFunction("IP_SUBNET_RANGE(IPPREFIX '1.2.3.128/31')", new ArrayType(IPADDRESS), ImmutableList.of("1.2.3.128", "1.2.3.129")); assertFunction("IP_SUBNET_RANGE(IPPREFIX '10.1.6.46/32')", new ArrayType(IPADDRESS), ImmutableList.of("10.1.6.46", "10.1.6.46")); assertFunction("IP_SUBNET_RANGE(IPPREFIX '10.1.6.46/0')", new ArrayType(IPADDRESS), ImmutableList.of("0.0.0.0", "255.255.255.255")); assertFunction("IP_SUBNET_RANGE(IPPREFIX '64:ff9b::17/64')", new ArrayType(IPADDRESS), ImmutableList.of("64:ff9b::", "64:ff9b::ffff:ffff:ffff:ffff")); assertFunction("IP_SUBNET_RANGE(IPPREFIX '64:ff9b::52f4/120')", new ArrayType(IPADDRESS), ImmutableList.of("64:ff9b::5200", "64:ff9b::52ff")); assertFunction("IP_SUBNET_RANGE(IPPREFIX '64:ff9b::17/128')", new ArrayType(IPADDRESS), ImmutableList.of("64:ff9b::17", "64:ff9b::17")); }
@Override public boolean tryClaim(Timestamp position) { checkArgument( lastAttemptedPosition == null || position.compareTo(lastAttemptedPosition) > 0, "Trying to claim offset %s while last attempted was %s", position, lastAttemptedPosition); checkArgument( position.compareTo(range.getFrom()) >= 0, "Trying to claim offset %s before start of the range %s", position, range); lastAttemptedPosition = position; // It is ok to try to claim offsets beyond of the range, this will simply return false if (position.compareTo(range.getTo()) >= 0) { return false; } lastClaimedPosition = position; return true; }
@Test public void testTryClaimFailsWhenPositionIsLessThanTheBeginningOfTheRange() { final Timestamp from = Timestamp.ofTimeMicroseconds(5L); final Timestamp to = Timestamp.ofTimeMicroseconds(10L); final Timestamp position = Timestamp.ofTimeMicroseconds(4L); final TimestampRange range = TimestampRange.of(from, to); final TimestampRangeTracker tracker = new TimestampRangeTracker(range); assertThrows(IllegalArgumentException.class, () -> tracker.tryClaim(position)); }
public static void deleteDirectory(File directory) throws IOException { checkNotNull(directory, "directory"); guardIfNotThreadSafe(FileUtils::deleteDirectoryInternal, directory); }
@Test void testDeleteSymbolicLinkDirectory() throws Exception { // creating a directory to which the test creates a symbolic link File linkedDirectory = TempDirUtils.newFolder(temporaryFolder); File fileInLinkedDirectory = new File(linkedDirectory, "child"); assertThat(fileInLinkedDirectory.createNewFile()).isTrue(); File symbolicLink = new File(temporaryFolder.toString(), "symLink"); try { Files.createSymbolicLink(symbolicLink.toPath(), linkedDirectory.toPath()); } catch (FileSystemException e) { // this operation can fail under Windows due to: "A required privilege is not held by // the client." assumeThat(OperatingSystem.isWindows()) .withFailMessage("This test does not work properly under Windows") .isFalse(); throw e; } FileUtils.deleteDirectory(symbolicLink); assertThat(fileInLinkedDirectory).exists(); }
public static void removeDupes( final List<CharSequence> suggestions, List<CharSequence> stringsPool) { if (suggestions.size() < 2) return; int i = 1; // Don't cache suggestions.size(), since we may be removing items while (i < suggestions.size()) { final CharSequence cur = suggestions.get(i); // Compare each suggestion with each previous suggestion for (int j = 0; j < i; j++) { CharSequence previous = suggestions.get(j); if (TextUtils.equals(cur, previous)) { removeSuggestion(suggestions, i, stringsPool); i--; break; } } i++; } }
@Test public void testRemoveDupesDupeIsNotFirstWithRecycle() throws Exception { ArrayList<CharSequence> list = new ArrayList<>( Arrays.<CharSequence>asList( "typed", "something", "duped", new StringBuilder("duped"), "something", new StringBuilder("new"))); Assert.assertEquals(0, mStringPool.size()); IMEUtil.removeDupes(list, mStringPool); Assert.assertEquals(4, list.size()); Assert.assertEquals("typed", list.get(0)); Assert.assertEquals("something", list.get(1)); Assert.assertEquals("duped", list.get(2)); Assert.assertEquals("new", list.get(3).toString()); Assert.assertTrue(list.get(3) instanceof StringBuilder); Assert.assertEquals(1, mStringPool.size()); Assert.assertEquals("duped", mStringPool.get(0).toString()); }
@Override public JavaCommand<EsServerCliJvmOptions> createEsCommand() { EsInstallation esInstallation = createEsInstallation(); String esHomeDirectoryAbsolutePath = esInstallation.getHomeDirectory().getAbsolutePath(); return new JavaCommand<EsServerCliJvmOptions>(ProcessId.ELASTICSEARCH, esInstallation.getHomeDirectory()) .setEsInstallation(esInstallation) .setJvmOptions(new EsServerCliJvmOptions(esInstallation)) .setEnvVariable("ES_JAVA_HOME", System.getProperties().getProperty("java.home")) .setClassName("org.elasticsearch.launcher.CliToolLauncher") .addClasspath(Paths.get(esHomeDirectoryAbsolutePath, "lib").toAbsolutePath() + File.separator + "*") .addClasspath(Paths.get(esHomeDirectoryAbsolutePath, "lib", "cli-launcher").toAbsolutePath() + File.separator + "*"); }
@Test public void createEsCommand_for_unix_returns_command_for_default_settings() throws Exception { when(system2.isOsWindows()).thenReturn(false); prepareEsFileSystem(); Properties props = new Properties(); props.setProperty("sonar.search.host", "localhost"); JavaCommand<?> esCommand = newFactory(props, system2).createEsCommand(); EsInstallation esConfig = esCommand.getEsInstallation(); assertThat(esConfig.getHost()).isNotEmpty(); assertThat(esConfig.getHttpPort()).isEqualTo(9001); assertThat(esConfig.getEsJvmOptions().getAll()) // enforced values .contains("-XX:+UseG1GC") .contains("-Dfile.encoding=UTF-8") // default settings .contains("-Xms512m", "-Xmx512m", "-XX:+HeapDumpOnOutOfMemoryError"); assertThat(esConfig.getEsYmlSettings()).isNotNull(); assertThat(esConfig.getLog4j2Properties()) .contains(entry("appender.file_es.fileName", new File(logsDir, "es.log").getAbsolutePath())); assertThat(esCommand.getEnvVariables()) .containsKey("ES_JAVA_HOME"); assertThat(esCommand.getJvmOptions().getAll()) .contains("-Xms4m", "-Xmx64m", "-XX:+UseSerialGC", "-Dcli.name=server", "-Dcli.script=./bin/elasticsearch", "-Dcli.libs=lib/tools/server-cli", "-Des.path.home=" + esConfig.getHomeDirectory().getAbsolutePath(), "-Des.path.conf=" + esConfig.getConfDirectory().getAbsolutePath(), "-Des.distribution.type=tar"); }
public static String join(final String... levels) { return join(Arrays.asList(levels)); }
@Test public void shouldJoinIterableCorrectly() { assertThat(ProcessingLoggerUtil.join(Arrays.asList("foo", "bar")), equalTo("foo.bar")); }
public static SchemaBuilder builder(final Schema schema) { requireDecimal(schema); return builder(precision(schema), scale(schema)); }
@Test public void shouldFailIfBuilderWithZeroPrecision() { // When: final Exception e = assertThrows( SchemaException.class, () -> builder(0, 0) ); // Then: assertThat(e.getMessage(), containsString("DECIMAL precision must be >= 1")); }
@Override public ObjectNode encode(Instruction instruction, CodecContext context) { checkNotNull(instruction, "Instruction cannot be null"); return new EncodeInstructionCodecHelper(instruction, context).encode(); }
@Test public void modVlanIdInstructionTest() { final L2ModificationInstruction.ModVlanIdInstruction instruction = (L2ModificationInstruction.ModVlanIdInstruction) Instructions.modVlanId(VlanId.vlanId((short) 12)); final ObjectNode instructionJson = instructionCodec.encode(instruction, context); assertThat(instructionJson, matchesInstruction(instruction)); }
@Override protected void decode(ChannelHandlerContext ctx, Object object, List out) throws Exception { try { if (object instanceof XMLEvent) { final XMLEvent event = (XMLEvent) object; if (event.isStartDocument() || event.isEndDocument()) { return; } if (event.isCharacters() && depth <= 1) { return; } if (depth < 1 && event.isStartElement()) { out.add(object); depth++; return; } if (depth <= 1 && event.isEndElement()) { out.add(object); depth--; return; } writer.add(event); if (event.isStartElement()) { depth++; } else if (event.isEndElement()) { depth--; if (depth == 1) { writer.flush(); org.dom4j.Element xmlElement = transform().getRootElement(); out.add(xmlElement); writer.close(); resetWriter(); } } } } catch (Exception e) { logger.info(e.getCause().getMessage()); throw e; } }
@Test public void testMergeSubscribeMsg() throws Exception { List<Object> list = Lists.newArrayList(); xmlMerger.depth = 1; subscribeMsgEventList.forEach(xmlEvent -> { try { xmlMerger.decode(new ChannelHandlerContextAdapter(), xmlEvent, list); } catch (Exception e) { fail(); } }); assertThat("Output list should have size of 1", list.size(), Matchers.is(1)); assertThat("Output object should be of type org.dom4j.Element", list.get(0), Matchers.is(instanceOf(Element.class))); Element root = (Element) list.get(0); assertThat("Top level element should be of type IQ", root.getQName().getName(), Matchers.is("iq")); assertThat(root.attributes().size(), Matchers.is(4)); assertThat(root.attribute("type").getValue(), Matchers.is("set")); assertNotNull("<pubsub> element should be accessible", root.element("pubsub")); assertThat(root.element("pubsub").getNamespaceURI(), Matchers.is("http://jabber.org/protocol/pubsub")); assertNotNull("<subscribe> element should be accessible", root.element("pubsub").element("subscribe")); }
@Override public void merge(String path, Object value) { get(mergeAsync(path, value)); }
@Test public void testMerge() { RJsonBucket<TestType> al = redisson.getJsonBucket("test", new JacksonCodec<>(TestType.class)); TestType t = new TestType(); t.setName("name1"); al.set(t); al.merge("$.name", "name2"); t = al.get(); assertThat(t.getName()).isEqualTo("name2"); }
@Override public Flowable<SyncingNotfication> syncingStatusNotifications() { return web3jService.subscribe( new Request<>( "eth_subscribe", Arrays.asList("syncing"), web3jService, EthSubscribe.class), "eth_unsubscribe", SyncingNotfication.class); }
@Test public void testSyncingStatusNotifications() { geth.syncingStatusNotifications(); verify(webSocketClient) .send( matches( "\\{\"jsonrpc\":\"2.0\",\"method\":\"eth_subscribe\"," + "\"params\":\\[\"syncing\"],\"id\":[0-9]{1,}}")); }
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { // Load the codec by message type. final AWSMessageType awsMessageType = AWSMessageType.valueOf(configuration.getString(CK_AWS_MESSAGE_TYPE)); final Codec.Factory<? extends Codec> codecFactory = this.availableCodecs.get(awsMessageType.getCodecName()); if (codecFactory == null) { LOG.error("A codec with name [{}] could not be found.", awsMessageType.getCodecName()); return null; } final Codec codec = codecFactory.create(configuration); // Parse the message with the specified codec. final Message message = codec.decode(new RawMessage(rawMessage.getPayload())); if (message == null) { LOG.error("Failed to decode message for codec [{}].", codec.getName()); return null; } return message; }
@Test public void testKinesisFlowLogCodec() throws JsonProcessingException { final HashMap<String, Object> configMap = new HashMap<>(); configMap.put(AWSCodec.CK_AWS_MESSAGE_TYPE, AWSMessageType.KINESIS_CLOUDWATCH_FLOW_LOGS.toString()); final Configuration configuration = new Configuration(configMap); final AWSCodec codec = new AWSCodec(configuration, AWSTestingUtils.buildTestCodecs()); DateTime timestamp = DateTime.now(DateTimeZone.UTC); KinesisLogEntry kinesisLogEntry = KinesisLogEntry.create("a-stream", "log-group", "log-stream", timestamp, "2 423432432432 eni-3244234 172.1.1.2 172.1.1.2 80 2264 6 1 52 1559738144 1559738204 ACCEPT OK"); Message message = codec.decode(new RawMessage(objectMapper.writeValueAsBytes(kinesisLogEntry))); Assert.assertEquals("log-group", message.getField(AbstractKinesisCodec.FIELD_LOG_GROUP)); Assert.assertEquals("log-stream", message.getField(AbstractKinesisCodec.FIELD_LOG_STREAM)); Assert.assertEquals("a-stream", message.getField(AbstractKinesisCodec.FIELD_KINESIS_STREAM)); Assert.assertEquals(6, message.getField(KinesisCloudWatchFlowLogCodec.FIELD_PROTOCOL_NUMBER)); Assert.assertEquals("172.1.1.2", message.getField(KinesisCloudWatchFlowLogCodec.FIELD_SRC_ADDR)); Assert.assertEquals(KinesisCloudWatchFlowLogCodec.SOURCE, message.getField("source")); Assert.assertEquals("eni-3244234 ACCEPT TCP 172.1.1.2:80 -> 172.1.1.2:2264", message.getField("message")); Assert.assertEquals(1L, message.getField(KinesisCloudWatchFlowLogCodec.FIELD_PACKETS)); Assert.assertEquals(80, message.getField(KinesisCloudWatchFlowLogCodec.FIELD_SRC_PORT)); Assert.assertEquals(60, message.getField(KinesisCloudWatchFlowLogCodec.FIELD_CAPTURE_WINDOW_DURATION)); Assert.assertEquals("TCP", message.getField(KinesisCloudWatchFlowLogCodec.FIELD_PROTOCOL)); Assert.assertEquals("423432432432", message.getField(KinesisCloudWatchFlowLogCodec.FIELD_ACCOUNT_ID)); Assert.assertEquals("eni-3244234", message.getField(KinesisCloudWatchFlowLogCodec.FIELD_INTERFACE_ID)); Assert.assertEquals("OK", message.getField(KinesisCloudWatchFlowLogCodec.FIELD_LOG_STATUS)); Assert.assertEquals(52L, message.getField(KinesisCloudWatchFlowLogCodec.FIELD_BYTES)); Assert.assertEquals(true, message.getField(KinesisCloudWatchFlowLogCodec.SOURCE_GROUP_IDENTIFIER)); Assert.assertEquals("172.1.1.2", message.getField(KinesisCloudWatchFlowLogCodec.FIELD_DST_ADDR)); Assert.assertEquals(2264, message.getField(KinesisCloudWatchFlowLogCodec.FIELD_DST_PORT)); Assert.assertEquals("ACCEPT", message.getField(KinesisCloudWatchFlowLogCodec.FIELD_ACTION)); Assert.assertEquals(timestamp, message.getTimestamp()); }
public Optional<String> findShardingColumn(final String columnName, final String tableName) { return Optional.ofNullable(shardingTables.get(tableName)).flatMap(optional -> findShardingColumn(optional, columnName)); }
@Test void assertIsNotShardingColumn() { ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); shardingRuleConfig.getTables().add(createTableRuleConfigWithAllStrategies()); Optional<String> actual = new ShardingRule(shardingRuleConfig, createDataSources(), mock(ComputeNodeInstanceContext.class)).findShardingColumn("column", "other_Table"); assertFalse(actual.isPresent()); }