focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static String formatDT(TimeZone tz, Date date) { return formatDT(tz, date, new DatePrecision()); }
@Test public void testFormatDTwithTZ() { assertEquals("19700101020000.000+0200", DateUtils.formatDT(tz, new Date(0), new DatePrecision(Calendar.MILLISECOND, true))); }
@Override public void changeClusterState(@Nonnull ClusterState newState) { throw new UnsupportedOperationException(); }
@Test(expected = UnsupportedOperationException.class) public void changeClusterState() { client().getCluster().changeClusterState(ClusterState.FROZEN); }
public static int firstSymlinkIndex(String path) { int fromIndex = 0; int index; while ((index = path.indexOf('/', fromIndex)) >= 0) { fromIndex = index + 1; if (fromIndex < path.length() && path.charAt(fromIndex) == SYMLINK_PREFIX) { if (path.indexOf('/', fromIndex) != -1) return path.indexOf('/', fromIndex); else return path.length(); } } return -1; }
@Test public void testFirstSymlinkIndex() { Assert.assertEquals(SymlinkUtil.firstSymlinkIndex(path1), path1.length()); Assert.assertEquals(SymlinkUtil.firstSymlinkIndex(path2), path2.length()); Assert.assertEquals(SymlinkUtil.firstSymlinkIndex(path3), path1.length()); Assert.assertEquals(SymlinkUtil.firstSymlinkIndex(path4), -1); Assert.assertEquals(SymlinkUtil.firstSymlinkIndex(path5), -1); }
@Override public <R> QueryResult<R> query(final Query<R> query, final PositionBound positionBound, final QueryConfig config) { return store.query(query, positionBound, config); }
@SuppressWarnings("unchecked") @Test public void shouldQueryTimestampedStore() { givenWrapperWithTimestampedStore(); when(timestampedStore.query(query, positionBound, queryConfig)).thenReturn(result); assertThat(wrapper.query(query, positionBound, queryConfig), equalTo(result)); }
@Override public void setDefaultDataTableCellTransformer(TableCellByTypeTransformer defaultDataTableByTypeTransformer) { dataTableTypeRegistry.setDefaultDataTableCellTransformer(defaultDataTableByTypeTransformer); }
@Test void should_set_default_table_cell_transformer() { TableCellByTypeTransformer expected = (cell, toValueType) -> null; registry.setDefaultDataTableCellTransformer(expected); }
@Override public <W extends Window> TimeWindowedCogroupedKStream<K, VOut> windowedBy(final Windows<W> windows) { Objects.requireNonNull(windows, "windows can't be null"); return new TimeWindowedCogroupedKStreamImpl<>( windows, builder, subTopologySourceNodes, name, aggregateBuilder, graphNode, groupPatterns); }
@Test public void shouldNotHaveNullWindowOnWindowedByTime() { assertThrows(NullPointerException.class, () -> cogroupedStream.windowedBy((Windows<? extends Window>) null)); }
public static boolean areSameColumns(List<FieldSchema> oldCols, List<FieldSchema> newCols) { if (oldCols == newCols) { return true; } if (oldCols == null || newCols == null || oldCols.size() != newCols.size()) { return false; } // We should ignore the case of field names, because some computing engines are case-sensitive, such as Spark. List<FieldSchema> transformedOldCols = oldCols.stream() .map(col -> new FieldSchema(col.getName().toLowerCase(), col.getType(), col.getComment())) .collect(Collectors.toList()); List<FieldSchema> transformedNewCols = newCols.stream() .map(col -> new FieldSchema(col.getName().toLowerCase(), col.getType(), col.getComment())) .collect(Collectors.toList()); return ListUtils.isEqualList(transformedOldCols, transformedNewCols); }
@Test public void testSameColumns() { FieldSchema col1 = new FieldSchema("col1", "string", "col1 comment"); FieldSchema Col1 = new FieldSchema("Col1", "string", "col1 comment"); FieldSchema col2 = new FieldSchema("col2", "string", "col2 comment"); Assert.assertTrue(MetaStoreServerUtils.areSameColumns(null, null)); Assert.assertFalse(MetaStoreServerUtils.areSameColumns(Arrays.asList(col1), null)); Assert.assertFalse(MetaStoreServerUtils.areSameColumns(null, Arrays.asList(col1))); Assert.assertTrue(MetaStoreServerUtils.areSameColumns(Arrays.asList(col1), Arrays.asList(col1))); Assert.assertTrue(MetaStoreServerUtils.areSameColumns(Arrays.asList(col1, col2), Arrays.asList(col1, col2))); Assert.assertTrue(MetaStoreServerUtils.areSameColumns(Arrays.asList(Col1, col2), Arrays.asList(col1, col2))); }
public static String getMaskedStatement(final String query) { try { final ParseTree tree = DefaultKsqlParser.getParseTree(query); return new Visitor().visit(tree); } catch (final Exception | StackOverflowError e) { return fallbackMasking(query); } }
@Test public void shouldMaskInvalidSinkConnector() { // Given: // Typo in "CONNECTOR" => "CONNECTO" final String query = "CREATE Sink CONNECTO `test-connector` WITH (" + " \"connector.class\" = 'PostgresSource', \n" + " 'connection.url' = 'jdbc:postgresql://localhost:5432/my.db',\n" + " `mode`='bulk',\n" + " \"topic.prefix\"='jdbc-',\n" + " \"table.whitelist\"='users',\n" + " \"key\"='username');"; // When final String maskedQuery = QueryMask.getMaskedStatement(query); // Then final String expected = "CREATE Sink CONNECTO `test-connector` WITH (" + " \"connector.class\" = 'PostgresSource', \n" + " 'connection.url'='[string]',\n" + " `mode`='[string]',\n" + " \"topic.prefix\"='[string]',\n" + " \"table.whitelist\"='[string]',\n" + " \"key\"='[string]');"; assertThat(maskedQuery, is(expected)); }
@Override public Response updateAppQueue(AppQueue targetQueue, HttpServletRequest hsr, String appId) throws AuthorizationException, YarnException, InterruptedException, IOException { if (targetQueue == null) { routerMetrics.incrUpdateAppQueueFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), UPDATE_APP_QUEUE, UNKNOWN, TARGET_WEB_SERVICE, "Parameter error, the targetQueue is null."); throw new IllegalArgumentException("Parameter error, the targetQueue is null."); } try { long startTime = clock.getTime(); DefaultRequestInterceptorREST interceptor = getOrCreateInterceptorByAppId(appId); Response response = interceptor.updateAppQueue(targetQueue, hsr, appId); if (response != null) { long stopTime = clock.getTime(); routerMetrics.succeededUpdateAppQueueRetrieved(stopTime - startTime); RouterAuditLogger.logSuccess(getUser().getShortUserName(), UPDATE_APP_QUEUE, TARGET_WEB_SERVICE); return response; } } catch (IllegalArgumentException e) { routerMetrics.incrUpdateAppQueueFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), UPDATE_APP_QUEUE, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException(e, "Unable to update app queue by appId: %s.", appId); } catch (YarnException e) { routerMetrics.incrUpdateAppQueueFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), UPDATE_APP_QUEUE, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException("updateAppQueue error.", e); } RouterAuditLogger.logFailure(getUser().getShortUserName(), UPDATE_APP_QUEUE, UNKNOWN, TARGET_WEB_SERVICE, "updateAppQueue Failed."); routerMetrics.incrUpdateAppQueueFailedRetrieved(); throw new RuntimeException("updateAppQueue Failed."); }
@Test public void testUpdateAppQueue() throws IOException, InterruptedException, YarnException { String oldQueue = "oldQueue"; String newQueue = "newQueue"; // Submit application to multiSubCluster ApplicationId appId = ApplicationId.newInstance(Time.now(), 1); ApplicationSubmissionContextInfo context = new ApplicationSubmissionContextInfo(); context.setApplicationId(appId.toString()); context.setQueue(oldQueue); // Submit the application Assert.assertNotNull(interceptor.submitApplication(context, null)); // Set New Queue for application Response response = interceptor.updateAppQueue(new AppQueue(newQueue), null, appId.toString()); Assert.assertNotNull(response); AppQueue appQueue = (AppQueue) response.getEntity(); Assert.assertEquals(newQueue, appQueue.getQueue()); // Get AppQueue by application AppQueue queue = interceptor.getAppQueue(null, appId.toString()); Assert.assertNotNull(queue); Assert.assertEquals(newQueue, queue.getQueue()); }
public static <T> CompletableFuture<T> supplyAsync( SupplierWithException<T, ?> supplier, Executor executor) { return CompletableFuture.supplyAsync( () -> { try { return supplier.get(); } catch (Throwable e) { throw new CompletionException(e); } }, executor); }
@Test void testSupplyAsync() { final Object expectedResult = new Object(); final CompletableFuture<Object> future = FutureUtils.supplyAsync(() -> expectedResult, EXECUTOR_RESOURCE.getExecutor()); assertThatFuture(future).eventuallySucceeds().isEqualTo(expectedResult); }
@Override public void startScheduling() { Set<ExecutionVertexID> sourceVertices = IterableUtils.toStream(schedulingTopology.getVertices()) .filter(vertex -> vertex.getConsumedPartitionGroups().isEmpty()) .map(SchedulingExecutionVertex::getId) .collect(Collectors.toSet()); maybeScheduleVertices(sourceVertices); }
@Test void testStartScheduling() { VertexwiseSchedulingStrategy schedulingStrategy = createSchedulingStrategy(testingSchedulingTopology); final List<List<TestingSchedulingExecutionVertex>> expectedScheduledVertices = new ArrayList<>(); expectedScheduledVertices.add(Collections.singletonList(source.get(0))); expectedScheduledVertices.add(Collections.singletonList(source.get(1))); inputConsumableDecider.addSourceVertices(new HashSet<>(source)); schedulingStrategy.startScheduling(); assertLatestScheduledVerticesAreEqualTo( expectedScheduledVertices, testingSchedulerOperation); }
public String getSignature(ZonedDateTime now, String policy) { try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(("AWS4" + awsAccessSecret).getBytes(StandardCharsets.UTF_8), "HmacSHA256")); byte[] dateKey = mac.doFinal(now.format(DateTimeFormatter.ofPattern("yyyyMMdd")).getBytes(StandardCharsets.UTF_8)); mac.init(new SecretKeySpec(dateKey, "HmacSHA256")); byte[] dateRegionKey = mac.doFinal(region.getBytes(StandardCharsets.UTF_8)); mac.init(new SecretKeySpec(dateRegionKey, "HmacSHA256")); byte[] dateRegionServiceKey = mac.doFinal("s3".getBytes(StandardCharsets.UTF_8)); mac.init(new SecretKeySpec(dateRegionServiceKey, "HmacSHA256")); byte[] signingKey = mac.doFinal("aws4_request".getBytes(StandardCharsets.UTF_8)); mac.init(new SecretKeySpec(signingKey, "HmacSHA256")); return HexFormat.of().formatHex(mac.doFinal(policy.getBytes(StandardCharsets.UTF_8))); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new AssertionError(e); } }
@Test void testSignature() { Instant time = Instant.parse("2015-12-29T00:00:00Z"); ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(time, ZoneOffset.UTC); String encodedPolicy = "eyAiZXhwaXJhdGlvbiI6ICIyMDE1LTEyLTMwVDEyOjAwOjAwLjAwMFoiLA0KICAiY29uZGl0aW9ucyI6IFsNCiAgICB7ImJ1Y2tldCI6ICJzaWd2NGV4YW1wbGVidWNrZXQifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci91c2VyMS8iXSwNCiAgICB7ImFjbCI6ICJwdWJsaWMtcmVhZCJ9LA0KICAgIHsic3VjY2Vzc19hY3Rpb25fcmVkaXJlY3QiOiAiaHR0cDovL3NpZ3Y0ZXhhbXBsZWJ1Y2tldC5zMy5hbWF6b25hd3MuY29tL3N1Y2Nlc3NmdWxfdXBsb2FkLmh0bWwifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiaW1hZ2UvIl0sDQogICAgeyJ4LWFtei1tZXRhLXV1aWQiOiAiMTQzNjUxMjM2NTEyNzQifSwNCiAgICB7IngtYW16LXNlcnZlci1zaWRlLWVuY3J5cHRpb24iOiAiQUVTMjU2In0sDQogICAgWyJzdGFydHMtd2l0aCIsICIkeC1hbXotbWV0YS10YWciLCAiIl0sDQoNCiAgICB7IngtYW16LWNyZWRlbnRpYWwiOiAiQUtJQUlPU0ZPRE5ON0VYQU1QTEUvMjAxNTEyMjkvdXMtZWFzdC0xL3MzL2F3czRfcmVxdWVzdCJ9LA0KICAgIHsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwNCiAgICB7IngtYW16LWRhdGUiOiAiMjAxNTEyMjlUMDAwMDAwWiIgfQ0KICBdDQp9"; PolicySigner policySigner = new PolicySigner("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "us-east-1"); assertEquals(policySigner.getSignature(zonedDateTime, encodedPolicy), "8afdbf4008c03f22c2cd3cdb72e4afbb1f6a588f3255ac628749a66d7f09699e"); }
@Override public void trackEvent(InputData input) { process(input); }
@Test public void trackEventItem() throws JSONException { initSensors(); String itemType = "product_id", itemId = "100"; InputData inputData = new InputData(); inputData.setEventType(EventType.ITEM_DELETE); inputData.setItemId(itemId); inputData.setItemType(itemType); JSONObject jsonObject = new JSONObject(); jsonObject.put("item", "item"); inputData.setProperties(jsonObject); TrackEventProcessor eventProcessor = new TrackEventProcessor(SensorsDataAPI.sharedInstance().getSAContextManager()); eventProcessor.trackEvent(inputData); // 检查事件类型和属性 try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } String eventData = DatabaseUtilsTest.loadEventFromDb(mApplication); assertNotNull(eventData); JSONObject jsonData = new JSONObject(eventData); ProfileTestUtils.checkItemEvent(jsonData, "item_delete", itemType, itemId); JSONObject propertyJson = jsonData.optJSONObject("properties"); assertNotNull(propertyJson); assertEquals("item", propertyJson.opt("item")); }
public String formatSourceAndFixImports(String input) throws FormatterException { input = ImportOrderer.reorderImports(input, options.style()); input = RemoveUnusedImports.removeUnusedImports(input); String formatted = formatSource(input); formatted = StringWrapper.wrap(formatted, this); return formatted; }
@Test public void throwsFormatterException() throws Exception { try { new Formatter().formatSourceAndFixImports("package foo; public class {"); fail(); } catch (FormatterException expected) { } }
@Override public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException { // If the request servlet path is in the whitelist, // skip Kerberos authentication and return anonymous token. final String path = request.getServletPath(); for(final String endpoint: whitelist) { if (endpoint.equals(path)) { return AuthenticationToken.ANONYMOUS; } } AuthenticationToken token = null; String authorization = request.getHeader( KerberosAuthenticator.AUTHORIZATION); if (authorization == null || !authorization.startsWith(KerberosAuthenticator.NEGOTIATE)) { response.setHeader(WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if (authorization == null) { LOG.trace("SPNEGO starting for url: {}", request.getRequestURL()); } else { LOG.warn("'" + KerberosAuthenticator.AUTHORIZATION + "' does not start with '" + KerberosAuthenticator.NEGOTIATE + "' : {}", authorization); } } else { authorization = authorization.substring( KerberosAuthenticator.NEGOTIATE.length()).trim(); final Base64 base64 = new Base64(0); final byte[] clientToken = base64.decode(authorization); try { final String serverPrincipal = KerberosUtil.getTokenServerName(clientToken); if (!serverPrincipal.startsWith("HTTP/")) { throw new IllegalArgumentException( "Invalid server principal " + serverPrincipal + "decoded from client request"); } token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() { @Override public AuthenticationToken run() throws Exception { return runWithPrincipal(serverPrincipal, clientToken, base64, response); } }); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } else { throw new AuthenticationException(ex.getException()); } } catch (Exception ex) { throw new AuthenticationException(ex); } } return token; }
@Test public void testRequestWithIncompleteAuthorization() { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION)) .thenReturn(KerberosAuthenticator.NEGOTIATE); try { handler.authenticate(request, response); Assert.fail(); } catch (AuthenticationException ex) { // Expected } catch (Exception ex) { Assert.fail(); } }
Mono<NotificationContent> inferenceTemplate(Reason reason, Subscriber subscriber, Locale locale) { var reasonTypeName = reason.getSpec().getReasonType(); return getReasonType(reasonTypeName) .flatMap(reasonType -> notificationTemplateSelector.select(reasonTypeName, locale) .flatMap(template -> { final var templateContent = template.getSpec().getTemplate(); var model = toReasonAttributes(reason); var subscriberInfo = new HashMap<>(); if (subscriber.isAnonymous()) { subscriberInfo.put("displayName", subscriber.getEmail().orElseThrow()); } else { subscriberInfo.put("displayName", "@" + subscriber.username()); } subscriberInfo.put("id", subscriber.name()); model.put("subscriber", subscriberInfo); var unsubscriptionMono = getUnsubscribeUrl(subscriber.subscriptionName()) .doOnNext(url -> model.put("unsubscribeUrl", url)); var builder = NotificationContent.builder() .reasonType(reasonType) .reasonAttributes(model); var titleMono = notificationTemplateRender .render(templateContent.getTitle(), model) .doOnNext(builder::title); var rawBodyMono = notificationTemplateRender .render(templateContent.getRawBody(), model) .doOnNext(builder::rawBody); var htmlBodyMono = notificationTemplateRender .render(templateContent.getHtmlBody(), model) .doOnNext(builder::htmlBody); return Mono.when(unsubscriptionMono, titleMono, rawBodyMono, htmlBodyMono) .then(Mono.fromSupplier(builder::build)); }) ); }
@Test public void testInferenceTemplate() { final var spyNotificationCenter = spy(notificationCenter); final var reasonType = mock(ReasonType.class); var reason = new Reason(); reason.setMetadata(new Metadata()); reason.getMetadata().setName("reason-a"); reason.setSpec(new Reason.Spec()); reason.getSpec().setReasonType("new-reply-on-comment"); var reasonTypeName = reason.getSpec().getReasonType(); doReturn(Mono.just(reasonType)) .when(spyNotificationCenter).getReasonType(eq(reasonTypeName)); doReturn(Mono.just("fake-unsubscribe-url")) .when(spyNotificationCenter).getUnsubscribeUrl(anyString()); final var locale = Locale.CHINESE; var template = new NotificationTemplate(); template.setMetadata(new Metadata()); template.getMetadata().setName("notification-template-a"); template.setSpec(new NotificationTemplate.Spec()); template.getSpec().setTemplate(new NotificationTemplate.Template()); template.getSpec().getTemplate().setRawBody("body"); template.getSpec().getTemplate().setHtmlBody("html-body"); template.getSpec().getTemplate().setTitle("title"); template.getSpec().setReasonSelector(new NotificationTemplate.ReasonSelector()); template.getSpec().getReasonSelector().setReasonType(reasonTypeName); template.getSpec().getReasonSelector().setLanguage(locale.getLanguage()); when(notificationTemplateRender.render(anyString(), any())) .thenReturn(Mono.empty()); when(notificationTemplateSelector.select(eq(reasonTypeName), any())) .thenReturn(Mono.just(template)); var subscriber = new Subscriber(UserIdentity.anonymousWithEmail("A"), "fake-name"); spyNotificationCenter.inferenceTemplate(reason, subscriber, locale).block(); verify(spyNotificationCenter).getReasonType(eq(reasonTypeName)); verify(notificationTemplateSelector).select(eq(reasonTypeName), any()); }
@Override public Optional<ConfigItem> resolve(final String propertyName, final boolean strict) { if (propertyName.startsWith(KSQL_REQUEST_CONFIG_PROPERTY_PREFIX)) { return resolveRequestConfig(propertyName); } else if (propertyName.startsWith(KSQL_CONFIG_PROPERTY_PREFIX) && !propertyName.startsWith(KSQL_STREAMS_PREFIX)) { return resolveKsqlConfig(propertyName); } return resolveStreamsConfig(propertyName, strict); }
@Test public void shouldFindUnknownConsumerPropertyIfNotStrict() { // Given: final String configName = StreamsConfig.CONSUMER_PREFIX + "custom.interceptor.config"; // Then: assertThat(resolver.resolve(configName, false), is(unresolvedItem(configName))); }
@Override public Collection<String> resolve(Class<? extends AnalysisIndexer> clazz) { if (clazz.isAssignableFrom(IssueIndexer.class)) { return changedIssuesRepository.getChangedIssuesKeys(); } throw new UnsupportedOperationException("Unsupported indexer: " + clazz); }
@Test public void resolve_whenUnsupportedIndexer_shouldThrowUPE() { when(changedIssuesRepository.getChangedIssuesKeys()).thenReturn(Set.of("key1", "key2","key3")); assertThatThrownBy(() ->underTest.resolve(ProjectMeasuresIndexer.class)) .isInstanceOf(UnsupportedOperationException.class) .hasMessage("Unsupported indexer: class org.sonar.server.measure.index.ProjectMeasuresIndexer"); }
public KafkaMetadataState computeNextMetadataState(KafkaStatus kafkaStatus) { KafkaMetadataState currentState = metadataState; metadataState = switch (currentState) { case KRaft -> onKRaft(kafkaStatus); case ZooKeeper -> onZooKeeper(kafkaStatus); case KRaftMigration -> onKRaftMigration(kafkaStatus); case KRaftDualWriting -> onKRaftDualWriting(kafkaStatus); case KRaftPostMigration -> onKRaftPostMigration(kafkaStatus); case PreKRaft -> onPreKRaft(kafkaStatus); }; if (metadataState != currentState) { LOGGER.infoCr(reconciliation, "Transitioning metadata state from [{}] to [{}] with strimzi.io/kraft annotation [{}]", currentState, metadataState, kraftAnno); } else { LOGGER.debugCr(reconciliation, "Metadata state [{}] with strimzi.io/kraft annotation [{}]", metadataState, kraftAnno); } return metadataState; }
@Test public void testWarningInKRaftMigration() { Kafka kafka = new KafkaBuilder(KAFKA) .editMetadata() .addToAnnotations(Annotations.ANNO_STRIMZI_IO_KRAFT, "enabled") .endMetadata() .withNewStatus() .withKafkaMetadataState(KRaftMigration) .endStatus() .build(); KafkaMetadataStateManager kafkaMetadataStateManager = new KafkaMetadataStateManager(Reconciliation.DUMMY_RECONCILIATION, kafka); kafkaMetadataStateManager.computeNextMetadataState(kafka.getStatus()); assertTrue(kafka.getStatus().getConditions().stream().anyMatch(condition -> "KafkaMetadataStateWarning".equals(condition.getReason()))); assertEquals(kafka.getStatus().getConditions().get(0).getMessage(), "The strimzi.io/kraft annotation can't be set to 'enabled' during a migration process. " + "It has to be used in post migration to finalize it and move definitely to KRaft."); kafka = new KafkaBuilder(KAFKA) .editMetadata() .addToAnnotations(Annotations.ANNO_STRIMZI_IO_KRAFT, "rollback") .endMetadata() .withNewStatus() .withKafkaMetadataState(KRaftMigration) .endStatus() .build(); kafkaMetadataStateManager = new KafkaMetadataStateManager(Reconciliation.DUMMY_RECONCILIATION, kafka); kafkaMetadataStateManager.computeNextMetadataState(kafka.getStatus()); assertTrue(kafka.getStatus().getConditions().stream().anyMatch(condition -> "KafkaMetadataStateWarning".equals(condition.getReason()))); assertEquals(kafka.getStatus().getConditions().get(0).getMessage(), "The strimzi.io/kraft annotation can't be set to 'rollback' during a migration process. " + "It can be used in post migration to start rollback process."); }
public static String dup(char c, int num) { if (c == 0 || num < 1) return ""; StringBuilder sb = new StringBuilder(num); for (int i = 0; i < num; i++) sb.append(c); return sb.toString(); }
@Test public void testDup() { String str = StringKit.dup('c', 6); Assert.assertEquals(6, str.length()); Assert.assertEquals("cccccc", str); }
@Override protected String throwableProxyToString(IThrowableProxy tp) { return PATTERN.matcher(super.throwableProxyToString(tp)).replaceAll(PREFIX); }
@Test void prefixesExceptionsWithExclamationMarks() throws Exception { assertThat(converter.throwableProxyToString(proxy)) .startsWith(String.format("! java.io.IOException: noo%n" + "! at io.dropwizard.logging.common.PrefixedThrowableProxyConverterTest.<init>(PrefixedThrowableProxyConverterTest.java:14)%n")); }
public boolean isEnabled() { return configuration.getBoolean(ENABLED).orElse(false) && configuration.get(PROVIDER_ID).isPresent() && configuration.get(APPLICATION_ID).isPresent() && configuration.get(LOGIN_URL).isPresent() && configuration.get(CERTIFICATE).isPresent() && configuration.get(USER_LOGIN_ATTRIBUTE).isPresent() && configuration.get(USER_NAME_ATTRIBUTE).isPresent(); }
@Test @UseDataProvider("settingsRequiredToEnablePlugin") public void is_enabled_return_false_when_one_required_setting_is_missing(String setting) { initAllSettings(); settings.setProperty(setting, (String) null); assertThat(underTest.isEnabled()).isFalse(); }
RunMapperResult mapRun(Run run) { if (run.getResults().isEmpty()) { return new RunMapperResult(); } String driverName = getToolDriverName(run); Map<String, Result.Level> ruleSeveritiesByRuleId = detectRulesSeverities(run, driverName); Map<String, Result.Level> ruleSeveritiesByRuleIdForNewCCT = detectRulesSeveritiesForNewTaxonomy(run, driverName); return new RunMapperResult() .newAdHocRules(toNewAdHocRules(run, driverName, ruleSeveritiesByRuleId, ruleSeveritiesByRuleIdForNewCCT)) .newExternalIssues(toNewExternalIssues(run, driverName, ruleSeveritiesByRuleId, ruleSeveritiesByRuleIdForNewCCT)); }
@Test public void mapRun_shouldNotFail_whenExtensionsDontHaveRules() { when(run.getTool().getDriver().getRules()).thenReturn(Set.of(rule)); ToolComponent extension = mock(ToolComponent.class); when(extension.getRules()).thenReturn(null); when(run.getTool().getExtensions()).thenReturn(Set.of(extension)); try (MockedStatic<RulesSeverityDetector> detector = mockStatic(RulesSeverityDetector.class)) { detector.when(() -> RulesSeverityDetector.detectRulesSeverities(run, TEST_DRIVER)).thenReturn(Map.of(RULE_ID, WARNING)); detector.when(() -> RulesSeverityDetector.detectRulesSeveritiesForNewTaxonomy(run, TEST_DRIVER)).thenReturn(Map.of(RULE_ID, WARNING)); assertThatNoException().isThrownBy(() -> runMapper.mapRun(run)); } }
@Override public void monitor(RedisServer master) { connection.sync(RedisCommands.SENTINEL_MONITOR, master.getName(), master.getHost(), master.getPort().intValue(), master.getQuorum().intValue()); }
@Test public void testMonitor() { Collection<RedisServer> masters = connection.masters(); RedisServer master = masters.iterator().next(); master.setName(master.getName() + ":"); connection.monitor(master); }
public void rename( Iterable<String> srcFilenames, Iterable<String> destFilenames, MoveOptions... moveOptions) throws IOException { // Rename is implemented as a rewrite followed by deleting the source. If the new object is in // the same location, the copy is a metadata-only operation. Set<MoveOptions> moveOptionSet = Sets.newHashSet(moveOptions); final boolean ignoreMissingSrc = moveOptionSet.contains(StandardMoveOptions.IGNORE_MISSING_FILES); final boolean ignoreExistingDest = moveOptionSet.contains(StandardMoveOptions.SKIP_IF_DESTINATION_EXISTS); rewriteHelper( srcFilenames, destFilenames, /*deleteSource=*/ true, ignoreMissingSrc, ignoreExistingDest); }
@Test public void testRename() throws IOException { GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); Storage mockStorage = Mockito.mock(Storage.class); gcsUtil.setStorageClient(mockStorage); gcsUtil.setBatchRequestSupplier(FakeBatcher::new); Storage.Objects mockStorageObjects = Mockito.mock(Storage.Objects.class); Storage.Objects.Rewrite mockStorageRewrite = Mockito.mock(Storage.Objects.Rewrite.class); Storage.Objects.Delete mockStorageDelete1 = Mockito.mock(Storage.Objects.Delete.class); Storage.Objects.Delete mockStorageDelete2 = Mockito.mock(Storage.Objects.Delete.class); when(mockStorage.objects()).thenReturn(mockStorageObjects); when(mockStorageObjects.rewrite("bucket", "s0", "bucket", "d0", null)) .thenReturn(mockStorageRewrite); when(mockStorageRewrite.execute()) .thenThrow(new InvalidObjectException("Test exception")) .thenReturn(new RewriteResponse().setDone(true)); when(mockStorageObjects.delete("bucket", "s0")) .thenReturn(mockStorageDelete1) .thenReturn(mockStorageDelete2); when(mockStorageDelete1.execute()).thenThrow(new InvalidObjectException("Test exception")); gcsUtil.rename(makeStrings("s", 1), makeStrings("d", 1)); verify(mockStorageRewrite, times(2)).execute(); verify(mockStorageDelete1, times(1)).execute(); verify(mockStorageDelete2, times(1)).execute(); }
public static URI getProxyUri(URI originalUri, URI proxyUri, ApplicationId id) { try { String path = getPath(id, originalUri == null ? "/" : originalUri.getPath()); return new URI(proxyUri.getScheme(), proxyUri.getAuthority(), path, originalUri == null ? null : originalUri.getQuery(), originalUri == null ? null : originalUri.getFragment()); } catch (URISyntaxException e) { throw new RuntimeException("Could not proxy "+originalUri, e); } }
@Test void testGetProxyUriNull() throws Exception { URI originalUri = null; URI proxyUri = new URI("http://proxy.net:8080/"); ApplicationId id = BuilderUtils.newApplicationId(6384623l, 5); URI expected = new URI("http://proxy.net:8080/proxy/application_6384623_0005/"); URI result = ProxyUriUtils.getProxyUri(originalUri, proxyUri, id); assertEquals(expected, result); }
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { final String resourceId = fileid.getFileId(file); final UiFsModel uiFsModel = new ListResourceApi(new EueApiClient(session)).resourceResourceIdGet(resourceId, null, null, null, null, null, null, Collections.singletonList(EueAttributesFinderFeature.OPTION_DOWNLOAD), null); final HttpUriRequest request = new HttpGet(uiFsModel.getUilink().getDownloadURI()); if(status.isAppend()) { final HttpRange range = HttpRange.withStatus(status); final String header; if(TransferStatus.UNKNOWN_LENGTH == range.getEnd()) { header = String.format("bytes=%d-", range.getStart()); } else { header = String.format("bytes=%d-%d", range.getStart(), range.getEnd()); } if(log.isDebugEnabled()) { log.debug(String.format("Add range header %s for file %s", header, file)); } request.addHeader(new BasicHeader(HttpHeaders.RANGE, header)); // Disable compression request.addHeader(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "identity")); } final HttpResponse response = session.getClient().execute(request); switch(response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: case HttpStatus.SC_PARTIAL_CONTENT: return new HttpMethodReleaseInputStream(response); default: throw new DefaultHttpResponseExceptionMappingService().map("Download {0} failed", new HttpResponseException( response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()), file); } } catch(ApiException e) { throw new EueExceptionMappingService().map("Download {0} failed", e, file); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map("Download {0} failed", e, file); } }
@Test public void testReadInterrupt() throws Exception { final EueResourceIdProvider fileid = new EueResourceIdProvider(session); final byte[] content = RandomUtils.nextBytes(32769); final Path container = new EueDirectoryFeature(session, fileid).mkdir( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus()); final Path test = createFile(fileid, new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), content); // Unknown length in status final TransferStatus readStatus = new TransferStatus(); // Read a single byte { final InputStream in = new EueReadFeature(session, fileid).read(test, readStatus, new DisabledConnectionCallback()); assertNotNull(in.read()); in.close(); } { final InputStream in = new EueReadFeature(session, fileid).read(test, readStatus, new DisabledConnectionCallback()); assertNotNull(in); in.close(); } new EueDeleteFeature(session, fileid).delete(Collections.singletonList(container), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
public void unregister(String name) { HealthCheck healthCheck; synchronized (lock) { healthCheck = healthChecks.remove(name); if (healthCheck instanceof AsyncHealthCheckDecorator) { ((AsyncHealthCheckDecorator) healthCheck).tearDown(); } } if (healthCheck != null) { onHealthCheckRemoved(name, healthCheck); } }
@Test public void asyncHealthCheckIsCanceledOnRemove() { registry.unregister("ahc"); verify(af).cancel(true); }
@Override public DescriptiveUrlBag toUrl(final Path file) { final DescriptiveUrlBag list = new DescriptiveUrlBag(); if(new HostPreferences(session.getHost()).getBoolean("s3.bucket.virtualhost.disable")) { list.addAll(new DefaultUrlProvider(session.getHost()).toUrl(file)); } else { list.add(this.toUrl(file, session.getHost().getProtocol().getScheme(), session.getHost().getPort())); list.add(this.toUrl(file, Scheme.http, 80)); if(StringUtils.isNotBlank(session.getHost().getWebURL())) { // Only include when custom domain is configured list.addAll(new HostWebUrlProvider(session.getHost()).toUrl(file)); } } if(file.isFile()) { if(!session.getHost().getCredentials().isAnonymousLogin()) { // X-Amz-Expires must be less than a week (in seconds); that is, the given X-Amz-Expires must be less // than 604800 seconds // In one hour list.add(this.toSignedUrl(file, (int) TimeUnit.HOURS.toSeconds(1))); // Default signed URL expiring in 24 hours. list.add(this.toSignedUrl(file, (int) TimeUnit.SECONDS.toSeconds( new HostPreferences(session.getHost()).getInteger("s3.url.expire.seconds")))); // 1 Week list.add(this.toSignedUrl(file, (int) TimeUnit.DAYS.toSeconds(7))); switch(session.getSignatureVersion()) { case AWS2: // 1 Month list.add(this.toSignedUrl(file, (int) TimeUnit.DAYS.toSeconds(30))); // 1 Year list.add(this.toSignedUrl(file, (int) TimeUnit.DAYS.toSeconds(365))); break; case AWS4HMACSHA256: break; } } } // AWS services require specifying an Amazon S3 bucket using S3://bucket list.add(new DescriptiveUrl(URI.create(String.format("s3://%s%s", containerService.getContainer(file).getName(), file.isRoot() ? Path.DELIMITER : containerService.isContainer(file) ? Path.DELIMITER : String.format("/%s", URIEncoder.encode(containerService.getKey(file))))), DescriptiveUrl.Type.provider, MessageFormat.format(LocaleFactory.localizedString("{0} URL"), "S3"))); // Filter by matching container name final Optional<Set<Distribution>> filtered = distributions.entrySet().stream().filter(entry -> new SimplePathPredicate(containerService.getContainer(file)).test(entry.getKey())) .map(Map.Entry::getValue).findFirst(); if(filtered.isPresent()) { // Add CloudFront distributions for(Distribution distribution : filtered.get()) { list.addAll(new DistributionUrlProvider(distribution).toUrl(file)); } } return list; }
@Test public void testPlaceholder() { assertTrue( new S3UrlProvider(session, Collections.emptyMap()).toUrl(new Path("/test-eu-west-1-cyberduck/test", EnumSet.of(Path.Type.directory))).filter(DescriptiveUrl.Type.signed).isEmpty()); }
@Nullable public String ensureBuiltinRole(String roleName, String description, Set<String> expectedPermissions) { Role previousRole = null; try { previousRole = roleService.load(roleName); if (!previousRole.isReadOnly() || !expectedPermissions.equals(previousRole.getPermissions())) { final String msg = "Invalid role '" + roleName + "', fixing it."; LOG.debug(msg); throw new IllegalArgumentException(msg); // jump to fix code } } catch (NotFoundException | IllegalArgumentException | NoSuchElementException ignored) { LOG.info("{} role is missing or invalid, re-adding it as a built-in role.", roleName); final RoleImpl fixedRole = new RoleImpl(); // copy the mongodb id over, in order to update the role instead of reading it if (previousRole != null) { fixedRole._id = previousRole.getId(); } fixedRole.setReadOnly(true); fixedRole.setName(roleName); fixedRole.setDescription(description); fixedRole.setPermissions(expectedPermissions); try { final Role savedRole = roleService.save(fixedRole); return savedRole.getId(); } catch (DuplicateKeyException | ValidationException e) { LOG.error("Unable to save fixed '" + roleName + "' role, please restart Graylog to fix this.", e); } } if (previousRole == null) { LOG.error("Unable to access fixed '" + roleName + "' role, please restart Graylog to fix this."); return null; } return previousRole.getId(); }
@Test public void ensureBuiltinRoleWithSaveError() throws Exception { when(roleService.load("test-role")).thenThrow(NotFoundException.class); when(roleService.save(any(Role.class))).thenThrow(DuplicateKeyException.class); // Throw database error assertThat(migrationHelpers.ensureBuiltinRole("test-role", "description", ImmutableSet.of("a", "b"))) .isNull(); }
@Override @Nullable protected ObjectStatus getObjectStatus(String key) { try { ObjectMetadata meta = mClient.getObjectMetadata(mBucketName, key); Date lastModifiedDate = meta.getLastModified(); Long lastModifiedTime = lastModifiedDate == null ? null : lastModifiedDate.getTime(); return new ObjectStatus(key, meta.getETag(), meta.getContentLength(), lastModifiedTime); } catch (AmazonServiceException e) { if (e.getStatusCode() == 404) { // file not found, possible for exists calls return null; } throw AlluxioS3Exception.from(e); } catch (AmazonClientException e) { throw AlluxioS3Exception.from(e); } }
@Test public void getNullLastModifiedTime() throws IOException { Mockito.when( mClient.getObjectMetadata(ArgumentMatchers.anyString(), ArgumentMatchers.anyString())) .thenReturn(new ObjectMetadata()); // throw NPE before https://github.com/Alluxio/alluxio/pull/14641 mS3UnderFileSystem.getObjectStatus(PATH); }
public String migrate(String oldJSON, int targetVersion) { LOGGER.debug("Migrating to version {}: {}", targetVersion, oldJSON); Chainr transform = getTransformerFor(targetVersion); Object transformedObject = transform.transform(JsonUtils.jsonToMap(oldJSON), getContextMap(targetVersion)); String transformedJSON = JsonUtils.toJsonString(transformedObject); LOGGER.debug("After migration to version {}: {}", targetVersion, transformedJSON); return transformedJSON; }
@Test void shouldMigrateV1ToV2_ByChangingEnablePipelineLockingFalse_To_LockBehaviorNone() { ConfigRepoDocumentMother documentMother = new ConfigRepoDocumentMother(); String oldJSON = documentMother.versionOneWithLockingSetTo(false); String transformedJSON = migrator.migrate(oldJSON, 2); assertThatJson(transformedJSON).node("target_version").isEqualTo("\"2\""); assertThatJson(transformedJSON).node("pipelines[0].name").isEqualTo("firstpipe"); assertThatJson(transformedJSON).node("pipelines[0].lock_behavior").isEqualTo("none"); assertThatJson(transformedJSON).node("errors").isArray().ofLength(0); }
public static Schema schemaFromPojoClass( TypeDescriptor<?> typeDescriptor, FieldValueTypeSupplier fieldValueTypeSupplier) { return StaticSchemaInference.schemaFromClass(typeDescriptor, fieldValueTypeSupplier); }
@Test public void testNestedArray() { Schema schema = POJOUtils.schemaFromPojoClass( new TypeDescriptor<NestedArrayPOJO>() {}, JavaFieldTypeSupplier.INSTANCE); SchemaTestUtils.assertSchemaEquivalent(NESTED_ARRAY_POJO_SCHEMA, schema); }
@Bean public SonarUserHome provide(ScannerProperties scannerProps) { Path home = findSonarHome(scannerProps); LOG.debug("Sonar User Home: {}", home); return new SonarUserHome(home); }
@Test void should_consider_scanner_property_over_env_and_user_home(@TempDir Path userHome, @TempDir Path sonarUserHomeFromEnv, @TempDir Path sonarUserHomeFromProps) { when(system.envVariable("SONAR_USER_HOME")).thenReturn(sonarUserHomeFromEnv.toString()); when(system.property("user.home")).thenReturn(userHome.toString()); var sonarUserHome = underTest.provide(new ScannerProperties(Map.of("sonar.userHome", sonarUserHomeFromProps.toString()))); assertThat(sonarUserHome.getPath()).isEqualTo(sonarUserHomeFromProps); }
@POST @ZeppelinApi public Response createNote(String message) throws IOException { String user = authenticationService.getPrincipal(); LOGGER.info("Creating new note by JSON {}", message); NewNoteRequest request = GSON.fromJson(message, NewNoteRequest.class); String defaultInterpreterGroup = request.getDefaultInterpreterGroup(); if (StringUtils.isBlank(defaultInterpreterGroup)) { defaultInterpreterGroup = zConf.getString(ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_GROUP_DEFAULT); } String noteId = notebookService.createNote( request.getName(), defaultInterpreterGroup, request.getAddingEmptyParagraph(), getServiceContext(), new RestServiceCallback<>()); return notebook.processNote(noteId, note -> { AuthenticationInfo subject = new AuthenticationInfo(authenticationService.getPrincipal()); if (request.getParagraphs() != null) { for (NewParagraphRequest paragraphRequest : request.getParagraphs()) { Paragraph p = note.addNewParagraph(subject); initParagraph(p, paragraphRequest, user); } } return new JsonResponse<>(Status.OK, "", note.getId()).build(); }); }
@Test void testCreateNote() throws Exception { LOG.info("Running testCreateNote"); String message1 = "{\n\t\"name\" : \"test1\",\n\t\"addingEmptyParagraph\" : true\n}"; CloseableHttpResponse post1 = httpPost("/notebook/", message1); assertThat(post1, isAllowed()); Map<String, Object> resp1 = gson.fromJson(EntityUtils.toString(post1.getEntity(), StandardCharsets.UTF_8), new TypeToken<Map<String, Object>>() {}.getType()); assertEquals("OK", resp1.get("status")); String note1Id = (String) resp1.get("body"); notebook.processNote(note1Id, note1 -> { assertEquals("test1", note1.getName()); assertEquals(1, note1.getParagraphCount()); assertNull(note1.getParagraph(0).getText()); assertNull(note1.getParagraph(0).getTitle()); return null; }); String message2 = "{\n\t\"name\" : \"test2\"\n}"; CloseableHttpResponse post2 = httpPost("/notebook/", message2); assertThat(post2, isAllowed()); Map<String, Object> resp2 = gson.fromJson(EntityUtils.toString(post2.getEntity(), StandardCharsets.UTF_8), new TypeToken<Map<String, Object>>() {}.getType()); assertEquals("OK", resp2.get("status")); String noteId2 = (String) resp2.get("body"); Note note2 = notebook.processNote(noteId2, note -> { return note; }); assertEquals("test2", note2.getName()); assertEquals(0, note2.getParagraphCount()); }
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) { checkArgument( OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp); return new AutoValue_UBinary(binaryOp, lhs, rhs); }
@Test public void conditionalAnd() { assertUnifiesAndInlines( "true && false", UBinary.create( Kind.CONDITIONAL_AND, ULiteral.booleanLit(true), ULiteral.booleanLit(false))); }
public RuntimeOptionsBuilder parse(Map<String, String> properties) { return parse(properties::get); }
@Test void should_parse_dry_run() { properties.put(Constants.EXECUTION_DRY_RUN_PROPERTY_NAME, "true"); RuntimeOptions options = cucumberPropertiesParser.parse(properties).build(); assertThat(options.isDryRun(), equalTo(true)); }
@Override protected void customAnalyze( GetXMLDataMeta meta, IMetaverseNode node ) throws MetaverseAnalyzerException { super.customAnalyze( meta, node ); // Add the XPath Loop to the step node node.setProperty( "loopXPath", meta.getLoopXPath() ); }
@Test public void testCustomAnalyze() throws Exception { when( meta.getLoopXPath() ).thenReturn( "file/xpath/name" ); analyzer.customAnalyze( meta, node ); verify( node ).setProperty( "loopXPath", "file/xpath/name" ); }
@Override public void importData(JsonReader reader) throws IOException { logger.info("Reading configuration for 1.2"); // this *HAS* to start as an object reader.beginObject(); while (reader.hasNext()) { JsonToken tok = reader.peek(); switch (tok) { case NAME: String name = reader.nextName(); // find out which member it is if (name.equals(CLIENTS)) { readClients(reader); } else if (name.equals(GRANTS)) { readGrants(reader); } else if (name.equals(WHITELISTEDSITES)) { readWhitelistedSites(reader); } else if (name.equals(BLACKLISTEDSITES)) { readBlacklistedSites(reader); } else if (name.equals(AUTHENTICATIONHOLDERS)) { readAuthenticationHolders(reader); } else if (name.equals(ACCESSTOKENS)) { readAccessTokens(reader); } else if (name.equals(REFRESHTOKENS)) { readRefreshTokens(reader); } else if (name.equals(SYSTEMSCOPES)) { readSystemScopes(reader); } else { for (MITREidDataServiceExtension extension : extensions) { if (extension.supportsVersion(THIS_VERSION)) { extension.importExtensionData(name, reader); break; } } // unknown token, skip it reader.skipValue(); } break; case END_OBJECT: // the object ended, we're done here reader.endObject(); continue; default: logger.debug("Found unexpected entry"); reader.skipValue(); continue; } } fixObjectReferences(); for (MITREidDataServiceExtension extension : extensions) { if (extension.supportsVersion(THIS_VERSION)) { extension.fixExtensionObjectReferences(maps); break; } } maps.clearAll(); }
@Test public void testImportClients() throws IOException { ClientDetailsEntity client1 = new ClientDetailsEntity(); client1.setId(1L); client1.setAccessTokenValiditySeconds(3600); client1.setClientId("client1"); client1.setClientSecret("clientsecret1"); client1.setRedirectUris(ImmutableSet.of("http://foo.com/")); client1.setScope(ImmutableSet.of("foo", "bar", "baz", "dolphin")); client1.setGrantTypes(ImmutableSet.of("implicit", "authorization_code", "urn:ietf:params:oauth:grant_type:redelegate", "refresh_token")); client1.setAllowIntrospection(true); ClientDetailsEntity client2 = new ClientDetailsEntity(); client2.setId(2L); client2.setAccessTokenValiditySeconds(3600); client2.setClientId("client2"); client2.setClientSecret("clientsecret2"); client2.setRedirectUris(ImmutableSet.of("http://bar.baz.com/")); client2.setScope(ImmutableSet.of("foo", "dolphin", "electric-wombat")); client2.setGrantTypes(ImmutableSet.of("client_credentials", "urn:ietf:params:oauth:grant_type:redelegate")); client2.setAllowIntrospection(false); String configJson = "{" + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [], " + "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.CLIENTS + "\": [" + "{\"id\":1,\"accessTokenValiditySeconds\":3600,\"clientId\":\"client1\",\"secret\":\"clientsecret1\"," + "\"redirectUris\":[\"http://foo.com/\"]," + "\"scope\":[\"foo\",\"bar\",\"baz\",\"dolphin\"]," + "\"grantTypes\":[\"implicit\",\"authorization_code\",\"urn:ietf:params:oauth:grant_type:redelegate\",\"refresh_token\"]," + "\"allowIntrospection\":true}," + "{\"id\":2,\"accessTokenValiditySeconds\":3600,\"clientId\":\"client2\",\"secret\":\"clientsecret2\"," + "\"redirectUris\":[\"http://bar.baz.com/\"]," + "\"scope\":[\"foo\",\"dolphin\",\"electric-wombat\"]," + "\"grantTypes\":[\"client_credentials\",\"urn:ietf:params:oauth:grant_type:redelegate\"]," + "\"allowIntrospection\":false}" + " ]" + "}"; logger.debug(configJson); JsonReader reader = new JsonReader(new StringReader(configJson)); dataService.importData(reader); verify(clientRepository, times(2)).saveClient(capturedClients.capture()); List<ClientDetailsEntity> savedClients = capturedClients.getAllValues(); assertThat(savedClients.size(), is(2)); assertThat(savedClients.get(0).getAccessTokenValiditySeconds(), equalTo(client1.getAccessTokenValiditySeconds())); assertThat(savedClients.get(0).getClientId(), equalTo(client1.getClientId())); assertThat(savedClients.get(0).getClientSecret(), equalTo(client1.getClientSecret())); assertThat(savedClients.get(0).getRedirectUris(), equalTo(client1.getRedirectUris())); assertThat(savedClients.get(0).getScope(), equalTo(client1.getScope())); assertThat(savedClients.get(0).getGrantTypes(), equalTo(client1.getGrantTypes())); assertThat(savedClients.get(0).isAllowIntrospection(), equalTo(client1.isAllowIntrospection())); assertThat(savedClients.get(1).getAccessTokenValiditySeconds(), equalTo(client2.getAccessTokenValiditySeconds())); assertThat(savedClients.get(1).getClientId(), equalTo(client2.getClientId())); assertThat(savedClients.get(1).getClientSecret(), equalTo(client2.getClientSecret())); assertThat(savedClients.get(1).getRedirectUris(), equalTo(client2.getRedirectUris())); assertThat(savedClients.get(1).getScope(), equalTo(client2.getScope())); assertThat(savedClients.get(1).getGrantTypes(), equalTo(client2.getGrantTypes())); assertThat(savedClients.get(1).isAllowIntrospection(), equalTo(client2.isAllowIntrospection())); }
public String getConfigClass(String className) { return getHeader() + "\n\n" + // getRootClassDeclaration(root, className) + "\n\n" + // indentCode(INDENTATION, getFrameworkCode()) + "\n\n" + // ConfigGenerator.generateContent(INDENTATION, root, true) + "\n" + // "}\n"; }
@Disabled @Test void visual_inspection_of_generated_class() { final String testDefinition = "namespace=test\n" + // "p path\n" + // "pathArr[] path\n" + // "u url\n" + // "urlArr[] url\n" + // "modelArr[] model\n" + // "f file\n" + // "fileArr[] file\n" + // "i int default=0\n" + // "# A long value\n" + // "l long default=0\n" + // "s string default=\"\"\n" + // "b bool\n" + // "# An enum value\n" + // "e enum {A, B, C}\n" + // "intArr[] int\n" + // "boolArr[] bool\n" + // "enumArr[] enum {FOO, BAR}\n" + // "intMap{} int\n" + // "# A struct\n" + // "# with multi-line\n" + // "# comment and \"quotes\".\n" + // "myStruct.i int\n" + // "myStruct.s string\n" + // "# An inner array\n" + // "myArr[].i int\n" + // "myArr[].newStruct.s string\n" + // "myArr[].newStruct.b bool\n" + // "myArr[].intArr[] int\n" + // "# An inner map\n" + // "myMap{}.i int\n" + // "myMap{}.newStruct.s string\n" + // "myMap{}.newStruct.b bool\n" + // "myMap{}.intArr[] int\n" + // "intMap{} int\n"; DefParser parser = new DefParser("test", new StringReader(testDefinition)); InnerCNode root = parser.getTree(); JavaClassBuilder builder = new JavaClassBuilder(root, parser.getNormalizedDefinition(), null, null); String configClass = builder.getConfigClass("TestConfig"); System.out.print(configClass); }
public void updatePet(Pet body) throws RestClientException { updatePetWithHttpInfo(body); }
@Test public void updatePetTest() { Pet body = null; api.updatePet(body); // TODO: test validations }
static String createUniqueSymbol(CNode node, String basis) { Set<String> usedSymbols = Arrays.stream(node.getChildren()).map(CNode::getName).collect(Collectors.toSet()); Random rng = new Random(); for (int i = 1;; i++) { String candidate = (i < basis.length()) ? basis.substring(0, i) : ReservedWords.INTERNAL_PREFIX + basis + rng.nextInt(Integer.MAX_VALUE); if ( ! usedSymbols.contains(candidate)) { return candidate; } } }
@Test void testCreateUniqueSymbol() { final String testDefinition = "namespace=test\n" + // "m int\n" + // "n int\n"; InnerCNode root = new DefParser("test", new StringReader(testDefinition)).getTree(); assertEquals("f", createUniqueSymbol(root, "foo")); assertEquals("na", createUniqueSymbol(root, "name")); assertTrue(createUniqueSymbol(root, "m").startsWith(ReservedWords.INTERNAL_PREFIX + "m")); // The basis string is not a legal return value, even if unique, to avoid // multiple symbols with the same name if the same basis string is given twice. assertTrue(createUniqueSymbol(root, "my").startsWith(ReservedWords.INTERNAL_PREFIX + "my")); }
public static OpenOptions defaults() { return new OpenOptions(); }
@Test public void defaults() throws IOException { OpenOptions options = OpenOptions.defaults(); assertEquals(0, options.getOffset()); }
private <T> T newPlugin(Class<T> klass) { // KAFKA-8340: The thread classloader is used during static initialization and must be // set to the plugin's classloader during instantiation try (LoaderSwap loaderSwap = withClassLoader(klass.getClassLoader())) { return Utils.newInstance(klass); } catch (Throwable t) { throw new ConnectException("Instantiation error", t); } }
@Test public void shouldThrowIfStaticInitializerThrowsServiceLoader() { assertThrows(ConnectException.class, () -> plugins.newPlugin( TestPlugin.BAD_PACKAGING_STATIC_INITIALIZER_THROWS_REST_EXTENSION.className(), new AbstractConfig(new ConfigDef(), Collections.emptyMap()), ConnectRestExtension.class )); }
public String getScope() { return (String) context.getRequestAttribute(OidcConfiguration.SCOPE) .or(() -> Optional.ofNullable(configuration.getScope())) .orElse("openid profile email"); }
@Test public void shouldResolveScopeWhenOverriddenFromRequest() { var webContext = MockWebContext.create(); webContext.setRequestAttribute(OidcConfiguration.SCOPE, "openid profile email phone"); var oidcConfiguration = new OidcConfiguration(); var oidcConfigurationContext = new OidcConfigurationContext(webContext, oidcConfiguration); var result = oidcConfigurationContext.getScope(); assertEquals("openid profile email phone", result); }
@Description("value raised to the power of exponent") @ScalarFunction(alias = "pow") @SqlType(StandardTypes.DOUBLE) public static double power(@SqlType(StandardTypes.DOUBLE) double num, @SqlType(StandardTypes.DOUBLE) double exponent) { return Math.pow(num, exponent); }
@Test public void testPower() { for (long left : intLefts) { for (long right : intRights) { assertFunction("power(" + left + ", " + right + ")", DOUBLE, Math.pow(left, right)); } } for (int left : intLefts) { for (int right : intRights) { assertFunction("power( BIGINT '" + left + "' , BIGINT '" + right + "')", DOUBLE, Math.pow(left, right)); } } for (long left : intLefts) { for (long right : intRights) { assertFunction("power(" + left * 10000000000L + ", " + right + ")", DOUBLE, Math.pow(left * 10000000000L, right)); } } for (long left : intLefts) { for (double right : doubleRights) { assertFunction("power(" + left + ", " + right + ")", DOUBLE, Math.pow(left, right)); assertFunction("power(" + left + ", REAL '" + (float) right + "')", DOUBLE, Math.pow(left, (float) right)); } } for (double left : doubleLefts) { for (long right : intRights) { assertFunction("power(" + left + ", " + right + ")", DOUBLE, Math.pow(left, right)); assertFunction("power(REAL '" + (float) left + "', " + right + ")", DOUBLE, Math.pow((float) left, right)); } } for (double left : doubleLefts) { for (double right : doubleRights) { assertFunction("power(" + left + ", " + right + ")", DOUBLE, Math.pow(left, right)); assertFunction("power(REAL '" + left + "', REAL '" + right + "')", DOUBLE, Math.pow((float) left, (float) right)); } } assertFunction("power(NULL, NULL)", DOUBLE, null); assertFunction("power(5.0E0, NULL)", DOUBLE, null); assertFunction("power(NULL, 5.0E0)", DOUBLE, null); // test alias assertFunction("pow(5.0E0, 2.0E0)", DOUBLE, 25.0); }
public OkHttpClient get(boolean keepAlive, boolean skipTLSVerify) { try { return cache.get(Parameters.fromBoolean(keepAlive, skipTLSVerify)); } catch (ExecutionException e) { throw new RuntimeException(e); } }
@Test @Disabled("Not enabled by default") public void testWithSystemDefaultTruststore() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException { final ParameterizedHttpClientProvider provider = new ParameterizedHttpClientProvider(client(null)); final OkHttpClient okHttpClient = provider.get(false, false); try (Response response = okHttpClient.newCall(new Request.Builder().url("https://google.com").get().build()).execute()) { assertThat(response.isSuccessful()).isTrue(); } }
@Override public AbstractWALEvent decode(final ByteBuffer data, final BaseLogSequenceNumber logSequenceNumber) { AbstractWALEvent result; byte[] bytes = new byte[data.remaining()]; data.get(bytes); String dataText = new String(bytes, StandardCharsets.UTF_8); if (decodeWithTX) { result = decodeDataWithTX(dataText); } else { result = decodeDataIgnoreTX(dataText); } result.setLogSequenceNumber(logSequenceNumber); return result; }
@Test void assertParallelDecodeWithTx() { MppTableData tableData = new MppTableData(); tableData.setTableName("public.test"); tableData.setOpType("INSERT"); tableData.setColumnsName(new String[]{"data"}); tableData.setColumnsType(new String[]{"raw"}); tableData.setColumnsVal(new String[]{"'7D'"}); List<String> dataList = Arrays.asList("BEGIN CSN: 951909 first_lsn: 5/59825858", JsonUtils.toJsonString(tableData), JsonUtils.toJsonString(tableData), "commit xid: 1006076"); MppdbDecodingPlugin mppdbDecodingPlugin = new MppdbDecodingPlugin(null, true, true); List<AbstractWALEvent> actual = new LinkedList<>(); for (String each : dataList) { actual.add(mppdbDecodingPlugin.decode(ByteBuffer.wrap(each.getBytes()), logSequenceNumber)); } assertThat(actual.size(), is(4)); assertInstanceOf(BeginTXEvent.class, actual.get(0)); assertThat(((BeginTXEvent) actual.get(0)).getCsn(), is(951909L)); assertThat(((WriteRowEvent) actual.get(1)).getAfterRow().get(0).toString(), is("7D")); assertThat(((WriteRowEvent) actual.get(2)).getAfterRow().get(0).toString(), is("7D")); assertThat(((CommitTXEvent) actual.get(3)).getXid(), is(1006076L)); assertNull(((CommitTXEvent) actual.get(3)).getCsn()); }
@Override public void request(Payload grpcRequest, StreamObserver<Payload> responseObserver) { traceIfNecessary(grpcRequest, true); String type = grpcRequest.getMetadata().getType(); long startTime = System.nanoTime(); //server is on starting. if (!ApplicationUtils.isStarted()) { Payload payloadResponse = GrpcUtils.convert( ErrorResponse.build(NacosException.INVALID_SERVER_STATUS, "Server is starting,please try later.")); traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, NacosException.INVALID_SERVER_STATUS, null, null, System.nanoTime() - startTime); return; } // server check. if (ServerCheckRequest.class.getSimpleName().equals(type)) { Payload serverCheckResponseP = GrpcUtils.convert(new ServerCheckResponse(GrpcServerConstants.CONTEXT_KEY_CONN_ID.get(), true)); traceIfNecessary(serverCheckResponseP, false); responseObserver.onNext(serverCheckResponseP); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, true, 0, null, null, System.nanoTime() - startTime); return; } RequestHandler requestHandler = requestHandlerRegistry.getByRequestType(type); //no handler found. if (requestHandler == null) { Loggers.REMOTE_DIGEST.warn(String.format("[%s] No handler for request type : %s :", "grpc", type)); Payload payloadResponse = GrpcUtils .convert(ErrorResponse.build(NacosException.NO_HANDLER, "RequestHandler Not Found")); traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, NacosException.NO_HANDLER, null, null, System.nanoTime() - startTime); return; } //check connection status. String connectionId = GrpcServerConstants.CONTEXT_KEY_CONN_ID.get(); boolean requestValid = connectionManager.checkValid(connectionId); if (!requestValid) { Loggers.REMOTE_DIGEST .warn("[{}] Invalid connection Id ,connection [{}] is un registered ,", "grpc", connectionId); Payload payloadResponse = GrpcUtils .convert(ErrorResponse.build(NacosException.UN_REGISTER, "Connection is unregistered.")); traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, NacosException.UN_REGISTER, null, null, System.nanoTime() - startTime); return; } Object parseObj = null; try { parseObj = GrpcUtils.parse(grpcRequest); } catch (Exception e) { Loggers.REMOTE_DIGEST .warn("[{}] Invalid request receive from connection [{}] ,error={}", "grpc", connectionId, e); Payload payloadResponse = GrpcUtils.convert(ErrorResponse.build(NacosException.BAD_GATEWAY, e.getMessage())); traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, NacosException.BAD_GATEWAY, e.getClass().getSimpleName(), null, System.nanoTime() - startTime); return; } if (parseObj == null) { Loggers.REMOTE_DIGEST.warn("[{}] Invalid request receive ,parse request is null", connectionId); Payload payloadResponse = GrpcUtils .convert(ErrorResponse.build(NacosException.BAD_GATEWAY, "Invalid request")); traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, NacosException.BAD_GATEWAY, null, null, System.nanoTime() - startTime); return; } if (!(parseObj instanceof Request)) { Loggers.REMOTE_DIGEST .warn("[{}] Invalid request receive ,parsed payload is not a request,parseObj={}", connectionId, parseObj); Payload payloadResponse = GrpcUtils .convert(ErrorResponse.build(NacosException.BAD_GATEWAY, "Invalid request")); traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, NacosException.BAD_GATEWAY, null, null, System.nanoTime() - startTime); return; } Request request = (Request) parseObj; try { Connection connection = connectionManager.getConnection(GrpcServerConstants.CONTEXT_KEY_CONN_ID.get()); RequestMeta requestMeta = new RequestMeta(); requestMeta.setClientIp(connection.getMetaInfo().getClientIp()); requestMeta.setConnectionId(GrpcServerConstants.CONTEXT_KEY_CONN_ID.get()); requestMeta.setClientVersion(connection.getMetaInfo().getVersion()); requestMeta.setLabels(connection.getMetaInfo().getLabels()); requestMeta.setAbilityTable(connection.getAbilityTable()); connectionManager.refreshActiveTime(requestMeta.getConnectionId()); prepareRequestContext(request, requestMeta, connection); Response response = requestHandler.handleRequest(request, requestMeta); Payload payloadResponse = GrpcUtils.convert(response); traceIfNecessary(payloadResponse, false); if (response.getErrorCode() == NacosException.OVER_THRESHOLD) { RpcScheduledExecutor.CONTROL_SCHEDULER.schedule(() -> { traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); }, 1000L, TimeUnit.MILLISECONDS); } else { traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); } MetricsMonitor.recordGrpcRequestEvent(type, response.isSuccess(), response.getErrorCode(), null, request.getModule(), System.nanoTime() - startTime); } catch (Throwable e) { Loggers.REMOTE_DIGEST .error("[{}] Fail to handle request from connection [{}] ,error message :{}", "grpc", connectionId, e); Payload payloadResponse = GrpcUtils.convert(ErrorResponse.build(e)); traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, ResponseCode.FAIL.getCode(), e.getClass().getSimpleName(), request.getModule(), System.nanoTime() - startTime); } finally { RequestContextHolder.removeContext(); } }
@Test void testNoRequestHandler() { ApplicationUtils.setStarted(true); RequestMeta metadata = new RequestMeta(); metadata.setClientIp("127.0.0.1"); metadata.setConnectionId(connectId); InstanceRequest instanceRequest = new InstanceRequest(); instanceRequest.setRequestId(requestId); Payload request = GrpcUtils.convert(instanceRequest, metadata); StreamObserver<Payload> streamObserver = new StreamObserver<Payload>() { @Override public void onNext(Payload payload) { System.out.println("Receive data from server: " + payload); Object res = GrpcUtils.parse(payload); assertTrue(res instanceof ErrorResponse); ErrorResponse errorResponse = (ErrorResponse) res; assertEquals(NacosException.NO_HANDLER, errorResponse.getErrorCode()); } @Override public void onError(Throwable throwable) { fail(throwable.getMessage()); } @Override public void onCompleted() { System.out.println("complete"); } }; streamStub.request(request, streamObserver); ApplicationUtils.setStarted(false); }
@Override public Optional<JavaClass> tryResolve(String typeName) { String typeFile = typeName.replace(".", "/") + ".class"; Optional<URI> uri = tryGetUriOf(typeFile); return uri.isPresent() ? classUriImporter.tryImport(uri.get()) : Optional.empty(); }
@Test @UseDataProvider("urls_with_spaces") public void is_resilient_against_wrongly_encoded_ClassLoader_resource_URLs(URL urlReturnedByClassLoader, URI expectedUriDerivedFromUrl) { // it seems like some OSGI ClassLoaders incorrectly return URLs with unencoded spaces. // This lead to `url.toURI()` throwing an exception -> https://github.com/TNG/ArchUnit/issues/683 verifyUrlCannotBeConvertedToUriInTheCurrentForm(urlReturnedByClassLoader); JavaClass expectedJavaClass = importClassWithContext(Object.class); when(uriImporter.tryImport(expectedUriDerivedFromUrl)).thenReturn(Optional.of(expectedJavaClass)); Optional<JavaClass> resolvedClass = withMockedContextClassLoader(classLoaderMock -> { String typeNameFromUrlWithSpaces = "some.TypeFromUrlWithSpaces"; String typeResourceFromUrlWithSpaces = typeNameFromUrlWithSpaces.replace(".", "/") + ".class"; when(classLoaderMock.getResource(typeResourceFromUrlWithSpaces)).thenReturn(urlReturnedByClassLoader); return resolver.tryResolve(typeNameFromUrlWithSpaces); }); assertThat(resolvedClass).contains(expectedJavaClass); }
public void setAuthResult(Object authResult) { this.authResult = authResult; }
@Test void testSetAuthResult() { assertNull(authContext.getAuthResult()); authContext.setAuthResult(true); assertTrue((boolean) authContext.getAuthResult()); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { final AttributedList<ch.cyberduck.core.Path> paths = new AttributedList<>(); final java.nio.file.Path p = session.toPath(directory); if(!Files.exists(p)) { throw new LocalExceptionMappingService().map("Listing directory {0} failed", new NoSuchFileException(directory.getAbsolute()), directory); } try (DirectoryStream<java.nio.file.Path> stream = Files.newDirectoryStream(p)) { for(java.nio.file.Path n : stream) { if(null == n.getFileName()) { continue; } try { final PathAttributes attributes = feature.toAttributes(n); final EnumSet<Path.Type> type = EnumSet.noneOf(Path.Type.class); if(Files.isDirectory(n)) { type.add(Path.Type.directory); } else { type.add(Path.Type.file); } final Path file = new Path(directory, n.getFileName().toString(), type, attributes); if(this.post(n, file)) { paths.add(file); listener.chunk(directory, paths); } } catch(IOException e) { log.warn(String.format("Failure reading attributes for %s", n)); } } } catch(IOException ex) { throw new LocalExceptionMappingService().map("Listing directory {0} failed", ex, directory); } return paths; }
@Test(expected = NotfoundException.class) public void testListFile() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCallback()); session.login(new DisabledLoginCallback(), new DisabledCancelCallback()); final Path home = new LocalHomeFinderFeature().find(); final LocalListService service = new LocalListService(session); service.list(new Path(home, "test", EnumSet.of(Path.Type.directory)), new DisabledListProgressListener()); }
public static boolean isBeanPropertyWriteMethod(Method method) { return method != null && Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers()) && method.getDeclaringClass() != Object.class && method.getParameterTypes().length == 1 && method.getName().startsWith("set") && method.getName().length() > 3; }
@Test void testIsBeanPropertyWriteMethod() throws Exception { Method method = EmptyClass.class.getMethod("setProperty", EmptyProperty.class); assertTrue(ReflectUtils.isBeanPropertyWriteMethod(method)); method = EmptyClass.class.getMethod("setSet", boolean.class); assertTrue(ReflectUtils.isBeanPropertyWriteMethod(method)); }
public FEELFnResult<BigDecimal> invoke(@ParameterName( "list" ) List list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } return FEELFnResult.ofResult( BigDecimal.valueOf( list.size() ) ); }
@Test void invokeParamArrayEmpty() { FunctionTestUtil.assertResult(countFunction.invoke(new Object[]{}), BigDecimal.ZERO); }
public void xor(Bitmap other) { requireNonNull(other, "cannot combine with null Bitmap"); checkArgument(length() == other.length(), "cannot XOR two bitmaps of different size"); bitSet.xor(other.bitSet); }
@Test public static void testXor() { Bitmap bitmapA = Bitmap.fromBytes(100 * 8, BYTE_STRING_A); Bitmap bitmapB = Bitmap.fromBytes(100 * 8, BYTE_STRING_B); Bitmap bitmapC = bitmapA.clone(); bitmapC.xor(bitmapB); for (int i = 0; i < 100 * 8; i++) { assertEquals(bitmapC.getBit(i), bitmapA.getBit(i) ^ bitmapB.getBit(i)); } }
@Bean @ConditionalOnMissingBean(ServerEndpointExporter.class) public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }
@Test public void testServerEndpointExporter() { WebSocketSyncConfiguration websocketListener = new WebSocketSyncConfiguration(); assertNotNull(websocketListener.serverEndpointExporter()); }
synchronized void add(int splitCount) { int pos = count % history.length; history[pos] = splitCount; count += 1; }
@Test public void testOneMoreThanFullHistory() { EnumerationHistory history = new EnumerationHistory(3); history.add(1); history.add(2); history.add(3); history.add(4); int[] expectedHistorySnapshot = {2, 3, 4}; testHistory(history, expectedHistorySnapshot); }
@VisibleForTesting int getReturnCode() { int successCode = CommandExecutorCodes.Kitchen.SUCCESS.getCode(); if ( getResult().getNrErrors() != 0 ) { getLog().logError( BaseMessages.getString( getPkgClazz(), "Kitchen.Error.FinishedWithErrors" ) ); return CommandExecutorCodes.Kitchen.ERRORS_DURING_PROCESSING.getCode(); } return getResult().getResult() ? successCode : CommandExecutorCodes.Kitchen.ERRORS_DURING_PROCESSING.getCode(); }
@Test public void testReturnCodeSuccess() { when( mockedKitchenCommandExecutor.getResult() ).thenReturn( result ); when( result.getResult() ).thenReturn( true ); assertEquals( mockedKitchenCommandExecutor.getReturnCode(), CommandExecutorCodes.Kitchen.SUCCESS.getCode() ); }
@Override public long getPreferredBlockSize() { return HeaderFormat.getPreferredBlockSize(header); }
@Test public void testInodeIdBasedPaths() throws Exception { Configuration conf = new Configuration(); conf.setInt(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_DEFAULT); conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_ACLS_ENABLED_KEY, true); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); cluster.waitActive(); DistributedFileSystem fs = cluster.getFileSystem(); NamenodeProtocols nnRpc = cluster.getNameNodeRpc(); // FileSystem#mkdirs "/testInodeIdBasedPaths" Path baseDir = getInodePath(INodeId.ROOT_INODE_ID, "testInodeIdBasedPaths"); Path baseDirRegPath = new Path("/testInodeIdBasedPaths"); fs.mkdirs(baseDir); fs.exists(baseDir); long baseDirFileId = nnRpc.getFileInfo(baseDir.toString()).getFileId(); // FileSystem#create file and FileSystem#close Path testFileInodePath = getInodePath(baseDirFileId, "test1"); Path testFileRegularPath = new Path(baseDir, "test1"); final int testFileBlockSize = 1024; FileSystemTestHelper.createFile(fs, testFileInodePath, 1, testFileBlockSize); assertTrue(fs.exists(testFileInodePath)); // FileSystem#setPermission FsPermission perm = new FsPermission((short)0666); fs.setPermission(testFileInodePath, perm); // FileSystem#getFileStatus and FileSystem#getPermission FileStatus fileStatus = fs.getFileStatus(testFileInodePath); assertEquals(perm, fileStatus.getPermission()); // FileSystem#setOwner fs.setOwner(testFileInodePath, fileStatus.getOwner(), fileStatus.getGroup()); // FileSystem#setTimes fs.setTimes(testFileInodePath, 0, 0); fileStatus = fs.getFileStatus(testFileInodePath); assertEquals(0, fileStatus.getModificationTime()); assertEquals(0, fileStatus.getAccessTime()); // FileSystem#setReplication fs.setReplication(testFileInodePath, (short)3); fileStatus = fs.getFileStatus(testFileInodePath); assertEquals(3, fileStatus.getReplication()); fs.setReplication(testFileInodePath, (short)1); // ClientProtocol#getPreferredBlockSize assertEquals(testFileBlockSize, nnRpc.getPreferredBlockSize(testFileInodePath.toString())); /* * HDFS-6749 added missing calls to FSDirectory.resolvePath in the * following four methods. The calls below ensure that * /.reserved/.inodes paths work properly. No need to check return * values as these methods are tested elsewhere. */ { fs.isFileClosed(testFileInodePath); fs.getAclStatus(testFileInodePath); fs.getXAttrs(testFileInodePath); fs.listXAttrs(testFileInodePath); fs.access(testFileInodePath, FsAction.READ_WRITE); } // symbolic link related tests // Reserved path is not allowed as a target String invalidTarget = new Path(baseDir, "invalidTarget").toString(); String link = new Path(baseDir, "link").toString(); testInvalidSymlinkTarget(nnRpc, invalidTarget, link); // Test creating a link using reserved inode path String validTarget = "/validtarget"; testValidSymlinkTarget(nnRpc, validTarget, link); // FileSystem#append fs.append(testFileInodePath); // DistributedFileSystem#recoverLease fs.recoverLease(testFileInodePath); // Namenode#getBlockLocations LocatedBlocks l1 = nnRpc.getBlockLocations(testFileInodePath.toString(), 0, Long.MAX_VALUE); LocatedBlocks l2 = nnRpc.getBlockLocations(testFileRegularPath.toString(), 0, Long.MAX_VALUE); checkEquals(l1, l2); // FileSystem#rename - both the variants Path renameDst = getInodePath(baseDirFileId, "test2"); fileStatus = fs.getFileStatus(testFileInodePath); // Rename variant 1: rename and rename bacck fs.rename(testFileInodePath, renameDst); fs.rename(renameDst, testFileInodePath); assertEquals(fileStatus, fs.getFileStatus(testFileInodePath)); // Rename variant 2: rename and rename bacck fs.rename(testFileInodePath, renameDst, Rename.OVERWRITE); fs.rename(renameDst, testFileInodePath, Rename.OVERWRITE); assertEquals(fileStatus, fs.getFileStatus(testFileInodePath)); // FileSystem#getContentSummary assertEquals(fs.getContentSummary(testFileRegularPath).toString(), fs.getContentSummary(testFileInodePath).toString()); // FileSystem#listFiles checkEquals(fs.listFiles(baseDirRegPath, false), fs.listFiles(baseDir, false)); // FileSystem#delete fs.delete(testFileInodePath, true); assertFalse(fs.exists(testFileInodePath)); } finally { if (cluster != null) { cluster.shutdown(); } } }
public void setExpectedValue(String expectedValue) { setProperty(EXPECTEDVALUE, expectedValue); }
@Test void testSetExpectedValue() { String expectedValue = "some value"; JSONPathAssertion instance = new JSONPathAssertion(); instance.setExpectedValue(expectedValue); assertEquals(expectedValue, instance.getExpectedValue()); }
public boolean fileExists(String path) throws IOException, InvalidTokenException { String url; try { url = getUriBuilder() .setPath(API_PATH_PREFIX + "/mounts/primary/files/info") .setParameter("path", path) .build() .toString(); } catch (URISyntaxException e) { throw new IllegalStateException("Could not produce url.", e); } Request.Builder requestBuilder = getRequestBuilder(url); try (Response response = getResponse(requestBuilder)) { int code = response.code(); if (code == 200) { return true; } if (code == 404) { return false; } throw new KoofrClientIOException(response); } }
@Test public void testFileExistsTokenExpired() throws Exception { when(credentialFactory.refreshCredential(credential)) .then( (InvocationOnMock invocation) -> { final Credential cred = invocation.getArgument(0); cred.setAccessToken("acc1"); return cred; }); server.enqueue(new MockResponse().setResponseCode(401)); server.enqueue(new MockResponse().setResponseCode(200)); boolean exists = client.fileExists("/path/to/file"); assertTrue(exists); assertEquals(2, server.getRequestCount()); RecordedRequest recordedRequest = server.takeRequest(); assertEquals("GET", recordedRequest.getMethod()); assertEquals( "/api/v2/mounts/primary/files/info?path=%2Fpath%2Fto%2Ffile", recordedRequest.getPath()); assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); recordedRequest = server.takeRequest(); assertEquals("GET", recordedRequest.getMethod()); assertEquals( "/api/v2/mounts/primary/files/info?path=%2Fpath%2Fto%2Ffile", recordedRequest.getPath()); assertEquals("Bearer acc1", recordedRequest.getHeader("Authorization")); assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); }
@Override public Health checkNode() { return nodeHealthChecks.stream() .map(NodeHealthCheck::check) .reduce(Health.GREEN, HealthReducer::merge); }
@Test public void check_returns_green_status_without_any_cause_when_there_is_no_NodeHealthCheck() { HealthCheckerImpl underTest = new HealthCheckerImpl(nodeInformation, new NodeHealthCheck[0]); assertThat(underTest.checkNode()).isEqualTo(Health.GREEN); }
public static String format( String xml ) { XMLStreamReader rd = null; XMLStreamWriter wr = null; StringWriter result = new StringWriter(); try { rd = INPUT_FACTORY.createXMLStreamReader( new StringReader( xml ) ); synchronized ( OUTPUT_FACTORY ) { // BACKLOG-18743: This object was not thread safe in some scenarios // causing the `result` variable to have data from other concurrent executions // and making the final output invalid. wr = OUTPUT_FACTORY.createXMLStreamWriter( result ); } StartElementBuffer startElementBuffer = null; StringBuilder str = new StringBuilder(); StringBuilder prefix = new StringBuilder(); StringBuilder cdata = new StringBuilder(); boolean wasStart = false; boolean wasSomething = false; while ( rd.hasNext() ) { int event = rd.next(); if ( event != XMLStreamConstants.CDATA && cdata.length() > 0 ) { // was CDATA wr.writeCData( cdata.toString() ); cdata.setLength( 0 ); } if ( startElementBuffer != null ) { if ( event == XMLStreamConstants.END_ELEMENT ) { startElementBuffer.writeTo( wr, true ); startElementBuffer = null; prefix.setLength( prefix.length() - STEP_PREFIX.length() ); wasStart = false; continue; } else { startElementBuffer.writeTo( wr, false ); startElementBuffer = null; } } switch ( event ) { case XMLStreamConstants.START_ELEMENT: if ( !whitespacesOnly( str ) ) { wr.writeCharacters( str.toString() ); } else if ( wasSomething ) { wr.writeCharacters( "\n" + prefix ); } str.setLength( 0 ); prefix.append( STEP_PREFIX ); startElementBuffer = new StartElementBuffer( rd ); wasStart = true; wasSomething = true; break; case XMLStreamConstants.END_ELEMENT: prefix.setLength( prefix.length() - STEP_PREFIX.length() ); if ( wasStart ) { wr.writeCharacters( str.toString() ); } else { if ( !whitespacesOnly( str ) ) { wr.writeCharacters( str.toString() ); } else { wr.writeCharacters( "\n" + prefix ); } } str.setLength( 0 ); wr.writeEndElement(); wasStart = false; break; case XMLStreamConstants.SPACE: case XMLStreamConstants.CHARACTERS: str.append( rd.getText() ); break; case XMLStreamConstants.CDATA: if ( !whitespacesOnly( str ) ) { wr.writeCharacters( str.toString() ); } str.setLength( 0 ); cdata.append( rd.getText() ); wasSomething = true; break; case XMLStreamConstants.COMMENT: if ( !whitespacesOnly( str ) ) { wr.writeCharacters( str.toString() ); } else if ( wasSomething ) { wr.writeCharacters( "\n" + prefix ); } str.setLength( 0 ); wr.writeComment( rd.getText() ); wasSomething = true; break; case XMLStreamConstants.END_DOCUMENT: wr.writeCharacters( "\n" ); wr.writeEndDocument(); break; default: throw new RuntimeException( "Unknown XML event: " + event ); } } wr.flush(); return result.toString(); } catch ( XMLStreamException ex ) { throw new RuntimeException( ex ); } finally { try { if ( wr != null ) { wr.close(); } } catch ( Exception ex ) { } try { if ( rd != null ) { rd.close(); } } catch ( Exception ex ) { } } }
@Test public void test1() throws Exception { String inXml, expectedXml; try ( InputStream in = XMLFormatterTest.class.getResourceAsStream( "XMLFormatterIn1.xml" ) ) { inXml = IOUtils.toString( in ); } try ( InputStream in = XMLFormatterTest.class.getResourceAsStream( "XMLFormatterExpected1.xml" ) ) { expectedXml = IOUtils.toString( in ); } String result = XMLFormatter.format( inXml ); assertXMLEqual( expectedXml, result ); }
@Override public Object handle(ProceedingJoinPoint proceedingJoinPoint, RateLimiter rateLimiter, String methodName) throws Throwable { RateLimiterOperator<?> rateLimiterOperator = RateLimiterOperator.of(rateLimiter); Object returnValue = proceedingJoinPoint.proceed(); return executeRxJava3Aspect(rateLimiterOperator, returnValue); }
@Test public void testRxTypes() throws Throwable { RateLimiter rateLimiter = RateLimiter.ofDefaults("test"); when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test")); assertThat( rxJava3RateLimiterAspectExt.handle(proceedingJoinPoint, rateLimiter, "testMethod")) .isNotNull(); when(proceedingJoinPoint.proceed()).thenReturn(Flowable.just("Test")); assertThat( rxJava3RateLimiterAspectExt.handle(proceedingJoinPoint, rateLimiter, "testMethod")) .isNotNull(); when(proceedingJoinPoint.proceed()).thenReturn(Completable.complete()); assertThat( rxJava3RateLimiterAspectExt.handle(proceedingJoinPoint, rateLimiter, "testMethod")) .isNotNull(); when(proceedingJoinPoint.proceed()).thenReturn(Maybe.just("Test")); assertThat( rxJava3RateLimiterAspectExt.handle(proceedingJoinPoint, rateLimiter, "testMethod")) .isNotNull(); when(proceedingJoinPoint.proceed()).thenReturn(Observable.just("Test")); assertThat( rxJava3RateLimiterAspectExt.handle(proceedingJoinPoint, rateLimiter, "testMethod")) .isNotNull(); }
@Override public void run() { doHealthCheck(); }
@Test void testRunHealthyInstanceWithTimeoutFromMetadata() throws InterruptedException { injectInstance(true, System.currentTimeMillis()); Service service = Service.newService(NAMESPACE, GROUP_NAME, SERVICE_NAME); InstanceMetadata metadata = new InstanceMetadata(); metadata.getExtendData().put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, 500L); String address = IP + InternetAddressUtil.IP_PORT_SPLITER + PORT + InternetAddressUtil.IP_PORT_SPLITER + UtilsAndCommons.DEFAULT_CLUSTER_NAME; when(namingMetadataManager.getInstanceMetadata(service, address)).thenReturn(Optional.of(metadata)); when(globalConfig.isExpireInstance()).thenReturn(true); TimeUnit.SECONDS.sleep(1); beatCheckTask.run(); assertFalse(client.getAllInstancePublishInfo().isEmpty()); assertFalse(client.getInstancePublishInfo(Service.newService(NAMESPACE, GROUP_NAME, SERVICE_NAME)).isHealthy()); }
@Override public <T> void storeObject( String accountName, ObjectType objectType, String objectKey, T obj, String filename, boolean isAnUpdate) { if (objectType.equals(ObjectType.CANARY_RESULT_ARCHIVE)) { var draftRecord = new SqlCanaryArchive(); draftRecord.setId(objectKey); draftRecord.setContent(mapToJson(obj, objectType)); draftRecord.setCreatedAt(Instant.now()); draftRecord.setUpdatedAt(Instant.now()); sqlCanaryArchiveRepo.save(draftRecord); return; } if (objectType.equals(ObjectType.CANARY_CONFIG)) { var draftRecord = new SqlCanaryConfig(); draftRecord.setId(objectKey); draftRecord.setContent(mapToJson(obj, objectType)); draftRecord.setCreatedAt(Instant.now()); draftRecord.setUpdatedAt(Instant.now()); sqlCanaryConfigRepo.save(draftRecord); return; } if (objectType.equals(ObjectType.METRIC_SET_PAIR_LIST)) { var draftRecord = new SqlMetricSetPairs(); draftRecord.setId(objectKey); draftRecord.setContent(mapToJson(obj, objectType)); draftRecord.setCreatedAt(Instant.now()); draftRecord.setUpdatedAt(Instant.now()); sqlMetricSetPairsRepo.save(draftRecord); return; } if (objectType.equals(ObjectType.METRIC_SET_LIST)) { var draftRecord = new SqlMetricSets(); draftRecord.setId(objectKey); draftRecord.setContent(mapToJson(obj, objectType)); draftRecord.setCreatedAt(Instant.now()); draftRecord.setUpdatedAt(Instant.now()); sqlMetricSetsRepo.save(draftRecord); return; } throw new IllegalArgumentException("Unsupported object type: " + objectType); }
@Test public void testStoreObjectWhenMetricSetPairs() { var testAccountName = UUID.randomUUID().toString(); var testObjectType = ObjectType.METRIC_SET_PAIR_LIST; var testObjectKey = UUID.randomUUID().toString(); var testMetricSetPair = createTestMetricSetPair(); sqlStorageService.storeObject( testAccountName, testObjectType, testObjectKey, List.of(testMetricSetPair)); verify(sqlMetricSetPairsRepo).save(any(SqlMetricSetPairs.class)); }
protected List<ProviderInfo> directUrl2IpUrl(ProviderInfo providerInfo, List<ProviderInfo> originList) { List<ProviderInfo> result = new ArrayList<>(); try { String originHost = providerInfo.getHost(); String originUrl = providerInfo.getOriginUrl(); InetAddress[] addresses = InetAddress.getAllByName(originHost); if (addresses != null && addresses.length > 0) { Map<ProviderInfo, ProviderInfo> originMap = originList == null ? EMPTY_MAP : originList.stream().collect(Collectors.toMap(Function.identity(), Function.identity())); String firstHost = addresses[0].getHostAddress(); if (firstHost == null || firstHost.equals(providerInfo.getHost())) { addProviderInfo(result, originMap, providerInfo); return result; } else if (StringUtils.isNotBlank(originUrl)) { for (InetAddress address : addresses) { String newHost = address.getHostAddress(); ProviderInfo tmp = providerInfo.clone(); String newUrl = originUrl.replace(originHost, newHost); tmp.setOriginUrl(newUrl); tmp.setHost(newHost); addProviderInfo(result, originMap, tmp); } return result; } } } catch (Exception e) { LOGGER.error("directUrl2IpUrl error", e); } List<ProviderInfo> providerInfos = new ArrayList<>(); providerInfos.add(providerInfo); return providerInfos; }
@Test public void testDirectUrl2IpUrl() { ProviderInfo providerInfo = ProviderHelper.toProviderInfo("bolt://alipay.com:12200"); List<ProviderInfo> providerInfos = domainRegistry.directUrl2IpUrl(providerInfo, null); assertTrue(providerInfos.size() > 0); String host = providerInfos.get(0).getHost(); assertNotEquals("alipay.com", host); assertFalse(DomainRegistryHelper.isDomain(host)); ProviderInfo notExist = ProviderHelper.toProviderInfo("bolt://notexist:12200"); providerInfos = domainRegistry.directUrl2IpUrl(notExist, null); assertEquals(1, providerInfos.size()); host = providerInfos.get(0).getHost(); assertEquals("notexist", host); ProviderInfo ipProviderInfo = ProviderHelper.toProviderInfo("bolt://127.0.0.1:12200"); providerInfos = domainRegistry.directUrl2IpUrl(ipProviderInfo, null); assertEquals(1, providerInfos.size()); host = providerInfos.get(0).getHost(); assertEquals("127.0.0.1", host); }
@VisibleForTesting StreamConfig getConfig( OperatorID operatorID, StateBackend stateBackend, Configuration additionalConfig, StreamOperator<TaggedOperatorSubtaskState> operator) { // Eagerly perform a deep copy of the configuration, otherwise it will result in undefined // behavior when deploying with multiple bootstrap transformations. Configuration deepCopy = new Configuration( MutableConfig.of(stream.getExecutionEnvironment().getConfiguration())); deepCopy.addAll(additionalConfig); final StreamConfig config = new StreamConfig(deepCopy); config.setChainStart(); config.setCheckpointingEnabled(true); config.setCheckpointMode(CheckpointingMode.EXACTLY_ONCE); if (keyType != null) { TypeSerializer<?> keySerializer = keyType.createSerializer( stream.getExecutionEnvironment().getConfig().getSerializerConfig()); config.setStateKeySerializer(keySerializer); config.setStatePartitioner(0, keySelector); } config.setStreamOperator(operator); config.setOperatorName(operatorID.toHexString()); config.setOperatorID(operatorID); config.setStateBackend(stateBackend); config.setManagedMemoryFractionOperatorOfUseCase(ManagedMemoryUseCase.STATE_BACKEND, 1.0); config.serializeAllConfigs(); return config; }
@Test public void testStreamConfig() { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream<String> input = env.fromData(""); StateBootstrapTransformation<String> transformation = OperatorTransformation.bootstrapWith(input) .keyBy(new CustomKeySelector()) .transform(new ExampleKeyedStateBootstrapFunction()); StreamConfig config = transformation.getConfig( OperatorIDGenerator.fromUid("uid"), new HashMapStateBackend(), new Configuration(), null); KeySelector selector = config.getStatePartitioner(0, Thread.currentThread().getContextClassLoader()); Assert.assertEquals( "Incorrect key selector forwarded to stream operator", CustomKeySelector.class, selector.getClass()); }
@Converter(fallback = true) public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) { if (NodeInfo.class.isAssignableFrom(value.getClass())) { // use a fallback type converter so we can convert the embedded body if the value is NodeInfo NodeInfo ni = (NodeInfo) value; // first try to find a Converter for Node TypeConverter tc = registry.lookup(type, Node.class); if (tc != null) { Node node = NodeOverNodeInfo.wrap(ni); return tc.convertTo(type, exchange, node); } // if this does not exist we can also try NodeList (there are some type converters for that) as // the default Xerces Node implementation also implements NodeList. tc = registry.lookup(type, NodeList.class); if (tc != null) { List<NodeInfo> nil = new LinkedList<>(); nil.add(ni); return tc.convertTo(type, exchange, toDOMNodeList(nil)); } } else if (List.class.isAssignableFrom(value.getClass())) { TypeConverter tc = registry.lookup(type, NodeList.class); if (tc != null) { List<NodeInfo> lion = new LinkedList<>(); for (Object o : (List<?>) value) { if (o instanceof NodeInfo) { lion.add((NodeInfo) o); } } if (!lion.isEmpty()) { NodeList nl = toDOMNodeList(lion); return tc.convertTo(type, exchange, nl); } } } else if (NodeOverNodeInfo.class.isAssignableFrom(value.getClass())) { // NodeOverNode info is a read-only Node implementation from Saxon. In contrast to the JDK // com.sun.org.apache.xerces.internal.dom.NodeImpl class it does not implement NodeList, but // many Camel type converters are based on that interface. Therefore we convert to NodeList and // try type conversion in the fallback type converter. TypeConverter tc = registry.lookup(type, NodeList.class); if (tc != null) { List<Node> domNodeList = new LinkedList<>(); domNodeList.add((NodeOverNodeInfo) value); return tc.convertTo(type, exchange, new DOMNodeList(domNodeList)); } } return null; }
@Test public void convertToByteArray() { byte[] ba = context.getTypeConverter().convertTo(byte[].class, exchange, doc); assertNotNull(ba); String string = context.getTypeConverter().convertTo(String.class, exchange, ba); assertEquals(CONTENT, string); }
public boolean acquire(final Object o) { if (Objects.isNull(o)) { throw new NullPointerException(); } if (memory.sum() >= memoryLimit) { return false; } acquireLock.lock(); try { final long sum = memory.sum(); final long objectSize = inst.getObjectSize(o); if (sum + objectSize >= memoryLimit) { return false; } memory.add(objectSize); if (memory.sum() < memoryLimit) { notLimited.signal(); } } finally { acquireLock.unlock(); } if (memory.sum() > 0) { signalNotEmpty(); } return true; }
@Test public void testAcquireWhenEqualToLimit() { MemoryLimiter memoryLimiter = new MemoryLimiter(testObjectSize, instrumentation); assertFalse(memoryLimiter.acquire(testObject)); }
@Override public RemoveMembersFromConsumerGroupResult removeMembersFromConsumerGroup(String groupId, RemoveMembersFromConsumerGroupOptions options) { String reason = options.reason() == null || options.reason().isEmpty() ? DEFAULT_LEAVE_GROUP_REASON : JoinGroupRequest.maybeTruncateReason(options.reason()); List<MemberIdentity> members; if (options.removeAll()) { members = getMembersFromGroup(groupId, reason); } else { members = options.members().stream() .map(m -> m.toMemberIdentity().setReason(reason)) .collect(Collectors.toList()); } SimpleAdminApiFuture<CoordinatorKey, Map<MemberIdentity, Errors>> future = RemoveMembersFromConsumerGroupHandler.newFuture(groupId); RemoveMembersFromConsumerGroupHandler handler = new RemoveMembersFromConsumerGroupHandler(groupId, members, logContext); invokeDriver(handler, future, options.timeoutMs); return new RemoveMembersFromConsumerGroupResult(future.get(CoordinatorKey.byGroupId(groupId)), options.members()); }
@Test public void testRemoveMembersFromGroupNumRetries() throws Exception { final Cluster cluster = mockCluster(3, 0); final Time time = new MockTime(); try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(time, cluster, AdminClientConfig.RETRIES_CONFIG, "0")) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); env.kafkaClient().prepareResponse(prepareFindCoordinatorResponse(Errors.NONE, env.cluster().controller())); env.kafkaClient().prepareResponse(new LeaveGroupResponse(new LeaveGroupResponseData().setErrorCode(Errors.NOT_COORDINATOR.code()))); env.kafkaClient().prepareResponse(prepareFindCoordinatorResponse(Errors.NONE, env.cluster().controller())); Collection<MemberToRemove> membersToRemove = asList(new MemberToRemove("instance-1"), new MemberToRemove("instance-2")); final RemoveMembersFromConsumerGroupResult result = env.adminClient().removeMembersFromConsumerGroup( GROUP_ID, new RemoveMembersFromConsumerGroupOptions(membersToRemove)); TestUtils.assertFutureError(result.all(), TimeoutException.class); } }
@Deprecated public static Method findMethodByMethodName(Class<?> clazz, String methodName) throws NoSuchMethodException, ClassNotFoundException { return findMethodByMethodSignature(clazz, methodName, null); }
@Test void testFindMethodByMethodName2() { Assertions.assertThrows(IllegalStateException.class, () -> { ReflectUtils.findMethodByMethodName(Foo2.class, "hello"); }); }
@Override public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) { final Stacker contextStacker = buildContext.buildNodeContext(getId().toString()); return schemaKStreamFactory.create( buildContext, dataSource, contextStacker.push(SOURCE_OP_NAME) ); }
@Test public void shouldBuildSourceStreamWithCorrectTimestampIndex() { // Given: givenNodeWithMockSource(); // When: node.buildStream(buildContext); // Then: verify(schemaKStreamFactory).create(any(), any(), any()); }
@Override public RedisClusterNode clusterGetNodeForSlot(int slot) { Iterable<RedisClusterNode> res = clusterGetNodes(); for (RedisClusterNode redisClusterNode : res) { if (redisClusterNode.isMaster() && redisClusterNode.getSlotRange().contains(slot)) { return redisClusterNode; } } return null; }
@Test public void testClusterGetNodeForSlot() { RedisClusterNode node1 = connection.clusterGetNodeForSlot(1); RedisClusterNode node2 = connection.clusterGetNodeForSlot(16000); assertThat(node1.getId()).isNotEqualTo(node2.getId()); }
@Override public List<Integer> applyTransforms(List<Integer> originalGlyphIds) { List<Integer> intermediateGlyphsFromGsub = adjustRephPosition(originalGlyphIds); intermediateGlyphsFromGsub = repositionGlyphs(intermediateGlyphsFromGsub); for (String feature : FEATURES_IN_ORDER) { if (!gsubData.isFeatureSupported(feature)) { if (feature.equals(RKRF_FEATURE) && gsubData.isFeatureSupported(VATU_FEATURE)) { // Create your own rkrf feature from vatu feature intermediateGlyphsFromGsub = applyRKRFFeature( gsubData.getFeature(VATU_FEATURE), intermediateGlyphsFromGsub); } LOG.debug("the feature {} was not found", feature); continue; } LOG.debug("applying the feature {}", feature); ScriptFeature scriptFeature = gsubData.getFeature(feature); intermediateGlyphsFromGsub = applyGsubFeature(scriptFeature, intermediateGlyphsFromGsub); } return Collections.unmodifiableList(intermediateGlyphsFromGsub); }
@Test void testApplyTransforms_pres() { // given List<Integer> glyphsAfterGsub = Arrays.asList(284,294,314,315); // when List<Integer> result = gsubWorkerForGujarati.applyTransforms(getGlyphIds("ગ્નટ્ટપ્તલ્લ")); // then assertEquals(glyphsAfterGsub, result); }
@Override public List<Intent> compile(MultiPointToSinglePointIntent intent, List<Intent> installable) { Map<DeviceId, Link> links = new HashMap<>(); ConnectPoint egressPoint = intent.egressPoint(); final boolean allowMissingPaths = intentAllowsPartialFailure(intent); boolean hasPaths = false; boolean missingSomePaths = false; for (ConnectPoint ingressPoint : intent.ingressPoints()) { if (ingressPoint.deviceId().equals(egressPoint.deviceId())) { if (deviceService.isAvailable(ingressPoint.deviceId())) { hasPaths = true; } else { missingSomePaths = true; } continue; } Path path = getPath(intent, ingressPoint.deviceId(), egressPoint.deviceId()); if (path != null) { hasPaths = true; for (Link link : path.links()) { if (links.containsKey(link.dst().deviceId())) { // We've already reached the existing tree with the first // part of this path. Add the merging point with different // incoming port, but don't add the remainder of the path // in case it differs from the path we already have. links.put(link.src().deviceId(), link); break; } links.put(link.src().deviceId(), link); } } else { missingSomePaths = true; } } // Allocate bandwidth on existing paths if a bandwidth constraint is set List<ConnectPoint> ingressCPs = intent.filteredIngressPoints().stream() .map(fcp -> fcp.connectPoint()) .collect(Collectors.toList()); ConnectPoint egressCP = intent.filteredEgressPoint().connectPoint(); List<ConnectPoint> pathCPs = links.values().stream() .flatMap(l -> Stream.of(l.src(), l.dst())) .collect(Collectors.toList()); pathCPs.addAll(ingressCPs); pathCPs.add(egressCP); allocateBandwidth(intent, pathCPs); if (!hasPaths) { throw new IntentException("Cannot find any path between ingress and egress points."); } else if (!allowMissingPaths && missingSomePaths) { throw new IntentException("Missing some paths between ingress and egress points."); } Intent result = LinkCollectionIntent.builder() .appId(intent.appId()) .key(intent.key()) .treatment(intent.treatment()) .selector(intent.selector()) .links(Sets.newHashSet(links.values())) .filteredIngressPoints(intent.filteredIngressPoints()) .filteredEgressPoints(ImmutableSet.of(intent.filteredEgressPoint())) .priority(intent.priority()) .constraints(intent.constraints()) .resourceGroup(intent.resourceGroup()) .build(); return Collections.singletonList(result); }
@Test public void testNonTrivialSelectorsIntent() { Set<FilteredConnectPoint> ingress = ImmutableSet.of( new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1), DefaultTrafficSelector.builder().matchVlanId(VlanId.vlanId("100")).build()), new FilteredConnectPoint(new ConnectPoint(DID_2, PORT_1), DefaultTrafficSelector.builder().matchVlanId(VlanId.vlanId("200")).build()) ); FilteredConnectPoint egress = new FilteredConnectPoint(new ConnectPoint(DID_4, PORT_2)); TrafficSelector ipPrefixSelector = DefaultTrafficSelector.builder() .matchIPDst(IpPrefix.valueOf("192.168.100.0/24")) .build(); MultiPointToSinglePointIntent intent = makeIntent(ingress, egress, ipPrefixSelector); String[] hops = {S3}; MultiPointToSinglePointIntentCompiler compiler = makeCompiler(hops); assertThat(compiler, is(notNullValue())); List<Intent> result = compiler.compile(intent, null); assertThat(result, is(notNullValue())); assertThat(result, hasSize(1)); Intent resultIntent = result.get(0); assertThat(resultIntent, instanceOf(LinkCollectionIntent.class)); if (resultIntent instanceof LinkCollectionIntent) { LinkCollectionIntent linkIntent = (LinkCollectionIntent) resultIntent; assertThat(linkIntent.links(), hasSize(3)); assertThat(linkIntent.links(), linksHasPath(S1, S3)); assertThat(linkIntent.links(), linksHasPath(S2, S3)); assertThat(linkIntent.links(), linksHasPath(S3, S4)); assertThat(linkIntent.selector(), is(ipPrefixSelector)); } assertThat("key is inherited", resultIntent.key(), is(intent.key())); }
public static AvroGenericCoder of(Schema schema) { return AvroGenericCoder.of(schema); }
@Test public void testDeterminismList() { assertDeterministic(AvroCoder.of(StringList.class)); assertDeterministic(AvroCoder.of(StringArrayList.class)); }
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) { ProjectMeasuresQuery query = new ProjectMeasuresQuery(); Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids); criteria.forEach(criterion -> processCriterion(criterion, query)); return query; }
@Test public void fail_when_not_double() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(GT).setValue("ten").build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Value 'ten' is not a number"); }
public static byte buildHigh2Low6Bytes(byte high2, byte low6) { return (byte) ((high2 << 6) + low6); }
@Test public void buildHigh2Low6Bytes() { byte bs = CodecUtils.buildHigh2Low6Bytes((byte) 1, (byte) 53); Assert.assertEquals(bs, (byte) 117); }
@Nonnull public List<String> value() { return parsedValue; }
@Test void valueWithoutProtocol() { final RemoteReindexAllowlist allowlist = new RemoteReindexAllowlist(URI.create("http://example.com:9200"), "example.com:9200"); Assertions.assertThat(allowlist.value()) .containsExactly("example.com:9200"); }
@Override public boolean parseClientIpAndPort(Span span) { if (parseClientIpFromXForwardedFor(span)) return true; return span.remoteIpAndPort(delegate.getRemoteAddr(), delegate.getRemotePort()); }
@Test void parseClientIpAndPort_prefersXForwardedFor() { when(span.remoteIpAndPort("1.2.3.4", 0)).thenReturn(true); when(request.getHeader("X-Forwarded-For")).thenReturn("1.2.3.4"); wrapper.parseClientIpAndPort(span); verify(span).remoteIpAndPort("1.2.3.4", 0); verifyNoMoreInteractions(span); }
public int allocate(final String label) { return allocate(label, DEFAULT_TYPE_ID); }
@Test void shouldStoreLabels() { final int counterId = manager.allocate("abc"); reader.forEach(consumer); verify(consumer).accept(counterId, "abc"); }
@Override @Private public boolean isApplicationActive(ApplicationId id) throws YarnException { ApplicationReport report = null; try { report = client.getApplicationReport(id); } catch (ApplicationNotFoundException e) { // the app does not exist return false; } catch (IOException e) { throw new YarnException(e); } if (report == null) { // the app does not exist return false; } return ACTIVE_STATES.contains(report.getYarnApplicationState()); }
@Test void testRunningApp() throws Exception { YarnClient client = createCheckerWithMockedClient(); ApplicationId id = ApplicationId.newInstance(1, 1); // create a report and set the state to an active one ApplicationReport report = new ApplicationReportPBImpl(); report.setYarnApplicationState(YarnApplicationState.ACCEPTED); doReturn(report).when(client).getApplicationReport(id); assertTrue(checker.isApplicationActive(id)); }
public synchronized boolean isServing() { return mWebServer != null && mWebServer.getServer().isRunning(); }
@Test public void primaryOnlyTest() { Configuration.set(PropertyKey.STANDBY_MASTER_WEB_ENABLED, false); WebServerService webService = WebServerService.Factory.create(mWebAddress, mMasterProcess); Assert.assertTrue(webService instanceof PrimaryOnlyWebServerService); Assert.assertTrue(waitForFree()); Assert.assertFalse(webService.isServing()); webService.start(); // after start and before stop the web port is always bound as either the web server or the // rejecting server is bound to is (depending on whether it is in PRIMARY or STANDBY state) Assert.assertTrue(isBound()); Assert.assertFalse(webService.isServing()); for (int i = 0; i < 5; i++) { webService.promote(); Assert.assertTrue(webService.isServing()); Assert.assertTrue(isBound()); webService.demote(); Assert.assertTrue(isBound()); Assert.assertFalse(webService.isServing()); } webService.stop(); Assert.assertFalse(webService.isServing()); Assert.assertFalse(isBound()); }
static ConfusionMatrixTuple tabulate(ImmutableOutputInfo<MultiLabel> domain, List<Prediction<MultiLabel>> predictions) { // this just keeps track of how many times [class x] was predicted to be [class y] DenseMatrix confusion = new DenseMatrix(domain.size(), domain.size()); Set<MultiLabel> observed = new HashSet<>(); DenseMatrix[] mcm = new DenseMatrix[domain.size()]; for (int i = 0; i < domain.size(); i++) { mcm[i] = new DenseMatrix(2, 2); } int predIndex = 0; for (Prediction<MultiLabel> prediction : predictions) { MultiLabel predictedOutput = prediction.getOutput(); MultiLabel trueOutput = prediction.getExample().getOutput(); if (trueOutput.equals(MultiLabelFactory.UNKNOWN_MULTILABEL)) { throw new IllegalArgumentException("The sentinel Unknown MultiLabel was used as a ground truth label at prediction number " + predIndex); } else if (predictedOutput.equals(MultiLabelFactory.UNKNOWN_MULTILABEL)) { throw new IllegalArgumentException("The sentinel Unknown MultiLabel was predicted by the model at prediction number " + predIndex); } Set<Label> trueSet = trueOutput.getLabelSet(); Set<Label> predSet = predictedOutput.getLabelSet(); // // Count true positives and false positives for (Label pred : predSet) { int idx = domain.getID(new MultiLabel(pred.getLabel())); if (trueSet.contains(pred)) { // // true positive: mcm[i, 1, 1]++ mcm[idx].add(1, 1, 1d); } else { // // false positive: mcm[i, 1, 0]++ mcm[idx].add(1, 0, 1d); } observed.add(new MultiLabel(pred)); } // // Count false negatives and populate the confusion table for (Label trueLabel : trueSet) { int idx = domain.getID(new MultiLabel(trueLabel.getLabel())); if (idx < 0) { throw new IllegalArgumentException("Unknown label '" + trueLabel.getLabel() + "' found in the ground truth labels at prediction number " + predIndex + ", this label is not known by the model which made the predictions."); } // // Doing two things in this loop: // 1) Checking if predSet contains trueLabel // 2) Counting the # of times [trueLabel] was predicted to be [predLabel] to populate the confusion table boolean found = false; for (Label predLabel : predSet) { int jdx = domain.getID(new MultiLabel(predLabel.getLabel())); confusion.add(jdx, idx, 1d); if (predLabel.equals(trueLabel)) { found = true; } } if (!found) { // // false negative: mcm[i, 0, 1]++ mcm[idx].add(0, 1, 1d); } // else { true positive: already counted } observed.add(new MultiLabel(trueLabel)); } // // True negatives everywhere else for (MultiLabel multilabel : domain.getDomain()) { Set<Label> labels = multilabel.getLabelSet(); for (Label label : labels) { if (!trueSet.contains(label) && !predSet.contains(label)) { int ix = domain.getID(new MultiLabel(label)); mcm[ix].add(0, 0, 1d); } } } predIndex++; } return new ConfusionMatrixTuple(mcm, confusion, observed); }
@Test public void testTabulateUnexpectedMultiLabel() { MultiLabel a = label("a"); MultiLabel bc = label("b","c"); MultiLabel abd = label("a","b","d"); ImmutableOutputInfo<MultiLabel> domain = mkDomain(a,bc,abd); List<Prediction<MultiLabel>> predictions = Arrays.asList( mkPrediction(label("a"), label("a")), mkPrediction(label("c"), label("b")), mkPrediction(label("b"), label("b")), //Note "e" is not in the domain. mkPrediction(label("e"), label("a", "c")) ); try { MultiLabelConfusionMatrix.ConfusionMatrixTuple t = MultiLabelConfusionMatrix.tabulate(domain, predictions); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("Unknown label 'e' found")); } }
public static <T> T loginWithKerberos( Configuration configuration, String krb5FilePath, String kerberosPrincipal, String kerberosKeytabPath, LoginFunction<T> action) throws IOException, InterruptedException { if (!configuration.get("hadoop.security.authentication").equals("kerberos")) { throw new IllegalArgumentException("hadoop.security.authentication must be kerberos"); } // Use global lock to avoid multiple threads to execute setConfiguration at the same time synchronized (UserGroupInformation.class) { if (StringUtils.isNotEmpty(krb5FilePath)) { System.setProperty("java.security.krb5.conf", krb5FilePath); } // init configuration UserGroupInformation.setConfiguration(configuration); UserGroupInformation userGroupInformation = UserGroupInformation.loginUserFromKeytabAndReturnUGI( kerberosPrincipal, kerberosKeytabPath); return userGroupInformation.doAs( (PrivilegedExceptionAction<T>) () -> action.run(configuration, userGroupInformation)); } }
@Test void loginWithKerberos_success() throws Exception { miniKdc.createPrincipal(new File(workDir, "tom.keytab"), "tom"); UserGroupInformation userGroupInformation = HadoopLoginFactory.loginWithKerberos( createConfiguration(), null, "tom", workDir.getPath() + "/" + "tom.keytab", (conf, ugi) -> ugi); assertNotNull(userGroupInformation); assertEquals("tom@EXAMPLE.COM", userGroupInformation.getUserName()); }
@Override public void await() throws InterruptedException { _delegate.await(); }
@Test public void testAwait() throws InterruptedException { final SettablePromise<String> delegate = Promises.settable(); final Promise<String> promise = new DelegatingPromise<String>(delegate); final String value = "value"; delegate.done(value); assertTrue(promise.await(20, TimeUnit.MILLISECONDS)); assertEquals(value, promise.get()); }
@Override public Object read(final MySQLPacketPayload payload, final boolean unsigned) { if (unsigned) { return payload.getByteBuf().readUnsignedByte(); } return payload.getByteBuf().readByte(); }
@Test void assertRead() { when(payload.getByteBuf()).thenReturn(Unpooled.wrappedBuffer(new byte[]{1, 1})); assertThat(new MySQLInt1BinaryProtocolValue().read(payload, false), is((byte) 1)); assertThat(new MySQLInt1BinaryProtocolValue().read(payload, true), is((short) 1)); }
public String getStartTimeStr() { String str = NA; if (startTime >= 0) { str = new Date(startTime).toString(); } return str; }
@Test public void testGetStartTimeStr() { JobReport jobReport = mock(JobReport.class); when(jobReport.getStartTime()).thenReturn(-1L); Job job = mock(Job.class); when(job.getReport()).thenReturn(jobReport); when(job.getName()).thenReturn("TestJobInfo"); when(job.getState()).thenReturn(JobState.SUCCEEDED); JobId jobId = MRBuilderUtils.newJobId(1L, 1, 1); when(job.getID()).thenReturn(jobId); JobInfo jobInfo = new JobInfo(job); Assert.assertEquals(JobInfo.NA, jobInfo.getStartTimeStr()); Date date = new Date(); when(jobReport.getStartTime()).thenReturn(date.getTime()); jobInfo = new JobInfo(job); Assert.assertEquals(date.toString(), jobInfo.getStartTimeStr()); }
@Override public void run() { if (processor != null) { processor.execute(); } else { if (!beforeHook()) { logger.info("before-feature hook returned [false], aborting: {}", this); } else { scenarios.forEachRemaining(this::processScenario); } afterFeature(); } }
@Test void testEvalAndSet() { run("eval-and-set.feature"); }
public static String createJobName(String prefix) { return createJobName(prefix, 0); }
@Test public void testCreateJobNameWithUppercaseSuffix() { assertThat(createJobName("testWithUpperCase", 8)) .matches("test-with-upper-case-\\d{17}-[a-z0-9]{8}"); }
@SuppressWarnings({"unchecked", "rawtypes"}) public static int compareTo(final Comparable thisValue, final Comparable otherValue, final OrderDirection orderDirection, final NullsOrderType nullsOrderType, final boolean caseSensitive) { if (null == thisValue && null == otherValue) { return 0; } if (null == thisValue) { return NullsOrderType.FIRST == nullsOrderType ? -1 : 1; } if (null == otherValue) { return NullsOrderType.FIRST == nullsOrderType ? 1 : -1; } if (!caseSensitive && thisValue instanceof String && otherValue instanceof String) { return compareToCaseInsensitiveString((String) thisValue, (String) otherValue, orderDirection); } return OrderDirection.ASC == orderDirection ? thisValue.compareTo(otherValue) : -thisValue.compareTo(otherValue); }
@Test void assertCompareToWhenSecondValueIsNullForOrderByAscAndNullsFirst() { assertThat(CompareUtils.compareTo(1, null, OrderDirection.ASC, NullsOrderType.FIRST, caseSensitive), is(1)); }
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .nullable(typeDefine.isNullable()) .defaultValue(typeDefine.getDefaultValue()) .comment(typeDefine.getComment()); String dmType = typeDefine.getDataType().toUpperCase(); switch (dmType) { case DM_BIT: builder.sourceType(DM_BIT); builder.dataType(BasicType.BOOLEAN_TYPE); break; case DM_TINYINT: builder.sourceType(DM_TINYINT); builder.dataType(BasicType.BYTE_TYPE); break; case DM_BYTE: builder.sourceType(DM_BYTE); builder.dataType(BasicType.BYTE_TYPE); break; case DM_SMALLINT: builder.sourceType(DM_SMALLINT); builder.dataType(BasicType.SHORT_TYPE); break; case DM_INT: builder.sourceType(DM_INT); builder.dataType(BasicType.INT_TYPE); break; case DM_INTEGER: builder.sourceType(DM_INTEGER); builder.dataType(BasicType.INT_TYPE); break; case DM_PLS_INTEGER: builder.sourceType(DM_PLS_INTEGER); builder.dataType(BasicType.INT_TYPE); break; case DM_BIGINT: builder.sourceType(DM_BIGINT); builder.dataType(BasicType.LONG_TYPE); break; case DM_REAL: builder.sourceType(DM_REAL); builder.dataType(BasicType.FLOAT_TYPE); break; case DM_FLOAT: builder.sourceType(DM_FLOAT); builder.dataType(BasicType.DOUBLE_TYPE); break; case DM_DOUBLE: builder.sourceType(DM_DOUBLE); builder.dataType(BasicType.DOUBLE_TYPE); break; case DM_DOUBLE_PRECISION: builder.sourceType(DM_DOUBLE_PRECISION); builder.dataType(BasicType.DOUBLE_TYPE); break; case DM_NUMERIC: case DM_NUMBER: case DM_DECIMAL: case DM_DEC: DecimalType decimalType; if (typeDefine.getPrecision() != null && typeDefine.getPrecision() > 0) { decimalType = new DecimalType( typeDefine.getPrecision().intValue(), typeDefine.getScale()); } else { decimalType = new DecimalType(DEFAULT_PRECISION, DEFAULT_SCALE); } builder.sourceType( String.format( "%s(%s,%s)", DM_DECIMAL, decimalType.getPrecision(), decimalType.getScale())); builder.dataType(decimalType); builder.columnLength((long) decimalType.getPrecision()); builder.scale(decimalType.getScale()); break; case DM_CHAR: case DM_CHARACTER: builder.sourceType(String.format("%s(%s)", DM_CHAR, typeDefine.getLength())); builder.dataType(BasicType.STRING_TYPE); builder.columnLength(TypeDefineUtils.charTo4ByteLength(typeDefine.getLength())); break; case DM_VARCHAR: case DM_VARCHAR2: builder.sourceType(String.format("%s(%s)", DM_VARCHAR2, typeDefine.getLength())); builder.dataType(BasicType.STRING_TYPE); builder.columnLength(TypeDefineUtils.charTo4ByteLength(typeDefine.getLength())); break; case DM_TEXT: builder.sourceType(DM_TEXT); builder.dataType(BasicType.STRING_TYPE); // dm text max length is 2147483647 builder.columnLength(typeDefine.getLength()); break; case DM_LONG: builder.sourceType(DM_LONG); builder.dataType(BasicType.STRING_TYPE); // dm long max length is 2147483647 builder.columnLength(typeDefine.getLength()); break; case DM_LONGVARCHAR: builder.sourceType(DM_LONGVARCHAR); builder.dataType(BasicType.STRING_TYPE); // dm longvarchar max length is 2147483647 builder.columnLength(typeDefine.getLength()); break; case DM_CLOB: builder.sourceType(DM_CLOB); builder.dataType(BasicType.STRING_TYPE); // dm clob max length is 2147483647 builder.columnLength(typeDefine.getLength()); break; case DM_BINARY: builder.sourceType(String.format("%s(%s)", DM_BINARY, typeDefine.getLength())); builder.dataType(PrimitiveByteArrayType.INSTANCE); builder.columnLength(typeDefine.getLength()); break; case DM_VARBINARY: builder.sourceType(String.format("%s(%s)", DM_VARBINARY, typeDefine.getLength())); builder.dataType(PrimitiveByteArrayType.INSTANCE); builder.columnLength(typeDefine.getLength()); break; case DM_LONGVARBINARY: builder.sourceType(DM_LONGVARBINARY); builder.dataType(PrimitiveByteArrayType.INSTANCE); builder.columnLength(typeDefine.getLength()); break; case DM_IMAGE: builder.sourceType(DM_IMAGE); builder.dataType(PrimitiveByteArrayType.INSTANCE); builder.columnLength(typeDefine.getLength()); break; case DM_BLOB: builder.sourceType(DM_BLOB); builder.dataType(PrimitiveByteArrayType.INSTANCE); builder.columnLength(typeDefine.getLength()); break; case DM_BFILE: builder.sourceType(DM_BFILE); builder.dataType(BasicType.STRING_TYPE); builder.columnLength(typeDefine.getLength()); break; case DM_DATE: builder.sourceType(DM_DATE); builder.dataType(LocalTimeType.LOCAL_DATE_TYPE); break; case DM_TIME: if (typeDefine.getScale() == null) { builder.sourceType(DM_TIME); } else { builder.sourceType(String.format("%s(%s)", DM_TIME, typeDefine.getScale())); } builder.dataType(LocalTimeType.LOCAL_TIME_TYPE); builder.scale(typeDefine.getScale()); break; case DM_TIME_WITH_TIME_ZONE: if (typeDefine.getScale() == null) { builder.sourceType(DM_TIME_WITH_TIME_ZONE); } else { builder.sourceType( String.format("TIME(%s) WITH TIME ZONE", typeDefine.getScale())); } builder.dataType(LocalTimeType.LOCAL_TIME_TYPE); builder.scale(typeDefine.getScale()); break; case DM_TIMESTAMP: if (typeDefine.getScale() == null) { builder.sourceType(DM_TIMESTAMP); } else { builder.sourceType( String.format("%s(%s)", DM_TIMESTAMP, typeDefine.getScale())); } builder.dataType(LocalTimeType.LOCAL_DATE_TIME_TYPE); builder.scale(typeDefine.getScale()); break; case DM_DATETIME: if (typeDefine.getScale() == null) { builder.sourceType(DM_DATETIME); } else { builder.sourceType(String.format("%s(%s)", DM_DATETIME, typeDefine.getScale())); } builder.dataType(LocalTimeType.LOCAL_DATE_TIME_TYPE); builder.scale(typeDefine.getScale()); break; case DM_DATETIME_WITH_TIME_ZONE: if (typeDefine.getScale() == null) { builder.sourceType(DM_DATETIME_WITH_TIME_ZONE); } else { builder.sourceType( String.format("DATETIME(%s) WITH TIME ZONE", typeDefine.getScale())); } builder.dataType(LocalTimeType.LOCAL_DATE_TIME_TYPE); builder.scale(typeDefine.getScale()); break; default: throw CommonError.convertToSeaTunnelTypeError( DatabaseIdentifier.DAMENG, typeDefine.getDataType(), typeDefine.getName()); } return builder.build(); }
@Test public void testConvertTimestamp() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("timestamp") .dataType("timestamp") .build(); Column column = DmdbTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), column.getName()); Assertions.assertEquals(LocalTimeType.LOCAL_DATE_TIME_TYPE, column.getDataType()); Assertions.assertEquals(typeDefine.getColumnType(), column.getSourceType().toLowerCase()); }
<T extends PipelineOptions> T as(Class<T> iface) { checkNotNull(iface); checkArgument(iface.isInterface(), "Not an interface: %s", iface); T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface); if (existingOption == null) { synchronized (this) { // double check existingOption = computedProperties.interfaceToProxyCache.getInstance(iface); if (existingOption == null) { Registration<T> registration = PipelineOptionsFactory.CACHE .get() .validateWellFormed(iface, computedProperties.knownInterfaces); List<PropertyDescriptor> propertyDescriptors = registration.getPropertyDescriptors(); Class<T> proxyClass = registration.getProxyClass(); existingOption = InstanceBuilder.ofType(proxyClass) .fromClass(proxyClass) .withArg(InvocationHandler.class, this) .build(); computedProperties = computedProperties.updated(iface, existingOption, propertyDescriptors); } } } return existingOption; }
@Test public void testJsonConversionForComplexType() throws Exception { ComplexType complexType = new ComplexType(); complexType.stringField = "stringField"; complexType.intField = 12; complexType.innerType = InnerType.of(12); complexType.genericType = ImmutableList.of(InnerType.of(16234), InnerType.of(24)); ComplexTypes options = PipelineOptionsFactory.as(ComplexTypes.class); options.setComplexType(complexType); ComplexTypes options2 = serializeDeserialize(ComplexTypes.class, options); assertEquals(complexType, options2.getComplexType()); }
private void updateControllerAddr() { if (brokerConfig.isFetchControllerAddrByDnsLookup()) { List<String> adders = brokerOuterAPI.dnsLookupAddressByDomain(this.brokerConfig.getControllerAddr()); if (CollectionUtils.isNotEmpty(adders)) { this.controllerAddresses = adders; } } else { final String controllerPaths = this.brokerConfig.getControllerAddr(); final String[] controllers = controllerPaths.split(";"); assert controllers.length > 0; this.controllerAddresses = Arrays.asList(controllers); } }
@Test public void testUpdateControllerAddr() throws Exception { final String controllerAddr = "192.168.1.1"; brokerConfig.setFetchControllerAddrByDnsLookup(true); when(brokerOuterAPI.dnsLookupAddressByDomain(anyString())).thenReturn(Lists.newArrayList(controllerAddr)); Method method = ReplicasManager.class.getDeclaredMethod("updateControllerAddr"); method.setAccessible(true); method.invoke(replicasManager); List<String> addresses = replicasManager.getControllerAddresses(); Assertions.assertThat(addresses).contains(controllerAddr); // Simulating dns resolution exceptions when(brokerOuterAPI.dnsLookupAddressByDomain(anyString())).thenReturn(new ArrayList<>()); method.invoke(replicasManager); addresses = replicasManager.getControllerAddresses(); Assertions.assertThat(addresses).contains(controllerAddr); }
static JavaInput reorderModifiers(String text) throws FormatterException { return reorderModifiers( new JavaInput(text), ImmutableList.of(Range.closedOpen(0, text.length()))); }
@Test public void simple() throws FormatterException { assertThat(ModifierOrderer.reorderModifiers("static abstract class InnerClass {}").getText()) .isEqualTo("abstract static class InnerClass {}"); }
@Override public ValidationTaskResult validateImpl(Map<String, String> optionMap) throws InterruptedException { return accessNativeLib(); }
@Test public void nativeLibPresent() throws Exception { File testLibDir = ValidationTestUtils.createTemporaryDirectory(); String testLibPath = testLibDir.getPath(); String libPath = testLibPath; System.setProperty(NativeLibValidationTask.NATIVE_LIB_PATH, libPath); NativeLibValidationTask task = new NativeLibValidationTask(); ValidationTaskResult result = task.validateImpl(ImmutableMap.of()); assertEquals(ValidationUtils.State.OK, result.getState()); }
public static String parsePath(String uri, Map<String, String> patterns) { if (uri == null) { return null; } else if (StringUtils.isBlank(uri)) { return String.valueOf(SLASH); } CharacterIterator ci = new StringCharacterIterator(uri); StringBuilder pathBuffer = new StringBuilder(); char c = ci.first(); if (c == CharacterIterator.DONE) { return String.valueOf(SLASH); } do { if (c == OPEN) { String regexBuffer = cutParameter(ci, patterns); if (regexBuffer == null) { LOGGER.warn("Operation path \"{}\" contains syntax error.", uri); return null; } pathBuffer.append(regexBuffer); } else { int length = pathBuffer.length(); if (!(c == SLASH && (length != 0 && pathBuffer.charAt(length - 1) == SLASH))) { pathBuffer.append(c); } } } while ((c = ci.next()) != CharacterIterator.DONE); return pathBuffer.toString(); }
@Test(description = "parse two part path with one param") public void parseTwoPartPathWithOneParam() { final Map<String, String> regexMap = new HashMap<String, String>(); final String path = PathUtils.parsePath("/api/{itemId: [0-9]{4}/[0-9]{2,4}/[A-Za-z0-9]+}", regexMap); assertEquals(path, "/api/{itemId}"); assertEquals(regexMap.get("itemId"), "[0-9]{4}/[0-9]{2,4}/[A-Za-z0-9]+"); }
@Override public void createService(Service service) { checkNotNull(service, ERR_NULL_SERVICE); checkArgument(!Strings.isNullOrEmpty(service.getMetadata().getUid()), ERR_NULL_SERVICE_UID); k8sServiceStore.createService(service); log.info(String.format(MSG_SERVICE, service.getMetadata().getName(), MSG_CREATED)); }
@Test(expected = IllegalArgumentException.class) public void testCreateDuplicateService() { target.createService(SERVICE); target.createService(SERVICE); }
public String failureMessage( int epoch, OptionalLong deltaUs, boolean isActiveController, long lastCommittedOffset ) { StringBuilder bld = new StringBuilder(); if (deltaUs.isPresent()) { bld.append("event failed with "); } else { bld.append("event unable to start processing because of "); } bld.append(internalException.getClass().getSimpleName()); if (externalException.isPresent()) { bld.append(" (treated as "). append(externalException.get().getClass().getSimpleName()).append(")"); } if (causesFailover()) { bld.append(" at epoch ").append(epoch); } if (deltaUs.isPresent()) { bld.append(" in ").append(deltaUs.getAsLong()).append(" microseconds"); } if (causesFailover()) { if (isActiveController) { bld.append(". Renouncing leadership and reverting to the last committed offset "); bld.append(lastCommittedOffset); } else { bld.append(". The controller is already in standby mode"); } } bld.append("."); if (!isFault && internalException.getMessage() != null) { bld.append(" Exception message: "); bld.append(internalException.getMessage()); } return bld.toString(); }
@Test public void testNotLeaderExceptionFailureMessage() { assertEquals("event unable to start processing because of NotLeaderException (treated as " + "NotControllerException) at epoch 123. Renouncing leadership and reverting to the " + "last committed offset 456. Exception message: Append failed", NOT_LEADER.failureMessage(123, OptionalLong.empty(), true, 456L)); }