focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void release() { if (fileChannel != null) { try { fileChannel.close(); } catch (IOException e) { ExceptionUtils.rethrow(e, "Failed to close file channel."); } } IOUtils.deleteFileQuietly(dataFilePath); }
@Test void testRelease() { assertThat(testFilePath.toFile().exists()).isTrue(); partitionFileReader.release(); assertThat(testFilePath.toFile().exists()).isFalse(); }
public final Logger getLogger(final Class<?> clazz) { return getLogger(clazz.getName()); }
@Test public void testStatusWithUnconfiguredContext() { Logger logger = lc.getLogger(LoggerContextTest.class); for (int i = 0; i < 3; i++) { logger.debug("test"); } logger = lc.getLogger("x.y.z"); for (int i = 0; i < 3; i++) { logger.debug("test"); } StatusManager sm = lc.getStatusManager(); assertTrue("StatusManager has recieved too many messages", sm.getCount() == 1); }
public EvictionConfig getEvictionConfig() { return evictionConfig; }
@Test(expected = IllegalArgumentException.class) public void testSetMaxSizeCannotBeNegative() { new MapConfig().getEvictionConfig().setSize(-1); }
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) { return invoke(n, BigDecimal.ZERO); }
@Test void invokeRoundingEven() { FunctionTestUtil.assertResult(roundDownFunction.invoke(BigDecimal.valueOf(10.25)), BigDecimal.valueOf(10)); FunctionTestUtil.assertResult(roundDownFunction.invoke(BigDecimal.valueOf(10.25), BigDecimal.ONE), BigDecimal.valueOf(10.2)); }
public static <T, IdT> Deduplicate.WithRepresentativeValues<T, IdT> withRepresentativeValueFn( SerializableFunction<T, IdT> representativeValueFn) { return new Deduplicate.WithRepresentativeValues<T, IdT>( DEFAULT_TIME_DOMAIN, DEFAULT_DURATION, representativeValueFn, null, null); }
@Test @Category({NeedsRunner.class, UsesTestStreamWithProcessingTime.class}) public void testTriggeredRepresentativeValuesWithType() { Instant base = new Instant(0); TestStream<KV<Long, String>> values = TestStream.create(KvCoder.of(VarLongCoder.of(), StringUtf8Coder.of())) .advanceWatermarkTo(base) .addElements( TimestampedValue.of(KV.of(1L, "k1"), base), TimestampedValue.of(KV.of(2L, "k2"), base.plus(Duration.standardSeconds(10))), TimestampedValue.of(KV.of(3L, "k3"), base.plus(Duration.standardSeconds(20)))) .advanceProcessingTime(Duration.standardMinutes(1)) .addElements( TimestampedValue.of(KV.of(1L, "k1"), base.plus(Duration.standardSeconds(30))), TimestampedValue.of(KV.of(2L, "k2"), base.plus(Duration.standardSeconds(40))), TimestampedValue.of(KV.of(3L, "k3"), base.plus(Duration.standardSeconds(50)))) .advanceWatermarkToInfinity(); PCollection<KV<Long, String>> distinctValues = p.apply(values) .apply( Deduplicate.withRepresentativeValueFn(new Keys<Long>()) .withRepresentativeCoder(VarLongCoder.of())); PAssert.that(distinctValues) .containsInAnyOrder(KV.of(1L, "k1"), KV.of(2L, "k2"), KV.of(3L, "k3")); p.run(); }
public Predicate<InMemoryFilterable> parse(final List<String> filterExpressions, final List<EntityAttribute> attributes) { if (filterExpressions == null || filterExpressions.isEmpty()) { return Predicates.alwaysTrue(); } final Map<String, List<Filter>> groupedByField = filterExpressions.stream() .map(expr -> singleFilterParser.parseSingleExpression(expr, attributes)) .collect(groupingBy(Filter::field)); return groupedByField.values().stream() .map(grouped -> grouped.stream() .map(Filter::toPredicate) .collect(Collectors.toList())) .map(groupedPredicates -> groupedPredicates.stream().reduce(Predicate::or).orElse(Predicates.alwaysTrue())) .reduce(Predicate::and).orElse(Predicates.alwaysTrue()); }
@Test void throwsExceptionOnWrongFilterFormat() { final List<EntityAttribute> attributes = List.of( EntityAttribute.builder().id("good").title("Good").filterable(true).build(), EntityAttribute.builder().id("another").title("Hidden and dangerous").filterable(true).build() ); assertThrows(IllegalArgumentException.class, () -> toTest.parse(List.of("No separator"), attributes)); assertThrows(IllegalArgumentException.class, () -> toTest.parse(List.of(FIELD_AND_VALUE_SEPARATOR + "no field name"), attributes)); assertThrows(IllegalArgumentException.class, () -> toTest.parse(List.of("no field value" + FIELD_AND_VALUE_SEPARATOR), attributes)); assertThrows(IllegalArgumentException.class, () -> toTest.parse( List.of("good" + FIELD_AND_VALUE_SEPARATOR + "one", "another" + FIELD_AND_VALUE_SEPARATOR + "good_one", "single wrong one is enough to throw exception"), attributes) ); }
public void acceptRow(final List<?> key, final GenericRow value) { try { if (passedLimit()) { return; } final KeyValue<List<?>, GenericRow> row = keyValue(key, value); final KeyValueMetadata<List<?>, GenericRow> keyValueMetadata = new KeyValueMetadata<>(row); while (!closed) { if (rowQueue.offer(keyValueMetadata, offerTimeoutMs, TimeUnit.MILLISECONDS)) { onQueued(); totalRowsQueued.incrementAndGet(); break; } } } catch (final InterruptedException e) { // Forced shutdown? Thread.currentThread().interrupt(); } }
@Test public void shouldCallLimitHandlerAsLimitReached() { // When: IntStream.range(0, SOME_LIMIT) .forEach(idx -> queue.acceptRow(KEY_ONE, VAL_ONE)); // Then: verify(limitHandler).limitReached(); }
@Bean public SofaServiceEventListener sofaServiceEventListener(final ShenyuClientConfig clientConfig, final ShenyuClientRegisterRepository shenyuClientRegisterRepository) { return new SofaServiceEventListener(clientConfig.getClient().get(RpcTypeEnum.SOFA.getName()), shenyuClientRegisterRepository); }
@Test public void testSofaServiceEventListener() { MockedStatic<RegisterUtils> registerUtilsMockedStatic = mockStatic(RegisterUtils.class); registerUtilsMockedStatic.when(() -> RegisterUtils.doLogin(any(), any(), any())).thenReturn(Optional.ofNullable("token")); applicationContextRunner.run(context -> { SofaServiceEventListener eventListener = context.getBean("sofaServiceEventListener", SofaServiceEventListener.class); assertNotNull(eventListener); assertEquals(eventListener.getAppName(), "sofa"); assertEquals(eventListener.getHost(), "127.0.0.1"); assertEquals(eventListener.getPort(), "8888"); assertEquals(eventListener.getContextPath(), "/sofa"); }); registerUtilsMockedStatic.close(); }
public double calculateMinPercentageUsedBy(NormalizedResources used, double totalMemoryMb, double usedMemoryMb) { if (LOG.isTraceEnabled()) { LOG.trace("Calculating min percentage used by. Used Mem: {} Total Mem: {}" + " Used Normalized Resources: {} Total Normalized Resources: {}", totalMemoryMb, usedMemoryMb, toNormalizedMap(), used.toNormalizedMap()); } double min = 1.0; if (usedMemoryMb > totalMemoryMb) { throwBecauseUsedIsNotSubsetOfTotal(used, totalMemoryMb, usedMemoryMb); } if (totalMemoryMb != 0.0) { min = Math.min(min, usedMemoryMb / totalMemoryMb); } double totalCpu = getTotalCpu(); if (used.getTotalCpu() > totalCpu) { throwBecauseUsedIsNotSubsetOfTotal(used, totalMemoryMb, usedMemoryMb); } if (totalCpu != 0.0) { min = Math.min(min, used.getTotalCpu() / totalCpu); } if (used.otherResources.length > otherResources.length) { throwBecauseUsedIsNotSubsetOfTotal(used, totalMemoryMb, usedMemoryMb); } for (int i = 0; i < otherResources.length; i++) { if (otherResources[i] == 0.0) { //Skip any resources where the total is 0, the percent used for this resource isn't meaningful. //We fall back to prioritizing by cpu, memory and any other resources by ignoring this value continue; } if (i >= used.otherResources.length) { //Resources missing from used are using none of that resource return 0; } if (used.otherResources[i] > otherResources[i]) { String info = String.format("%s, %f > %f", getResourceNameForResourceIndex(i), used.otherResources[i], otherResources[i]); throwBecauseUsedIsNotSubsetOfTotal(used, totalMemoryMb, usedMemoryMb, info); } min = Math.min(min, used.otherResources[i] / otherResources[i]); } return min * 100.0; }
@Test public void testCalculateMinThrowsIfTotalIsMissingMemory() { NormalizedResources resources = new NormalizedResources(normalize(Collections.singletonMap(Constants.COMMON_CPU_RESOURCE_NAME, 2))); NormalizedResources usedResources = new NormalizedResources(normalize(Collections.singletonMap(Constants.COMMON_CPU_RESOURCE_NAME, 1))); assertThrows(IllegalArgumentException.class, () -> resources.calculateMinPercentageUsedBy(usedResources, 100, 500)); }
public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec> specs) { return buildPartitionProjectionType("grouping key", specs, commonActiveFieldIds(schema, specs)); }
@Test public void testGroupingKeyTypeWithSpecEvolutionInV1Tables() { TestTables.TestTable table = TestTables.create(tableDir, "test", SCHEMA, BY_DATA_SPEC, V1_FORMAT_VERSION); table.updateSpec().addField(Expressions.bucket("category", 8)).commit(); assertThat(table.specs()).hasSize(2); StructType expectedType = StructType.of(NestedField.optional(1000, "data", Types.StringType.get())); StructType actualType = Partitioning.groupingKeyType(table.schema(), table.specs().values()); assertThat(actualType).isEqualTo(expectedType); }
@Override protected String transform(ILoggingEvent event, String in) { AnsiElement element = ELEMENTS.get(getFirstOption()); List<Marker> markers = event.getMarkerList(); if ((markers != null && !markers.isEmpty() && markers.get(0).contains(CRLF_SAFE_MARKER)) || isLoggerSafe(event)) { return in; } String replacement = element == null ? "_" : toAnsiString("_", element); return in.replaceAll("[\n\r\t]", replacement); }
@Test void transformShouldReturnInputStringWhenMarkersNotContainCRLFSafeMarker() { ILoggingEvent event = mock(ILoggingEvent.class); Marker marker = MarkerFactory.getMarker("CRLF_NOT_SAFE"); List<Marker> markers = Collections.singletonList(marker); when(event.getMarkerList()).thenReturn(markers); when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger"); String input = "Test input string"; CRLFLogConverter converter = new CRLFLogConverter(); String result = converter.transform(event, input); assertEquals(input, result); }
@Override public ServiceStateTransition.Response mayTransitionServiceTo(final ServiceInstance instance, final Service.ServiceState newState, final String reason) { return transactionResult(configuration -> mayTransitServiceTo(configuration, instance, newState, reason)); }
@Test void shouldReturnEmptyForTransitionWorkerStateGivenInvalidWorker() { // Given ServiceInstance instance = Fixtures.RunningServiceInstance; // When ServiceStateTransition.Response result = repository .mayTransitionServiceTo(instance, Service.ServiceState.TERMINATING); // Then Assertions.assertEquals(new ServiceStateTransition.Response(ServiceStateTransition.Result.ABORTED), result); }
void addGetModelsMethod(StringBuilder sb) { sb.append( " @Override\n" + " public java.util.List<Model> getModels() {\n" + " return java.util.Arrays.asList(" ); String collected = modelsByKBase.values().stream().flatMap( List::stream ).distinct() .map(element -> "new " + element + "()") .collect(Collectors.joining(",")); sb.append(collected); sb.append( ");\n" + " }\n" + "\n"); }
@Test public void addGetModelsMethodEmptyModelsByKBaseTest() { ModelSourceClass modelSourceClass = new ModelSourceClass(RELEASE_ID, new HashMap<>(), new HashMap<>()); StringBuilder sb = new StringBuilder(); modelSourceClass.addGetModelsMethod(sb); String retrieved = sb.toString(); String expected = "return java.util.Arrays.asList();"; assertThat(retrieved.contains(expected)).isTrue(); }
static void process(int maxMessages, MessageFormatter formatter, ConsumerWrapper consumer, PrintStream output, boolean skipMessageOnError) { while (messageCount < maxMessages || maxMessages == -1) { ConsumerRecord<byte[], byte[]> msg; try { msg = consumer.receive(); } catch (WakeupException we) { LOG.trace("Caught WakeupException because consumer is shutdown, ignore and terminate."); // Consumer will be closed return; } catch (Throwable t) { LOG.error("Error processing message, terminating consumer process: ", t); // Consumer will be closed return; } messageCount += 1; try { formatter.writeTo(new ConsumerRecord<>(msg.topic(), msg.partition(), msg.offset(), msg.timestamp(), msg.timestampType(), 0, 0, msg.key(), msg.value(), msg.headers(), Optional.empty()), output); } catch (Throwable t) { if (skipMessageOnError) { LOG.error("Error processing message, skipping this message: ", t); } else { // Consumer will be closed throw t; } } if (checkErr(output)) { // Consumer will be closed return; } } }
@Test public void shouldLimitReadsToMaxMessageLimit() { ConsoleConsumer.ConsumerWrapper consumer = mock(ConsoleConsumer.ConsumerWrapper.class); MessageFormatter formatter = mock(MessageFormatter.class); ConsumerRecord<byte[], byte[]> record = new ConsumerRecord<>("foo", 1, 1, new byte[0], new byte[0]); int messageLimit = 10; when(consumer.receive()).thenReturn(record); ConsoleConsumer.process(messageLimit, formatter, consumer, System.out, true); verify(consumer, times(messageLimit)).receive(); verify(formatter, times(messageLimit)).writeTo(any(), any()); consumer.cleanup(); }
public static String serialize(AWSCredentialsProvider awsCredentialsProvider) { ObjectMapper om = new ObjectMapper(); om.registerModule(new AwsModule()); try { return om.writeValueAsString(awsCredentialsProvider); } catch (JsonProcessingException e) { throw new IllegalArgumentException("AwsCredentialsProvider can not be serialized to Json", e); } }
@Test(expected = IllegalArgumentException.class) public void testFailOnAWSCredentialsProviderSerialization() { AWSCredentialsProvider credentialsProvider = new UnknownAwsCredentialsProvider(); serialize(credentialsProvider); }
@Override public void getConfig(FederationConfig.Builder builder) { for (Target target : resolvedTargets.values()) builder.target(target.getTargetConfig()); targetSelector.ifPresent(selector -> builder.targetSelector(selector.getGlobalComponentId().stringValue())); }
@Test void manually_specified_targets_overrides_inherited_targets() throws Exception { FederationFixture f = new FederationFixture(); f.registerProviderWithSources(createProvider(ComponentId.fromString("provider1"))); FederationSearcher federation = newFederationSearcher(true, List.of(new TargetSpec(ComponentSpecification.fromString("provider1"), new FederationOptions().setTimeoutInMilliseconds(12345)))); f.initializeFederationSearcher(federation); FederationConfig federationConfig = getConfig(federation); assertEquals(1, federationConfig.target().size()); FederationConfig.Target target = federationConfig.target(0); assertEquals(1, target.searchChain().size()); FederationConfig.Target.SearchChain searchChain = target.searchChain(0); assertEquals(12345, searchChain.timeoutMillis()); }
public static int read(final AtomicBuffer buffer, final EntryConsumer entryConsumer) { final int capacity = buffer.capacity(); int recordsRead = 0; int offset = 0; while (offset < capacity) { final long observationCount = buffer.getLongVolatile(offset + OBSERVATION_COUNT_OFFSET); if (observationCount <= 0) { break; } ++recordsRead; final String channel = buffer.getStringAscii(offset + CHANNEL_OFFSET); final String source = buffer.getStringAscii( offset + CHANNEL_OFFSET + BitUtil.align(SIZE_OF_INT + channel.length(), SIZE_OF_INT)); entryConsumer.accept( observationCount, buffer.getLongVolatile(offset + TOTAL_BYTES_LOST_OFFSET), buffer.getLong(offset + FIRST_OBSERVATION_OFFSET), buffer.getLongVolatile(offset + LAST_OBSERVATION_OFFSET), buffer.getInt(offset + SESSION_ID_OFFSET), buffer.getInt(offset + STREAM_ID_OFFSET), channel, source); final int recordLength = CHANNEL_OFFSET + BitUtil.align(SIZE_OF_INT + channel.length(), SIZE_OF_INT) + SIZE_OF_INT + source.length(); offset += BitUtil.align(recordLength, ENTRY_ALIGNMENT); } return recordsRead; }
@Test void shouldReadTwoEntries() { final long initialBytesLostOne = 32; final int timestampMsOne = 7; final int sessionIdOne = 3; final int streamIdOne = 1; final String channelOne = "aeron:udp://stuffOne"; final String sourceOne = "127.0.0.1:8888"; final long initialBytesLostTwo = 48; final int timestampMsTwo = 17; final int sessionIdTwo = 13; final int streamIdTwo = 11; final String channelTwo = "aeron:udp://stuffTwo"; final String sourceTwo = "127.0.0.1:9999"; lossReport.createEntry(initialBytesLostOne, timestampMsOne, sessionIdOne, streamIdOne, channelOne, sourceOne); lossReport.createEntry(initialBytesLostTwo, timestampMsTwo, sessionIdTwo, streamIdTwo, channelTwo, sourceTwo); assertEquals(2, LossReportReader.read(buffer, entryConsumer)); final InOrder inOrder = inOrder(entryConsumer); inOrder.verify(entryConsumer).accept( 1L, initialBytesLostOne, timestampMsOne, timestampMsOne, sessionIdOne, streamIdOne, channelOne, sourceOne); inOrder.verify(entryConsumer).accept( 1L, initialBytesLostTwo, timestampMsTwo, timestampMsTwo, sessionIdTwo, streamIdTwo, channelTwo, sourceTwo); verifyNoMoreInteractions(entryConsumer); }
@Override public boolean tableExists(String dbName, String tblName) { return hmsOps.tableExists(dbName, tblName); }
@Test public void testTableExists() { boolean exists = hiveMetadata.tableExists("db1", "tbl1"); Assert.assertTrue(exists); }
@Override protected Release findActiveOne(long id, ApolloNotificationMessages clientMessages) { Tracer.logEvent(TRACER_EVENT_CACHE_GET_ID, String.valueOf(id)); return configIdCache.getUnchecked(id).orElse(null); }
@Test public void testFindActiveOneWithMultipleIdMultipleTimes() throws Exception { long someId = 1; long anotherId = 2; Release anotherRelease = mock(Release.class); when(releaseService.findActiveOne(someId)).thenReturn(someRelease); when(releaseService.findActiveOne(anotherId)).thenReturn(anotherRelease); assertEquals(someRelease, configServiceWithCache.findActiveOne(someId, someNotificationMessages)); assertEquals(someRelease, configServiceWithCache.findActiveOne(someId, someNotificationMessages)); assertEquals(anotherRelease, configServiceWithCache.findActiveOne(anotherId, someNotificationMessages)); assertEquals(anotherRelease, configServiceWithCache.findActiveOne(anotherId, someNotificationMessages)); verify(releaseService, times(1)).findActiveOne(someId); verify(releaseService, times(1)).findActiveOne(anotherId); }
public static float toFloat(final String str) { return toFloat(str, 0.0f); }
@Test void testToFloatString() { assertEquals(NumberUtils.toFloat("-1.2345"), -1.2345f, 0); assertEquals(1.2345f, NumberUtils.toFloat("1.2345"), 0); assertEquals(0.0f, NumberUtils.toFloat("abc"), 0); assertEquals(NumberUtils.toFloat("-001.2345"), -1.2345f, 0); assertEquals(1.2345f, NumberUtils.toFloat("+001.2345"), 0); assertEquals(1.2345f, NumberUtils.toFloat("001.2345"), 0); assertEquals(0f, NumberUtils.toFloat("000.00"), 0); assertEquals(Float.MAX_VALUE, NumberUtils.toFloat(Float.MAX_VALUE + ""), 0); assertEquals(Float.MIN_VALUE, NumberUtils.toFloat(Float.MIN_VALUE + ""), 0); assertEquals(0.0f, NumberUtils.toFloat(""), 0); assertEquals(0.0f, NumberUtils.toFloat(null), 0); }
@Override public void reset() { set(INIT); }
@Test public void testReset() { SnapshotRegistry registry = new SnapshotRegistry(new LogContext()); TimelineInteger value = new TimelineInteger(registry); registry.getOrCreateSnapshot(2); value.set(1); registry.getOrCreateSnapshot(3); value.set(2); registry.reset(); assertEquals(Collections.emptyList(), registry.epochsList()); assertEquals(TimelineInteger.INIT, value.get()); }
protected boolean evaluation(Object inputValue) { switch (operator) { case EQUAL: return value.equals(inputValue); case NOT_EQUAL: return !value.equals(inputValue); case LESS_THAN: if (inputValue instanceof Number && value instanceof Number) { return ((Number) inputValue).doubleValue() < ((Number) value).doubleValue(); } else { return false; } case LESS_OR_EQUAL: if (inputValue instanceof Number && value instanceof Number) { return ((Number) inputValue).doubleValue() <= ((Number) value).doubleValue(); } else { return false; } case GREATER_THAN: if (inputValue instanceof Number && value instanceof Number) { return ((Number) inputValue).doubleValue() > ((Number) value).doubleValue(); } else { return false; } case GREATER_OR_EQUAL: if (inputValue instanceof Number && value instanceof Number) { return ((Number) inputValue).doubleValue() >= ((Number) value).doubleValue(); } else { return false; } case IS_MISSING: case IS_NOT_MISSING: // TODO {gcardosi} DROOLS-5604 throw new IllegalArgumentException(SURROGATE + " not supported, yet"); default: throw new KiePMMLException("Unknown OPERATOR " + operator); } }
@Test void evaluationStringIsMissing() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { Object value = "43"; KiePMMLSimplePredicate kiePMMLSimplePredicate = getKiePMMLSimplePredicate(OPERATOR.IS_MISSING, value); kiePMMLSimplePredicate.evaluation(value); }); }
@Override public int hashCode() { return executionId.hashCode() + executionState.ordinal(); }
@Test public void testEqualsHashCode() { try { final ExecutionAttemptID executionId = createExecutionAttemptId(); final ExecutionState state = ExecutionState.RUNNING; final Throwable error = new RuntimeException("some test error message"); TaskExecutionState s1 = new TaskExecutionState(executionId, state, error); TaskExecutionState s2 = new TaskExecutionState(executionId, state, error); assertEquals(s1.hashCode(), s2.hashCode()); assertEquals(s1, s2); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
@Override public void removeDataConnection(String name) { dataConnections.computeIfPresent(name, (k, v) -> { if (CONFIG == v.source) { throw new HazelcastException("Data connection '" + name + "' is configured via Config " + "and can't be removed"); } v.instance.release(); return null; }); }
@Test public void remove_non_existing_data_connection_should_be_no_op() { dataConnectionService.removeDataConnection("does-not-exist"); }
@Override public int remainingCapacity() { return capacity() - size(); }
@Test public void testRemainingCapacity() { assertEquals(CAPACITY, queue.remainingCapacity()); queue.offer(1); assertEquals(CAPACITY - 1, queue.remainingCapacity()); }
@Override public String[] split(String text) { if (splitContraction) { text = WONT_CONTRACTION.matcher(text).replaceAll("$1ill not"); text = SHANT_CONTRACTION.matcher(text).replaceAll("$1ll not"); text = AINT_CONTRACTION.matcher(text).replaceAll("$1m not"); for (Pattern regexp : NOT_CONTRACTIONS) { text = regexp.matcher(text).replaceAll("$1 not"); } for (Pattern regexp : CONTRACTIONS2) { text = regexp.matcher(text).replaceAll("$1 $2"); } for (Pattern regexp : CONTRACTIONS3) { text = regexp.matcher(text).replaceAll("$1 $2 $3"); } } text = DELIMITERS[0].matcher(text).replaceAll(" $1 "); text = DELIMITERS[1].matcher(text).replaceAll(" $1"); text = DELIMITERS[2].matcher(text).replaceAll(" $1"); text = DELIMITERS[3].matcher(text).replaceAll(" . "); text = DELIMITERS[4].matcher(text).replaceAll(" $1 "); String[] words = WHITESPACE.split(text); if (words.length > 1 && words[words.length-1].equals(".")) { if (EnglishAbbreviations.contains(words[words.length-2])) { words[words.length-2] = words[words.length-2] + "."; } } ArrayList<String> result = new ArrayList<>(); for (String token : words) { if (!token.isEmpty()) { result.add(token); } } return result.toArray(new String[0]); }
@Test public void testTokenize() { System.out.println("tokenize"); String text = "Good muffins cost $3.88\nin New York. Please buy " + "me\ntwo of them.\n\nYou cannot eat them. I gonna eat them. " + "Thanks. Of course, I won't. "; String[] expResult = {"Good", "muffins", "cost", "$", "3.88", "in", "New", "York.", "Please", "buy", "me", "two", "of", "them", ".", "You", "can", "not", "eat", "them.", "I", "gon", "na", "eat", "them.", "Thanks.", "Of", "course", ",", "I", "will", "not", "."}; SimpleTokenizer instance = new SimpleTokenizer(true); String[] result = instance.split(text); assertEquals(expResult.length, result.length); for (int i = 0; i < result.length; i++) { assertEquals(expResult[i], result[i]); } }
@VisibleForTesting public static JobGraph createJobGraph(StreamGraph streamGraph) { return new StreamingJobGraphGenerator( Thread.currentThread().getContextClassLoader(), streamGraph, null, Runnable::run) .createJobGraph(); }
@Test void testSlotSharingResourceConfiguration() { final String slotSharingGroup1 = "slot-a"; final String slotSharingGroup2 = "slot-b"; final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10); final ResourceProfile resourceProfile2 = ResourceProfile.fromResources(2, 20); final ResourceProfile resourceProfile3 = ResourceProfile.fromResources(3, 30); final Map<String, ResourceProfile> slotSharingGroupResource = new HashMap<>(); slotSharingGroupResource.put(slotSharingGroup1, resourceProfile1); slotSharingGroupResource.put(slotSharingGroup2, resourceProfile2); slotSharingGroupResource.put( StreamGraphGenerator.DEFAULT_SLOT_SHARING_GROUP, resourceProfile3); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.fromData(1, 2, 3) .name(slotSharingGroup1) .slotSharingGroup(slotSharingGroup1) .map(x -> x + 1) .name(slotSharingGroup2) .slotSharingGroup(slotSharingGroup2) .map(x -> x * x) .name(StreamGraphGenerator.DEFAULT_SLOT_SHARING_GROUP) .slotSharingGroup(StreamGraphGenerator.DEFAULT_SLOT_SHARING_GROUP); final StreamGraph streamGraph = env.getStreamGraph(); streamGraph.setSlotSharingGroupResource(slotSharingGroupResource); final JobGraph jobGraph = StreamingJobGraphGenerator.createJobGraph(streamGraph); int numVertex = 0; for (JobVertex jobVertex : jobGraph.getVertices()) { numVertex += 1; if (jobVertex.getName().contains(slotSharingGroup1)) { assertThat(jobVertex.getSlotSharingGroup().getResourceProfile()) .isEqualTo(resourceProfile1); } else if (jobVertex.getName().contains(slotSharingGroup2)) { assertThat(jobVertex.getSlotSharingGroup().getResourceProfile()) .isEqualTo(resourceProfile2); } else if (jobVertex .getName() .contains(StreamGraphGenerator.DEFAULT_SLOT_SHARING_GROUP)) { assertThat(jobVertex.getSlotSharingGroup().getResourceProfile()) .isEqualTo(resourceProfile3); } else { Assertions.fail(""); } } assertThat(numVertex).isEqualTo(3); }
@Override public boolean rename(Path src, Path dst) throws IOException { return fs.rename(src, dst); }
@Test public void testRenameOptions() throws Exception { FileSystem mockFs = mock(FileSystem.class); FileSystem fs = new FilterFileSystem(mockFs); Path src = new Path("/src"); Path dst = new Path("/dest"); Rename opt = Rename.TO_TRASH; fs.rename(src, dst, opt); verify(mockFs).rename(eq(src), eq(dst), eq(opt)); }
public Node parse() throws ScanException { if (tokenList == null || tokenList.isEmpty()) return null; return E(); }
@Test public void nested() throws ScanException { Tokenizer tokenizer = new Tokenizer("a${b${c}}d"); Parser parser = new Parser(tokenizer.tokenize()); Node node = parser.parse(); Node witness = new Node(Node.Type.LITERAL, "a"); Node bLiteralNode = new Node(Node.Type.LITERAL, "b"); Node cLiteralNode = new Node(Node.Type.LITERAL, "c"); Node bVariableNode = new Node(Node.Type.VARIABLE, bLiteralNode); Node cVariableNode = new Node(Node.Type.VARIABLE, cLiteralNode); bLiteralNode.next = cVariableNode; witness.next = bVariableNode; witness.next.next = new Node(Node.Type.LITERAL, "d"); assertEquals(witness, node); }
public WebServiceField getFieldOutFromWsName( String wsName, boolean ignoreWsNsPrefix ) { WebServiceField param = null; if ( Utils.isEmpty( wsName ) ) { return param; } // if we are ignoring the name space prefix if ( ignoreWsNsPrefix ) { // we split the wsName and set it to the last element of what was parsed String[] wsNameParsed = wsName.split( ":" ); wsName = wsNameParsed[wsNameParsed.length - 1]; } // we now look for the wsname for ( Iterator<WebServiceField> iter = getFieldsOut().iterator(); iter.hasNext(); ) { WebServiceField paramCour = iter.next(); if ( paramCour.getWsName().equals( wsName ) ) { param = paramCour; break; } } return param; }
@Test public void testGetFieldOut() throws Exception { DatabaseMeta dbMeta = mock( DatabaseMeta.class ); IMetaStore metastore = mock( IMetaStore.class ); WebServiceMeta webServiceMeta = new WebServiceMeta( getTestNode(), Collections.singletonList( dbMeta ), metastore ); assertNull( webServiceMeta.getFieldOutFromWsName( "", true ) ); assertEquals( "GetCurrentExchangeRateResult", webServiceMeta.getFieldOutFromWsName( "GetCurrentExchangeRateResult", false ).getName() ); assertEquals( "GetCurrentExchangeRateResult", webServiceMeta.getFieldOutFromWsName( "something:GetCurrentExchangeRateResult", true ).getName() ); }
public static StatementExecutorResponse execute( final ConfiguredStatement<ListProperties> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final KsqlConfigResolver resolver = new KsqlConfigResolver(); final Map<String, String> engineProperties = statement .getSessionConfig() .getConfig(false) .getAllConfigPropsWithSecretsObfuscated(); final List<Property> mergedProperties = mergedProperties(statement); final List<String> overwritten = mergedProperties .stream() .filter(property -> !Objects.equals( engineProperties.get(property.getName()), property.getValue())) .map(Property::getName) .collect(Collectors.toList()); final List<String> defaultProps = mergedProperties.stream() .filter(property -> resolver.resolve(property.getName(), false) .map(resolved -> resolved.isDefaultValue(property.getValue())) .orElse(false)) .map(Property::getName) .collect(Collectors.toList()); return StatementExecutorResponse.handled(Optional.of(new PropertiesList( statement.getMaskedStatementText(), mergedProperties, overwritten, defaultProps))); }
@Test public void shouldListPropertiesWithOverrides() { // When: final PropertiesList properties = (PropertiesList) CustomExecutors.LIST_PROPERTIES.execute( engine.configure("LIST PROPERTIES;") .withConfigOverrides(ImmutableMap.of("ksql.streams.auto.offset.reset", "latest")), mock(SessionProperties.class), engine.getEngine(), engine.getServiceContext() ).getEntity().orElseThrow(IllegalStateException::new); // Then: assertThat( properties.getProperties(), hasItem(new Property("ksql.streams.auto.offset.reset", "KSQL", "latest"))); assertThat(properties.getOverwrittenProperties(), hasItem("ksql.streams.auto.offset.reset")); }
@Override public void debug(String msg) { logger.debug(msg); }
@Test public void testDebugWithException() { Logger mockLogger = mock(Logger.class); when(mockLogger.getName()).thenReturn("foo"); InternalLogger logger = new Slf4JLogger(mockLogger); logger.debug("a", e); verify(mockLogger).getName(); verify(mockLogger).debug("a", e); }
private ContentType getContentType(Exchange exchange) throws ParseException { String contentTypeStr = ExchangeHelper.getContentType(exchange); if (contentTypeStr == null) { contentTypeStr = DEFAULT_CONTENT_TYPE; } ContentType contentType = new ContentType(contentTypeStr); String contentEncoding = ExchangeHelper.getContentEncoding(exchange); // add a charset parameter for text subtypes if (contentEncoding != null && contentType.match("text/*")) { contentType.setParameter("charset", MimeUtility.mimeCharset(contentEncoding)); } return contentType; }
@Test public void attachmentReadOnce() throws IOException { String attContentType = "text/plain"; String attText = "Attachment Text"; InputStream attInputStream = new ByteArrayInputStream(attText.getBytes()); String attFileName = "Attachment File Name"; in.setBody("Body text"); in.setHeader(Exchange.CONTENT_TYPE, "text/plain;charset=iso8859-1;other-parameter=true"); in.setHeader("Content-Transfer-Encoding", "UTF8"); in.setHeader(Exchange.CONTENT_ENCODING, "UTF8"); Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Description", "Sample Attachment Data"); headers.put("X-AdditionalData", "additional data"); CountingByteArrayDataSource attachmentDs = new CountingByteArrayDataSource(attInputStream, attContentType); addAttachment(attachmentDs, attFileName, headers); Exchange result = template.send("direct:roundtrip", exchange); AttachmentMessage out = result.getMessage(AttachmentMessage.class); assertEquals("Body text", out.getBody(String.class)); assertTrue(out.getHeader(Exchange.CONTENT_TYPE, String.class).startsWith("text/plain")); assertEquals("UTF8", out.getHeader(Exchange.CONTENT_ENCODING)); assertTrue(out.hasAttachments()); assertEquals(1, out.getAttachmentNames().size()); assertTrue(out.getAttachmentNames().contains(attFileName)); Attachment att = out.getAttachmentObject(attFileName); DataHandler dh = att.getDataHandler(); assertNotNull(dh); assertEquals(attContentType, dh.getContentType()); InputStream is = dh.getInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); IOHelper.copyAndCloseInput(is, os); assertEquals(attText, new String(os.toByteArray())); assertEquals("Sample Attachment Data", att.getHeader("content-description")); assertEquals("additional data", att.getHeader("X-AdditionalData")); assertEquals(1, attachmentDs.readCounts); // Fails - input is read twice }
List<GcpAddress> instances(String project, String zone, Label label, String accessToken) { String response = RestClient .create(urlFor(project, zone, label)) .withHeader("Authorization", String.format("OAuth %s", accessToken)) .get() .getBody(); List<GcpAddress> result = new ArrayList<>(); for (JsonValue item : toJsonArray(Json.parse(response).asObject().get("items"))) { if ("RUNNING".equals(item.asObject().get("status").asString())) { String privateAddress = null; String publicAddress = null; for (JsonValue networkInterface : toJsonArray(item.asObject().get("networkInterfaces"))) { privateAddress = networkInterface.asObject().getString("networkIP", null); for (JsonValue accessConfig : toJsonArray(networkInterface.asObject().get("accessConfigs"))) { publicAddress = accessConfig.asObject().getString("natIP", null); } } if (privateAddress != null) { result.add(new GcpAddress(privateAddress, publicAddress)); } } } return result; }
@Test public void instances() { // given stubFor(get(urlEqualTo( String.format("/compute/v1/projects/%s/zones/%s/instances?filter=labels.%s+eq+%s", PROJECT, ZONE, LABEL_KEY, LABEL_VALUE))) .withHeader("Authorization", equalTo(String.format("OAuth %s", ACCESS_TOKEN))) .willReturn(aResponse().withStatus(HttpURLConnection.HTTP_OK).withBody(instancesResponse()))); Label label = new Label(String.format("%s=%s", LABEL_KEY, LABEL_VALUE)); // when List<GcpAddress> result = gcpComputeApi.instances(PROJECT, ZONE, label, ACCESS_TOKEN); // then GcpAddress address1 = new GcpAddress(INSTANCE_1_PRIVATE_IP, INSTANCE_1_PUBLIC_IP); GcpAddress address2 = new GcpAddress(INSTANCE_2_PRIVATE_IP, INSTANCE_2_PUBLIC_IP); assertEquals(asList(address1, address2), result); }
@Override public synchronized void editSchedule() { updateConfigIfNeeded(); long startTs = clock.getTime(); CSQueue root = scheduler.getRootQueue(); Resource clusterResources = Resources.clone(scheduler.getClusterResource()); containerBasedPreemptOrKill(root, clusterResources); if (LOG.isDebugEnabled()) { LOG.debug("Total time used=" + (clock.getTime() - startTs) + " ms."); } }
@Test public void testExpireKill() { final long killTime = 10000L; int[][] qData = new int[][]{ // / A B C { 100, 40, 40, 20 }, // abs { 100, 100, 100, 100 }, // maxCap { 100, 0, 60, 40 }, // used { 10, 10, 0, 0 }, // pending { 0, 0, 0, 0 }, // reserved { 3, 1, 1, 1 }, // apps { -1, 1, 1, 1 }, // req granularity { 3, 0, 0, 0 }, // subqueues }; conf.setLong( CapacitySchedulerConfiguration.PREEMPTION_WAIT_TIME_BEFORE_KILL, killTime); ProportionalCapacityPreemptionPolicy policy = buildPolicy(qData); // ensure all pending rsrc from A get preempted from other queues when(mClock.getTime()).thenReturn(0L); policy.editSchedule(); verify(mDisp, times(10)).handle(argThat(new IsPreemptionRequestFor(appC))); // requests reiterated when(mClock.getTime()).thenReturn(killTime / 2); policy.editSchedule(); verify(mDisp, times(10)).handle(argThat(new IsPreemptionRequestFor(appC))); // kill req sent when(mClock.getTime()).thenReturn(killTime + 1); policy.editSchedule(); verify(mDisp, times(20)).handle(evtCaptor.capture()); List<ContainerPreemptEvent> events = evtCaptor.getAllValues(); for (ContainerPreemptEvent e : events.subList(20, 20)) { assertEquals(appC, e.getAppId()); assertEquals(MARK_CONTAINER_FOR_KILLABLE, e.getType()); } }
public void waitUntilFinished() { while ( !isFinished() && !job.isStopped() ) { try { Thread.sleep( 0, 1 ); } catch ( InterruptedException e ) { // Ignore errors } } }
@Test public void testWaitUntilFinished() throws Exception { when( mockJob.isStopped() ).thenReturn( true ); when( mockJob.getParentJob() ).thenReturn( parentJob ); when( parentJob.isStopped() ).thenReturn( false ); when( mockJob.execute( Mockito.anyInt(), Mockito.any( Result.class ) ) ).thenReturn( mockResult ); jobRunner.waitUntilFinished(); }
public long getId() { return id; }
@Test public void getMethodTest() { Assert.assertEquals(indexId, index.getId()); }
@Override public BeamSqlTable buildBeamSqlTable(Table table) { return new MongoDbTable(table); }
@Test public void testBuildBeamSqlTable_withUsernameAndPassword() { Table table = fakeTable("TEST", "mongodb://username:pasword@localhost:27017/database/collection"); BeamSqlTable sqlTable = provider.buildBeamSqlTable(table); assertNotNull(sqlTable); assertTrue(sqlTable instanceof MongoDbTable); MongoDbTable mongoTable = (MongoDbTable) sqlTable; assertEquals("mongodb://username:pasword@localhost:27017", mongoTable.dbUri); assertEquals("database", mongoTable.dbName); assertEquals("collection", mongoTable.dbCollection); }
@Override public List<Long> getTenantIdList() { List<TenantDO> tenants = tenantMapper.selectList(); return CollectionUtils.convertList(tenants, TenantDO::getId); }
@Test public void testGetTenantIdList() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L)); tenantMapper.insert(tenant); // 调用,并断言业务异常 List<Long> result = tenantService.getTenantIdList(); assertEquals(Collections.singletonList(1L), result); }
@Nonnull public static List<JetSqlRow> evaluate( @Nullable Expression<Boolean> predicate, @Nullable List<Expression<?>> projection, @Nonnull Stream<JetSqlRow> rows, @Nonnull ExpressionEvalContext context ) { return rows .map(row -> evaluate(predicate, projection, row, context)) .filter(Objects::nonNull) .collect(Collectors.toList()); }
@Test public void test_evaluateWithProjection() { List<Object[]> rows = asList(new Object[]{0, "a"}, new Object[]{1, "b"}, new Object[]{2, "c"}); MultiplyFunction<?> projection = MultiplyFunction.create(ColumnExpression.create(0, INT), ConstantExpression.create(2, INT), INT); List<JetSqlRow> evaluated = ExpressionUtil.evaluate(null, singletonList(projection), rows.stream().map(v -> new JetSqlRow(TEST_SS, v)), mock(ExpressionEvalContext.class)); assertThat(toList(evaluated, JetSqlRow::getValues)).containsExactly(new Object[]{0}, new Object[]{2}, new Object[]{4}); }
String getJwtFromBearerAuthorization(HttpServletRequest req) { String authorizationHeader = req.getHeader(HttpHeader.AUTHORIZATION.asString()); if (authorizationHeader == null || !authorizationHeader.startsWith(BEARER)) { return null; } else { return authorizationHeader.substring(BEARER.length()).trim(); } }
@Test public void testParseTokenFromAuthHeader() { JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN); HttpServletRequest request = mock(HttpServletRequest.class); expect(request.getHeader(HttpHeader.AUTHORIZATION.asString())).andReturn(JwtAuthenticator.BEARER + " " + EXPECTED_TOKEN); replay(request); String actualToken = authenticator.getJwtFromBearerAuthorization(request); verify(request); assertEquals(EXPECTED_TOKEN, actualToken); }
public static void checkParamV2(String tag) throws NacosApiException { if (StringUtils.isNotBlank(tag)) { if (!isValid(tag.trim())) { throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.PARAMETER_VALIDATE_ERROR, "invalid tag : " + tag); } if (tag.length() > TAG_MAX_LEN) { throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.PARAMETER_VALIDATE_ERROR, "too long tag, over 16"); } } }
@Test void testCheckParamV2() { //tag invalid String tag = "test!"; try { ParamUtils.checkParam(tag); fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } //tag over length tag = "testtesttesttest1"; try { ParamUtils.checkParam(tag); fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } }
public static Driver load(String className) throws DriverLoadException { final ClassLoader loader = DriverLoader.class.getClassLoader(); return load(className, loader); }
@Test public void testLoad_String() throws SQLException { String className = "org.h2.Driver"; Driver d = null; try { d = DriverLoader.load(className); } catch (DriverLoadException ex) { fail(ex.getMessage()); } finally { if (d != null) { DriverManager.deregisterDriver(d); } } }
@Override public void download(String src, File destFile) { get(src, FileUtil.getAbsolutePath(destFile)); }
@Test @Disabled public void downloadTest() { sshjSftp.recursiveDownloadFolder("/home/test/temp", new File("C:\\Users\\akwangl\\Downloads\\temp")); }
public List<String> getRoles() { ArrayList<String> sortedRoles = new ArrayList<>(roles); Collections.sort(sortedRoles); return sortedRoles; }
@Test public void shouldReturnSortedRoles() { UserModel foo = new UserModel(new User("foo", new ArrayList<>(), "foo@bar.com", false), List.of("bbb", "aaa", "BBB"), true); assertThat(foo.getRoles(), is(List.of("BBB", "aaa", "bbb"))); }
@Override public byte[] deserialize(Asn1ObjectInputStream in) { return in.readAll(); }
@Test public void shouldDeserialize() { assertArrayEquals(new byte[] { 0x31 }, deserialize( new ByteArrayConverter(), byte[].class, new byte[] { 0x31 } )); }
public static String buildStoreNamePrefix(Scheme scheme) { // rule of key: /registry/[group]/plural-name/extension-name StringBuilder builder = new StringBuilder("/registry/"); if (StringUtils.hasText(scheme.groupVersionKind().group())) { builder.append(scheme.groupVersionKind().group()).append('/'); } builder.append(scheme.plural()); return builder.toString(); }
@Test void buildStoreNamePrefix() { var prefix = ExtensionStoreUtil.buildStoreNamePrefix(scheme); assertEquals("/registry/fake.halo.run/fakes", prefix); prefix = ExtensionStoreUtil.buildStoreNamePrefix(grouplessScheme); assertEquals("/registry/fakes", prefix); }
<T extends PipelineOptions> T as(Class<T> iface) { checkNotNull(iface); checkArgument(iface.isInterface(), "Not an interface: %s", iface); T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface); if (existingOption == null) { synchronized (this) { // double check existingOption = computedProperties.interfaceToProxyCache.getInstance(iface); if (existingOption == null) { Registration<T> registration = PipelineOptionsFactory.CACHE .get() .validateWellFormed(iface, computedProperties.knownInterfaces); List<PropertyDescriptor> propertyDescriptors = registration.getPropertyDescriptors(); Class<T> proxyClass = registration.getProxyClass(); existingOption = InstanceBuilder.ofType(proxyClass) .fromClass(proxyClass) .withArg(InvocationHandler.class, this) .build(); computedProperties = computedProperties.updated(iface, existingOption, propertyDescriptors); } } } return existingOption; }
@Test public void testDisplayDataNullValuesConvertedToEmptyString() throws Exception { FooOptions options = PipelineOptionsFactory.as(FooOptions.class); options.setFoo(null); DisplayData data = DisplayData.from(options); assertThat(data, hasDisplayItem("foo", "")); FooOptions deserializedOptions = serializeDeserialize(FooOptions.class, options); DisplayData deserializedData = DisplayData.from(deserializedOptions); assertThat(deserializedData, hasDisplayItem("foo", "")); }
public List<String> extensionNames() { return stream().map(PluginInfo::getExtensionName).collect(toList()); }
@Test public void shouldGetExtensionNamesOfAllExtensionsContainedWithin() { CombinedPluginInfo pluginInfo = new CombinedPluginInfo(List.of( new PluggableTaskPluginInfo(null, null, null), new NotificationPluginInfo(null, null))); assertThat(pluginInfo.extensionNames().size(), is(2)); assertThat(pluginInfo.extensionNames(), hasItems(NOTIFICATION_EXTENSION, PLUGGABLE_TASK_EXTENSION)); }
@Override public int compareTo(RestartRequest o) { int result = connectorName.compareTo(o.connectorName); return result == 0 ? impactRank() - o.impactRank() : result; }
@Test public void compareImpact() { RestartRequest onlyFailedConnector = new RestartRequest(CONNECTOR_NAME, true, false); RestartRequest failedConnectorAndTasks = new RestartRequest(CONNECTOR_NAME, true, true); RestartRequest onlyConnector = new RestartRequest(CONNECTOR_NAME, false, false); RestartRequest connectorAndTasks = new RestartRequest(CONNECTOR_NAME, false, true); List<RestartRequest> restartRequests = Arrays.asList(connectorAndTasks, onlyConnector, onlyFailedConnector, failedConnectorAndTasks); Collections.sort(restartRequests); assertEquals(onlyFailedConnector, restartRequests.get(0)); assertEquals(failedConnectorAndTasks, restartRequests.get(1)); assertEquals(onlyConnector, restartRequests.get(2)); assertEquals(connectorAndTasks, restartRequests.get(3)); RestartRequest onlyFailedDiffConnector = new RestartRequest(CONNECTOR_NAME + "foo", true, false); assertTrue(onlyFailedConnector.compareTo(onlyFailedDiffConnector) != 0); }
public UniVocityFixedDataFormat setFieldLengths(int[] fieldLengths) { this.fieldLengths = fieldLengths; return this; }
@Test public void shouldConfigureHeadersDisabled() { UniVocityFixedDataFormat dataFormat = new UniVocityFixedDataFormat() .setFieldLengths(new int[] { 1, 2, 3 }) .setHeadersDisabled(true); assertTrue(dataFormat.isHeadersDisabled()); assertNull(dataFormat.createAndConfigureWriterSettings().getHeaders()); assertNull(dataFormat.createAndConfigureParserSettings().getHeaders()); }
static InetSocketAddress parse( final String value, final String uriParamName, final boolean isReResolution, final NameResolver nameResolver) { if (Strings.isEmpty(value)) { throw new NullPointerException("input string must not be null or empty"); } final String nameAndPort = nameResolver.lookup(value, uriParamName, isReResolution); ParseResult result = tryParseIpV4(nameAndPort); if (null == result) { result = tryParseIpV6(nameAndPort); } if (null == result) { throw new IllegalArgumentException("invalid format: " + nameAndPort); } final InetAddress inetAddress = nameResolver.resolve(result.host, uriParamName, isReResolution); return null == inetAddress ? InetSocketAddress.createUnresolved(result.host, result.port) : new InetSocketAddress(inetAddress, result.port); }
@Test void shouldRejectOnInvalidIpV6() { assertThrows(IllegalArgumentException.class, () -> SocketAddressParser.parse( "[FG07::789:1:0:0:3]:111", ENDPOINT_PARAM_NAME, false, DEFAULT_RESOLVER)); }
public Result checkout(String pluginId, final SCMPropertyConfiguration scmConfiguration, final String destinationFolder, final SCMRevision revision) { return pluginRequestHelper.submitRequest(pluginId, SCMExtension.REQUEST_CHECKOUT, new DefaultPluginInteractionCallback<>() { @Override public String requestBody(String resolvedExtensionVersion) { return messageHandlerMap.get(resolvedExtensionVersion).requestMessageForCheckout(scmConfiguration, destinationFolder, revision); } @Override public Result onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return messageHandlerMap.get(resolvedExtensionVersion).responseMessageForCheckout(responseBody); } }); }
@Test public void shouldTalkToPluginToCheckout() throws Exception { String destination = "destination"; SCMRevision revision = new SCMRevision(); when(jsonMessageHandler.requestMessageForCheckout(scmPropertyConfiguration, destination, revision)).thenReturn(requestBody); Result deserializedResponse = new Result(); when(jsonMessageHandler.responseMessageForCheckout(responseBody)).thenReturn(deserializedResponse); Result response = scmExtension.checkout(PLUGIN_ID, scmPropertyConfiguration, destination, revision); assertRequest(requestArgumentCaptor.getValue(), SCM_EXTENSION, "1.0", SCMExtension.REQUEST_CHECKOUT, requestBody); verify(jsonMessageHandler).requestMessageForCheckout(scmPropertyConfiguration, destination, revision); verify(jsonMessageHandler).responseMessageForCheckout(responseBody); assertSame(response, deserializedResponse); }
@Override public byte[] serialize(final String topic, final List<?> data) { if (data == null) { return null; } try { final StringWriter stringWriter = new StringWriter(); final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat); csvPrinter.printRecord(() -> new FieldIterator(data, schema)); final String result = stringWriter.toString(); return result.substring(0, result.length() - 2).getBytes(StandardCharsets.UTF_8); } catch (final Exception e) { throw new SerializationException("Error serializing CSV message", e); } }
@Test public void shouldSerializeRowWithNull() { // Given: final List<?> values = Arrays.asList(1511897796092L, 1L, "item_1", null, null, null, null, null, null); // When: final byte[] bytes = serializer.serialize("t1", values); // Then: final String delimitedString = new String(bytes, StandardCharsets.UTF_8); assertThat(delimitedString, equalTo("1511897796092,1,item_1,,,,,,")); }
@Override @MethodNotAvailable public CompletionStage<V> getAsync(K key) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testGetAsync() { adapter.getAsync(42); }
@Override public List<String> pop(String queueName, int count, int timeout) { List<String> tasks = new ArrayList<>(count); if (!queues.containsKey(queueName)) { queues.put(queueName, new ConcurrentLinkedDeque<>()); } for (int i = 0; i < count; ++i) { String entry = queues.get(queueName).pollFirst(); if (entry != null) { tasks.add(entry); } else { break; } } if (!tasks.isEmpty()) { LOG.info("pop messages [{}] for queue [{}]", tasks, queueName); } return tasks; }
@Test public void testPop() { String queueName = "test-queue"; String id = "abcd-1234-defg-5678"; assertEquals(Collections.emptyList(), queueDao.pop(queueName, 2, 100)); queueDao.pushIfNotExists(queueName, id, 123); assertEquals(Collections.singletonList(id), queueDao.pop(queueName, 2, 100)); assertEquals(Collections.emptyList(), queueDao.pop(queueName, 2, 100)); }
@Override public void append(LogEvent event) { all.mark(); switch (event.getLevel().getStandardLevel()) { case TRACE: trace.mark(); break; case DEBUG: debug.mark(); break; case INFO: info.mark(); break; case WARN: warn.mark(); break; case ERROR: error.mark(); break; case FATAL: fatal.mark(); break; default: break; } }
@Test public void metersDebugEvents() { when(event.getLevel()).thenReturn(Level.DEBUG); appender.append(event); assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) .isEqualTo(1); assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()) .isEqualTo(1); }
boolean touches(Bubble b) { //distance between them is greater than sum of radii (both sides of equation squared) return (this.coordinateX - b.coordinateX) * (this.coordinateX - b.coordinateX) + (this.coordinateY - b.coordinateY) * (this.coordinateY - b.coordinateY) <= (this.radius + b.radius) * (this.radius + b.radius); }
@Test void touchesTest() { var b1 = new Bubble(0, 0, 1, 2); var b2 = new Bubble(1, 1, 2, 1); var b3 = new Bubble(10, 10, 3, 1); //b1 touches b2 but not b3 assertTrue(b1.touches(b2)); assertFalse(b1.touches(b3)); }
@Override public String named() { return PluginEnum.RATE_LIMITER.getName(); }
@Test public void namedTest() { assertEquals(PluginEnum.RATE_LIMITER.getName(), rateLimiterPlugin.named()); }
public abstract VoiceInstructionValue getConfigForDistance( double distance, String turnDescription, String thenVoiceInstruction);
@Test public void fixedDistanceInitialVICMetricTest() { FixedDistanceVoiceInstructionConfig configMetric = new FixedDistanceVoiceInstructionConfig(IN_HIGHER_DISTANCE_PLURAL.metric, trMap, locale, 2000, 2); compareVoiceInstructionValues( 2000, "In 2 kilometers turn", configMetric.getConfigForDistance(2100, "turn", " then") ); compareVoiceInstructionValues( 2000, "In 2 kilometers turn", configMetric.getConfigForDistance(2000, "turn", " then") ); assertNull(configMetric.getConfigForDistance(1999, "turn", " then")); }
@Override public YamlSQLParserRuleConfiguration swapToYamlConfiguration(final SQLParserRuleConfiguration data) { YamlSQLParserRuleConfiguration result = new YamlSQLParserRuleConfiguration(); result.setParseTreeCache(cacheOptionSwapper.swapToYamlConfiguration(data.getParseTreeCache())); result.setSqlStatementCache(cacheOptionSwapper.swapToYamlConfiguration(data.getSqlStatementCache())); return result; }
@Test void assertSwapToYamlConfiguration() { SQLParserRuleConfiguration ruleConfig = new SQLParserRuleConfiguration(new CacheOption(2, 5L), new CacheOption(4, 7L)); YamlSQLParserRuleConfiguration actual = new YamlSQLParserRuleConfigurationSwapper().swapToYamlConfiguration(ruleConfig); assertThat(actual.getParseTreeCache().getInitialCapacity(), is(2)); assertThat(actual.getParseTreeCache().getMaximumSize(), is(5L)); assertThat(actual.getSqlStatementCache().getInitialCapacity(), is(4)); assertThat(actual.getSqlStatementCache().getMaximumSize(), is(7L)); }
public static void init(Class<?> clazz) { String rs = clazz.getResource("").toString(); if (rs.contains(SUFFIX_JAR)) { isJarContext = true; } }
@Test public void testInit() { DynamicContext.init(DynamicContext.class); }
public static double byte2MemorySize(final long byteNum, @MemoryConst.Unit final int unit) { if (byteNum < 0) return -1; return (double) byteNum / unit; }
@Test public void byte2MemorySize() throws Exception { Assert.assertEquals( 1024, ConvertKit.byte2MemorySize(MemoryConst.GB, MemoryConst.MB), 0.001 ); }
@Override public List<TransferItem> normalize(final List<TransferItem> roots) { final List<TransferItem> normalized = new ArrayList<>(); for(final TransferItem download : roots) { boolean duplicate = false; for(Iterator<TransferItem> iter = normalized.iterator(); iter.hasNext(); ) { TransferItem n = iter.next(); if(download.remote.isChild(n.remote)) { // The selected file is a child of a directory already included duplicate = true; break; } if(n.remote.isChild(download.remote)) { iter.remove(); } if(download.local.equals(n.local)) { // The selected file has the same name; if downloaded as a root element // it would overwrite the earlier final String parent = download.local.getParent().getAbsolute(); final String filename = download.remote.getName(); String proposal; int no = 0; Local local; do { proposal = String.format("%s-%d", FilenameUtils.getBaseName(filename), ++no); if(StringUtils.isNotBlank(Path.getExtension(filename))) { proposal += String.format(".%s", Path.getExtension(filename)); } local = LocalFactory.get(parent, proposal); } while(local.exists()); if(log.isInfoEnabled()) { log.info(String.format("Changed local name from %s to %s", filename, local.getName())); } download.local = local; } } // Prunes the list of selected files. Files which are a child of an already included directory // are removed from the returned list. if(!duplicate) { normalized.add(new TransferItem(download.remote, download.local)); } } return normalized; }
@Test public void testNormalize() { DownloadRootPathsNormalizer n = new DownloadRootPathsNormalizer(); final List<TransferItem> list = new ArrayList<>(); list.add(new TransferItem(new Path("/a", EnumSet.of(Path.Type.directory)), new NullLocal(System.getProperty("java.io.tmpdir"), "a"))); list.add(new TransferItem(new Path("/a/b", EnumSet.of(Path.Type.file)), new NullLocal(System.getProperty("java.io.tmpdir"), "a/b"))); final List<TransferItem> normalized = n.normalize(list); assertEquals(1, normalized.size()); assertEquals(new Path("/a", EnumSet.of(Path.Type.directory)), normalized.iterator().next().remote); }
public static Counter allocate( final Aeron aeron, final UnsafeBuffer tempBuffer, final long archiveId, final long recordingId, final int sessionId, final int streamId, final String strippedChannel, final String sourceIdentity) { tempBuffer.putLong(RECORDING_ID_OFFSET, recordingId); tempBuffer.putInt(SESSION_ID_OFFSET, sessionId); final int sourceIdentityLength = Math.min( sourceIdentity.length(), MAX_KEY_LENGTH - SOURCE_IDENTITY_OFFSET - SIZE_OF_LONG); tempBuffer.putInt(SOURCE_IDENTITY_LENGTH_OFFSET, sourceIdentityLength); tempBuffer.putStringWithoutLengthAscii(SOURCE_IDENTITY_OFFSET, sourceIdentity, 0, sourceIdentityLength); final int archiveIdOffset = SOURCE_IDENTITY_OFFSET + sourceIdentityLength; tempBuffer.putLong(archiveIdOffset, archiveId); final int keyLength = archiveIdOffset + SIZE_OF_LONG; final int labelOffset = BitUtil.align(keyLength, SIZE_OF_INT); int labelLength = 0; labelLength += tempBuffer.putStringWithoutLengthAscii(labelOffset, NAME + ": "); labelLength += tempBuffer.putLongAscii(labelOffset + labelLength, recordingId); labelLength += tempBuffer.putStringWithoutLengthAscii(labelOffset + labelLength, " "); labelLength += tempBuffer.putIntAscii(labelOffset + labelLength, sessionId); labelLength += tempBuffer.putStringWithoutLengthAscii(labelOffset + labelLength, " "); labelLength += tempBuffer.putIntAscii(labelOffset + labelLength, streamId); labelLength += tempBuffer.putStringWithoutLengthAscii(labelOffset + labelLength, " "); labelLength += tempBuffer.putStringWithoutLengthAscii( labelOffset + labelLength, strippedChannel, 0, MAX_LABEL_LENGTH - labelLength - ArchiveCounters.lengthOfArchiveIdLabel(archiveId)); labelLength += ArchiveCounters.appendArchiveIdLabel(tempBuffer, labelOffset + labelLength, archiveId); return aeron.addCounter( RECORDING_POSITION_TYPE_ID, tempBuffer, 0, keyLength, tempBuffer, labelOffset, labelLength); }
@Test void allocateShouldAlignLabelByFourBytes() { final long archiveId = 888; final long recordingId = 1; final int sessionId = 30; final int streamId = 222; final String strippedChannel = "channel"; final String sourceIdentity = "source"; final UnsafeBuffer tempBuffer = new UnsafeBuffer(new byte[METADATA_LENGTH]); final Counter counter = mock(Counter.class); final Aeron aeron = mock(Aeron.class); when(aeron.addCounter( eq(RECORDING_POSITION_TYPE_ID), eq(tempBuffer), eq(0), eq(30), eq(tempBuffer), eq(32), eq(41))) .thenReturn(counter); final Counter result = RecordingPos.allocate( aeron, tempBuffer, archiveId, recordingId, sessionId, streamId, strippedChannel, sourceIdentity); assertSame(counter, result); int offset = 0; assertEquals(recordingId, tempBuffer.getLong(offset)); offset += SIZE_OF_LONG; assertEquals(sessionId, tempBuffer.getInt(offset)); offset += SIZE_OF_INT; assertEquals(sourceIdentity.length(), tempBuffer.getInt(offset)); offset += SIZE_OF_INT; assertEquals(sourceIdentity, tempBuffer.getStringWithoutLengthAscii(offset, sourceIdentity.length())); offset += sourceIdentity.length(); assertEquals(archiveId, tempBuffer.getLong(offset)); offset += SIZE_OF_LONG; offset = BitUtil.align(offset, SIZE_OF_INT); final String expectedLabelPrefix = "rec-pos: 1 30 222 "; assertEquals(expectedLabelPrefix, tempBuffer.getStringWithoutLengthAscii(offset, expectedLabelPrefix.length())); offset += expectedLabelPrefix.length(); assertEquals(strippedChannel, tempBuffer.getStringWithoutLengthAscii(offset, strippedChannel.length())); offset += strippedChannel.length(); assertEquals( " - archiveId=888", tempBuffer.getStringWithoutLengthAscii(offset, ArchiveCounters.lengthOfArchiveIdLabel(archiveId))); }
void execute(Runnable runnable) { try { runnable.run(); } catch (Throwable t) { rethrowIfUnrecoverable(t); add(t); } }
@Test void rethrows_unrecoverable() { assertThrows(OutOfMemoryError.class, () -> collector.execute(() -> { throw new OutOfMemoryError(); })); }
public static double shuffleCompressionRatio( SparkSession spark, FileFormat outputFileFormat, String outputCodec) { if (outputFileFormat == FileFormat.ORC || outputFileFormat == FileFormat.PARQUET) { return columnarCompression(shuffleCodec(spark), outputCodec); } else if (outputFileFormat == FileFormat.AVRO) { return rowBasedCompression(shuffleCodec(spark), outputCodec); } else { return 1.0; } }
@Test public void testOrcCompressionRatios() { configureShuffle("lz4", true); double ratio1 = shuffleCompressionRatio(ORC, "zlib"); assertThat(ratio1).isEqualTo(3.0); double ratio2 = shuffleCompressionRatio(ORC, "lz4"); assertThat(ratio2).isEqualTo(2.0); }
T call() throws IOException, RegistryException { String apiRouteBase = "https://" + registryEndpointRequestProperties.getServerUrl() + "/v2/"; URL initialRequestUrl = registryEndpointProvider.getApiRoute(apiRouteBase); return call(initialRequestUrl); }
@Test public void testCall_unknown() throws IOException, RegistryException { ResponseException responseException = mockResponseException(HttpStatusCodes.STATUS_CODE_SERVER_ERROR); setUpRegistryResponse(responseException); try { endpointCaller.call(); Assert.fail("Call should have failed"); } catch (ResponseException ex) { Assert.assertSame(responseException, ex); } }
Path getTemporaryDirectory() { return cacheDirectory.resolve(TEMPORARY_DIRECTORY); }
@Test public void testGetTemporaryDirectory() { Assert.assertEquals( Paths.get("cache/directory/tmp"), TEST_CACHE_STORAGE_FILES.getTemporaryDirectory()); }
public static <T> Either<String, T> resolveImportDMN(Import importElement, Collection<T> dmns, Function<T, QName> idExtractor) { final String importerDMNNamespace = ((Definitions) importElement.getParent()).getNamespace(); final String importerDMNName = ((Definitions) importElement.getParent()).getName(); final String importNamespace = importElement.getNamespace(); final String importName = importElement.getName(); final String importLocationURI = importElement.getLocationURI(); // This is optional final String importModelName = importElement.getAdditionalAttributes().get(TImport.MODELNAME_QNAME); LOGGER.debug("Resolving an Import in DMN Model with name={} and namespace={}. " + "Importing a DMN model with namespace={} name={} locationURI={}, modelName={}", importerDMNName, importerDMNNamespace, importNamespace, importName, importLocationURI, importModelName); List<T> matchingDMNList = dmns.stream() .filter(m -> idExtractor.apply(m).getNamespaceURI().equals(importNamespace)) .toList(); if (matchingDMNList.size() == 1) { T located = matchingDMNList.get(0); // Check if the located DMN Model in the NS, correspond for the import `drools:modelName`. if (importModelName == null || idExtractor.apply(located).getLocalPart().equals(importModelName)) { LOGGER.debug("DMN Model with name={} and namespace={} successfully imported a DMN " + "with namespace={} name={} locationURI={}, modelName={}", importerDMNName, importerDMNNamespace, importNamespace, importName, importLocationURI, importModelName); return Either.ofRight(located); } else { LOGGER.error("DMN Model with name={} and namespace={} can't import a DMN with namespace={}, name={}, modelName={}, " + "located within namespace only {} but does not match for the actual modelName", importerDMNName, importerDMNNamespace, importNamespace, importName, importModelName, idExtractor.apply(located)); return Either.ofLeft(String.format( "DMN Model with name=%s and namespace=%s can't import a DMN with namespace=%s, name=%s, modelName=%s, " + "located within namespace only %s but does not match for the actual modelName", importerDMNName, importerDMNNamespace, importNamespace, importName, importModelName, idExtractor.apply(located))); } } else { List<T> usingNSandName = matchingDMNList.stream() .filter(dmn -> idExtractor.apply(dmn).getLocalPart().equals(importModelName)) .toList(); if (usingNSandName.size() == 1) { LOGGER.debug("DMN Model with name={} and namespace={} successfully imported a DMN " + "with namespace={} name={} locationURI={}, modelName={}", importerDMNName, importerDMNNamespace, importNamespace, importName, importLocationURI, importModelName); return Either.ofRight(usingNSandName.get(0)); } else if (usingNSandName.isEmpty()) { LOGGER.error("DMN Model with name={} and namespace={} failed to import a DMN with namespace={} name={} locationURI={}, modelName={}.", importerDMNName, importerDMNNamespace, importNamespace, importName, importLocationURI, importModelName); return Either.ofLeft(String.format( "DMN Model with name=%s and namespace=%s failed to import a DMN with namespace=%s name=%s locationURI=%s, modelName=%s. ", importerDMNName, importerDMNNamespace, importNamespace, importName, importLocationURI, importModelName)); } else { LOGGER.error("DMN Model with name={} and namespace={} detected a collision ({} elements) trying to import a DMN with namespace={} name={} locationURI={}, modelName={}", importerDMNName, importerDMNNamespace, usingNSandName.size(), importNamespace, importName, importLocationURI, importModelName); return Either.ofLeft(String.format( "DMN Model with name=%s and namespace=%s detected a collision trying to import a DMN with %s namespace, " + "%s name and modelName %s. There are %s DMN files with the same namespace in your project. " + "Please change the DMN namespaces and make them unique to fix this issue.", importerDMNName, importerDMNNamespace, importNamespace, importName, importModelName, usingNSandName.size())); } } }
@Test void locateInNSnoModelNameWithAlias2() { final Import i = makeImport("nsA", "boh", null); final List<QName> available = Arrays.asList(new QName("nsA", "m1"), new QName("nsA", "m2"), new QName("nsB", "m3")); final Either<String, QName> result = ImportDMNResolverUtil.resolveImportDMN(i, available, Function.identity()); assertThat(result.isLeft()).isTrue(); }
@Override public Collection<LocalDataQueryResultRow> getRows(final ShowDistVariableStatement sqlStatement, final ContextManager contextManager) { ShardingSphereMetaData metaData = contextManager.getMetaDataContexts().getMetaData(); String variableName = sqlStatement.getName(); if (isConfigurationKey(variableName)) { return Collections.singleton(new LocalDataQueryResultRow(variableName.toLowerCase(), getConfigurationValue(metaData, variableName))); } if (isTemporaryConfigurationKey(variableName)) { return Collections.singleton(new LocalDataQueryResultRow(variableName.toLowerCase(), getTemporaryConfigurationValue(metaData, variableName))); } return Collections.singleton(new LocalDataQueryResultRow(variableName.toLowerCase(), getConnectionSize(variableName))); }
@Test void assertShowPropsVariableForTypedSPI() { when(contextManager.getMetaDataContexts().getMetaData().getProps()) .thenReturn(new ConfigurationProperties(PropertiesBuilder.build(new Property("proxy-frontend-database-protocol-type", "MySQL")))); ShowDistVariableExecutor executor = new ShowDistVariableExecutor(); Collection<LocalDataQueryResultRow> actual = executor.getRows(new ShowDistVariableStatement("PROXY_FRONTEND_DATABASE_PROTOCOL_TYPE"), contextManager); assertThat(actual.size(), is(1)); LocalDataQueryResultRow row = actual.iterator().next(); assertThat(row.getCell(1), is("proxy_frontend_database_protocol_type")); assertThat(row.getCell(2), is("MySQL")); }
@Override public synchronized void editSchedule() { updateConfigIfNeeded(); long startTs = clock.getTime(); CSQueue root = scheduler.getRootQueue(); Resource clusterResources = Resources.clone(scheduler.getClusterResource()); containerBasedPreemptOrKill(root, clusterResources); if (LOG.isDebugEnabled()) { LOG.debug("Total time used=" + (clock.getTime() - startTs) + " ms."); } }
@Test public void testHierarchical() { int[][] qData = new int[][] { // / A B C D E F { 200, 100, 50, 50, 100, 10, 90 }, // abs { 200, 200, 200, 200, 200, 200, 200 }, // maxCap { 200, 110, 60, 50, 90, 90, 0 }, // used { 10, 0, 0, 0, 10, 0, 10 }, // pending { 0, 0, 0, 0, 0, 0, 0 }, // reserved { 4, 2, 1, 1, 2, 1, 1 }, // apps { -1, -1, 1, 1, -1, 1, 1 }, // req granularity { 2, 2, 0, 0, 2, 0, 0 }, // subqueues }; ProportionalCapacityPreemptionPolicy policy = buildPolicy(qData); policy.editSchedule(); // verify capacity taken from A1, not B1 despite B1 being far over // its absolute guaranteed capacity verify(mDisp, times(10)).handle(argThat(new IsPreemptionRequestFor(appA))); }
public Account changeNumber(final Account account, final String number, @Nullable final IdentityKey pniIdentityKey, @Nullable final Map<Byte, ECSignedPreKey> deviceSignedPreKeys, @Nullable final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys, @Nullable final List<IncomingMessage> deviceMessages, @Nullable final Map<Byte, Integer> pniRegistrationIds) throws InterruptedException, MismatchedDevicesException, StaleDevicesException { if (ObjectUtils.allNotNull(pniIdentityKey, deviceSignedPreKeys, deviceMessages, pniRegistrationIds)) { // AccountsManager validates the device set on deviceSignedPreKeys and pniRegistrationIds validateDeviceMessages(account, deviceMessages); } else if (!ObjectUtils.allNull(pniIdentityKey, deviceSignedPreKeys, deviceMessages, pniRegistrationIds)) { throw new IllegalArgumentException("PNI identity key, signed pre-keys, device messages, and registration IDs must be all null or all non-null"); } if (number.equals(account.getNumber())) { // The client has gotten confused/desynchronized with us about their own phone number, most likely due to losing // our OK response to an immediately preceding change-number request, and are sending a change they don't realize // is a no-op change. // // We don't need to actually do a number-change operation in our DB, but we *do* need to accept their new key // material and distribute the sync messages, to be sure all clients agree with us and each other about what their // keys are. Pretend this change-number request was actually a PNI key distribution request. if (pniIdentityKey == null) { return account; } return updatePniKeys(account, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, deviceMessages, pniRegistrationIds); } final Account updatedAccount = accountsManager.changeNumber( account, number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds); if (deviceMessages != null) { sendDeviceMessages(updatedAccount, deviceMessages); } return updatedAccount; }
@Test void changeNumberMissingData() { final Account account = mock(Account.class); when(account.getNumber()).thenReturn("+18005551234"); final List<Device> devices = new ArrayList<>(); for (byte i = 1; i <= 3; i++) { final Device device = mock(Device.class); when(device.getId()).thenReturn(i); when(device.getRegistrationId()).thenReturn((int) i); devices.add(device); when(account.getDevice(i)).thenReturn(Optional.of(device)); } when(account.getDevices()).thenReturn(devices); final byte destinationDeviceId2 = 2; final byte destinationDeviceId3 = 3; final List<IncomingMessage> messages = List.of( new IncomingMessage(1, destinationDeviceId2, 2, "foo"), new IncomingMessage(1, destinationDeviceId3, 3, "foo")); final Map<Byte, Integer> registrationIds = Map.of((byte) 1, 17, destinationDeviceId2, 47, destinationDeviceId3, 89); assertThrows(IllegalArgumentException.class, () -> changeNumberManager.changeNumber(account, "+18005559876", new IdentityKey(Curve.generateKeyPair().getPublicKey()), null, null, messages, registrationIds)); }
public static OptionalInt getBucketNumber(String fileName) { for (Pattern pattern : BUCKET_PATTERNS) { Matcher matcher = pattern.matcher(fileName); if (matcher.matches()) { return OptionalInt.of(parseInt(matcher.group(1))); } } // Numerical file name when "file_renaming_enabled" is true if (fileName.matches("\\d+")) { return OptionalInt.of(parseInt(fileName)); } return OptionalInt.empty(); }
@Test public void testGetBucketNumber() { assertEquals(getBucketNumber("0234_0"), OptionalInt.of(234)); assertEquals(getBucketNumber("000234_0"), OptionalInt.of(234)); assertEquals(getBucketNumber("0234_99"), OptionalInt.of(234)); assertEquals(getBucketNumber("0234_0.txt"), OptionalInt.of(234)); assertEquals(getBucketNumber("0234_0_copy_1"), OptionalInt.of(234)); assertEquals(getBucketNumber("20190526_072952_00009_fn7s5_bucket-00234"), OptionalInt.of(234)); assertEquals(getBucketNumber("20190526_072952_00009_fn7s5_bucket-00234.txt"), OptionalInt.of(234)); assertEquals(getBucketNumber("20190526_235847_87654_fn7s5_bucket-56789"), OptionalInt.of(56789)); assertEquals(getBucketNumber("234_99"), OptionalInt.empty()); assertEquals(getBucketNumber("0234.txt"), OptionalInt.empty()); assertEquals(getBucketNumber("0234.txt"), OptionalInt.empty()); }
@Override protected boolean isInfinite(Long number) { // Infinity never applies here because only types like Float and Double have Infinity return false; }
@Test void testIsInfinite() { LongSummaryAggregator ag = new LongSummaryAggregator(); // always false for Long assertThat(ag.isInfinite(-1L)).isFalse(); assertThat(ag.isInfinite(0L)).isFalse(); assertThat(ag.isInfinite(23L)).isFalse(); assertThat(ag.isInfinite(Long.MAX_VALUE)).isFalse(); assertThat(ag.isInfinite(Long.MIN_VALUE)).isFalse(); assertThat(ag.isInfinite(null)).isFalse(); }
@Override public Page download(Request request, Task task) { if (task == null || task.getSite() == null) { throw new NullPointerException("task or site can not be null"); } CloseableHttpResponse httpResponse = null; CloseableHttpClient httpClient = getHttpClient(task.getSite()); Proxy proxy = proxyProvider != null ? proxyProvider.getProxy(request, task) : null; HttpClientRequestContext requestContext = httpUriRequestConverter.convert(request, task.getSite(), proxy); Page page = Page.fail(request); try { httpResponse = httpClient.execute(requestContext.getHttpUriRequest(), requestContext.getHttpClientContext()); page = handleResponse(request, request.getCharset() != null ? request.getCharset() : task.getSite().getCharset(), httpResponse, task); onSuccess(page, task); return page; } catch (IOException e) { onError(page, task, e); return page; } finally { if (httpResponse != null) { //ensure the connection is released back to pool EntityUtils.consumeQuietly(httpResponse.getEntity()); } if (proxyProvider != null && proxy != null) { proxyProvider.returnProxy(proxy, page, task); } } }
@Test public void test_download_fail() { HttpClientDownloader httpClientDownloader = new HttpClientDownloader(); Task task = Site.me().setDomain("localhost").setCycleRetryTimes(5).toTask(); Request request = new Request(PAGE_ALWAYS_NOT_EXISTS); Page page = httpClientDownloader.download(request, task); assertThat(page.isDownloadSuccess()).isFalse(); }
@Override protected Function3<EntityColumnMapping, Object[], Map<String, Object>, Object> compile(String sql) { StringBuilder builder = new StringBuilder(sql.length()); int argIndex = 0; for (int i = 0; i < sql.length(); i++) { char c = sql.charAt(i); if (c == '?') { builder.append("_arg").append(argIndex++); } else { builder.append(c); } } try { SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression(builder.toString()); AtomicLong errorCount = new AtomicLong(); return (mapping, args, object) -> { if (errorCount.get() > 1024) { return null; } object = createArguments(mapping, object); if (args != null && args.length != 0) { int index = 0; for (Object parameter : args) { object.put("_arg" + index, parameter); } } StandardEvaluationContext context = SHARED_CONTEXT.get(); try { context.setRootObject(object); Object val = expression.getValue(context); errorCount.set(0); return val; } catch (Throwable err) { log.warn("invoke native sql [{}] value error", sql, err); errorCount.incrementAndGet(); } finally { context.setRootObject(null); } return null; }; } catch (Throwable error) { return spelError(sql, error); } }
@Test void testAddNull(){ SpelSqlExpressionInvoker invoker = new SpelSqlExpressionInvoker(); EntityColumnMapping mapping = Mockito.mock(EntityColumnMapping.class); Function3<EntityColumnMapping, Object[], Map<String, Object>, Object> func = invoker.compile("IFNULL(test,0) + ?"); assertEquals(2, func.apply(mapping, new Object[]{2}, Collections.emptyMap())); }
public static InstrumentedThreadFactory defaultThreadFactory(MetricRegistry registry, String name) { return new InstrumentedThreadFactory(Executors.defaultThreadFactory(), registry, name); }
@Test public void testDefaultThreadFactory() throws Exception { final ThreadFactory threadFactory = InstrumentedExecutors.defaultThreadFactory(registry); threadFactory.newThread(new NoopRunnable()); final Field delegateField = InstrumentedThreadFactory.class.getDeclaredField("delegate"); delegateField.setAccessible(true); final ThreadFactory delegate = (ThreadFactory) delegateField.get(threadFactory); assertThat(delegate.getClass().getCanonicalName()).isEqualTo("java.util.concurrent.Executors.DefaultThreadFactory"); }
public static void cleanDirectory(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); // null if security restricted if (files == null) { throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (File file : files) { try { delete(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } }
@Test void testCleanDirectoryForNonExistingDirectory() throws IOException { assertThrows(IllegalArgumentException.class, () -> { File nonexistentDir = new File("non_exist"); IoUtils.cleanDirectory(nonexistentDir); }); }
protected void addNode(NodeEvent event) { String nodeName = event.getNodeName(); String url = event.getUrl(); String username = event.getUsername(); String password = event.getPassword(); Map<String, DataSource> map = highAvailableDataSource.getDataSourceMap(); if (nodeName == null || nodeName.isEmpty()) { return; } LOG.info("Adding Node " + nodeName + "[url: " + url + ", username: " + username + "]."); if (map.containsKey(nodeName)) { cancelBlacklistNode(nodeName); return; } DruidDataSource dataSource = null; try { dataSource = DataSourceCreator.create(nodeName, url, username, password, this.highAvailableDataSource); map.put(nodeName, dataSource); LOG.info("Creating Node " + nodeName + "[url: " + url + ", username: " + username + "]."); } catch (Exception e) { LOG.error("Can NOT create DataSource " + nodeName + ". IGNORE IT.", e); JdbcUtils.close(dataSource); } }
@Test public void testAddNode() { String url = "jdbc:derby:memory:foo;create=true"; String name = "foo"; addNode(url, name); String targetUrl = ((DruidDataSource) haDataSource.getDataSourceMap().get(name)).getUrl(); assertEquals(1, haDataSource.getDataSourceMap().size()); assertEquals(url, targetUrl); }
@Override public synchronized Snapshot record(long duration, TimeUnit durationUnit, Outcome outcome) { totalAggregation.record(duration, durationUnit, outcome); moveWindowByOne().record(duration, durationUnit, outcome); return new SnapshotImpl(totalAggregation); }
@Test public void testSlidingWindowMetricsWithSlowCalls() { FixedSizeSlidingWindowMetrics metrics = new FixedSizeSlidingWindowMetrics(2); Snapshot snapshot = metrics.record(100, TimeUnit.MILLISECONDS, Metrics.Outcome.SLOW_ERROR); assertThat(snapshot.getTotalNumberOfCalls()).isEqualTo(1); assertThat(snapshot.getTotalNumberOfSlowCalls()).isEqualTo(1); assertThat(snapshot.getNumberOfSuccessfulCalls()).isZero(); assertThat(snapshot.getNumberOfFailedCalls()).isEqualTo(1); assertThat(snapshot.getNumberOfSlowSuccessfulCalls()).isZero(); assertThat(snapshot.getNumberOfSlowFailedCalls()).isEqualTo(1); assertThat(snapshot.getTotalDuration().toMillis()).isEqualTo(100); assertThat(snapshot.getAverageDuration().toMillis()).isEqualTo(100); assertThat(snapshot.getFailureRate()).isEqualTo(100); snapshot = metrics.record(100, TimeUnit.MILLISECONDS, Metrics.Outcome.SLOW_SUCCESS); assertThat(snapshot.getTotalNumberOfCalls()).isEqualTo(2); assertThat(snapshot.getTotalNumberOfSlowCalls()).isEqualTo(2); assertThat(snapshot.getNumberOfSuccessfulCalls()).isEqualTo(1); assertThat(snapshot.getNumberOfFailedCalls()).isEqualTo(1); assertThat(snapshot.getNumberOfSlowSuccessfulCalls()).isEqualTo(1); assertThat(snapshot.getNumberOfSlowFailedCalls()).isEqualTo(1); assertThat(snapshot.getTotalDuration().toMillis()).isEqualTo(200); assertThat(snapshot.getAverageDuration().toMillis()).isEqualTo(100); assertThat(snapshot.getFailureRate()).isEqualTo(50); snapshot = metrics.record(100, TimeUnit.MILLISECONDS, Metrics.Outcome.SUCCESS); assertThat(snapshot.getTotalNumberOfCalls()).isEqualTo(2); assertThat(snapshot.getTotalNumberOfSlowCalls()).isEqualTo(1); assertThat(snapshot.getNumberOfSuccessfulCalls()).isEqualTo(2); assertThat(snapshot.getNumberOfFailedCalls()).isZero(); assertThat(snapshot.getNumberOfSlowSuccessfulCalls()).isEqualTo(1); assertThat(snapshot.getNumberOfSlowFailedCalls()).isZero(); assertThat(snapshot.getTotalDuration().toMillis()).isEqualTo(200); assertThat(snapshot.getAverageDuration().toMillis()).isEqualTo(100); assertThat(snapshot.getFailureRate()).isZero(); snapshot = metrics.record(100, TimeUnit.MILLISECONDS, Metrics.Outcome.SUCCESS); assertThat(snapshot.getTotalNumberOfCalls()).isEqualTo(2); assertThat(snapshot.getTotalNumberOfSlowCalls()).isZero(); assertThat(snapshot.getNumberOfSuccessfulCalls()).isEqualTo(2); assertThat(snapshot.getNumberOfFailedCalls()).isZero(); assertThat(snapshot.getNumberOfSlowSuccessfulCalls()).isZero(); assertThat(snapshot.getNumberOfSlowFailedCalls()).isZero(); assertThat(snapshot.getTotalDuration().toMillis()).isEqualTo(200); assertThat(snapshot.getAverageDuration().toMillis()).isEqualTo(100); assertThat(snapshot.getFailureRate()).isZero(); snapshot = metrics.record(100, TimeUnit.MILLISECONDS, Metrics.Outcome.SUCCESS); assertThat(snapshot.getTotalNumberOfCalls()).isEqualTo(2); assertThat(snapshot.getTotalNumberOfSlowCalls()).isZero(); assertThat(snapshot.getNumberOfSuccessfulCalls()).isEqualTo(2); assertThat(snapshot.getNumberOfFailedCalls()).isZero(); assertThat(snapshot.getNumberOfSlowSuccessfulCalls()).isZero(); assertThat(snapshot.getNumberOfSlowFailedCalls()).isZero(); assertThat(snapshot.getTotalDuration().toMillis()).isEqualTo(200); assertThat(snapshot.getAverageDuration().toMillis()).isEqualTo(100); assertThat(snapshot.getFailureRate()).isZero(); }
public void writeTo(OutputStream out, int offset, int length) throws IOException { out.write(buffer, offset, length); }
@Test public void testWriteTo() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); RandomAccessData stream = new RandomAccessData(); stream.asOutputStream().write(TEST_DATA_B); stream.writeTo(baos, 1, 2); assertArrayEquals(new byte[] {0x05, 0x04}, baos.toByteArray()); baos.close(); }
@Override public Optional<InetAddress> getLocalInetAddress(Predicate<InetAddress> predicate) { try { return Collections.list(NetworkInterface.getNetworkInterfaces()).stream() .flatMap(ni -> Collections.list(ni.getInetAddresses()).stream()) .filter(a -> a.getHostAddress() != null) .filter(predicate) .findFirst(); } catch (SocketException e) { LOG.trace("getLocalInetAddress(Predicate<InetAddress>) failed", e); throw new IllegalStateException("Can not retrieve network interfaces", e); } }
@Test public void getLocalInetAddress_filters_local_addresses() { InetAddress address = underTest.getLocalInetAddress(InetAddress::isLoopbackAddress).get(); assertThat(address.isLoopbackAddress()).isTrue(); }
public void loadV2(SRMetaBlockReader reader) throws IOException, SRMetaBlockException, SRMetaBlockEOFException { try { // 1 json for myself AuthorizationMgr ret = reader.readJson(AuthorizationMgr.class); ret.globalStateMgr = globalStateMgr; ret.provider = Objects.requireNonNullElseGet(provider, DefaultAuthorizationProvider::new); ret.initBuiltinRolesAndUsers(); // 1 json for num user int numUser = reader.readInt(); LOG.info("loading {} users", numUser); for (int i = 0; i != numUser; ++i) { // 2 json for each user(kv) UserIdentity userIdentity = reader.readJson(UserIdentity.class); UserPrivilegeCollectionV2 collection = reader.readJson(UserPrivilegeCollectionV2.class); if (userIdentity.equals(UserIdentity.ROOT)) { UserPrivilegeCollectionV2 rootUserPrivCollection = ret.getUserPrivilegeCollectionUnlocked(UserIdentity.ROOT); collection.grantRoles(rootUserPrivCollection.getAllRoles()); collection.setDefaultRoleIds(rootUserPrivCollection.getDefaultRoleIds()); collection.typeToPrivilegeEntryList = rootUserPrivCollection.typeToPrivilegeEntryList; } ret.userToPrivilegeCollection.put(userIdentity, collection); } // 1 json for num roles int numRole = reader.readInt(); LOG.info("loading {} roles", numRole); for (int i = 0; i != numRole; ++i) { // 2 json for each role(kv) Long roleId = reader.readLong(); RolePrivilegeCollectionV2 collection = reader.readJson(RolePrivilegeCollectionV2.class); // Use hard-code PrivilegeCollection in the memory as the built-in role permission. // The reason why need to replay from the image here // is because the associated information of the role-id is stored in the image. if (PrivilegeBuiltinConstants.IMMUTABLE_BUILT_IN_ROLE_IDS.contains(roleId)) { RolePrivilegeCollectionV2 builtInRolePrivilegeCollection = ret.roleIdToPrivilegeCollection.get(roleId); collection.typeToPrivilegeEntryList = builtInRolePrivilegeCollection.typeToPrivilegeEntryList; } ret.roleIdToPrivilegeCollection.put(roleId, collection); } LOG.info("loaded {} users, {} roles", ret.userToPrivilegeCollection.size(), ret.roleIdToPrivilegeCollection.size()); // mark data is loaded isLoaded = true; roleNameToId = ret.roleNameToId; pluginId = ret.pluginId; pluginVersion = ret.pluginVersion; userToPrivilegeCollection = ret.userToPrivilegeCollection; roleIdToPrivilegeCollection = ret.roleIdToPrivilegeCollection; // Initialize the Authorizer class in advance during the loading phase // to prevent loading errors and lack of permissions. Authorizer.getInstance(); } catch (PrivilegeException e) { throw new IOException("failed to load AuthorizationManager!", e); } }
@Test public void testLoadV2() throws Exception { GlobalStateMgr masterGlobalStateMgr = ctx.getGlobalStateMgr(); AuthorizationMgr masterManager = masterGlobalStateMgr.getAuthorizationMgr(); UtFrameUtils.PseudoJournalReplayer.resetFollowerJournalQueue(); setCurrentUserAndRoles(ctx, UserIdentity.ROOT); for (int i = 0; i != 2; ++i) { DDLStmtExecutor.execute(UtFrameUtils.parseStmtWithNewParser( "create role test_persist_role" + i, ctx), ctx); Assert.assertTrue(masterManager.checkRoleExists("test_persist_role" + i)); } UtFrameUtils.PseudoImage emptyImage = new UtFrameUtils.PseudoImage(); masterGlobalStateMgr.getAuthorizationMgr().saveV2(emptyImage.getImageWriter()); AuthorizationMgr authorizationMgr = new AuthorizationMgr(); SRMetaBlockReader reader = new SRMetaBlockReaderV2(emptyImage.getJsonReader()); authorizationMgr.loadV2(reader); Assert.assertNotNull(authorizationMgr.getRolePrivilegeCollection("test_persist_role0")); }
public ConfigurationProperty create(String key, String value, String encryptedValue, Boolean isSecure) { ConfigurationProperty configurationProperty = new ConfigurationProperty(); configurationProperty.setConfigurationKey(new ConfigurationKey(key)); if (isNotBlank(value) && isNotBlank(encryptedValue)) { configurationProperty.addError("configurationValue", "You may only specify `value` or `encrypted_value`, not both!"); configurationProperty.addError("encryptedValue", "You may only specify `value` or `encrypted_value`, not both!"); configurationProperty.setConfigurationValue(new ConfigurationValue(value)); configurationProperty.setEncryptedValue(new EncryptedConfigurationValue(encryptedValue)); return configurationProperty; } if (isSecure) { if (isNotBlank(encryptedValue)) { configurationProperty.setEncryptedValue(new EncryptedConfigurationValue(encryptedValue)); } if (isNotBlank(value)) { configurationProperty.setEncryptedValue(new EncryptedConfigurationValue(encrypt(value))); } } else { if (isNotBlank(encryptedValue)) { configurationProperty.addError("encryptedValue", "encrypted_value cannot be specified to a unsecured property."); configurationProperty.setEncryptedValue(new EncryptedConfigurationValue(encryptedValue)); } if (value != null) { configurationProperty.setConfigurationValue(new ConfigurationValue(value)); } } if (isNotBlank(configurationProperty.getEncryptedValue())) { configurationProperty.setEncryptedValue(new EncryptedConfigurationValue(configurationProperty.getEncryptedValue())); } return configurationProperty; }
@Test public void shouldCreateWithErrorsIfBothPlainAndEncryptedTextInputAreSpecifiedForSecureProperty() { Property key = new Property("key"); key.with(Property.SECURE, true); ConfigurationProperty property = new ConfigurationPropertyBuilder().create("key", "value", "enc_value", true); assertThat(property.errors().get("configurationValue").get(0), is("You may only specify `value` or `encrypted_value`, not both!")); assertThat(property.errors().get("encryptedValue").get(0), is("You may only specify `value` or `encrypted_value`, not both!")); assertThat(property.getConfigurationValue().getValue(), is("value")); assertThat(property.getEncryptedValue(), is("enc_value")); }
public Map<String, String> match(String text) { final HashMap<String, String> result = MapUtil.newHashMap(true); int from = 0; String key = null; int to; for (String part : patterns) { if (StrUtil.isWrap(part, "${", "}")) { // 变量 key = StrUtil.sub(part, 2, part.length() - 1); } else { to = text.indexOf(part, from); if (to < 0) { //普通字符串未匹配到,说明整个模式不能匹配,返回空 return MapUtil.empty(); } if (null != key && to > from) { // 变量对应部分有内容 result.put(key, text.substring(from, to)); } // 下一个起始点是普通字符串的末尾 from = to + part.length(); key = null; } } if (null != key && from < text.length()) { // 变量对应部分有内容 result.put(key, text.substring(from)); } return result; }
@Test public void matcherTest(){ final StrMatcher strMatcher = new StrMatcher("${name}-${age}-${gender}-${country}-${province}-${city}-${status}"); final Map<String, String> match = strMatcher.match("小明-19-男-中国-河南-郑州-已婚"); assertEquals("小明", match.get("name")); assertEquals("19", match.get("age")); assertEquals("男", match.get("gender")); assertEquals("中国", match.get("country")); assertEquals("河南", match.get("province")); assertEquals("郑州", match.get("city")); assertEquals("已婚", match.get("status")); }
public synchronized TopologyDescription describe() { return internalTopologyBuilder.describe(); }
@Test public void tableNamedMaterializedCountWithTopologyConfigShouldPreserveTopologyStructure() { // override the default store into in-memory final StreamsBuilder builder = new StreamsBuilder(overrideDefaultStore(StreamsConfig.IN_MEMORY)); builder.table("input-topic") .groupBy((key, value) -> null) // can still override the default store dynamically .count(Materialized.as(Materialized.StoreType.ROCKS_DB)); final Topology topology = builder.build(); final TopologyDescription describe = topology.describe(); assertEquals( "Topology: my-topology:\n" + " Sub-topology: 0\n" + " Source: KSTREAM-SOURCE-0000000001 (topics: [input-topic])\n" + " --> KTABLE-SOURCE-0000000002\n" + " Processor: KTABLE-SOURCE-0000000002 (stores: [input-topic-STATE-STORE-0000000000])\n" + " --> KTABLE-SELECT-0000000003\n" + " <-- KSTREAM-SOURCE-0000000001\n" + " Processor: KTABLE-SELECT-0000000003 (stores: [])\n" + " --> KSTREAM-SINK-0000000005\n" + " <-- KTABLE-SOURCE-0000000002\n" + " Sink: KSTREAM-SINK-0000000005 (topic: KTABLE-AGGREGATE-STATE-STORE-0000000004-repartition)\n" + " <-- KTABLE-SELECT-0000000003\n" + "\n" + " Sub-topology: 1\n" + " Source: KSTREAM-SOURCE-0000000006 (topics: [KTABLE-AGGREGATE-STATE-STORE-0000000004-repartition])\n" + " --> KTABLE-AGGREGATE-0000000007\n" + " Processor: KTABLE-AGGREGATE-0000000007 (stores: [KTABLE-AGGREGATE-STATE-STORE-0000000004])\n" + " --> none\n" + " <-- KSTREAM-SOURCE-0000000006\n" + "\n", describe.toString() ); topology.internalTopologyBuilder.setStreamsConfig(streamsConfig); final ProcessorTopology processorTopology = topology.internalTopologyBuilder.setApplicationId("test").buildTopology(); // one for ktable, and one for count operation assertThat(processorTopology.stateStores().size(), is(2)); // ktable store is in-memory (default is in-memory) assertThat(processorTopology.stateStores().get(0).persistent(), is(false)); // count store is rocksDB assertThat(processorTopology.stateStores().get(1).persistent(), is(true)); }
@Override public void isEqualTo(@Nullable Object expected) { super.isEqualTo(expected); }
@Test public void isEqualTo_WithoutToleranceParameter_Fail_NotAnArray() { expectFailureWhenTestingThat(array(2.2f, 3.3f, 4.4f)).isEqualTo(new Object()); }
@ExecuteOn(TaskExecutors.IO) @Get(uri = "/{executionId}") @Operation(tags = {"Executions"}, summary = "Get an execution") public Execution get( @Parameter(description = "The execution id") @PathVariable String executionId ) { return executionRepository .findById(tenantService.resolveTenant(), executionId) .orElse(null); }
@Test void badDate() { HttpClientResponseException exception = assertThrows(HttpClientResponseException.class, () -> client.toBlocking().retrieve(GET("/api/v1/executions/search?startDate=2024-06-03T00:00:00.000%2B02:00&endDate=2023-06-05T00:00:00.000%2B02:00"), PagedResults.class)); assertThat(exception.getStatus().getCode(), is(422)); assertThat(exception.getMessage(),is("Illegal argument: Start date must be before End Date")); }
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { char subCommand = safeReadLine(reader).charAt(0); String returnCommand = null; if (subCommand == ARRAY_GET_SUB_COMMAND_NAME) { returnCommand = getArray(reader); } else if (subCommand == ARRAY_SET_SUB_COMMAND_NAME) { returnCommand = setArray(reader); } else if (subCommand == ARRAY_SLICE_SUB_COMMAND_NAME) { returnCommand = sliceArray(reader); } else if (subCommand == ARRAY_LEN_SUB_COMMAND_NAME) { returnCommand = lenArray(reader); } else if (subCommand == ARRAY_CREATE_SUB_COMMAND_NAME) { returnCommand = createArray(reader); } else { returnCommand = Protocol.getOutputErrorCommand("Unknown Array SubCommand Name: " + subCommand); } logger.finest("Returning command: " + returnCommand); writer.write(returnCommand); writer.flush(); }
@Test public void testSetNoneInPrimitiveArray() { String inputCommand = ArrayCommand.ARRAY_SET_SUB_COMMAND_NAME + "\n" + target2 + "\ni1\nn\ne\n"; try { command.execute("a", new BufferedReader(new StringReader(inputCommand)), writer); assertEquals("!yv\n", sWriter.toString()); assertNull(Array.get(array2, 1)); fail(); } catch (Py4JException pe) { assertTrue(true); } catch (Exception e) { e.printStackTrace(); fail(); } }
@JsonProperty public abstract OptionalInt to();
@Test void doesNotSupportOnlyToParameter() { assertThatThrownBy(() -> RelativeRange.Builder.builder() .to(60) .build()) .isInstanceOf(InvalidRangeParametersException.class) .hasMessage("If `to` is specified, `from` must be specified to!"); }
@Public @Deprecated public static String toString(ApplicationId appId) { return appId.toString(); }
@Test void testContainerIdWithEpoch() throws URISyntaxException { ContainerId id = TestContainerId.newContainerId(0, 0, 0, 25645811); String cid = id.toString(); assertEquals("container_0_0000_00_25645811", cid); ContainerId gen = ContainerId.fromString(cid); assertEquals(gen.toString(), id.toString()); long ts = System.currentTimeMillis(); ContainerId id2 = TestContainerId.newContainerId(36473, 4365472, ts, 4298334883325L); String cid2 = id2.toString(); assertEquals( "container_e03_" + ts + "_36473_4365472_999799999997", cid2); ContainerId gen2 = ContainerId.fromString(cid2); assertEquals(gen2.toString(), id2.toString()); ContainerId id3 = TestContainerId.newContainerId(36473, 4365472, ts, 844424930131965L); String cid3 = id3.toString(); assertEquals( "container_e767_" + ts + "_36473_4365472_1099511627773", cid3); ContainerId gen3 = ContainerId.fromString(cid3); assertEquals(gen3.toString(), id3.toString()); }
@Override @Deprecated public <K1, V1> KStream<K1, V1> flatTransform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, Iterable<KeyValue<K1, V1>>> transformerSupplier, final String... stateStoreNames) { Objects.requireNonNull(transformerSupplier, "transformerSupplier can't be null"); final String name = builder.newProcessorName(TRANSFORM_NAME); return flatTransform(transformerSupplier, Named.as(name), stateStoreNames); }
@Test @SuppressWarnings("deprecation") public void shouldNotAllowNullTransformerSupplierOnFlatTransformWithNamed() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.flatTransform(null, Named.as("flatTransformer"))); assertThat(exception.getMessage(), equalTo("transformerSupplier can't be null")); }
@Override public Object adapt(final HttpAction action, final WebContext context) { if (action != null) { var code = action.getCode(); val response = ((JEEContext) context).getNativeResponse(); if (code < 400) { response.setStatus(code); } else { try { response.sendError(code); } catch (final IOException e) { throw new TechnicalException(e); } } if (action instanceof WithLocationAction withLocationAction) { context.setResponseHeader(HttpConstants.LOCATION_HEADER, withLocationAction.getLocation()); } else if (action instanceof WithContentAction withContentAction) { val content = withContentAction.getContent(); if (content != null) { try { response.getWriter().write(content); } catch (final IOException e) { throw new TechnicalException(e); } } } return null; } throw new TechnicalException("No action provided"); }
@Test public void testActionWithLocation() { JEEHttpActionAdapter.INSTANCE.adapt(new FoundAction(TestsConstants.PAC4J_URL), context); verify(response).setStatus(302); verify(context).setResponseHeader(HttpConstants.LOCATION_HEADER, TestsConstants.PAC4J_URL); }
@SuppressWarnings("unchecked") public static void addNamedOutput(Job job, String namedOutput, Class<? extends OutputFormat> outputFormatClass, Schema keySchema) { addNamedOutput(job, namedOutput, outputFormatClass, keySchema, null); }
@Test void avroGenericOutput() throws Exception { Job job = Job.getInstance(); FileInputFormat.setInputPaths(job, new Path(getClass().getResource("/org/apache/avro/mapreduce/mapreduce-test-input.txt").toURI().toString())); job.setInputFormatClass(TextInputFormat.class); job.setMapperClass(LineCountMapper.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(IntWritable.class); job.setReducerClass(GenericStatsReducer.class); AvroJob.setOutputKeySchema(job, STATS_SCHEMA); AvroMultipleOutputs.addNamedOutput(job, "myavro", AvroKeyOutputFormat.class, STATS_SCHEMA, null); AvroMultipleOutputs.addNamedOutput(job, "myavro1", AvroKeyOutputFormat.class, STATS_SCHEMA_2); job.setOutputFormatClass(AvroKeyOutputFormat.class); Path outputPath = new Path(DIR.getPath() + "/testAvroGenericOutput"); outputPath.getFileSystem(job.getConfiguration()).delete(outputPath, true); FileOutputFormat.setOutputPath(job, outputPath); assertTrue(job.waitForCompletion(true)); // Check that the results from the MapReduce were as expected. FileSystem fileSystem = FileSystem.get(job.getConfiguration()); FileStatus[] outputFiles = fileSystem.globStatus(outputPath.suffix("/myavro-r-00000.avro")); assertEquals(1, outputFiles.length); Map<String, Integer> counts = new HashMap<>(); try (DataFileReader<GenericData.Record> reader = new DataFileReader<>( new FsInput(outputFiles[0].getPath(), job.getConfiguration()), new GenericDatumReader<>(STATS_SCHEMA))) { for (GenericData.Record record : reader) { counts.put(((Utf8) record.get("name")).toString(), (Integer) record.get("count")); } } assertEquals(3, counts.get("apple").intValue()); assertEquals(2, counts.get("banana").intValue()); assertEquals(1, counts.get("carrot").intValue()); outputFiles = fileSystem.globStatus(outputPath.suffix("/myavro1-r-00000.avro")); assertEquals(1, outputFiles.length); counts.clear(); try (DataFileReader<GenericData.Record> reader = new DataFileReader<>( new FsInput(outputFiles[0].getPath(), job.getConfiguration()), new GenericDatumReader<>(STATS_SCHEMA_2))) { for (GenericData.Record record : reader) { counts.put(((Utf8) record.get("name1")).toString(), (Integer) record.get("count1")); } } assertEquals(3, counts.get("apple").intValue()); assertEquals(2, counts.get("banana").intValue()); assertEquals(1, counts.get("carrot").intValue()); outputFiles = fileSystem.globStatus(outputPath.suffix("/testnewwrite-r-00000.avro")); assertEquals(1, outputFiles.length); counts.clear(); try (DataFileReader<GenericData.Record> reader = new DataFileReader<>( new FsInput(outputFiles[0].getPath(), job.getConfiguration()), new GenericDatumReader<>(STATS_SCHEMA))) { for (GenericData.Record record : reader) { counts.put(((Utf8) record.get("name")).toString(), (Integer) record.get("count")); } } assertEquals(3, counts.get("apple").intValue()); assertEquals(2, counts.get("banana").intValue()); assertEquals(1, counts.get("carrot").intValue()); outputFiles = fileSystem.globStatus(outputPath.suffix("/testnewwrite2-r-00000.avro")); assertEquals(1, outputFiles.length); counts.clear(); try (DataFileReader<GenericData.Record> reader = new DataFileReader<>( new FsInput(outputFiles[0].getPath(), job.getConfiguration()), new GenericDatumReader<>(STATS_SCHEMA_2))) { for (GenericData.Record record : reader) { counts.put(((Utf8) record.get("name1")).toString(), (Integer) record.get("count1")); } } assertEquals(3, counts.get("apple").intValue()); assertEquals(2, counts.get("banana").intValue()); assertEquals(1, counts.get("carrot").intValue()); outputFiles = fileSystem.globStatus(outputPath.suffix("/testwritenonschema-r-00000.avro")); assertEquals(1, outputFiles.length); counts.clear(); try (DataFileReader<GenericData.Record> reader = new DataFileReader<>( new FsInput(outputFiles[0].getPath(), job.getConfiguration()), new GenericDatumReader<>(STATS_SCHEMA))) { for (GenericData.Record record : reader) { counts.put(((Utf8) record.get("name")).toString(), (Integer) record.get("count")); } } assertEquals(3, counts.get("apple").intValue()); assertEquals(2, counts.get("banana").intValue()); assertEquals(1, counts.get("carrot").intValue()); }
@SuppressWarnings("unchecked") @Override public void execute(String mapName, Predicate predicate, Collection<Integer> partitions, Result result) { runUsingPartitionScanWithoutPaging(mapName, predicate, partitions, result); if (predicate instanceof PagingPredicateImpl pagingPredicate) { Map.Entry<Integer, Map.Entry> nearestAnchorEntry = pagingPredicate.getNearestAnchorEntry(); result.orderAndLimit(pagingPredicate, nearestAnchorEntry); } }
@Test public void execute_success() throws Exception { IPartitionService partitionService = mock(IPartitionService.class); when(partitionService.getPartitionCount()).thenReturn(271); PartitionScanRunner runner = mock(PartitionScanRunner.class); ReflectionUtils.setFieldValueReflectively(runner, "partitionService", partitionService); ParallelPartitionScanExecutor executor = executor(runner); Predicate<Object, Object> predicate = Predicates.equal("attribute", 1); QueryResult queryResult = new QueryResult(IterationType.ENTRY, null, null, Long.MAX_VALUE, false); executor.execute("Map", predicate, asList(1, 2, 3), queryResult); List<QueryResultRow> result = queryResult.getRows(); assertEquals(0, result.size()); }
@Override public XmlStringBuilder toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) { XmlStringBuilder xml = new XmlStringBuilder(this, enclosingNamespace); xml.rightAngleBracket(); xml.emptyElement(compressFailureError); xml.optElement(stanzaError); xml.closeElement(this); return xml; }
@Test public void withStanzaErrrorFailureTest() throws SAXException, IOException { StanzaError stanzaError = StanzaError.getBuilder() .setCondition(Condition.bad_request) .build(); Failure failure = new Failure(Failure.CompressFailureError.setup_failed, stanzaError); CharSequence xml = failure.toXML(); final String expectedXml = "<failure xmlns='http://jabber.org/protocol/compress'>" + "<setup-failed/>" + "<error xmlns='jabber:client' type='modify'>" + "<bad-request xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>" + "</error>" + "</failure>"; assertXmlSimilar(expectedXml, xml.toString()); }
public ConcurrentMap<Integer, Long> getOffsetTable() { return offsetTable; }
@Test public void testGetOffsetTable_ShouldReturnConcurrentHashMap() { ConcurrentMap<Integer, Long> offsetTable = wrapper.getOffsetTable(); assertNotNull("The offsetTable should not be null", offsetTable); }
public static <K, V> PerKeyDistinct<K, V> perKey() { return PerKeyDistinct.<K, V>builder().build(); }
@Test public void perKey() { final int cardinality = 1000; final int p = 15; final double expectedErr = 1.04 / Math.sqrt(p); List<Integer> stream = new ArrayList<>(); for (int i = 1; i <= cardinality; i++) { stream.addAll(Collections.nCopies(2, i)); } Collections.shuffle(stream); PCollection<Long> results = tp.apply("per key stream", Create.of(stream)) .apply("create keys", WithKeys.of(1)) .apply( "per key cardinality", ApproximateDistinct.<Integer, Integer>perKey().withPrecision(p)) .apply("extract values", Values.create()); PAssert.that("Verify Accuracy for cardinality per key", results) .satisfies(new VerifyAccuracy(cardinality, expectedErr)); tp.run(); }
public static DarkClusterConfigMap toConfig(Map<String, Object> properties) { DarkClusterConfigMap configMap = new DarkClusterConfigMap(); for (Map.Entry<String, Object> entry : properties.entrySet()) { String darkClusterName = entry.getKey(); DarkClusterConfig darkClusterConfig = new DarkClusterConfig(); @SuppressWarnings("unchecked") Map<String, Object> props = (Map<String, Object>) entry.getValue(); if (props.containsKey(PropertyKeys.DARK_CLUSTER_MULTIPLIER)) { darkClusterConfig.setMultiplier(PropertyUtil.coerce(props.get(PropertyKeys.DARK_CLUSTER_MULTIPLIER), Float.class)); } else { // to maintain backwards compatibility with previously ser/de, set the default on deserialization darkClusterConfig.setMultiplier(DARK_CLUSTER_DEFAULT_MULTIPLIER); } if (props.containsKey(PropertyKeys.DARK_CLUSTER_OUTBOUND_TARGET_RATE)) { darkClusterConfig.setDispatcherOutboundTargetRate( PropertyUtil.coerce(props.get(PropertyKeys.DARK_CLUSTER_OUTBOUND_TARGET_RATE), Float.class)); } else { darkClusterConfig.setDispatcherOutboundTargetRate(DARK_CLUSTER_DEFAULT_TARGET_RATE); } if (props.containsKey(PropertyKeys.DARK_CLUSTER_MAX_REQUESTS_TO_BUFFER)) { darkClusterConfig.setDispatcherMaxRequestsToBuffer( PropertyUtil.coerce(props.get(PropertyKeys.DARK_CLUSTER_MAX_REQUESTS_TO_BUFFER), Integer.class)); } else { darkClusterConfig.setDispatcherMaxRequestsToBuffer(DARK_CLUSTER_DEFAULT_MAX_REQUESTS_TO_BUFFER); } if (props.containsKey(PropertyKeys.DARK_CLUSTER_BUFFERED_REQUEST_EXPIRY_IN_SECONDS)) { darkClusterConfig.setDispatcherBufferedRequestExpiryInSeconds( PropertyUtil.coerce(props.get(PropertyKeys.DARK_CLUSTER_BUFFERED_REQUEST_EXPIRY_IN_SECONDS), Integer.class)); } else { darkClusterConfig.setDispatcherBufferedRequestExpiryInSeconds(DARK_CLUSTER_DEFAULT_BUFFERED_REQUEST_EXPIRY_IN_SECONDS); } if (props.containsKey(PropertyKeys.DARK_CLUSTER_STRATEGY_LIST)) { DataList dataList = new DataList(); @SuppressWarnings("unchecked") List<String> strategyList = (List<String>)props.get(PropertyKeys.DARK_CLUSTER_STRATEGY_LIST); dataList.addAll(strategyList); DarkClusterStrategyNameArray darkClusterStrategyNameArray = new DarkClusterStrategyNameArray(dataList); darkClusterConfig.setDarkClusterStrategyPrioritizedList(darkClusterStrategyNameArray); } if (props.containsKey(PropertyKeys.DARK_CLUSTER_TRANSPORT_CLIENT_PROPERTIES)) { @SuppressWarnings("unchecked") D2TransportClientProperties transportClientProperties = TransportClientPropertiesConverter.toConfig( (Map<String, Object>)props.get(PropertyKeys.DARK_CLUSTER_TRANSPORT_CLIENT_PROPERTIES)); darkClusterConfig.setTransportClientProperties(transportClientProperties); } configMap.put(darkClusterName, darkClusterConfig); } return configMap; }
@Test public void testBadStrategies() { Map<String, Object> props = new HashMap<>(); List<String> myStrategyList = new ArrayList<>(); myStrategyList.add("RELATIVE_TRAFFIC"); myStrategyList.add("BLAH_BLAH"); Map<String, Object> darkClusterMap = new HashMap<>(); darkClusterMap.put(PropertyKeys.DARK_CLUSTER_STRATEGY_LIST, myStrategyList); props.put(DARK_CLUSTER_KEY, darkClusterMap); DarkClusterConfigMap configMap = DarkClustersConverter.toConfig(props); DarkClusterStrategyNameArray strategyList = configMap.get(DARK_CLUSTER_KEY).getDarkClusterStrategyPrioritizedList(); Assert.assertEquals(strategyList.get(0), DarkClusterStrategyName.RELATIVE_TRAFFIC, "first strategy should be RELATIVE_TRAFFIC"); // the bad strategy BLAH_BLAH gets converted to unknown on access Assert.assertEquals(strategyList.get(1), DarkClusterStrategyName.$UNKNOWN, "second strategy should be unknown"); }