focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static ParamType getSchemaFromType(final Type type) { return getSchemaFromType(type, JAVA_TO_ARG_TYPE); }
@Test public void shouldGetTriFunction() throws NoSuchMethodException { final Type type = getClass().getDeclaredMethod("triFunctionType", TriFunction.class) .getGenericParameterTypes()[0]; final ParamType schema = UdfUtil.getSchemaFromType(type); assertThat(schema, instanceOf(LambdaType.class)); assertThat(((LambdaType) schema).inputTypes(), equalTo(ImmutableList.of(ParamTypes.LONG, ParamTypes.INTEGER, ParamTypes.BOOLEAN))); assertThat(((LambdaType) schema).returnType(), equalTo(ParamTypes.BOOLEAN)); }
public Optional<ComputationState> get(String computationId) { try { return Optional.ofNullable(computationCache.get(computationId)); } catch (UncheckedExecutionException | ExecutionException | ComputationStateNotFoundException e) { if (e.getCause() instanceof ComputationStateNotFoundException || e instanceof ComputationStateNotFoundException) { LOG.error( "Trying to fetch unknown computation={}, known computations are {}.", computationId, ImmutableSet.copyOf(computationCache.asMap().keySet())); } else { LOG.warn("Error occurred fetching computation for computationId={}", computationId, e); } } return Optional.empty(); }
@Test public void testGet_computationStateConfigFetcherFailure() { String computationId = "computationId"; when(configFetcher.fetchConfig(eq(computationId))).thenThrow(new RuntimeException()); Optional<ComputationState> computationState = computationStateCache.get(computationId); assertFalse(computationState.isPresent()); // Fetch again to make sure we call configFetcher and nulls/empty are not cached. Optional<ComputationState> computationState2 = computationStateCache.get(computationId); assertFalse(computationState2.isPresent()); verify(configFetcher, times(2)).fetchConfig(eq(computationId)); }
public Path getLocalPath(String dirsProp, String path) throws IOException { String[] dirs = getTrimmedStrings(dirsProp); int hashCode = path.hashCode(); FileSystem fs = FileSystem.getLocal(this); for (int i = 0; i < dirs.length; i++) { // try each local dir int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length; Path file = new Path(dirs[index], path); Path dir = file.getParent(); if (fs.mkdirs(dir) || fs.exists(dir)) { return file; } } LOG.warn("Could not make " + path + " in local directories from " + dirsProp); for(int i=0; i < dirs.length; i++) { int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length; LOG.warn(dirsProp + "[" + index + "]=" + dirs[index]); } throw new IOException("No valid local directories in property: "+dirsProp); }
@Test public void testGetLocalPath() throws IOException { Configuration conf = new Configuration(); String[] dirs = new String[]{"a", "b", "c"}; for (int i = 0; i < dirs.length; i++) { dirs[i] = new Path(GenericTestUtils.getTempPath(dirs[i])).toString(); } conf.set("dirs", StringUtils.join(dirs, ",")); for (int i = 0; i < 1000; i++) { String localPath = conf.getLocalPath("dirs", "dir" + i).toString(); assertTrue("Path doesn't end in specified dir: " + localPath, localPath.endsWith("dir" + i)); assertFalse("Path has internal whitespace: " + localPath, localPath.contains(" ")); } }
public static void validate(FilterPredicate predicate, MessageType schema) { Objects.requireNonNull(predicate, "predicate cannot be null"); Objects.requireNonNull(schema, "schema cannot be null"); predicate.accept(new SchemaCompatibilityValidator(schema)); }
@Test public void testRepeatedSupportedForContainsPredicates() { try { validate(contains(eq(lotsOfLongs, 10L)), schema); validate(and(contains(eq(lotsOfLongs, 10L)), contains(eq(lotsOfLongs, 5l))), schema); validate(or(contains(eq(lotsOfLongs, 10L)), contains(eq(lotsOfLongs, 5l))), schema); } catch (IllegalArgumentException e) { fail("Valid repeated column predicates should not throw exceptions"); } }
public String toString(JimfsPath path) { Name root = path.root(); String rootString = root == null ? null : root.toString(); Iterable<String> names = Iterables.transform(path.names(), Functions.toStringFunction()); return type.toString(rootString, names); }
@Test public void testToString() { // not much to test for this since it just delegates to PathType anyway JimfsPath path = new JimfsPath(service, null, ImmutableList.of(Name.simple("foo"), Name.simple("bar"))); assertThat(service.toString(path)).isEqualTo("foo/bar"); path = new JimfsPath(service, Name.simple("/"), ImmutableList.of(Name.simple("foo"))); assertThat(service.toString(path)).isEqualTo("/foo"); }
public static CircuitBreakerRegistry of(Configuration configuration, CompositeCustomizer<CircuitBreakerConfigCustomizer> customizer){ CommonCircuitBreakerConfigurationProperties circuitBreakerProperties = CommonsConfigurationCircuitBreakerConfiguration.of(configuration); Map<String, CircuitBreakerConfig> circuitBreakerConfigMap = circuitBreakerProperties.getInstances() .entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, entry -> circuitBreakerProperties.createCircuitBreakerConfig(entry.getKey(), entry.getValue(), customizer))); return CircuitBreakerRegistry.of(circuitBreakerConfigMap); }
@Test public void testCircuitBreakerRegistryFromPropertiesFile() throws ConfigurationException { Configuration config = CommonsConfigurationUtil.getConfiguration(PropertiesConfiguration.class, TestConstants.RESILIENCE_CONFIG_PROPERTIES_FILE_NAME); CircuitBreakerRegistry circuitBreakerRegistry = CommonsConfigurationCircuitBreakerRegistry.of(config, new CompositeCustomizer<>(List.of())); Assertions.assertThat(circuitBreakerRegistry.circuitBreaker(TestConstants.BACKEND_A).getName()).isEqualTo(TestConstants.BACKEND_A); Assertions.assertThat(circuitBreakerRegistry.circuitBreaker(TestConstants.BACKEND_B).getName()).isEqualTo(TestConstants.BACKEND_B); }
public HealthCheckResponse checkHealth() { final Map<String, HealthCheckResponseDetail> results = DEFAULT_CHECKS.stream() .collect(Collectors.toMap( Check::getName, check -> check.check(this) )); final boolean allHealthy = results.values().stream() .allMatch(HealthCheckResponseDetail::getIsHealthy); final State serverState = commandRunner.checkServerState(); return new HealthCheckResponse(allHealthy, results, Optional.of(serverState.toString())); }
@Test public void shouldReturnHealthyIfKafkaCheckFailsWithUnknownTopicOrPartitionException() { // Given: givenDescribeTopicsThrows(new UnknownTopicOrPartitionException()); // When: final HealthCheckResponse response = healthCheckAgent.checkHealth(); // Then: assertThat(response.getDetails().get(KAFKA_CHECK_NAME).getIsHealthy(), is(true)); assertThat(response.getIsHealthy(), is(true)); }
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } return results; }
@Test public void tooOldJava() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/too_old_java.txt")), CrashReportAnalyzer.Rule.TOO_OLD_JAVA); assertEquals("60", result.getMatcher().group("expected")); }
public static String getRmPrincipal(Configuration conf) throws IOException { String principal = conf.get(YarnConfiguration.RM_PRINCIPAL); String prepared = null; if (principal != null) { prepared = getRmPrincipal(principal, conf); } return prepared; }
@Test public void testGetRMPrincipalStandAlone_Configuration() throws IOException { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_ADDRESS, "myhost"); conf.setBoolean(YarnConfiguration.RM_HA_ENABLED, false); String result = YarnClientUtils.getRmPrincipal(conf); assertNull("The hostname translation did return null when the principal is " + "missing from the conf: " + result, result); conf = new Configuration(); conf.set(YarnConfiguration.RM_ADDRESS, "myhost"); conf.set(YarnConfiguration.RM_PRINCIPAL, "test/_HOST@REALM"); conf.setBoolean(YarnConfiguration.RM_HA_ENABLED, false); result = YarnClientUtils.getRmPrincipal(conf); assertEquals("The hostname translation did not produce the expected " + "results: " + result, "test/myhost@REALM", result); conf.set(YarnConfiguration.RM_PRINCIPAL, "test/yourhost@REALM"); result = YarnClientUtils.getRmPrincipal(conf); assertEquals("The hostname translation did not produce the expected " + "results: " + result, "test/yourhost@REALM", result); }
@Override public boolean accept(Object object) { return factToCheck.stream() .allMatch(factCheckerHandle -> factCheckerHandle.getClazz().isAssignableFrom(object.getClass()) && factCheckerHandle.getCheckFuction().apply(object).isValid()); }
@Test public void accept() { ConditionFilter conditionFilter = createConditionFilter(ValueWrapper::of); assertThat(conditionFilter.accept(1)).isFalse(); assertThat(conditionFilter.accept("String")).isTrue(); }
@Override public String getURL( String hostname, String port, String databaseName ) { String url = "jdbc:sqlserver://" + hostname + ":" + port + ";database=" + databaseName + ";encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;"; if ( getAttribute( IS_ALWAYS_ENCRYPTION_ENABLED, "" ).equals( "true" ) ) { url += "columnEncryptionSetting=Enabled;keyVaultProviderClientId=" + getAttribute( CLIENT_ID, "" ) + ";keyVaultProviderClientKey=" + getAttribute( CLIENT_SECRET_KEY, "" ) + ";"; } if ( ACTIVE_DIRECTORY_PASSWORD.equals( getAttribute( JDBC_AUTH_METHOD, "" ) ) ) { return url + "authentication=ActiveDirectoryPassword;"; } else if ( ACTIVE_DIRECTORY_MFA.equals( getAttribute( JDBC_AUTH_METHOD, "" ) ) ) { return url + "authentication=ActiveDirectoryInteractive;"; } else if ( ACTIVE_DIRECTORY_INTEGRATED.equals( getAttribute( JDBC_AUTH_METHOD, "" ) ) ) { return url + "Authentication=ActiveDirectoryIntegrated;"; } else { return url; } }
@Test public void testGetUrlWithAadMfaAuth(){ dbMeta.setAccessType( DatabaseMeta.TYPE_ACCESS_NATIVE ); dbMeta.addAttribute( IS_ALWAYS_ENCRYPTION_ENABLED, "false" ); dbMeta.addAttribute( JDBC_AUTH_METHOD, ACTIVE_DIRECTORY_MFA ); String expectedUrl = "jdbc:sqlserver://abc.database.windows.net:1433;database=AzureDB;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;authentication=ActiveDirectoryInteractive;"; String actualUrl = dbMeta.getURL( "abc.database.windows.net", "1433", "AzureDB" ); assertEquals( expectedUrl, actualUrl ); }
@Override public com.thoughtworks.go.plugin.domain.artifact.Capabilities getCapabilitiesFromResponseBody(String responseBody) { return Capabilities.fromJSON(responseBody).toCapabilities(); }
@Test public void shouldDeserializeCapabilities() { final Capabilities capabilities = new ArtifactMessageConverterV2().getCapabilitiesFromResponseBody("{}"); assertNotNull(capabilities); }
@Override public List<ImportValidationFeedback> verifyRule( Object subject ) { List<ImportValidationFeedback> feedback = new ArrayList<>(); if ( !isEnabled() || !( subject instanceof TransMeta ) ) { return feedback; } TransMeta transMeta = (TransMeta) subject; String description = transMeta.getDescription(); if ( null != description && minLength <= description.length() ) { feedback.add( new ImportValidationFeedback( this, ImportValidationResultType.APPROVAL, "A description is present" ) ); } else { feedback.add( new ImportValidationFeedback( this, ImportValidationResultType.ERROR, "A description is not present or is too short." ) ); } return feedback; }
@Test public void testVerifyRule_LongDescription_EnabledRule() { TransformationHasDescriptionImportRule importRule = getImportRule( 10, true ); TransMeta transMeta = new TransMeta(); transMeta.setDescription( "A very long description that has more characters than the minimum required to be a valid one!" ); List<ImportValidationFeedback> feedbackList = importRule.verifyRule( transMeta ); assertNotNull( feedbackList ); assertFalse( feedbackList.isEmpty() ); ImportValidationFeedback feedback = feedbackList.get( 0 ); assertNotNull( feedback ); assertEquals( ImportValidationResultType.APPROVAL, feedback.getResultType() ); assertTrue( feedback.isApproval() ); }
@Override public Endpoints leaderEndpoints() { return Endpoints.empty(); }
@Test void testLeaderEndpoints() { UnattachedState state = newUnattachedState(Utils.mkSet(1, 2, 3), OptionalInt.empty()); assertEquals(Endpoints.empty(), state.leaderEndpoints()); }
public void writeEncodedLong(int valueType, long value) throws IOException { int index = 0; if (value >= 0) { while (value > 0x7f) { tempBuf[index++] = (byte)value; value >>= 8; } } else { while (value < -0x80) { tempBuf[index++] = (byte)value; value >>= 8; } } tempBuf[index++] = (byte)value; writeEncodedValueHeader(valueType, index-1); write(tempBuf, 0, index); }
@Test public void testWriteEncodedLong() throws IOException { testWriteEncodedLongHelper(0x00L, 0x00); testWriteEncodedLongHelper(0x40L, 0x40); testWriteEncodedLongHelper(0x7fL, 0x7f); testWriteEncodedLongHelper(0xffL, 0xff, 0x00); testWriteEncodedLongHelper(0xffffffffffffff80L, 0x80); testWriteEncodedLongHelper(0xffffffffffffffffL, 0xff); testWriteEncodedLongHelper(0x100L, 0x00, 0x01); testWriteEncodedLongHelper(0x7fffL, 0xff, 0x7f); testWriteEncodedLongHelper(0x8000L, 0x00, 0x80, 0x00); testWriteEncodedLongHelper(0xffffffffffff8000L, 0x00, 0x80); testWriteEncodedLongHelper(0x10000L, 0x00, 0x00, 0x01); testWriteEncodedLongHelper(0x10203L, 0x03, 0x02, 0x01); testWriteEncodedLongHelper(0x810203L, 0x03, 0x02, 0x81, 0x00); testWriteEncodedLongHelper(0xffffffffff810203L, 0x03, 0x02, 0x81); testWriteEncodedLongHelper(0x1000000L, 0x00, 0x00, 0x00, 0x01); testWriteEncodedLongHelper(0x1020304L, 0x04, 0x03, 0x02, 0x01); testWriteEncodedLongHelper(0x7fffffffL, 0xff, 0xff, 0xff, 0x7f); testWriteEncodedLongHelper(0x80000000L, 0x00, 0x00, 0x00, 0x80, 0x00); testWriteEncodedLongHelper(0xffffffff80000000L, 0x00, 0x00, 0x00, 0x80); testWriteEncodedLongHelper(0xffffffff80000001L, 0x01, 0x00, 0x00, 0x80); testWriteEncodedLongHelper(0x100000000L, 0x00, 0x00, 0x00, 0x00, 0x01); testWriteEncodedLongHelper(0x102030405L, 0x05, 0x04, 0x03, 0x02, 0x01); testWriteEncodedLongHelper(0x7fffffffffL, 0xff, 0xff, 0xff, 0xff, 0x7f); testWriteEncodedLongHelper(0x8000000000L, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00); testWriteEncodedLongHelper(0xffffff8000000000L, 0x00, 0x00, 0x00, 0x00, 0x80); testWriteEncodedLongHelper(0xffffff8000000001L, 0x01, 0x00, 0x00, 0x00, 0x80); testWriteEncodedLongHelper(0x10000000000L, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01); testWriteEncodedLongHelper(0x10203040506L, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01); testWriteEncodedLongHelper(0x7fffffffffffL, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f); testWriteEncodedLongHelper(0x800000000000L, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00); testWriteEncodedLongHelper(0xffff800000000000L, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80); testWriteEncodedLongHelper(0xffff800000000001L, 0x01, 0x00, 0x00, 0x00, 0x00, 0x80); testWriteEncodedLongHelper(0x1000000000000L, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01); testWriteEncodedLongHelper(0x1020304050607L, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01); testWriteEncodedLongHelper(0x7fffffffffffffL, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f); testWriteEncodedLongHelper(0x80000000000000L, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00); testWriteEncodedLongHelper(0xff80000000000000L, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80); testWriteEncodedLongHelper(0xff80000000000001L, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80); testWriteEncodedLongHelper(0x100000000000000L, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01); testWriteEncodedLongHelper(0x102030405060708L, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01); testWriteEncodedLongHelper(0x7fffffffffffffffL, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f); testWriteEncodedLongHelper(0x8000000000000000L, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80); testWriteEncodedLongHelper(0x8000000000000001L, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80); testWriteEncodedLongHelper(0xfeffffffffffffffL, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe); testWriteEncodedLongHelper(0x123456789ABCDEF0L, 0xF0, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12); }
Set<Queue> getChildren() { return children; }
@Test (timeout=5000) public void testDefaultConfig() { QueueManager manager = new QueueManager(true); assertThat(manager.getRoot().getChildren().size()).isEqualTo(2); }
static void toJson(ManifestFile manifestFile, JsonGenerator generator) throws IOException { Preconditions.checkArgument(manifestFile != null, "Invalid manifest file: null"); Preconditions.checkArgument(generator != null, "Invalid JSON generator: null"); generator.writeStartObject(); generator.writeStringField(PATH, manifestFile.path()); generator.writeNumberField(LENGTH, manifestFile.length()); generator.writeNumberField(SPEC_ID, manifestFile.partitionSpecId()); if (manifestFile.content() != null) { generator.writeNumberField(CONTENT, manifestFile.content().id()); } generator.writeNumberField(SEQUENCE_NUMBER, manifestFile.sequenceNumber()); generator.writeNumberField(MIN_SEQUENCE_NUMBER, manifestFile.minSequenceNumber()); if (manifestFile.snapshotId() != null) { generator.writeNumberField(ADDED_SNAPSHOT_ID, manifestFile.snapshotId()); } if (manifestFile.addedFilesCount() != null) { generator.writeNumberField(ADDED_FILES_COUNT, manifestFile.addedFilesCount()); } if (manifestFile.existingFilesCount() != null) { generator.writeNumberField(EXISTING_FILES_COUNT, manifestFile.existingFilesCount()); } if (manifestFile.deletedFilesCount() != null) { generator.writeNumberField(DELETED_FILES_COUNT, manifestFile.deletedFilesCount()); } if (manifestFile.addedRowsCount() != null) { generator.writeNumberField(ADDED_ROWS_COUNT, manifestFile.addedRowsCount()); } if (manifestFile.existingRowsCount() != null) { generator.writeNumberField(EXISTING_ROWS_COUNT, manifestFile.existingRowsCount()); } if (manifestFile.deletedRowsCount() != null) { generator.writeNumberField(DELETED_ROWS_COUNT, manifestFile.deletedRowsCount()); } if (manifestFile.partitions() != null) { generator.writeArrayFieldStart(PARTITION_FIELD_SUMMARY); for (ManifestFile.PartitionFieldSummary summary : manifestFile.partitions()) { PartitionFieldSummaryParser.toJson(summary, generator); } generator.writeEndArray(); } if (manifestFile.keyMetadata() != null) { generator.writeFieldName(KEY_METADATA); SingleValueParser.toJson(DataFile.KEY_METADATA.type(), manifestFile.keyMetadata(), generator); } generator.writeEndObject(); }
@Test public void testParser() throws Exception { ManifestFile manifest = createManifestFile(); String jsonStr = JsonUtil.generate(gen -> ManifestFileParser.toJson(manifest, gen), false); assertThat(jsonStr).isEqualTo(manifestFileJson()); }
static String toJson(ViewHistoryEntry entry) { return JsonUtil.generate(gen -> toJson(entry, gen), false); }
@Test public void testViewHistoryEntryToJson() { String json = "{\"timestamp-ms\":123,\"version-id\":1}"; ViewHistoryEntry viewHistoryEntry = ImmutableViewHistoryEntry.builder().versionId(1).timestampMillis(123).build(); assertThat(ViewHistoryEntryParser.toJson(viewHistoryEntry)) .as("Should be able to serialize view history entry") .isEqualTo(json); }
@Override public boolean equals(Object o) { if (!super.equals(o)) { return false; } ObjectRecordWithStats that = (ObjectRecordWithStats) o; return value.equals(that.value); }
@Test public void testEquals() { assertEquals(record, record); assertEquals(record, recordSameAttributes); assertNotEquals(null, record); assertNotEquals(new Object(), record); assertNotEquals(record, dataRecord); assertNotEquals(record, recordOtherLastStoredTime); assertNotEquals(record, recordOtherKeyAndValue); }
@CheckForNull public Duration calculate(DefaultIssue issue) { if (issue.isFromExternalRuleEngine()) { return issue.effort(); } Rule rule = ruleRepository.getByKey(issue.ruleKey()); DebtRemediationFunction fn = rule.getRemediationFunction(); if (fn != null) { verifyEffortToFix(issue, fn); Duration debt = Duration.create(0); String gapMultiplier = fn.gapMultiplier(); if (fn.type().usesGapMultiplier() && !Strings.isNullOrEmpty(gapMultiplier)) { int effortToFixValue = MoreObjects.firstNonNull(issue.gap(), 1).intValue(); // TODO convert to Duration directly in Rule#remediationFunction -> better performance + error handling debt = durations.decode(gapMultiplier).multiply(effortToFixValue); } String baseEffort = fn.baseEffort(); if (fn.type().usesBaseEffort() && !Strings.isNullOrEmpty(baseEffort)) { // TODO convert to Duration directly in Rule#remediationFunction -> better performance + error handling debt = debt.add(durations.decode(baseEffort)); } return debt; } return null; }
@Test public void linear_function() { double effortToFix = 3.0; int coefficient = 2; issue.setGap(effortToFix); rule.setFunction(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR, coefficient + "min", null)); assertThat(underTest.calculate(issue).toMinutes()).isEqualTo((int) (coefficient * effortToFix)); }
public static boolean isIPInSubnet(String ip, String subnetCidr) { SubnetUtils subnetUtils = new SubnetUtils(subnetCidr); subnetUtils.setInclusiveHostCount(true); return subnetUtils.getInfo().isInRange(ip); }
@Test public void testIsIPInSubnet() { assertThat(NetUtils.isIPInSubnet("192.168.0.1", "192.168.0.1/32")).isTrue(); assertThat(NetUtils.isIPInSubnet("192.168.0.1", "192.168.1.1/32")).isFalse(); assertThat(NetUtils.isIPInSubnet("192.168.0.1", "192.168.0.1/24")).isTrue(); assertThat(NetUtils.isIPInSubnet("192.168.0.1", "192.168.0.2/24")).isTrue(); assertThat(NetUtils.isIPInSubnet("192.168.0.1", "192.168.1.0/24")).isFalse(); assertThat(NetUtils.isIPInSubnet("192.168.0.1", "10.0.0.0/8")).isFalse(); }
static String tryToExtractErrorMessage(Reconciliation reconciliation, Buffer buffer) { try { return buffer.toJsonObject().getString("message"); } catch (DecodeException e) { LOGGER.warnCr(reconciliation, "Failed to decode the error message from the response: " + buffer, e); } return "Unknown error message"; }
@Test public void testJsonDecoding() { assertThat(KafkaConnectApiImpl.tryToExtractErrorMessage(Reconciliation.DUMMY_RECONCILIATION, Buffer.buffer("{\"message\": \"This is the error\"}")), is("This is the error")); assertThat(KafkaConnectApiImpl.tryToExtractErrorMessage(Reconciliation.DUMMY_RECONCILIATION, Buffer.buffer("{\"message\": \"This is the error\"")), is("Unknown error message")); assertThat(KafkaConnectApiImpl.tryToExtractErrorMessage(Reconciliation.DUMMY_RECONCILIATION, Buffer.buffer("Not a JSON")), is("Unknown error message")); }
@Override protected Endpoint createEndpoint(final String uri, final String path, final Map<String, Object> parameters) throws Exception { if (autoConfiguration != null && autoConfiguration.isAutoConfigurable()) { autoConfiguration.ensureNameSpaceAndTenant(path); } final PulsarConfiguration copy = configuration.copy(); PulsarEndpoint answer = new PulsarEndpoint(uri, this); answer.setPulsarConfiguration(copy); answer.setPulsarClient(pulsarClient); setProperties(answer, parameters); PulsarPath pp = new PulsarPath(path); if (pp.isAutoConfigurable()) { answer.setPersistence(pp.getPersistence()); answer.setTenant(pp.getTenant()); answer.setNamespace(pp.getNamespace()); answer.setTopic(pp.getTopic()); } else { throw new IllegalArgumentException("Pulsar name structure is invalid: was " + path); } return answer; }
@Test public void testPulsarEndpointDefaultConfiguration() throws Exception { PulsarComponent component = context.getComponent("pulsar", PulsarComponent.class); PulsarEndpoint endpoint = (PulsarEndpoint) component.createEndpoint("pulsar://persistent/test/foobar/BatchCreated"); assertNotNull(endpoint); assertEquals("sole-consumer", endpoint.getPulsarConfiguration().getConsumerName()); assertEquals("cons", endpoint.getPulsarConfiguration().getConsumerNamePrefix()); assertEquals(10, endpoint.getPulsarConfiguration().getConsumerQueueSize()); assertEquals(1, endpoint.getPulsarConfiguration().getNumberOfConsumers()); assertNull(endpoint.getPulsarConfiguration().getProducerName()); assertEquals("subs", endpoint.getPulsarConfiguration().getSubscriptionName()); assertEquals(SubscriptionType.EXCLUSIVE, endpoint.getPulsarConfiguration().getSubscriptionType()); assertFalse(endpoint.getPulsarConfiguration().isAllowManualAcknowledgement()); assertFalse(endpoint.getPulsarConfiguration().isReadCompacted()); assertTrue(endpoint.getPulsarConfiguration().isMessageListener()); }
@Override public void cancel() { context.goToFinished(context.getArchivedExecutionGraph(JobStatus.CANCELED, null)); }
@Test void testCancelTransitionsToFinished() { TestingStateWithoutExecutionGraph state = new TestingStateWithoutExecutionGraph(ctx, LOG); ctx.setExpectFinished( archivedExecutionGraph -> { assertThat(archivedExecutionGraph.getState()).isEqualTo(JobStatus.CANCELED); assertThat(archivedExecutionGraph.getFailureInfo()).isNull(); }); state.cancel(); }
public static void validateValue(Schema schema, Object value) { validateValue(null, schema, value); }
@Test public void testValidateValueMismatchString() { // CharSequence is a similar type (supertype of String), but we restrict to String. CharBuffer cbuf = CharBuffer.wrap("abc"); assertThrows(DataException.class, () -> ConnectSchema.validateValue(Schema.STRING_SCHEMA, cbuf)); }
@Override public String getDataSource() { return DataSourceConstant.DERBY; }
@Test void testGetDataSource() { String dataSource = configInfoAggrMapperByDerby.getDataSource(); assertEquals(DataSourceConstant.DERBY, dataSource); }
@ConstantFunction(name = "bitxor", argTypes = {TINYINT, TINYINT}, returnType = TINYINT) public static ConstantOperator bitxorTinyInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createTinyInt((byte) (first.getTinyInt() ^ second.getTinyInt())); }
@Test public void bitxorTinyInt() { assertEquals(0, ScalarOperatorFunctions.bitxorTinyInt(O_TI_10, O_TI_10).getTinyInt()); }
@Override public Point calculatePositionForPreview( Keyboard.Key key, PreviewPopupTheme theme, int[] windowOffset) { Point point = new Point(key.x + windowOffset[0], key.y + windowOffset[1]); Rect padding = new Rect(); theme.getPreviewKeyBackground().getPadding(padding); point.offset((key.width / 2), padding.bottom); if (theme.getPreviewAnimationType() == PreviewPopupTheme.ANIMATION_STYLE_EXTEND) { // taking it down a bit to the edge of the origin key point.offset(0, key.height); } return point; }
@Test public void testCalculatePositionForPreviewWithNoneExtendAnimation() throws Exception { mTheme.setPreviewAnimationType(PreviewPopupTheme.ANIMATION_STYLE_APPEAR); int[] offsets = new int[] {50, 60}; Point result = mUnderTest.calculatePositionForPreview(mTestKey, mTheme, offsets); Assert.assertEquals(mTestKey.x + mTestKey.width / 2 + offsets[0], result.x); Assert.assertEquals(mTestKey.y + offsets[1], result.y); }
public LiveMeasureDto toLiveMeasureDto(Measure measure, Metric metric, Component component) { LiveMeasureDto out = new LiveMeasureDto(); out.setMetricUuid(metric.getUuid()); out.setComponentUuid(component.getUuid()); out.setProjectUuid(treeRootHolder.getRoot().getUuid()); out.setValue(valueAsDouble(measure)); out.setData(data(measure)); return out; }
@Test public void toLiveMeasureDto() { treeRootHolder.setRoot(SOME_COMPONENT); LiveMeasureDto liveMeasureDto = underTest.toLiveMeasureDto( Measure.newMeasureBuilder().create(Measure.Level.OK), SOME_LEVEL_METRIC, SOME_COMPONENT); assertThat(liveMeasureDto.getTextValue()).isEqualTo(Measure.Level.OK.name()); }
public static String formatSql(final AstNode root) { final StringBuilder builder = new StringBuilder(); new Formatter(builder).process(root, 0); return StringUtils.stripEnd(builder.toString(), "\n"); }
@Test public void shouldFormatShowConnectorPlugins() { // Given: final ListConnectorPlugins listConnectorPlugins = new ListConnectorPlugins(Optional.empty()); // When: final String formatted = SqlFormatter.formatSql(listConnectorPlugins); // Then: assertThat(formatted, is("SHOW CONNECTOR PLUGINS")); }
public static ParamType getSchemaFromType(final Type type) { return getSchemaFromType(type, JAVA_TO_ARG_TYPE); }
@Test(expected = KsqlException.class) public void shouldThrowExceptionForObjClass() { UdfUtil.getSchemaFromType(Object.class); }
@Override protected LinkedHashMap<String, Callable<? extends ChannelHandler>> getChildChannelHandlers(MessageInput input) { final LinkedHashMap<String, Callable<? extends ChannelHandler>> handlers = new LinkedHashMap<>(); final CodecAggregator aggregator = getAggregator(); handlers.put("channel-registration", () -> new ChannelRegistrationHandler(childChannels)); handlers.put("traffic-counter", () -> throughputCounter); handlers.put("connection-counter", () -> connectionCounter); if (tlsEnable) { LOG.info("Enabled TLS for input {}. key-file=\"{}\" cert-file=\"{}\"", input.toIdentifier(), tlsKeyFile, tlsCertFile); handlers.put("tls", getSslHandlerCallable(input)); } handlers.putAll(getCustomChildChannelHandlers(input)); if (aggregator != null) { LOG.debug("Adding codec aggregator {} to channel pipeline", aggregator); handlers.put("codec-aggregator", () -> new ByteBufMessageAggregationHandler(aggregator, localRegistry)); } handlers.put("rawmessage-handler", () -> new RawMessageHandler(input)); handlers.put("exception-logger", () -> new ExceptionLoggingChannelHandler(input, LOG, this.tcpKeepalive)); return handlers; }
@Test public void getChildChannelHandlersGeneratesSelfSignedCertificates() { final Configuration configuration = new Configuration(ImmutableMap.of( "bind_address", "localhost", "port", 12345, "tls_enable", true) ); final AbstractTcpTransport transport = new AbstractTcpTransport( configuration, throughputCounter, localRegistry, eventLoopGroup, eventLoopGroupFactory, nettyTransportConfiguration, tlsConfiguration) { }; final MessageInput input = mock(MessageInput.class); assertThat(transport.getChildChannelHandlers(input)).containsKey("tls"); }
@Override @Nullable public byte[] readByteArray(@Nonnull String fieldName) throws IOException { return readIncompatibleField(fieldName, BYTE_ARRAY, super::readByteArray); }
@Test(expected = IncompatibleClassChangeError.class) public void testReadPortableArray_IncompatibleClass() throws Exception { reader.readByteArray("byte"); }
@Override public void write(int b) throws IOException { checkClosed(); if (chunkSize - currentBufferPointer <= 0) { expandBuffer(); } currentBuffer.put((byte) b); currentBufferPointer++; pointer++; if (pointer > size) { size = pointer; } }
@Test void testBufferSeek() throws IOException { try (RandomAccess randomAccessReadWrite = new RandomAccessReadWriteBuffer()) { byte[] bytes = new byte[RandomAccessReadBuffer.DEFAULT_CHUNK_SIZE_4KB]; randomAccessReadWrite.write(bytes); assertThrows(IOException.class, () -> randomAccessReadWrite.seek(-1)); } }
public void start() throws IOException { this.start(new ArrayList<>()); }
@Test public void testCuratorFrameworkFactory() throws Exception{ // By not explicitly calling the NewZooKeeper method validate that the Curator override works. ZKClientConfig zkClientConfig = new ZKClientConfig(); Configuration conf = new Configuration(); conf.set(CommonConfigurationKeys.ZK_ADDRESS, this.server.getConnectString()); int numRetries = conf.getInt(CommonConfigurationKeys.ZK_NUM_RETRIES, CommonConfigurationKeys.ZK_NUM_RETRIES_DEFAULT); int zkSessionTimeout = conf.getInt(CommonConfigurationKeys.ZK_TIMEOUT_MS, CommonConfigurationKeys.ZK_TIMEOUT_MS_DEFAULT); int zkRetryInterval = conf.getInt( CommonConfigurationKeys.ZK_RETRY_INTERVAL_MS, CommonConfigurationKeys.ZK_RETRY_INTERVAL_MS_DEFAULT); RetryNTimes retryPolicy = new RetryNTimes(numRetries, zkRetryInterval); CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(conf.get(CommonConfigurationKeys.ZK_ADDRESS)) .zkClientConfig(zkClientConfig) .sessionTimeoutMs(zkSessionTimeout).retryPolicy(retryPolicy) .authorization(new ArrayList<>()) .zookeeperFactory(new ZKCuratorManager.HadoopZookeeperFactory( "foo1", "bar1", "bar1.keytab", false, new SecurityUtil.TruststoreKeystore(conf)) ).build(); client.start(); validateJaasConfiguration(ZKCuratorManager.HadoopZookeeperFactory.JAAS_CLIENT_ENTRY, "bar1", "bar1.keytab", client.getZookeeperClient().getZooKeeper()); }
@Override public ConcurrentJobModificationResolveResult resolve(Job localJob, Job storageProviderJob) { if (localJob.getState() == StateName.SUCCEEDED && storageProviderJob.getState() == StateName.SUCCEEDED) { throw shouldNotHappenException("Should not happen as matches filter should be filtering out this StateChangeFilter"); } else if (localJob.getState() == StateName.PROCESSING && storageProviderJob.getState() == StateName.SUCCEEDED) { localJob.delete("Job has already succeeded in StorageProvider"); final Thread threadProcessingJob = jobSteward.getThreadProcessingJob(localJob); if (threadProcessingJob != null) { threadProcessingJob.interrupt(); } } return ConcurrentJobModificationResolveResult.succeeded(localJob); }
@Test void ifJobSucceededWhileGoingToProcessingButThreadIsAlreadyRemoved() { final Job jobInProgress = aJobInProgress().build(); final Job jobInProgressWithUpdate = aCopyOf(jobInProgress).withMetadata("extra", "metadata").build(); final Job succeededJob = aCopyOf(jobInProgress).withSucceededState().build(); final ConcurrentJobModificationResolveResult resolveResult = allowedStateChange.resolve(jobInProgressWithUpdate, succeededJob); assertThat(resolveResult.failed()).isFalse(); }
@Override public synchronized void execute() { boolean debugMode = conf.isLoadBalancerDebugModeEnabled() || log.isDebugEnabled(); if (debugMode) { log.info("Load balancer enabled: {}, Shedding enabled: {}.", conf.isLoadBalancerEnabled(), conf.isLoadBalancerSheddingEnabled()); } if (!isLoadBalancerSheddingEnabled()) { if (debugMode) { log.info("The load balancer or load balancer shedding already disabled. Skipping."); } return; } // Remove bundles who have been unloaded for longer than the grace period from the recently unloaded map. final long timeout = System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(conf.getLoadBalancerSheddingGracePeriodMinutes()); recentlyUnloadedBundles.keySet().removeIf(e -> recentlyUnloadedBundles.get(e) < timeout); long asyncOpTimeoutMs = conf.getNamespaceBundleUnloadingTimeoutMs(); synchronized (namespaceUnloadStrategy) { try { Boolean isChannelOwner = channel.isChannelOwnerAsync().get(asyncOpTimeoutMs, TimeUnit.MILLISECONDS); if (!isChannelOwner) { if (debugMode) { log.info("Current broker is not channel owner. Skipping."); } return; } List<String> availableBrokers = context.brokerRegistry().getAvailableBrokersAsync() .get(asyncOpTimeoutMs, TimeUnit.MILLISECONDS); if (debugMode) { log.info("Available brokers: {}", availableBrokers); } if (availableBrokers.size() <= 1) { log.info("Only 1 broker available: no load shedding will be performed. Skipping."); return; } final Set<UnloadDecision> decisions = namespaceUnloadStrategy .findBundlesForUnloading(context, recentlyUnloadedBundles, recentlyUnloadedBrokers); if (debugMode) { log.info("[{}] Unload decision result: {}", namespaceUnloadStrategy.getClass().getSimpleName(), decisions); } if (decisions.isEmpty()) { if (debugMode) { log.info("[{}] Unload decision unloads is empty. Skipping.", namespaceUnloadStrategy.getClass().getSimpleName()); } return; } List<CompletableFuture<Void>> futures = new ArrayList<>(); unloadBrokers.clear(); decisions.forEach(decision -> { if (decision.getLabel() == Success) { Unload unload = decision.getUnload(); log.info("[{}] Unloading bundle: {}", namespaceUnloadStrategy.getClass().getSimpleName(), unload); futures.add(unloadManager.waitAsync(channel.publishUnloadEventAsync(unload), unload.serviceUnit(), decision, asyncOpTimeoutMs, TimeUnit.MILLISECONDS) .thenAccept(__ -> { unloadBrokers.add(unload.sourceBroker()); recentlyUnloadedBundles.put(unload.serviceUnit(), System.currentTimeMillis()); recentlyUnloadedBrokers.put(unload.sourceBroker(), System.currentTimeMillis()); })); } }); FutureUtil.waitForAll(futures) .whenComplete((__, ex) -> counter.updateUnloadBrokerCount(unloadBrokers.size())) .get(asyncOpTimeoutMs, TimeUnit.MILLISECONDS); } catch (Exception ex) { log.error("[{}] Namespace unload has exception.", namespaceUnloadStrategy.getClass().getSimpleName(), ex); } finally { if (counter.updatedAt() > counterLastUpdatedAt) { unloadMetrics.set(counter.toMetrics(pulsar.getAdvertisedAddress())); counterLastUpdatedAt = counter.updatedAt(); } } } }
@Test(timeOut = 30 * 1000) public void testDisableLoadBalancer() { AtomicReference<List<Metrics>> reference = new AtomicReference<>(); UnloadCounter counter = new UnloadCounter(); LoadManagerContext context = setupContext(); context.brokerConfiguration().setLoadBalancerEnabled(false); ServiceUnitStateChannel channel = mock(ServiceUnitStateChannel.class); NamespaceUnloadStrategy unloadStrategy = mock(NamespaceUnloadStrategy.class); UnloadManager unloadManager = mock(UnloadManager.class); PulsarService pulsar = mock(PulsarService.class); UnloadScheduler scheduler = new UnloadScheduler(pulsar, loadManagerExecutor, unloadManager, context, channel, unloadStrategy, counter, reference); scheduler.execute(); verify(channel, times(0)).isChannelOwnerAsync(); context.brokerConfiguration().setLoadBalancerEnabled(true); context.brokerConfiguration().setLoadBalancerSheddingEnabled(false); scheduler.execute(); verify(channel, times(0)).isChannelOwnerAsync(); }
@PostConstruct public void init() { if (!environment.getAgentStatusEnabled()) { LOG.info("Agent status HTTP API server has been disabled."); return; } InetSocketAddress address = new InetSocketAddress(environment.getAgentStatusHostname(), environment.getAgentStatusPort()); try { server = HttpServer.create(address, SERVER_SOCKET_BACKLOG); setupRoutes(server); server.start(); LOG.info("Agent status HTTP API server running on http://{}:{}.", server.getAddress().getHostName(), server.getAddress().getPort()); } catch (Exception e) { LOG.warn("Could not start agent status HTTP API server on host {}, port {}.", address.getHostName(), address.getPort(), e); } }
@Test void shouldInitializeServerIfSettingIsTurnedOn() { try (MockedStatic<HttpServer> mockedStaticHttpServer = mockStatic(HttpServer.class)) { var serverSocket = setupAgentStatusParameters(); var spiedHttpServer = spy(HttpServer.class); when(spiedHttpServer.getAddress()).thenReturn(serverSocket); mockedStaticHttpServer.when(() -> HttpServer.create(eq(serverSocket), anyInt())).thenReturn(spiedHttpServer); agentStatusHttpd.init(); verify(spiedHttpServer).start(); } }
public UiTopoLayout scale(double scale) { checkArgument(scaleWithinBounds(scale), E_SCALE_OOB); this.scale = scale; return this; }
@Test(expected = IllegalArgumentException.class) public void scaleTooSmall() { mkRootLayout(); layout.scale(0.0099); }
@Override public void doPush(String clientId, Subscriber subscriber, PushDataWrapper data) { pushService.pushWithoutAck(clientId, NotifySubscriberRequest.buildNotifySubscriberRequest(getServiceInfo(data, subscriber))); }
@Test void testDoPush() { pushExecutor.doPush(rpcClientId, subscriber, pushData); verify(pushService).pushWithoutAck(eq(rpcClientId), any(NotifySubscriberRequest.class)); }
public NewIssuesNotification newNewIssuesNotification(Map<String, UserDto> assigneesByUuid) { verifyAssigneesByUuid(assigneesByUuid); return new NewIssuesNotification(new DetailsSupplierImpl(assigneesByUuid)); }
@Test public void newNewIssuesNotification_DetailsSupplier_getComponentNameByUuid_returns_shortName_of_dir_and_file_in_TreeRootHolder() { treeRootHolder.setRoot(ReportComponent.builder(PROJECT, 1).setUuid("rootUuid").setName("root") .addChildren(ReportComponent.builder(DIRECTORY, 2).setUuid("dir1Uuid").setName("dir1").setShortName("dir1_short") .addChildren(ReportComponent.builder(FILE, 21).setUuid("file21Uuid").setName("file21").setShortName("file21_short").build()) .build()) .addChildren(ReportComponent.builder(DIRECTORY, 3).setUuid("dir2Uuid").setName("dir2").setShortName("dir2_short") .addChildren(ReportComponent.builder(FILE, 31).setUuid("file31Uuid").setName("file31").setShortName("file31_short").build()) .addChildren(ReportComponent.builder(FILE, 32).setUuid("file32Uuid").setName("file32").setShortName("file32_short").build()) .build()) .addChildren(ReportComponent.builder(FILE, 11).setUuid("file11Uuid").setName("file11").setShortName("file11_short").build()) .build()); NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); Stream.of("dir1", "dir2", "file11", "file21", "file31", "file32") .forEach(name -> { assertThat(detailsSupplier.getComponentNameByUuid(name + "Uuid")).contains(name + "_short"); assertThat(detailsSupplier.getComponentNameByUuid(name)).isEmpty(); }); }
@VisibleForTesting public ResultStore getResultStore() { return resultStore; }
@Test void testFetchResultInParallel() throws Exception { ResultFetcher fetcher = buildResultFetcher(Collections.singletonList(data.iterator()), data.size() / 2); CommonTestUtils.waitUtil( () -> fetcher.getResultStore().getBufferedRecordSize() > 0, Duration.ofSeconds(10), "Failed to wait the buffer has data."); checkFetchResultInParallel(fetcher); }
@Override public void run() { if (runnable != null) { runnable.run(); } else { try { callable.call(); } catch (Exception ex) { throw new RuntimeException(ex); } } }
@Test(expected = RuntimeException.class) public void callableExRun() throws Exception { CEx c = new CEx(); RunnableCallable rc = new RunnableCallable(c); rc.run(); }
@Override public boolean isOnSameNodeGroup(Node node1, Node node2) { if (node1 == null || node2 == null) { return false; } netlock.readLock().lock(); try { return isSameParents(node1, node2); } finally { netlock.readLock().unlock(); } }
@Test public void testNodeGroups() throws Exception { assertEquals(3, cluster.getNumOfRacks()); assertTrue(cluster.isOnSameNodeGroup(dataNodes[0], dataNodes[1])); assertFalse(cluster.isOnSameNodeGroup(dataNodes[1], dataNodes[2])); assertFalse(cluster.isOnSameNodeGroup(dataNodes[2], dataNodes[3])); assertTrue(cluster.isOnSameNodeGroup(dataNodes[3], dataNodes[4])); assertFalse(cluster.isOnSameNodeGroup(dataNodes[4], dataNodes[5])); assertFalse(cluster.isOnSameNodeGroup(dataNodes[5], dataNodes[6])); assertFalse(cluster.isOnSameNodeGroup(dataNodes[6], dataNodes[7])); }
public static List<Event> computeEventDiff(final Params params) { final List<Event> events = new ArrayList<>(); emitPerNodeDiffEvents(createBaselineParams(params), events); emitWholeClusterDiffEvent(createBaselineParams(params), events); emitDerivedBucketSpaceStatesDiffEvents(params, events); return events; }
@Test void enabling_distribution_config_in_state_bundle_emits_cluster_level_event() { var fixture = EventFixture.createForNodes(3) .clusterStateBefore("distributor:3 storage:3") .clusterStateAfter("distributor:3 storage:3") .distributionConfigBefore(null) .distributionConfigAfter(flatClusterDistribution(3)); var events = fixture.computeEventDiff(); assertThat(events.size(), equalTo(1)); assertThat(events, hasItem(clusterEventWithDescription( "Cluster controller is now the authoritative source for distribution config. " + "Active config: 3 nodes; 1 groups; redundancy 2; searchable-copies 0"))); }
@Override public boolean register(final Application application) { try { if(finder.isInstalled(application)) { service.add(new FinderLocal(workspace.absolutePathForAppBundleWithIdentifier(application.getIdentifier()))); return true; } return false; } catch(LocalAccessDeniedException e) { return false; } }
@Test @Ignore public void testRegister() { final SharedFileListApplicationLoginRegistry registry = new SharedFileListApplicationLoginRegistry(new LaunchServicesApplicationFinder()); final Application application = new Application("ch.sudo.cyberduck"); assertTrue(registry.register(application)); assertTrue(new FinderSidebarService(SidebarService.List.login).contains(new FinderLocal(NSWorkspace.sharedWorkspace().absolutePathForAppBundleWithIdentifier(application.getIdentifier())))); assertTrue(registry.unregister(application)); }
public static Map<String, Task> getUserDefinedRealTaskMap(Workflow workflow) { return workflow.getTasks().stream() .filter(TaskHelper::isUserDefinedRealTask) .collect( Collectors.toMap( Task::getReferenceTaskName, Function.identity(), // it includes retried tasks so pick the last one (task1, task2) -> task2)); }
@Test public void testGetUserDefinedRealTaskMap() { when(workflow.getTasks()).thenReturn(Collections.singletonList(task)); when(task.getTaskType()).thenReturn(Constants.MAESTRO_TASK_NAME); when(task.getReferenceTaskName()).thenReturn("test-job"); Assert.assertEquals( Collections.singletonMap("test-job", task), TaskHelper.getUserDefinedRealTaskMap(workflow)); when(task.getSeq()).thenReturn(-1); Assert.assertEquals(Collections.emptyMap(), TaskHelper.getUserDefinedRealTaskMap(workflow)); }
@GetMapping("/switches") public SwitchDomain switches(HttpServletRequest request) { return switchDomain; }
@Test void testSwitchDomain() { SwitchDomain switchDomain = operatorController.switches(new MockHttpServletRequest()); assertEquals(this.switchDomain, switchDomain); }
@Override public Map<String, List<String>> getRequestTag(String path, String methodName, Map<String, List<String>> headers, Map<String, String[]> parameters, Keys keys) { Set<String> injectTags = keys.getInjectTags(); if (CollectionUtils.isEmpty(injectTags)) { // The staining mark is empty, which means that there are no staining rules, and it is returned directly LOGGER.fine("Lane tags are empty."); return Collections.emptyMap(); } // Markers for upstream transparent transmissions Map<String, List<String>> tags = getRequestTag(headers, injectTags); // This staining marker Map<String, List<String>> laneTag = laneService.getLaneByParameterArray(path, methodName, headers, parameters); if (CollectionUtils.isEmpty(laneTag)) { LOGGER.fine("Lane is empty."); return tags; } // If there is a marker in the upstream transmission that is the same as the one in this staining, // the upstream transmission shall prevail laneTag.forEach(tags::putIfAbsent); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Lane is " + tags); } return tags; }
@Test public void testGetRequestTag() { // Test matchTags as null Map<String, List<String>> requestTag = handler.getRequestTag("", "", null, null, new Keys(null, null)); Assert.assertEquals(requestTag, Collections.emptyMap()); // Test getLane returns null laneService.setReturnEmpty(true); Map<String, List<String>> headers = new HashMap<>(); headers.put("bar", Collections.singletonList("bar1")); headers.put("foo", Collections.singletonList("foo1")); Set<String> matchTags = new HashSet<>(); matchTags.add("bar"); matchTags.add("foo"); requestTag = handler.getRequestTag("", "", headers, null, new Keys(null, matchTags)); Assert.assertEquals(2, requestTag.size()); Assert.assertEquals("bar1", requestTag.get("bar").get(0)); Assert.assertEquals("foo1", requestTag.get("foo").get(0)); // Test getLane is not empty laneService.setReturnEmpty(false); requestTag = handler.getRequestTag("", "", headers, null, new Keys(null, matchTags)); Assert.assertEquals(3, requestTag.size()); Assert.assertEquals("bar1", requestTag.get("bar").get(0)); Assert.assertEquals("foo1", requestTag.get("foo").get(0)); Assert.assertEquals("flag1", requestTag.get("sermant-flag").get(0)); }
List<AlternativeInfo> calcAlternatives(final int s, final int t) { // First, do a regular bidirectional route search checkAlreadyRun(); init(s, 0, t, 0); runAlgo(); final Path bestPath = extractPath(); if (!bestPath.isFound()) { return Collections.emptyList(); } alternatives.add(new AlternativeInfo(bestPath, 0)); final ArrayList<PotentialAlternativeInfo> potentialAlternativeInfos = new ArrayList<>(); final Map<Integer, SPTEntry> bestWeightMapByNode = new HashMap<>(); bestWeightMapTo.forEach((IntObjectPredicate<SPTEntry>) (key, value) -> { bestWeightMapByNode.put(value.adjNode, value); return true; }); bestWeightMapFrom.forEach((IntObjectPredicate<SPTEntry>) (wurst, fromSPTEntry) -> { SPTEntry toSPTEntry = bestWeightMapByNode.get(fromSPTEntry.adjNode); if (toSPTEntry == null) return true; if (fromSPTEntry.getWeightOfVisitedPath() + toSPTEntry.getWeightOfVisitedPath() > bestPath.getWeight() * maxWeightFactor) return true; // This gives us a path s -> v -> t, but since we are using contraction hierarchies, // s -> v and v -> t need not be shortest paths. In fact, they can sometimes be pretty strange. // We still use this preliminary path to filter for shared path length with other alternatives, // so we don't have to work so much. Path preliminaryRoute = createPathExtractor().extract(fromSPTEntry, toSPTEntry, fromSPTEntry.getWeightOfVisitedPath() + toSPTEntry.getWeightOfVisitedPath()); double preliminaryShare = calculateShare(preliminaryRoute); if (preliminaryShare > maxShareFactor) { return true; } assert fromSPTEntry.adjNode == toSPTEntry.adjNode; PotentialAlternativeInfo potentialAlternativeInfo = new PotentialAlternativeInfo(); potentialAlternativeInfo.v = fromSPTEntry.adjNode; potentialAlternativeInfo.edgeIn = getIncomingEdge(fromSPTEntry); potentialAlternativeInfo.weight = 2 * (fromSPTEntry.getWeightOfVisitedPath() + toSPTEntry.getWeightOfVisitedPath()) + preliminaryShare; potentialAlternativeInfos.add(potentialAlternativeInfo); return true; }); potentialAlternativeInfos.sort(Comparator.comparingDouble(o -> o.weight)); for (PotentialAlternativeInfo potentialAlternativeInfo : potentialAlternativeInfos) { int v = potentialAlternativeInfo.v; int tailSv = potentialAlternativeInfo.edgeIn; // Okay, now we want the s -> v -> t shortest via-path, so we route s -> v and v -> t // and glue them together. DijkstraBidirectionEdgeCHNoSOD svRouter = new DijkstraBidirectionEdgeCHNoSOD(graph); final Path suvPath = svRouter.calcPath(s, v, ANY_EDGE, tailSv); extraVisitedNodes += svRouter.getVisitedNodes(); int u = graph.getBaseGraph().getEdgeIteratorState(tailSv, v).getBaseNode(); DijkstraBidirectionEdgeCHNoSOD vtRouter = new DijkstraBidirectionEdgeCHNoSOD(graph); final Path uvtPath = vtRouter.calcPath(u, t, tailSv, ANY_EDGE); Path path = concat(graph.getBaseGraph(), suvPath, uvtPath); extraVisitedNodes += vtRouter.getVisitedNodes(); double sharedDistanceWithShortest = sharedDistanceWithShortest(path); double detourLength = path.getDistance() - sharedDistanceWithShortest; double directLength = bestPath.getDistance() - sharedDistanceWithShortest; if (detourLength > directLength * maxWeightFactor) { continue; } double share = calculateShare(path); if (share > maxShareFactor) { continue; } // This is the final test we need: Discard paths that are not "locally shortest" around v. // So move a couple of nodes to the left and right from v on our path, // route, and check if v is on the shortest path. final IntIndexedContainer svNodes = suvPath.calcNodes(); int vIndex = svNodes.size() - 1; if (!tTest(path, vIndex)) continue; alternatives.add(new AlternativeInfo(path, share)); if (alternatives.size() >= maxPaths) break; } return alternatives; }
@Test public void testCalcOtherAlternatives() { BaseGraph g = createTestGraph(em); PMap hints = new PMap(); hints.putObject("alternative_route.max_weight_factor", 4); hints.putObject("alternative_route.local_optimality_factor", 0.5); hints.putObject("alternative_route.max_paths", 4); RoutingCHGraph routingCHGraph = prepareCH(g); AlternativeRouteEdgeCH altDijkstra = new AlternativeRouteEdgeCH(routingCHGraph, hints); List<AlternativeRouteEdgeCH.AlternativeInfo> pathInfos = altDijkstra.calcAlternatives(10, 5); assertEquals(2, pathInfos.size()); assertEquals(IntArrayList.from(10, 4, 3, 6, 5), pathInfos.get(0).path.calcNodes()); assertEquals(IntArrayList.from(10, 12, 11, 4, 3, 6, 5), pathInfos.get(1).path.calcNodes()); // The shortest path works (no restrictions on the way back }
boolean isContainerizable() { String moduleSpecification = getProperty(PropertyNames.CONTAINERIZE); if (project == null || Strings.isNullOrEmpty(moduleSpecification)) { return true; } // modules can be specified in one of three ways: // 1) a `groupId:artifactId` // 2) an `:artifactId` // 3) relative path within the repository if (moduleSpecification.equals(project.getGroupId() + ":" + project.getArtifactId()) || moduleSpecification.equals(":" + project.getArtifactId())) { return true; } // Relative paths never have a colon on *nix nor Windows. This moduleSpecification could be an // :artifactId or groupId:artifactId for a different artifact. if (moduleSpecification.contains(":")) { return false; } try { Path projectBase = project.getBasedir().toPath(); return projectBase.endsWith(moduleSpecification); } catch (InvalidPathException ex) { // ignore since moduleSpecification may not actually be a path return false; } }
@Test public void testIsContainerizable_directory() { project.setGroupId("group"); project.setArtifactId("artifact"); Properties projectProperties = project.getProperties(); projectProperties.setProperty("jib.containerize", "project"); assertThat(testPluginConfiguration.isContainerizable()).isTrue(); projectProperties.setProperty("jib.containerize", "project2"); assertThat(testPluginConfiguration.isContainerizable()).isFalse(); }
public double monitoredPercentage(Cluster cluster) { AggregationOptions<String, PartitionEntity> options = new AggregationOptions<>(0.0, 0.0, 1, _maxAllowedExtrapolationsPerPartition, allPartitions(cluster), AggregationOptions.Granularity.ENTITY, true); MetricSampleCompleteness<String, PartitionEntity> completeness = completeness(-1, Long.MAX_VALUE, options); return completeness.validEntityRatio(); }
@Test public void testMonitoredPercentage() { TestContext ctx = setupScenario1(); KafkaPartitionMetricSampleAggregator aggregator = ctx.aggregator(); MetadataClient.ClusterAndGeneration clusterAndGeneration = ctx.clusterAndGeneration(0); assertEquals(1.0, aggregator.monitoredPercentage(clusterAndGeneration.cluster()), 0.01); ctx = setupScenario2(); aggregator = ctx.aggregator(); clusterAndGeneration = ctx.clusterAndGeneration(0); assertEquals(0.75, aggregator.monitoredPercentage(clusterAndGeneration.cluster()), 0.01); ctx = setupScenario3(); aggregator = ctx.aggregator(); clusterAndGeneration = ctx.clusterAndGeneration(0); assertEquals((double) 4 / 6, aggregator.monitoredPercentage(clusterAndGeneration.cluster()), 0.01); ctx = setupScenario4(); aggregator = ctx.aggregator(); clusterAndGeneration = ctx.clusterAndGeneration(0); assertEquals((double) 4 / 6, aggregator.monitoredPercentage(clusterAndGeneration.cluster()), 0.01); }
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void setWebhook() throws IOException { String url = "https://google.com"; Integer maxConnections = 100; String[] allowedUpdates = {"message", "callback_query"}; String ipAddress = "1.1.1.1"; BaseResponse response = bot.execute(new SetWebhook() .url(url) .certificate(new File(certificateFile)) .ipAddress(ipAddress) .maxConnections(100) .allowedUpdates(allowedUpdates) .secretToken("secret-token") .dropPendingUpdates(true) ); assertTrue(response.isOk()); WebhookInfo webhookInfo = bot.execute(new GetWebhookInfo()).webhookInfo(); assertEquals(url, webhookInfo.url()); assertTrue(webhookInfo.hasCustomCertificate()); assertEquals(maxConnections, webhookInfo.maxConnections()); assertArrayEquals(allowedUpdates, webhookInfo.allowedUpdates()); Integer lastErrorDate = webhookInfo.lastErrorDate(); if (lastErrorDate != null) { assertEquals(System.currentTimeMillis(), lastErrorDate * 1000L, 30_000L); } String lastErrorMessage = webhookInfo.lastErrorMessage(); if (lastErrorMessage != null) { assertTrue(lastErrorMessage.contains("SSL")); } assertEquals(ipAddress, webhookInfo.ipAddress()); assertTrue(webhookInfo.pendingUpdateCount() >= 0); response = bot.execute(new SetWebhook().url("https://google.com") .certificate(Files.readAllBytes(new File(certificateFile).toPath())).allowedUpdates("")); assertTrue(response.isOk()); response = bot.execute(new SetWebhook()); assertTrue(response.isOk()); }
public synchronized long calculateObjectSize(Object obj) { // Breadth-first traversal instead of naive depth-first with recursive // implementation, so we don't blow the stack traversing long linked lists. boolean init = true; try { for (;;) { visit(obj, init); init = false; if (mPending.isEmpty()) { return mSize; } obj = mPending.removeFirst(); } } finally { mVisited.clear(); mPending.clear(); mSize = 0; } }
@Test public void testCircular() { Circular c1 = new Circular(); long size = mObjectSizeCalculator.calculateObjectSize(c1); c1.mCircular = c1; assertEquals(size, mObjectSizeCalculator.calculateObjectSize(c1)); }
@Override public ConfigOperateResult insertOrUpdateTagCas(final ConfigInfo configInfo, final String tag, final String srcIp, final String srcUser) { if (findConfigInfo4TagState(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant(), tag) == null) { return addConfigInfo4Tag(configInfo, tag, srcIp, srcUser); } else { return updateConfigInfo4TagCas(configInfo, tag, srcIp, srcUser); } }
@Test void testInsertOrUpdateTagCasOfUpdate() { String dataId = "dataId111222"; String group = "group"; String tenant = "tenant"; String appName = "appname1234"; String content = "c12345"; ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content); configInfo.setEncryptedDataKey("key23456"); configInfo.setMd5("casMd5"); //mock query config state and return obj after update ConfigInfoStateWrapper configInfoStateWrapper = new ConfigInfoStateWrapper(); configInfoStateWrapper.setLastModified(System.currentTimeMillis()); configInfoStateWrapper.setId(234567890L); String tag = "tag123"; Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, tag}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper()).thenReturn(configInfoStateWrapper); String srcIp = "ip345678"; String srcUser = "user1234567"; //mock cas update return 1 Mockito.when(jdbcTemplate.update(anyString(), eq(configInfo.getContent()), eq(MD5Utils.md5Hex(configInfo.getContent(), Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), any(Timestamp.class), eq(appName), eq(dataId), eq(group), eq(tenant), eq(tag), eq(configInfo.getMd5()))).thenReturn(1); ConfigOperateResult configOperateResult = externalConfigInfoTagPersistService.insertOrUpdateTagCas(configInfo, tag, srcIp, srcUser); //verify update to be invoked Mockito.verify(jdbcTemplate, times(1)) .update(anyString(), eq(configInfo.getContent()), eq(MD5Utils.md5Hex(configInfo.getContent(), Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), any(Timestamp.class), eq(appName), eq(dataId), eq(group), eq(tenant), eq(tag), eq(configInfo.getMd5())); assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); }
@Override public OptionRule optionRule() { return OptionRule.builder() .required(SUBSCRIPTION_NAME, CLIENT_SERVICE_URL, ADMIN_SERVICE_URL) .optional( CURSOR_STARTUP_MODE, CURSOR_STOP_MODE, TOPIC_DISCOVERY_INTERVAL, POLL_TIMEOUT, POLL_INTERVAL, POLL_BATCH_SIZE, TableSchemaOptions.SCHEMA) .exclusive(TOPIC, TOPIC_PATTERN) .conditional( CURSOR_STARTUP_MODE, SourceProperties.StartMode.TIMESTAMP, CURSOR_STARTUP_TIMESTAMP) .conditional( CURSOR_STARTUP_MODE, SourceProperties.StartMode.SUBSCRIPTION, CURSOR_RESET_MODE) .conditional( CURSOR_STOP_MODE, SourceProperties.StopMode.TIMESTAMP, CURSOR_STOP_TIMESTAMP) .bundled(AUTH_PLUGIN_CLASS, AUTH_PARAMS) .build(); }
@Test void optionRule() { PulsarSourceFactory pulsarSourceFactory = new PulsarSourceFactory(); OptionRule optionRule = pulsarSourceFactory.optionRule(); Assertions.assertNotNull(optionRule); }
public String computeFor(String serverId) { String jdbcUrl = config.get(JDBC_URL.getKey()).orElseThrow(() -> new IllegalStateException("Missing JDBC URL")); return DigestUtils.sha256Hex(serverId + "|" + jdbcUrlSanitizer.sanitize(jdbcUrl)); }
@Test public void test_checksum() { assertThat(computeFor("id1", "url1")) .isNotEmpty() .isEqualTo(computeFor("id1", "url1")) .isNotEqualTo(computeFor("id1", "url2")) .isNotEqualTo(computeFor("id2", "url1")) .isNotEqualTo(computeFor("id2", "url2")); }
public ConfigDef define(ConfigKey key) { if (configKeys.containsKey(key.name)) { throw new ConfigException("Configuration " + key.name + " is defined twice."); } if (key.group != null && !groups.contains(key.group)) { groups.add(key.group); } configKeys.put(key.name, key); return this; }
@Test public void testDefinedTwice() { assertThrows(ConfigException.class, () -> new ConfigDef().define("a", Type.STRING, Importance.HIGH, "docs").define("a", Type.INT, Importance.HIGH, "docs")); }
public static boolean isMirrorServerSetAssignment(TableConfig tableConfig, InstancePartitionsType instancePartitionsType) { // If the instance assignment config is not null and the partition selector is // MIRROR_SERVER_SET_PARTITION_SELECTOR, return tableConfig.getInstanceAssignmentConfigMap() != null && tableConfig.getInstanceAssignmentConfigMap().get(instancePartitionsType.toString()) != null && InstanceAssignmentConfigUtils.getInstanceAssignmentConfig(tableConfig, instancePartitionsType) .getPartitionSelector() == InstanceAssignmentConfig.PartitionSelector.MIRROR_SERVER_SET_PARTITION_SELECTOR; }
@Test public void testIsMirrorServerSetAssignment() { Map<String, InstanceAssignmentConfig> instanceAssignmentConfigMap = new HashMap<>(); instanceAssignmentConfigMap.put(InstancePartitionsType.OFFLINE.name(), getInstanceAssignmentConfig(InstanceAssignmentConfig.PartitionSelector.MIRROR_SERVER_SET_PARTITION_SELECTOR)); TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName("testTable") .setInstanceAssignmentConfigMap(instanceAssignmentConfigMap) .build(); Assert.assertTrue(InstanceAssignmentConfigUtils.isMirrorServerSetAssignment(tableConfig, InstancePartitionsType.OFFLINE)); }
public void execute() { Optional<String> login = configuration.get(CoreProperties.LOGIN); Optional<String> password = configuration.get(CoreProperties.PASSWORD); String warningMessage = null; if (password.isPresent()) { warningMessage = PASSWORD_WARN_MESSAGE; } else if (login.isPresent()) { warningMessage = LOGIN_WARN_MESSAGE; } if (warningMessage != null) { if (isScannerDotNet()) { warningMessage += SCANNER_DOTNET_WARN_MESSAGE; } LOG.warn(warningMessage); analysisWarnings.addUnique(warningMessage); } }
@Test public void execute_whenNotUsingLoginOrPassword_shouldNotAddWarning() { underTest.execute(); verifyNoInteractions(analysisWarnings); Assertions.assertThat(logger.logs(Level.WARN)).isEmpty(); }
public static Point<AriaCsvHit> parsePointFromAriaCsv(String rawCsvText) { AriaCsvHit ariaHit = AriaCsvHit.from(rawCsvText); Position pos = new Position(ariaHit.time(), ariaHit.latLong(), ariaHit.altitude()); return new Point<>(pos, null, ariaHit.linkId(), ariaHit); }
@Test public void exampleParsing_noExtraData() { String rawCsv = ",,2018-03-24T14:41:09.371Z,vehicleIdNumber,42.9525,-83.7056,2700"; Point<AriaCsvHit> pt = AriaCsvHits.parsePointFromAriaCsv(rawCsv); assertThat(pt.time(), is(Instant.parse("2018-03-24T14:41:09.371Z"))); assertThat(pt.trackId(), is("vehicleIdNumber")); assertThat(pt.latitude(), is(42.9525)); assertThat(pt.longitude(), is(-83.7056)); assertThat(pt.altitude(), is(Distance.ofFeet(2700))); assertThat(pt.velocity(), nullValue()); assertThat("The entire rawCsv text is accessible from the parsed point", pt.rawData().rawCsvText(), is(rawCsv)); }
@Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { List<Header> warnings = Arrays.stream(response.getHeaders("Warning")).filter(header -> !this.isDeprecationMessage(header.getValue())).collect(Collectors.toList()); response.removeHeaders("Warning"); warnings.stream().forEach(header -> response.addHeader(header)); }
@Test public void testInterceptorMultipleHeaderFilteredWarningAndMultipleTriggers() throws IOException, HttpException { ElasticsearchFilterDeprecationWarningsInterceptor interceptor = new ElasticsearchFilterDeprecationWarningsInterceptor(); HttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 0, 0), 0, null)); response.addHeader("Test", "This header should not trigger the interceptor."); response.addHeader("Warning", "This warning should not trigger the interceptor."); response.addHeader("Warning", "This text contains the trigger: but in a future major version, direct access to system indices and their aliases will not be allowed - and should be filtered out"); response.addHeader("Warning", "This text contains the trigger: setting was deprecated in Elasticsearch - and should be filtered out"); assertThat(response.getAllHeaders()) .as("Number of Headers should be 4 before start.") .hasSize(4); interceptor.process(response, null); assertThat(response.getAllHeaders()) .as("Number of Headers should be 2 less after running the interceptor.") .hasSize(2); }
public static InputStream getResourceAsStream(String resource) throws IOException { ClassLoader loader = ResourceUtils.class.getClassLoader(); return getResourceAsStream(loader, resource); }
@Test void testGetResourceAsStreamForClasspath() throws IOException { try (InputStream inputStream = ResourceUtils.getResourceAsStream("test-tls-cert.pem")) { assertNotNull(inputStream); } }
public int boundedControlledPoll( final ControlledFragmentHandler handler, final long limitPosition, final int fragmentLimit) { if (isClosed) { return 0; } long initialPosition = subscriberPosition.get(); if (initialPosition >= limitPosition) { return 0; } int fragmentsRead = 0; int initialOffset = (int)initialPosition & termLengthMask; int offset = initialOffset; final UnsafeBuffer termBuffer = activeTermBuffer(initialPosition); final int limitOffset = (int)Math.min(termBuffer.capacity(), (limitPosition - initialPosition) + offset); final Header header = this.header; header.buffer(termBuffer); try { while (fragmentsRead < fragmentLimit && offset < limitOffset) { final int length = frameLengthVolatile(termBuffer, offset); if (length <= 0) { break; } final int frameOffset = offset; final int alignedLength = BitUtil.align(length, FRAME_ALIGNMENT); offset += alignedLength; if (isPaddingFrame(termBuffer, frameOffset)) { continue; } ++fragmentsRead; header.offset(frameOffset); final Action action = handler.onFragment( termBuffer, frameOffset + HEADER_LENGTH, length - HEADER_LENGTH, header); if (ABORT == action) { --fragmentsRead; offset -= alignedLength; break; } if (BREAK == action) { break; } if (COMMIT == action) { initialPosition += (offset - initialOffset); initialOffset = offset; subscriberPosition.setOrdered(initialPosition); } } } catch (final Exception ex) { errorHandler.onError(ex); } finally { final long resultingPosition = initialPosition + (offset - initialOffset); if (resultingPosition > initialPosition) { subscriberPosition.setOrdered(resultingPosition); } } return fragmentsRead; }
@Test void shouldPollFragmentsToBoundedControlledFragmentHandlerWithMaxPositionBeforeNextMessage() { final long initialPosition = computePosition(INITIAL_TERM_ID, 0, POSITION_BITS_TO_SHIFT, INITIAL_TERM_ID); final long maxPosition = initialPosition + ALIGNED_FRAME_LENGTH; position.setOrdered(initialPosition); final Image image = createImage(); insertDataFrame(INITIAL_TERM_ID, offsetForFrame(0)); insertDataFrame(INITIAL_TERM_ID, offsetForFrame(1)); when(mockControlledFragmentHandler.onFragment(any(DirectBuffer.class), anyInt(), anyInt(), any(Header.class))) .thenReturn(Action.CONTINUE); final int fragmentsRead = image.boundedControlledPoll( mockControlledFragmentHandler, maxPosition, Integer.MAX_VALUE); assertThat(fragmentsRead, is(1)); final InOrder inOrder = Mockito.inOrder(position, mockControlledFragmentHandler); inOrder.verify(mockControlledFragmentHandler).onFragment( any(UnsafeBuffer.class), eq(HEADER_LENGTH), eq(DATA.length), any(Header.class)); inOrder.verify(position).setOrdered(initialPosition + ALIGNED_FRAME_LENGTH); }
public static void assignFieldParams(Object bean, Map<String, Param> params) throws TikaConfigException { Class<?> beanClass = bean.getClass(); if (!PARAM_INFO.containsKey(beanClass)) { synchronized (TikaConfig.class) { if (!PARAM_INFO.containsKey(beanClass)) { List<AccessibleObject> aObjs = collectInfo(beanClass, org.apache.tika.config.Field.class); List<ParamField> fields = new ArrayList<>(aObjs.size()); for (AccessibleObject aObj : aObjs) { fields.add(new ParamField(aObj)); } PARAM_INFO.put(beanClass, fields); } } } List<ParamField> fields = PARAM_INFO.get(beanClass); for (ParamField field : fields) { Param<?> param = params.get(field.getName()); if (param != null) { if (field.getType().isAssignableFrom(param.getType())) { try { field.assignValue(bean, param.getValue()); } catch (InvocationTargetException e) { LOG.error("Error assigning value '{}' to '{}'", param.getValue(), param.getName()); final Throwable cause = e.getCause() == null ? e : e.getCause(); throw new TikaConfigException(cause.getMessage(), cause); } catch (IllegalAccessException e) { LOG.error("Error assigning value '{}' to '{}'", param.getValue(), param.getName()); throw new TikaConfigException(e.getMessage(), e); } } else { String msg = String.format(Locale.ROOT, "Value '%s' of type '%s' can't be" + " assigned to field '%s' of defined type '%s'", param.getValue(), param.getValue().getClass(), field.getName(), field.getType()); throw new TikaConfigException(msg); } } else if (field.isRequired()) { //param not supplied but field is declared as required? String msg = String.format(Locale.ROOT, "Param %s is required for %s," + " but it is not given in config.", field.getName(), bean.getClass().getName()); throw new TikaConfigException(msg); } else { LOG.debug("Param not supplied, field is not mandatory"); } } }
@Test public void testParamValueInheritance() { class Bean { @Field(required = true) CharSequence field; } Bean parser = new Bean(); Map<String, Param> params = new HashMap<>(); try { String val = "someval"; params.put("field", new Param<>("field", String.class, val)); AnnotationUtils.assignFieldParams(parser, params); assertEquals(val, parser.field); } catch (Exception e) { e.printStackTrace(); fail("Exception not expected, string is assignable to CharSequence"); } try { Date val = new Date(); params.put("field", new Param<>("field", Date.class, val)); AnnotationUtils.assignFieldParams(parser, params); fail("Exception expected, Date is not assignable to CharSequence."); } catch (TikaConfigException e) { //expected } }
@Override public Collection<DatabasePacket> execute() { failedIfContainsMultiStatements(); MetaDataContexts metaDataContexts = ProxyContext.getInstance().getContextManager().getMetaDataContexts(); SQLParserRule sqlParserRule = metaDataContexts.getMetaData().getGlobalRuleMetaData().getSingleRule(SQLParserRule.class); DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "MySQL"); SQLStatement sqlStatement = sqlParserRule.getSQLParserEngine(databaseType).parse(packet.getSQL(), true); if (!MySQLComStmtPrepareChecker.isAllowedStatement(sqlStatement)) { throw new UnsupportedPreparedStatementException(); } SQLStatementContext sqlStatementContext = new SQLBindEngine(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData(), connectionSession.getCurrentDatabaseName(), packet.getHintValueContext()).bind(sqlStatement, Collections.emptyList()); int statementId = MySQLStatementIdGenerator.getInstance().nextStatementId(connectionSession.getConnectionId()); MySQLServerPreparedStatement serverPreparedStatement = new MySQLServerPreparedStatement(packet.getSQL(), sqlStatementContext, packet.getHintValueContext(), new CopyOnWriteArrayList<>()); connectionSession.getServerPreparedStatementRegistry().addPreparedStatement(statementId, serverPreparedStatement); return createPackets(sqlStatementContext, statementId, serverPreparedStatement); }
@Test void assertPrepareMultiStatements() { when(packet.getSQL()).thenReturn("update t set v=v+1 where id=1;update t set v=v+1 where id=2;update t set v=v+1 where id=3"); when(connectionSession.getAttributeMap().hasAttr(MySQLConstants.OPTION_MULTI_STATEMENTS_ATTRIBUTE_KEY)).thenReturn(true); when(connectionSession.getAttributeMap().attr(MySQLConstants.OPTION_MULTI_STATEMENTS_ATTRIBUTE_KEY).get()).thenReturn(0); assertThrows(UnsupportedPreparedStatementException.class, () -> new MySQLComStmtPrepareExecutor(packet, connectionSession).execute()); }
public static void updateFinalModifierField(Field field) { final Field modifiersField = getField(Field.class, "modifiers"); if (modifiersField != null) { try { modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); } catch (IllegalAccessException ex) { LOGGER.log(Level.WARNING, String.format(Locale.ENGLISH, "Could not update final field named %s", field.getName())); } } }
@Test public void updateFinalModifierField() throws NoSuchFieldException { final Field finalField = TestReflect.class.getDeclaredField("finalField"); Assert.assertTrue(Modifier.isFinal(finalField.getModifiers())); ReflectUtils.updateFinalModifierField(finalField); }
public static boolean isNumber(String str) { return isNotEmpty(str) && NUM_PATTERN.matcher(str).matches(); }
@Test void testIsInteger() throws Exception { assertFalse(StringUtils.isNumber(null)); assertFalse(StringUtils.isNumber("")); assertTrue(StringUtils.isNumber("123")); }
@Override protected Result[] run(String value) { final Grok grok = grokPatternRegistry.cachedGrokForPattern(this.pattern, this.namedCapturesOnly); // the extractor instance is rebuilt every second anyway final Match match = grok.match(value); final Map<String, Object> matches = match.captureFlattened(); final List<Result> results = new ArrayList<>(matches.size()); for (final Map.Entry<String, Object> entry : matches.entrySet()) { // never add null values to the results, those don't make sense for us if (entry.getValue() != null) { results.add(new Result(entry.getValue(), entry.getKey(), -1, -1)); } } return results.toArray(new Result[0]); }
@Test public void testNamedCapturesOnly() { final Map<String, Object> config = new HashMap<>(); final GrokPattern mynumber = GrokPattern.create("MYNUMBER", "(?:%{BASE10NUM})"); patternSet.add(mynumber); config.put("named_captures_only", true); final GrokExtractor extractor1 = makeExtractor("%{MYNUMBER:num}", config); config.put("named_captures_only", true); final GrokExtractor extractor2 = makeExtractor("%{MYNUMBER:num;int}", config); config.put("named_captures_only", false); final GrokExtractor extractor3 = makeExtractor("%{MYNUMBER:num}", config); final GrokExtractor extractor4 = makeExtractor("%{MYNUMBER:num}"); assertThat(extractor1.run("2015")) .hasSize(1) .containsOnly(new Extractor.Result("2015", "num", -1, -1)); assertThat(extractor2.run("2015")) .hasSize(1) .containsOnly(new Extractor.Result(2015, "num", -1, -1)); assertThat(extractor3.run("2015")) .hasSize(2) .containsOnly( new Extractor.Result("2015", "num", -1, -1), new Extractor.Result("2015", "BASE10NUM", -1, -1) ); assertThat(extractor4.run("2015")) .hasSize(2) .containsOnly( new Extractor.Result("2015", "num", -1, -1), new Extractor.Result("2015", "BASE10NUM", -1, -1) ); }
@Override public void event(IntentEvent event) { // this is the fast path for CORRUPT intents, retry on event notification. //TODO we might consider using the timer to back off for subsequent retries if (enabled && event.type() == IntentEvent.Type.CORRUPT) { Key key = event.subject().key(); if (store.isMaster(key)) { IntentData data = store.getIntentData(event.subject().key()); resubmitCorrupt(data, true); } } }
@Test public void corruptEventThreshold() { IntentStoreDelegate mockDelegate = new IntentStoreDelegate() { @Override public void process(IntentData intentData) { intentData.setState(CORRUPT); intentData.setErrorCount(cleanup.retryThreshold); store.write(intentData); } @Override public void notify(IntentEvent event) { cleanup.event(event); } }; store.setDelegate(mockDelegate); Intent intent = new MockIntent(1L); IntentData data = new IntentData(intent, INSTALL_REQ, null); store.addPending(data); assertEquals("Expect number of submits incorrect", 0, service.submitCounter()); }
void fetchAndRunCommands() { lastPollTime.set(clock.instant()); final List<QueuedCommand> commands = commandStore.getNewCommands(NEW_CMDS_TIMEOUT); if (commands.isEmpty()) { if (!commandTopicExists.get()) { commandTopicDeleted = true; } return; } final List<QueuedCommand> compatibleCommands = checkForIncompatibleCommands(commands); final Optional<QueuedCommand> terminateCmd = findTerminateCommand(compatibleCommands, commandDeserializer); if (terminateCmd.isPresent()) { terminateCluster(terminateCmd.get().getAndDeserializeCommand(commandDeserializer)); return; } LOG.debug("Found {} new writes to command topic", compatibleCommands.size()); for (final QueuedCommand command : compatibleCommands) { if (closed) { return; } executeStatement(command); } }
@Test public void shouldPullAndRunStatements() { // Given: givenQueuedCommands(queuedCommand1, queuedCommand2, queuedCommand3); // When: commandRunner.fetchAndRunCommands(); // Then: final InOrder inOrder = inOrder(statementExecutor); inOrder.verify(statementExecutor).handleStatement(queuedCommand1); inOrder.verify(statementExecutor).handleStatement(queuedCommand2); inOrder.verify(statementExecutor).handleStatement(queuedCommand3); }
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { final String msg = new String(rawMessage.getPayload(), charset); try (Timer.Context ignored = this.decodeTime.time()) { final ResolvableInetSocketAddress address = rawMessage.getRemoteAddress(); final InetSocketAddress remoteAddress; if (address == null) { remoteAddress = null; } else { remoteAddress = address.getInetSocketAddress(); } return parse(msg, remoteAddress == null ? null : remoteAddress.getAddress(), rawMessage.getTimestamp()); } }
@Test public void testFortiGateFirewall() { final RawMessage rawMessage = buildRawMessage("<45>date=2017-03-06 time=12:53:10 devname=DEVICENAME devid=DEVICEID logid=0000000013 type=traffic subtype=forward level=notice vd=ALIAS srcip=IP srcport=45748 srcintf=\"IF\" dstip=IP dstport=443 dstintf=\"IF\" sessionid=1122686199 status=close policyid=77 dstcountry=\"COUNTRY\" srccountry=\"COUNTRY\" trandisp=dnat tranip=IP tranport=443 service=HTTPS proto=6 appid=41540 app=\"SSL_TLSv1.2\" appcat=\"Network.Service\" applist=\"ACLNAME\" appact=detected duration=1 sentbyte=2313 rcvdbyte=14883 sentpkt=19 rcvdpkt=19 utmaction=passthrough utmevent=app-ctrl attack=\"SSL\" hostname=\"HOSTNAME\""); final Message message = codec.decode(rawMessage); assertThat(message).isNotNull(); assertThat(message.getMessage()).isEqualTo("date=2017-03-06 time=12:53:10 devname=DEVICENAME devid=DEVICEID logid=0000000013 type=traffic subtype=forward level=notice vd=ALIAS srcip=IP srcport=45748 srcintf=\"IF\" dstip=IP dstport=443 dstintf=\"IF\" sessionid=1122686199 status=close policyid=77 dstcountry=\"COUNTRY\" srccountry=\"COUNTRY\" trandisp=dnat tranip=IP tranport=443 service=HTTPS proto=6 appid=41540 app=\"SSL_TLSv1.2\" appcat=\"Network.Service\" applist=\"ACLNAME\" appact=detected duration=1 sentbyte=2313 rcvdbyte=14883 sentpkt=19 rcvdpkt=19 utmaction=passthrough utmevent=app-ctrl attack=\"SSL\" hostname=\"HOSTNAME\""); assertThat(message.getTimestamp()).isEqualTo(new DateTime(2017, 3, 6, 12, 53, 10, DateTimeZone.UTC)); assertThat(message.getField("source")).isEqualTo("DEVICENAME"); assertThat(message.getField("level")).isEqualTo(5); assertThat(message.getField("facility")).isEqualTo("syslogd"); assertThat(message.getField("logid")).isEqualTo("0000000013"); assertThat(message.getField("app")).isEqualTo("SSL_TLSv1.2"); assertThat(message.getField("facility_num")).isEqualTo(5); }
@Deprecated public static <T> Task<T> callable(final String name, final Callable<? extends T> callable) { return Task.callable(name, () -> callable.call()); }
@Test public void testTimeoutTaskWithoutTimeout() throws InterruptedException { final String value = "value"; final Task<String> task = Task.callable("task", () -> value); final Task<String> timeoutTask = task.withTimeout(200, TimeUnit.MILLISECONDS); runAndWait("TestTasks.testTimeoutTaskWithoutTimeout", timeoutTask); assertEquals(value, task.get()); // The wrapping task should get the same value as the wrapped task assertEquals(value, timeoutTask.get()); }
public void setName(String name) throws IllegalStateException { if (name != null && name.equals(this.name)) { return; // idempotent naming } if (this.name == null || CoreConstants.DEFAULT_CONTEXT_NAME.equals(this.name)) { this.name = name; } else { throw new IllegalStateException("Context has been already given a name"); } }
@Test public void idempotentNameTest() { context.setName("hello"); context.setName("hello"); }
public static int getDigit(final int index, final byte value) { if (value < 0x30 || value > 0x39) { throw new AsciiNumberFormatException("'" + ((char)value) + "' is not a valid digit @ " + index); } return value - 0x30; }
@Test void shouldThrowExceptionWhenDecodingByteNonNumericValue() { assertThrows(AsciiNumberFormatException.class, () -> AsciiEncoding.getDigit(0, (byte)'a')); }
@Override public CloudConfiguration getCloudConfiguration() { return hdfsEnvironment.getCloudConfiguration(); }
@Test public void testGetCloudConfiguration() { CloudConfiguration cc = metadata.getCloudConfiguration(); Assert.assertEquals(cc.getCloudType(), CloudType.DEFAULT); }
public void addOrReplaceSlaveServer( SlaveServer slaveServer ) { int index = slaveServers.indexOf( slaveServer ); if ( index < 0 ) { slaveServers.add( slaveServer ); } else { SlaveServer previous = slaveServers.get( index ); previous.replaceMeta( slaveServer ); } setChanged(); }
@Test public void testAddOrReplaceSlaveServer() { // meta.addOrReplaceSlaveServer() right now will fail with an NPE assertNull( meta.getSlaveServers() ); List<SlaveServer> slaveServers = new ArrayList<>(); meta.setSlaveServers( slaveServers ); assertNotNull( meta.getSlaveServers() ); SlaveServer slaveServer = mock( SlaveServer.class ); meta.addOrReplaceSlaveServer( slaveServer ); assertFalse( meta.getSlaveServers().isEmpty() ); meta.addOrReplaceSlaveServer( slaveServer ); assertEquals( 1, meta.getSlaveServerNames().length ); assertNull( meta.findSlaveServer( null ) ); assertNull( meta.findSlaveServer( "" ) ); when( slaveServer.getName() ).thenReturn( "ss1" ); assertEquals( slaveServer, meta.findSlaveServer( "ss1" ) ); }
@Override @Transactional(rollbackFor = Exception.class) public void deleteCodegen(Long tableId) { // 校验是否已经存在 if (codegenTableMapper.selectById(tableId) == null) { throw exception(CODEGEN_TABLE_NOT_EXISTS); } // 删除 table 表定义 codegenTableMapper.deleteById(tableId); // 删除 column 字段定义 codegenColumnMapper.deleteListByTableId(tableId); }
@Test public void testDeleteCodegen_success() { // mock 数据 CodegenTableDO table = randomPojo(CodegenTableDO.class, o -> o.setScene(CodegenSceneEnum.ADMIN.getScene())); codegenTableMapper.insert(table); CodegenColumnDO column = randomPojo(CodegenColumnDO.class, o -> o.setTableId(table.getId())); codegenColumnMapper.insert(column); // 准备参数 Long tableId = table.getId(); // 调用 codegenService.deleteCodegen(tableId); // 断言 assertNull(codegenTableMapper.selectById(tableId)); assertEquals(0, codegenColumnMapper.selectList().size()); }
@Override public Long getLong(final int columnIndex) { return values.getLong(columnIndex - 1); }
@Test public void shouldGetLong() { assertThat(row.getLong("f_long"), is(1234L)); assertThat(row.getLong("f_int"), is(2L)); }
@VisibleForTesting void validateCaptcha(AuthLoginReqVO reqVO) { // 如果验证码关闭,则不进行校验 if (!captchaEnable) { return; } // 校验验证码 ValidationUtils.validate(validator, reqVO, AuthLoginReqVO.CodeEnableGroup.class); CaptchaVO captchaVO = new CaptchaVO(); captchaVO.setCaptchaVerification(reqVO.getCaptchaVerification()); ResponseModel response = captchaService.verification(captchaVO); // 验证不通过 if (!response.isSuccess()) { // 创建登录失败日志(验证码不正确) createLoginLog(null, reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME, LoginResultEnum.CAPTCHA_CODE_ERROR); throw exception(AUTH_LOGIN_CAPTCHA_CODE_ERROR, response.getRepMsg()); } }
@Test public void testValidateCaptcha_successWithEnable() { // 准备参数 AuthLoginReqVO reqVO = randomPojo(AuthLoginReqVO.class); // mock 验证码打开 ReflectUtil.setFieldValue(authService, "captchaEnable", true); // mock 验证通过 when(captchaService.verification(argThat(captchaVO -> { assertEquals(reqVO.getCaptchaVerification(), captchaVO.getCaptchaVerification()); return true; }))).thenReturn(ResponseModel.success()); // 调用,无需断言 authService.validateCaptcha(reqVO); }
public ParResponse requestPushedUri( URI pushedAuthorizationRequestUri, ParBodyBuilder parBodyBuilder) { var headers = List.of( new Header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON), new Header(HttpHeaders.CONTENT_TYPE, UrlFormBodyBuilder.MEDIA_TYPE)); var req = new Request(pushedAuthorizationRequestUri, "POST", headers, parBodyBuilder.build()); var res = httpClient.call(req); if (res.status() != 201) { throw HttpExceptions.httpFailBadStatus( req.method(), pushedAuthorizationRequestUri, res.status()); } return JsonCodec.readValue(res.body(), ParResponse.class); }
@Test void requestPushedUri(WireMockRuntimeInfo wm) { var body = """ { "request_uri":"https://example.com/auth/login", "expires_in": 600 } """ .getBytes(StandardCharsets.UTF_8); var path = "/auth/par"; stubFor(post(path).willReturn(created().withBody(body))); var base = URI.create(wm.getHttpBaseUrl()); var res = client.requestPushedUri(base.resolve(path), ParBodyBuilder.create()); assertEquals("https://example.com/auth/login", res.requestUri()); assertEquals(600L, res.expiresIn()); }
@Override public Set<MappedFieldTypeDTO> fieldTypesByStreamIds(Collection<String> streamIds, TimeRange timeRange) { final Set<String> indexSets = streamService.indexSetIdsByIds(streamIds); final Set<String> indexNames = this.indexLookup.indexNamesForStreamsInTimeRange(ImmutableSet.copyOf(streamIds), timeRange); final Set<FieldTypeDTO> fieldTypeDTOs = this.indexFieldTypesService.findForIndexSets(indexSets) .stream() .filter(fieldTypes -> indexNames.contains(fieldTypes.indexName())) .flatMap(fieldTypes -> fieldTypes.fields().stream()) .filter(fieldTypeDTO -> !streamAwareFieldTypes || !Collections.disjoint(fieldTypeDTO.streams(), streamIds)) .collect(Collectors.toSet()); return mergeCompoundFieldTypes(fieldTypeDTOs.stream() .map(this::mapPhysicalFieldType)); }
@Test public void requestsFieldTypesForRequestedTimeRange() throws Exception { this.mappedFieldTypesService.fieldTypesByStreamIds(Collections.singleton("stream1"), AbsoluteRange.create("2010-05-17T23:28:14.000+02:00", "2021-05-05T12:09:23.213+02:00")); verify(this.indexLookup, times(1)).indexNamesForStreamsInTimeRange(streamIdCaptor.capture(), timeRangeCaptor.capture()); assertThat(streamIdCaptor.getValue()).containsExactly("stream1"); assertThat(timeRangeCaptor.getValue()).isEqualTo(AbsoluteRange.create("2010-05-17T23:28:14.000+02:00", "2021-05-05T12:09:23.213+02:00")); }
@Override @Transactional(rollbackFor = Exception.class) public void updateCodegen(CodegenUpdateReqVO updateReqVO) { // 校验是否已经存在 if (codegenTableMapper.selectById(updateReqVO.getTable().getId()) == null) { throw exception(CODEGEN_TABLE_NOT_EXISTS); } // 校验主表字段存在 if (Objects.equals(updateReqVO.getTable().getTemplateType(), CodegenTemplateTypeEnum.SUB.getType())) { if (codegenTableMapper.selectById(updateReqVO.getTable().getMasterTableId()) == null) { throw exception(CODEGEN_MASTER_TABLE_NOT_EXISTS, updateReqVO.getTable().getMasterTableId()); } if (CollUtil.findOne(updateReqVO.getColumns(), // 关联主表的字段不存在 column -> column.getId().equals(updateReqVO.getTable().getSubJoinColumnId())) == null) { throw exception(CODEGEN_SUB_COLUMN_NOT_EXISTS, updateReqVO.getTable().getSubJoinColumnId()); } } // 更新 table 表定义 CodegenTableDO updateTableObj = BeanUtils.toBean(updateReqVO.getTable(), CodegenTableDO.class); codegenTableMapper.updateById(updateTableObj); // 更新 column 字段定义 List<CodegenColumnDO> updateColumnObjs = BeanUtils.toBean(updateReqVO.getColumns(), CodegenColumnDO.class); updateColumnObjs.forEach(updateColumnObj -> codegenColumnMapper.updateById(updateColumnObj)); }
@Test public void testUpdateCodegen_success() { // mock 数据 CodegenTableDO table = randomPojo(CodegenTableDO.class, o -> o.setTemplateType(CodegenTemplateTypeEnum.ONE.getType()) .setScene(CodegenSceneEnum.ADMIN.getScene())); codegenTableMapper.insert(table); CodegenColumnDO column01 = randomPojo(CodegenColumnDO.class, o -> o.setTableId(table.getId())); codegenColumnMapper.insert(column01); CodegenColumnDO column02 = randomPojo(CodegenColumnDO.class, o -> o.setTableId(table.getId())); codegenColumnMapper.insert(column02); // 准备参数 CodegenUpdateReqVO updateReqVO = randomPojo(CodegenUpdateReqVO.class, o -> o.getTable().setId(table.getId()) .setTemplateType(CodegenTemplateTypeEnum.ONE.getType()) .setScene(CodegenSceneEnum.ADMIN.getScene())); CodegenColumnSaveReqVO columnVO01 = randomPojo(CodegenColumnSaveReqVO.class, o -> o.setId(column01.getId()).setTableId(table.getId())); CodegenColumnSaveReqVO columnVO02 = randomPojo(CodegenColumnSaveReqVO.class, o -> o.setId(column02.getId()).setTableId(table.getId())); updateReqVO.setColumns(Arrays.asList(columnVO01, columnVO02)); // 调用 codegenService.updateCodegen(updateReqVO); // 断言 CodegenTableDO dbTable = codegenTableMapper.selectById(table.getId()); assertPojoEquals(updateReqVO.getTable(), dbTable); List<CodegenColumnDO> dbColumns = codegenColumnMapper.selectList(); assertEquals(2, dbColumns.size()); assertPojoEquals(columnVO01, dbColumns.get(0)); assertPojoEquals(columnVO02, dbColumns.get(1)); }
@Override public ShardingAlgorithm getShardingAlgorithm() { return null; }
@Test void assertDoSharding() { assertNull(noneShardingStrategy.getShardingAlgorithm()); }
@Override public void processElement(StreamRecord<E> element) throws Exception { final E externalRecord = element.getValue(); final Object internalRecord; try { internalRecord = converter.toInternal(externalRecord); } catch (Exception e) { throw new FlinkRuntimeException( String.format( "Error during input conversion from external DataStream API to " + "internal Table API data structures. Make sure that the " + "provided data types that configure the converters are " + "correctly declared in the schema. Affected record:\n%s", externalRecord), e); } final RowData payloadRowData; if (requiresWrapping) { final GenericRowData wrapped = new GenericRowData(RowKind.INSERT, 1); wrapped.setField(0, internalRecord); payloadRowData = wrapped; } else { // top-level records must not be null and will be skipped if (internalRecord == null) { return; } payloadRowData = (RowData) internalRecord; } final RowKind kind = payloadRowData.getRowKind(); if (isInsertOnly && kind != RowKind.INSERT) { throw new FlinkRuntimeException( String.format( "Error during input conversion. Conversion expects insert-only " + "records but DataStream API record contains: %s", kind)); } if (!produceRowtimeMetadata) { output.collect(outRecord.replace(payloadRowData)); return; } if (!element.hasTimestamp()) { throw new FlinkRuntimeException( "Could not find timestamp in DataStream API record. " + "Make sure that timestamps have been assigned before and " + "the event-time characteristic is enabled."); } final GenericRowData rowtimeRowData = new GenericRowData(1); rowtimeRowData.setField(0, TimestampData.fromEpochMillis(element.getTimestamp())); final JoinedRowData joinedRowData = new JoinedRowData(kind, payloadRowData, rowtimeRowData); output.collect(outRecord.replace(joinedRowData)); }
@Test public void testInvalidRecords() { final InputConversionOperator<Row> operator = new InputConversionOperator<>( createConverter(DataTypes.ROW(DataTypes.FIELD("f", DataTypes.INT()))), false, false, false, true); // invalid record due to missing field assertThatThrownBy( () -> operator.processElement( new StreamRecord<>(Row.ofKind(RowKind.INSERT)))) .satisfies( anyCauseMatches( FlinkRuntimeException.class, "Error during input conversion from external DataStream " + "API to internal Table API data structures")); // invalid row kind assertThatThrownBy( () -> operator.processElement( new StreamRecord<>(Row.ofKind(RowKind.DELETE, 12)))) .satisfies( anyCauseMatches( FlinkRuntimeException.class, "Conversion expects insert-only records")); }
public PrimitiveValue minValue() { return minValue; }
@Test void shouldReturnDefaultMinValueWhenSpecified() throws Exception { final String testXmlString = "<types>" + " <type name=\"testTypeDefaultCharMinValue\" primitiveType=\"char\"/>" + "</types>"; final Map<String, Type> map = parseTestXmlWithMap("/types/type", testXmlString); assertNull(((EncodedDataType)map.get("testTypeDefaultCharMinValue")).minValue()); }
public static <T> RestResult<T> failedWithMsg(int code, String errMsg) { return RestResult.<T>builder().withCode(code).withMsg(errMsg).build(); }
@Test void testFailedWithMsg() { RestResult<String> restResult = RestResultUtils.failed("test"); assertRestResult(restResult, 500, "test", null, false); }
public EventDefinitionDto update(EventDefinitionDto updatedEventDefinition, boolean schedule) { // Grab the old record so we can revert to it if something goes wrong final Optional<EventDefinitionDto> oldEventDefinition = eventDefinitionService.get(updatedEventDefinition.id()); final EventDefinitionDto eventDefinition = updateEventDefinition(updatedEventDefinition); try { if (schedule) { if (getJobDefinition(eventDefinition).isPresent()) { updateJobDefinitionAndTriggerIfScheduledType(eventDefinition); } else { createJobDefinitionAndTriggerIfScheduledType(eventDefinition); } } else { unschedule(eventDefinition.id()); } } catch (Exception e) { // Cleanup if anything goes wrong LOG.error("Reverting to old event definition <{}/{}> because of an error updating the job definition", eventDefinition.id(), eventDefinition.title(), e); oldEventDefinition.ifPresent(eventDefinitionService::save); throw e; } return eventDefinition; }
@Test @MongoDBFixtures("event-processors.json") public void updateWithErrors() { final String newTitle = "A NEW TITLE " + DateTime.now(DateTimeZone.UTC).toString(); final String newDescription = "A NEW DESCRIPTION " + DateTime.now(DateTimeZone.UTC).toString(); final EventDefinitionDto existingDto = eventDefinitionService.get("54e3deadbeefdeadbeef0000").orElse(null); final JobDefinitionDto existingJobDefinition = jobDefinitionService.get("54e3deadbeefdeadbeef0001").orElse(null); final JobTriggerDto existingTrigger = jobTriggerService.get("54e3deadbeefdeadbeef0002").orElse(null); assertThat(existingDto).isNotNull(); assertThat(existingJobDefinition).isNotNull(); assertThat(existingTrigger).isNotNull(); final EventDefinitionDto updatedDto = existingDto.toBuilder() .title(newTitle) .description(newDescription) .build(); // Reset all before doing new stubs reset(eventDefinitionService); reset(jobDefinitionService); reset(jobTriggerService); doThrow(new NullPointerException("yolo2")).when(jobDefinitionService).save(any()); assertThatCode(() -> handler.update(updatedDto, true)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("yolo2"); assertThat(eventDefinitionService.get(existingDto.id())).isPresent().get().satisfies(dto -> { assertThat(dto.id()).isEqualTo(existingDto.id()); assertThat(dto.title()).isEqualTo(existingDto.title()); assertThat(dto.description()).isEqualTo(existingDto.description()); }); assertThat(jobDefinitionService.get("54e3deadbeefdeadbeef0001")).isPresent().get().satisfies(definition -> { assertThat(definition.title()).isEqualTo(existingJobDefinition.title()); assertThat(definition.description()).isEqualTo(existingJobDefinition.description()); }); // Reset all before doing new stubs reset(eventDefinitionService); reset(jobDefinitionService); reset(jobTriggerService); doThrow(new NullPointerException("yolo3")).when(jobTriggerService).update(any()); assertThatCode(() -> handler.update(updatedDto, true)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("yolo3"); assertThat(eventDefinitionService.get(existingDto.id())).isPresent().get().satisfies(dto -> { assertThat(dto.id()).isEqualTo(existingDto.id()); assertThat(dto.title()).isEqualTo(existingDto.title()); assertThat(dto.description()).isEqualTo(existingDto.description()); }); assertThat(jobDefinitionService.get("54e3deadbeefdeadbeef0001")).isPresent().get().satisfies(definition -> { assertThat(definition.title()).isEqualTo(existingJobDefinition.title()); assertThat(definition.description()).isEqualTo(existingJobDefinition.description()); }); }
@Override public Client getClient(String clientId) { return getClientManagerById(clientId).getClient(clientId); }
@Test void testChooseConnectionClientForV6() { delegate.getClient(connectionIdForV6); verify(connectionBasedClientManager).getClient(connectionIdForV6); verify(ephemeralIpPortClientManager, never()).getClient(connectionIdForV6); verify(persistentIpPortClientManager, never()).getClient(connectionIdForV6); }
public static SimpleImputer fit(DataFrame data, String... columns) { return fit(data, 0.5, 0.5, columns); }
@Test public void testLongley() throws Exception { System.out.println(Longley.data); SimpleImputer imputer = SimpleImputer.fit(Longley.data); System.out.println(imputer); }
@Override public void preflight(final Path source, final Path target) throws BackgroundException { // defaults to Acl.EMPTY (disabling role checking) if target does not exist assumeRole(target, WRITEPERMISSION); // no createfilespermission required for now if(source.isDirectory()) { assumeRole(target.getParent(), target.getName(), CREATEDIRECTORIESPERMISSION); } }
@Test public void testPreflightFileAccessDeniedTargetExistsNotWritableCustomProps() throws Exception { final Path source = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); source.setAttributes(source.attributes().withAcl(new Acl(new Acl.CanonicalUser(), CteraAttributesFinderFeature.READPERMISSION))); final Path target = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); target.setAttributes(target.attributes().withAcl(new Acl(new Acl.CanonicalUser()))); // no createfilespermission required for now target.getParent().setAttributes(target.getParent().attributes().withAcl(new Acl(new Acl.CanonicalUser()))); final CteraAttributesFinderFeature mock = mock(CteraAttributesFinderFeature.class); // target exists and not writable when(mock.find(eq(target))).thenReturn(new PathAttributes().withAcl(new Acl(new Acl.CanonicalUser()))); final AccessDeniedException accessDeniedException = assertThrows(AccessDeniedException.class, () -> new CteraCopyFeature(session, mock).preflight(source, target)); assertTrue(accessDeniedException.getDetail().contains(MessageFormat.format(LocaleFactory.localizedString("Upload {0} failed", "Error"), target.getName()))); }
@Override public Num calculate(BarSeries series, Position position) { final Num maxDrawdown = maxDrawdownCriterion.calculate(series, position); if (maxDrawdown.isZero()) { return NaN.NaN; } else { final Num totalProfit = grossReturnCriterion.calculate(series, position); return totalProfit.dividedBy(maxDrawdown); } }
@Test public void testNoDrawDownForPosition() { final MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 95, 100, 90, 95, 80, 120); final Position position = new Position(Trade.buyAt(0, series), Trade.sellAt(1, series)); final Num result = rrc.calculate(series, position); assertNumEquals(NaN.NaN, result); }
@Override public Object decrypt(final Object cipherValue, final AlgorithmSQLContext algorithmSQLContext) { return cryptographicAlgorithm.decrypt(cipherValue); }
@Test void assertDecrypt() { Object actual = encryptAlgorithm.decrypt("dSpPiyENQGDUXMKFMJPGWA==", mock(AlgorithmSQLContext.class)); assertThat(actual.toString(), is("test")); }
public static String filenameOnly( String sFullPath ) { if ( Utils.isEmpty( sFullPath ) ) { return sFullPath; } int idx = sFullPath.lastIndexOf( FILE_SEPARATOR ); if ( idx != -1 ) { return sFullPath.substring( idx + 1 ); } else { idx = sFullPath.lastIndexOf( '/' ); // URL, VFS/**/ if ( idx != -1 ) { return sFullPath.substring( idx + 1 ); } else { return sFullPath; } } }
@Test public void testFilenameOnly() { assertNull( Const.filenameOnly( null ) ); assertTrue( Const.filenameOnly( "" ).isEmpty() ); assertEquals( "file.txt", Const.filenameOnly( "dir" + Const.FILE_SEPARATOR + "file.txt" ) ); assertEquals( "file.txt", Const.filenameOnly( "file.txt" ) ); }
@Override public int offer(E e) { @SuppressWarnings("deprecation") long z = mix64(Thread.currentThread().getId()); int increment = ((int) (z >>> 32)) | 1; int h = (int) z; int mask; int result; Buffer<E> buffer; boolean uncontended = true; Buffer<E>[] buffers = table; if ((buffers == null) || ((mask = buffers.length - 1) < 0) || ((buffer = buffers[h & mask]) == null) || !(uncontended = ((result = buffer.offer(e)) != Buffer.FAILED))) { return expandOrRetry(e, h, increment, uncontended); } return result; }
@Test @SuppressWarnings("ThreadPriorityCheck") public void expand_concurrent() { var buffer = new FakeBuffer<Boolean>(Buffer.FAILED); ConcurrentTestHarness.timeTasks(10 * NCPU, () -> { for (int i = 0; i < 1000; i++) { assertThat(buffer.offer(Boolean.TRUE)).isAnyOf(Buffer.SUCCESS, Buffer.FULL, Buffer.FAILED); Thread.yield(); } }); assertThat(buffer.table).hasLength(MAXIMUM_TABLE_SIZE); }
public Set<String> errorLogDirs() { return errorLogDirs; }
@Test public void testErrorLogDirsForFoo() { assertEquals(new HashSet<>(Collections.singletonList("/tmp/error3")), FOO.errorLogDirs()); }
@ConstantFunction(name = "int_divide", argTypes = {INT, INT}, returnType = INT) public static ConstantOperator intDivideInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createInt(first.getInt() / second.getInt()); }
@Test public void intDivideInt() { assertEquals(1, ScalarOperatorFunctions.intDivideInt(O_INT_10, O_INT_10).getInt()); }
static void closeSilently( final ServerWebSocket webSocket, final int code, final String message) { try { final ImmutableMap<String, String> finalMessage = ImmutableMap.of( "error", message != null ? message : "" ); final String json = ApiJsonMapper.INSTANCE.get().writeValueAsString(finalMessage); webSocket .writeFinalTextFrame(json, r -> { }) .close((short) code, truncate(message)); } catch (final Exception e) { LOG.info("Exception caught closing websocket", e); } }
@Test public void shouldNotTruncateShortReasons() throws Exception { // Given: final String reason = "some short reason"; // When: SessionUtil.closeSilently(websocket, INVALID_MESSAGE_TYPE.code(), reason); // Then: verify(websocket).writeFinalTextFrame(any(String.class), any(Handler.class)); verify(websocket).close(codeCaptor.capture(), reasonCaptor.capture()); assertThat(reasonCaptor.getValue(), is(reason)); }
public static <T> Window<T> into(WindowFn<? super T, ?> fn) { try { fn.windowCoder().verifyDeterministic(); } catch (NonDeterministicException e) { throw new IllegalArgumentException("Window coders must be deterministic.", e); } return Window.<T>configure().withWindowFn(fn); }
@Test public void testNonDeterministicWindowCoder() throws NonDeterministicException { FixedWindows mockWindowFn = Mockito.mock(FixedWindows.class); @SuppressWarnings({"unchecked", "rawtypes"}) Class<Coder<IntervalWindow>> coderClazz = (Class) Coder.class; Coder<IntervalWindow> mockCoder = Mockito.mock(coderClazz); when(mockWindowFn.windowCoder()).thenReturn(mockCoder); NonDeterministicException toBeThrown = new NonDeterministicException(mockCoder, "Its just not deterministic."); Mockito.doThrow(toBeThrown).when(mockCoder).verifyDeterministic(); thrown.expect(IllegalArgumentException.class); thrown.expectCause(Matchers.sameInstance(toBeThrown)); thrown.expectMessage("Window coders must be deterministic"); Window.into(mockWindowFn); }
public void registerOnline(final ComputeNodeInstance computeNodeInstance) { String instanceId = computeNodeInstance.getMetaData().getId(); repository.persistEphemeral(ComputeNode.getOnlineInstanceNodePath(instanceId, computeNodeInstance.getMetaData().getType()), YamlEngine.marshal( new YamlComputeNodeDataSwapper().swapToYamlConfiguration(new ComputeNodeData(computeNodeInstance.getMetaData().getAttributes(), computeNodeInstance.getMetaData().getVersion())))); repository.persistEphemeral(ComputeNode.getComputeNodeStateNodePath(instanceId), computeNodeInstance.getState().getCurrentState().name()); persistInstanceLabels(instanceId, computeNodeInstance.getLabels()); }
@Test void assertRegisterOnline() { ComputeNodeInstance computeNodeInstance = new ComputeNodeInstance(new ProxyInstanceMetaData("foo_instance_id", 3307)); computeNodeInstance.getLabels().add("test"); new ComputeNodePersistService(repository).registerOnline(computeNodeInstance); verify(repository).persistEphemeral(eq("/nodes/compute_nodes/online/proxy/" + computeNodeInstance.getMetaData().getId()), anyString()); verify(repository).persistEphemeral(ComputeNode.getComputeNodeStateNodePath(computeNodeInstance.getMetaData().getId()), InstanceState.OK.name()); verify(repository).persistEphemeral(ComputeNode.getInstanceLabelsNodePath(computeNodeInstance.getMetaData().getId()), YamlEngine.marshal(Collections.singletonList("test"))); }