focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public String getMethod() { return PATH; }
@Test public void testSetMyDefaultAdministratorRightsWithAllSet() { SetMyDefaultAdministratorRights setMyDefaultAdministratorRights = SetMyDefaultAdministratorRights .builder() .forChannels(true) .rights(ChatAdministratorRights .builder() .isAnonymous(true) .canManageChat(false) .canDeleteMessages(false) .canManageVideoChats(false) .canRestrictMembers(false) .canPromoteMembers(true) .canChangeInfo(true) .canInviteUsers(false) .build()) .build(); assertEquals("setMyDefaultAdministratorRights", setMyDefaultAdministratorRights.getMethod()); assertDoesNotThrow(setMyDefaultAdministratorRights::validate); }
long getCapacity() { long capacity = 0L; for (FsVolumeImpl v : volumes) { try (FsVolumeReference ref = v.obtainReference()) { capacity += v.getCapacity(); } catch (IOException e) { // ignore. } } return capacity; }
@Test public void testGetCachedVolumeCapacity() throws IOException { conf.setBoolean(DFSConfigKeys.DFS_DATANODE_FIXED_VOLUME_SIZE_KEY, DFSConfigKeys.DFS_DATANODE_FIXED_VOLUME_SIZE_DEFAULT); long capacity = 4000L; DF usage = mock(DF.class); when(usage.getCapacity()).thenReturn(capacity); FsVolumeImpl volumeChanged = new FsVolumeImplBuilder() .setConf(conf) .setDataset(dataset) .setStorageID("storage-id") .setStorageDirectory(new StorageDirectory(StorageLocation.parse( "[RAM_DISK]volume-changed"))) .setUsage(usage) .build(); int callTimes = 5; for(int i = 0; i < callTimes; i++) { assertEquals(capacity, volumeChanged.getCapacity()); } verify(usage, times(callTimes)).getCapacity(); conf.setBoolean(DFSConfigKeys.DFS_DATANODE_FIXED_VOLUME_SIZE_KEY, true); FsVolumeImpl volumeFixed = new FsVolumeImplBuilder() .setConf(conf) .setDataset(dataset) .setStorageID("storage-id") .setStorageDirectory(new StorageDirectory(StorageLocation.parse( "[RAM_DISK]volume-fixed"))) .setUsage(usage) .build(); for(int i = 0; i < callTimes; i++) { assertEquals(capacity, volumeFixed.getCapacity()); } // reuse the capacity for fixed sized volume, only call one time // getCapacity of DF verify(usage, times(callTimes+1)).getCapacity(); conf.setBoolean(DFSConfigKeys.DFS_DATANODE_FIXED_VOLUME_SIZE_KEY, DFSConfigKeys.DFS_DATANODE_FIXED_VOLUME_SIZE_DEFAULT); }
public Object createEnum(String symbol, Schema schema) { return new EnumSymbol(schema, symbol); }
@Test void enumCompare() { Schema s = Schema.createEnum("Kind", null, null, Arrays.asList("Z", "Y", "X")); GenericEnumSymbol z = new GenericData.EnumSymbol(s, "Z"); GenericEnumSymbol z2 = new GenericData.EnumSymbol(s, "Z"); assertEquals(0, z.compareTo(z2)); GenericEnumSymbol y = new GenericData.EnumSymbol(s, "Y"); assertTrue(y.compareTo(z) > 0); assertTrue(z.compareTo(y) < 0); }
public static List<AclEntry> filterAclEntriesByAclSpec( List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); EnumMap<AclEntryScope, AclEntry> providedMask = Maps.newEnumMap(AclEntryScope.class); EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class); EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class); for (AclEntry existingEntry: existingAcl) { if (aclSpec.containsKey(existingEntry)) { scopeDirty.add(existingEntry.getScope()); if (existingEntry.getType() == MASK) { maskDirty.add(existingEntry.getScope()); } } else { if (existingEntry.getType() == MASK) { providedMask.put(existingEntry.getScope(), existingEntry); } else { aclBuilder.add(existingEntry); } } } copyDefaultsIfNeeded(aclBuilder); calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty); return buildAndValidateAcl(aclBuilder); }
@Test public void testFilterAclEntriesByAclSpecEmptyAclSpec() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, USER, "bruce", READ_WRITE)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, MASK, ALL)) .add(aclEntry(ACCESS, OTHER, READ)) .add(aclEntry(DEFAULT, USER, ALL)) .add(aclEntry(DEFAULT, USER, "bruce", READ_WRITE)) .add(aclEntry(DEFAULT, GROUP, READ)) .add(aclEntry(DEFAULT, MASK, ALL)) .add(aclEntry(DEFAULT, OTHER, READ)) .build(); List<AclEntry> aclSpec = Lists.newArrayList(); assertEquals(existing, filterAclEntriesByAclSpec(existing, aclSpec)); }
@Override public SchemaTransform from(PubsubReadSchemaTransformConfiguration configuration) { if (configuration.getSubscription() == null && configuration.getTopic() == null) { throw new IllegalArgumentException( "To read from Pubsub, a subscription name or a topic name must be provided"); } if (configuration.getSubscription() != null && configuration.getTopic() != null) { throw new IllegalArgumentException( "To read from Pubsub, a subscription name or a topic name must be provided. Not both."); } if (!"RAW".equals(configuration.getFormat())) { if ((Strings.isNullOrEmpty(configuration.getSchema()) && !Strings.isNullOrEmpty(configuration.getFormat())) || (!Strings.isNullOrEmpty(configuration.getSchema()) && Strings.isNullOrEmpty(configuration.getFormat()))) { throw new IllegalArgumentException( "A schema was provided without a data format (or viceversa). Please provide " + "both of these parameters to read from Pubsub, or if you would like to use the Pubsub schema service," + " please leave both of these blank."); } } Schema payloadSchema; SerializableFunction<byte[], Row> payloadMapper; String format = configuration.getFormat() == null ? null : configuration.getFormat().toUpperCase(); if ("RAW".equals(format)) { payloadSchema = Schema.of(Schema.Field.of("payload", Schema.FieldType.BYTES)); payloadMapper = input -> Row.withSchema(payloadSchema).addValue(input).build(); } else if ("JSON".equals(format)) { payloadSchema = JsonUtils.beamSchemaFromJsonSchema(configuration.getSchema()); payloadMapper = JsonUtils.getJsonBytesToRowFunction(payloadSchema); } else if ("AVRO".equals(format)) { payloadSchema = AvroUtils.toBeamSchema( new org.apache.avro.Schema.Parser().parse(configuration.getSchema())); payloadMapper = AvroUtils.getAvroBytesToRowFunction(payloadSchema); } else { throw new IllegalArgumentException( String.format( "Format %s not supported. Only supported formats are %s", configuration.getFormat(), VALID_FORMATS_STR)); } PubsubReadSchemaTransform transform = new PubsubReadSchemaTransform(configuration, payloadSchema, payloadMapper); if (configuration.getClientFactory() != null) { transform.setClientFactory(configuration.getClientFactory()); } if (configuration.getClock() != null) { transform.setClock(configuration.getClock()); } return transform; }
@Test public void testReadRaw() throws IOException { PCollectionRowTuple begin = PCollectionRowTuple.empty(p); Schema rawSchema = Schema.of(Schema.Field.of("payload", Schema.FieldType.BYTES)); byte[] payload = "some payload".getBytes(StandardCharsets.UTF_8); try (PubsubTestClientFactory clientFactory = clientFactory(ImmutableList.of(incomingMessageOf(payload, CLOCK.currentTimeMillis())))) { PubsubReadSchemaTransformConfiguration config = PubsubReadSchemaTransformConfiguration.builder() .setFormat("RAW") .setSchema("") .setSubscription(SUBSCRIPTION) .setClientFactory(clientFactory) .setClock(CLOCK) .build(); SchemaTransform transform = new PubsubReadSchemaTransformProvider().from(config); PCollectionRowTuple reads = begin.apply(transform); PAssert.that(reads.get("output")) .containsInAnyOrder( ImmutableList.of(Row.withSchema(rawSchema).addValue(payload).build())); p.run().waitUntilFinish(); } catch (Exception e) { throw e; } }
public static FileCacheStore getInstance(String basePath, String cacheName) { return getInstance(basePath, cacheName, true); }
@Test void testPathIsFile() throws URISyntaxException, IOException { String basePath = getDirectoryOfClassPath(); String filePath = basePath + File.separator + "isFile"; new File(filePath).createNewFile(); Assertions.assertThrows(RuntimeException.class, () -> FileCacheStoreFactory.getInstance(filePath, "dubbo")); }
@VisibleForTesting public static void addUserAgentEnvironments(List<String> info) { info.add(String.format(OS_FORMAT, OSUtils.OS_NAME)); if (EnvironmentUtils.isDocker()) { info.add(DOCKER_KEY); } if (EnvironmentUtils.isKubernetes()) { info.add(KUBERNETES_KEY); } if (EnvironmentUtils.isGoogleComputeEngine()) { info.add(GCE_KEY); } else { addEC2Info(info); } }
@Test public void userAgentEnvironmentStringDocker() { Mockito.when(EnvironmentUtils.isDocker()).thenReturn(true); Mockito.when(EC2MetadataUtils.getUserData()) .thenThrow(new SdkClientException("Unable to contact EC2 metadata service.")); List<String> info = new ArrayList<>(); UpdateCheckUtils.addUserAgentEnvironments(info); Assert.assertEquals(2, info.size()); Assert.assertEquals(String.format(UpdateCheckUtils.OS_FORMAT, OSUtils.OS_NAME), info.get(0)); Assert.assertEquals(UpdateCheckUtils.DOCKER_KEY, info.get(1)); }
@Override public synchronized DefaultConnectClient get( final Optional<String> ksqlAuthHeader, final List<Entry<String, String>> incomingRequestHeaders, final Optional<KsqlPrincipal> userPrincipal ) { if (defaultConnectAuthHeader == null) { defaultConnectAuthHeader = buildDefaultAuthHeader(); } final Map<String, Object> configWithPrefixOverrides = ksqlConfig.valuesWithPrefixOverride(KsqlConfig.KSQL_CONNECT_PREFIX); return new DefaultConnectClient( ksqlConfig.getString(KsqlConfig.CONNECT_URL_PROPERTY), buildAuthHeader(ksqlAuthHeader, incomingRequestHeaders), requestHeadersExtension .map(extension -> extension.getHeaders(userPrincipal)) .orElse(Collections.emptyMap()), Optional.ofNullable(newSslContext(configWithPrefixOverrides)), shouldVerifySslHostname(configWithPrefixOverrides), ksqlConfig.getLong(KsqlConfig.CONNECT_REQUEST_TIMEOUT_MS) ); }
@Test public void shouldReloadCredentialsOnFileCreation() throws Exception { // Given: when(config.getBoolean(KsqlConfig.CONNECT_BASIC_AUTH_CREDENTIALS_RELOAD_PROPERTY)).thenReturn(true); givenCustomBasicAuthHeader(); // no credentials file present // verify that no auth header is present assertThat(connectClientFactory.get(Optional.empty(), Collections.emptyList(), Optional.empty()).getRequestHeaders(), is(EMPTY_HEADERS)); // When: credentials file is created waitForLastModifiedTick(); givenValidCredentialsFile(); // Then: auth header is present assertThatEventually( "Should load newly created credentials", () -> connectClientFactory.get(Optional.empty(), Collections.emptyList(), Optional.empty()).getRequestHeaders(), arrayContaining(header(AUTH_HEADER_NAME, EXPECTED_HEADER)), TimeUnit.SECONDS.toMillis(1), TimeUnit.SECONDS.toMillis(1) ); }
public static FileMetadata fromJson(String json) { return JsonUtil.parse(json, FileMetadataParser::fromJson); }
@Test public void testMissingBlobs() { assertThatThrownBy(() -> FileMetadataParser.fromJson("{\"properties\": {}}")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot parse missing field: blobs"); }
public void execute(){ logger.debug("[" + getOperationName() + "] Starting execution of paged operation. maximum time: " + maxTime + ", maximum pages: " + maxPages); long startTime = System.currentTimeMillis(); long executionTime = 0; int i = 0; int exceptionsSwallowedCount = 0; int operationsCompleted = 0; Set<String> exceptionsSwallowedClasses = new HashSet<String>(); while (i< maxPages && executionTime < maxTime){ Collection<T> page = fetchPage(); if(page == null || page.size() == 0){ break; } for (T item : page) { try { doOperation(item); operationsCompleted++; } catch (Exception e){ if(swallowExceptions){ exceptionsSwallowedCount++; exceptionsSwallowedClasses.add(e.getClass().getName()); logger.debug("Swallowing exception " + e.getMessage(), e); } else { logger.debug("Rethrowing exception " + e.getMessage()); throw e; } } } i++; executionTime = System.currentTimeMillis() - startTime; } finalReport(operationsCompleted, exceptionsSwallowedCount, exceptionsSwallowedClasses); }
@Test(timeout = 1000L) public void execute_zerotime(){ CountingPageOperation op = new CountingPageOperation(Integer.MAX_VALUE,0L); op.execute(); assertEquals(0L, op.getCounter()); assertEquals(0L, op.getTimeToLastFetch()); }
public Optional<ViewDefinition> getViewDefinition(QualifiedObjectName viewName) { if (!viewDefinitions.containsKey(viewName)) { throw new PrestoException(VIEW_NOT_FOUND, format("View %s not found, the available view names are: %s", viewName, viewDefinitions.keySet())); } try { return viewDefinitions.get(viewName).get(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); } catch (ExecutionException ex) { throwIfUnchecked(ex.getCause()); throw new RuntimeException(ex.getCause()); } }
@Test public void testGetViewDefinition() { Optional<ViewDefinition> viewDefinitionOptional = metadataHandle.getViewDefinition(QualifiedObjectName.valueOf("tpch.s1.t1")); assertTrue(viewDefinitionOptional.isPresent()); ViewDefinition viewDefinition = viewDefinitionOptional.get(); assertEquals("tpch", viewDefinition.getCatalog().get()); assertEquals("s1", viewDefinition.getSchema().get()); assertEquals("user", viewDefinition.getOwner().get()); assertEquals("select a from t1", viewDefinition.getOriginalSql()); assertFalse(viewDefinition.isRunAsInvoker()); }
@Override public String ping(RedisClusterNode node) { RedisClient entry = getEntry(node); RFuture<String> f = executorService.readAsync(entry, LongCodec.INSTANCE, RedisCommands.PING); return syncFuture(f); }
@Test public void testClusterPing() { RedisClusterNode master = getFirstMaster(); String res = connection.ping(master); assertThat(res).isEqualTo("PONG"); }
@Override public void addInterfaces(VplsData vplsData, Collection<Interface> interfaces) { requireNonNull(vplsData); requireNonNull(interfaces); VplsData newData = VplsData.of(vplsData); newData.addInterfaces(interfaces); updateVplsStatus(newData, VplsData.VplsState.UPDATING); }
@Test public void testAddInterfaces() { VplsData vplsData = vplsManager.createVpls(VPLS1, NONE); vplsManager.addInterfaces(vplsData, ImmutableSet.of(V100H1, V100H2)); vplsData = vplsStore.getVpls(VPLS1); assertNotNull(vplsData); assertEquals(vplsData.state(), UPDATING); assertEquals(2, vplsData.interfaces().size()); assertTrue(vplsData.interfaces().contains(V100H1)); assertTrue(vplsData.interfaces().contains(V100H2)); }
@Override public String getName() { return ANALYZER_NAME; }
@Test public void testGetName() { VersionFilterAnalyzer instance = new VersionFilterAnalyzer(); String expResult = "Version Filter Analyzer"; String result = instance.getName(); assertEquals(expResult, result); }
@Override public void define(Context context) { NewController controller = context.createController(CONTROLLER); controller.setDescription("Manage permission templates, and the granting and revoking of permissions at the global and project levels."); controller.setSince("3.7"); for (PermissionsWsAction action : actions) { action.define(controller); } controller.done(); }
@Test public void define_controller() { WebService.Context context = new WebService.Context(); underTest.define(context); WebService.Controller controller = context.controller("api/permissions"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.since()).isEqualTo("3.7"); assertThat(controller.actions()).hasSize(1); }
@Override protected Future<KafkaBridgeStatus> createOrUpdate(Reconciliation reconciliation, KafkaBridge assemblyResource) { KafkaBridgeStatus kafkaBridgeStatus = new KafkaBridgeStatus(); String namespace = reconciliation.namespace(); KafkaBridgeCluster bridge; try { bridge = KafkaBridgeCluster.fromCrd(reconciliation, assemblyResource, sharedEnvironmentProvider); } catch (Exception e) { LOGGER.warnCr(reconciliation, e); StatusUtils.setStatusConditionAndObservedGeneration(assemblyResource, kafkaBridgeStatus, e); return Future.failedFuture(new ReconciliationException(kafkaBridgeStatus, e)); } KafkaClientAuthentication auth = assemblyResource.getSpec().getAuthentication(); List<CertSecretSource> trustedCertificates = assemblyResource.getSpec().getTls() == null ? Collections.emptyList() : assemblyResource.getSpec().getTls().getTrustedCertificates(); Promise<KafkaBridgeStatus> createOrUpdatePromise = Promise.promise(); boolean bridgeHasZeroReplicas = bridge.getReplicas() == 0; String initCrbName = KafkaBridgeResources.initContainerClusterRoleBindingName(bridge.getCluster(), namespace); ClusterRoleBinding initCrb = bridge.generateClusterRoleBinding(); LOGGER.debugCr(reconciliation, "Updating Kafka Bridge cluster"); kafkaBridgeServiceAccount(reconciliation, namespace, bridge) .compose(i -> bridgeInitClusterRoleBinding(reconciliation, initCrbName, initCrb)) .compose(i -> deploymentOperations.scaleDown(reconciliation, namespace, bridge.getComponentName(), bridge.getReplicas(), operationTimeoutMs)) .compose(scale -> serviceOperations.reconcile(reconciliation, namespace, KafkaBridgeResources.serviceName(bridge.getCluster()), bridge.generateService())) .compose(i -> MetricsAndLoggingUtils.metricsAndLogging(reconciliation, configMapOperations, bridge.logging(), null)) .compose(metricsAndLogging -> configMapOperations.reconcile(reconciliation, namespace, KafkaBridgeResources.metricsAndLogConfigMapName(reconciliation.name()), bridge.generateMetricsAndLogConfigMap(metricsAndLogging))) .compose(i -> podDisruptionBudgetOperator.reconcile(reconciliation, namespace, bridge.getComponentName(), bridge.generatePodDisruptionBudget())) .compose(i -> VertxUtil.authTlsHash(secretOperations, namespace, auth, trustedCertificates)) .compose(hash -> deploymentOperations.reconcile(reconciliation, namespace, bridge.getComponentName(), bridge.generateDeployment(Collections.singletonMap(Annotations.ANNO_STRIMZI_AUTH_HASH, Integer.toString(hash)), pfa.isOpenshift(), imagePullPolicy, imagePullSecrets))) .compose(i -> deploymentOperations.scaleUp(reconciliation, namespace, bridge.getComponentName(), bridge.getReplicas(), operationTimeoutMs)) .compose(i -> deploymentOperations.waitForObserved(reconciliation, namespace, bridge.getComponentName(), 1_000, operationTimeoutMs)) .compose(i -> bridgeHasZeroReplicas ? Future.succeededFuture() : deploymentOperations.readiness(reconciliation, namespace, bridge.getComponentName(), 1_000, operationTimeoutMs)) .onComplete(reconciliationResult -> { StatusUtils.setStatusConditionAndObservedGeneration(assemblyResource, kafkaBridgeStatus, reconciliationResult.mapEmpty().cause()); if (!bridgeHasZeroReplicas) { int port = KafkaBridgeCluster.DEFAULT_REST_API_PORT; if (bridge.getHttp() != null) { port = bridge.getHttp().getPort(); } kafkaBridgeStatus.setUrl(KafkaBridgeResources.url(bridge.getCluster(), namespace, port)); } kafkaBridgeStatus.setReplicas(bridge.getReplicas()); kafkaBridgeStatus.setLabelSelector(bridge.getSelectorLabels().toSelectorString()); if (reconciliationResult.succeeded()) { createOrUpdatePromise.complete(kafkaBridgeStatus); } else { createOrUpdatePromise.fail(new ReconciliationException(kafkaBridgeStatus, reconciliationResult.cause())); } }); return createOrUpdatePromise.future(); }
@Test public void testCreateOrUpdateUpdatesCluster(VertxTestContext context) { ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(true); var mockBridgeOps = supplier.kafkaBridgeOperator; DeploymentOperator mockDcOps = supplier.deploymentOperations; PodDisruptionBudgetOperator mockPdbOps = supplier.podDisruptionBudgetOperator; ConfigMapOperator mockCmOps = supplier.configMapOperations; ServiceOperator mockServiceOps = supplier.serviceOperations; String kbName = "foo"; String kbNamespace = "test"; KafkaBridge kb = ResourceUtils.createKafkaBridge(kbNamespace, kbName, image, 1, BOOTSTRAP_SERVERS, KAFKA_BRIDGE_PRODUCER_SPEC, KAFKA_BRIDGE_CONSUMER_SPEC, KAFKA_BRIDGE_HTTP_SPEC, true); KafkaBridgeCluster bridge = KafkaBridgeCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kb, SHARED_ENV_PROVIDER); kb.getSpec().setImage("some/different:image"); // Change the image to generate some diff when(mockBridgeOps.get(kbNamespace, kbName)).thenReturn(kb); when(mockBridgeOps.getAsync(anyString(), anyString())).thenReturn(Future.succeededFuture(kb)); when(mockBridgeOps.updateStatusAsync(any(), any(KafkaBridge.class))).thenReturn(Future.succeededFuture()); when(mockServiceOps.get(kbNamespace, bridge.getComponentName())).thenReturn(bridge.generateService()); when(mockDcOps.get(kbNamespace, bridge.getComponentName())).thenReturn(bridge.generateDeployment(Map.of(), true, null, null)); when(mockDcOps.readiness(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture()); when(mockDcOps.waitForObserved(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture()); ArgumentCaptor<String> serviceNameCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Service> serviceCaptor = ArgumentCaptor.forClass(Service.class); when(mockServiceOps.reconcile(any(), eq(kbNamespace), serviceNameCaptor.capture(), serviceCaptor.capture())).thenReturn(Future.succeededFuture()); ArgumentCaptor<String> dcNameCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Deployment> dcCaptor = ArgumentCaptor.forClass(Deployment.class); when(mockDcOps.reconcile(any(), eq(kbNamespace), dcNameCaptor.capture(), dcCaptor.capture())).thenReturn(Future.succeededFuture()); ArgumentCaptor<String> dcScaleUpNameCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Integer> dcScaleUpReplicasCaptor = ArgumentCaptor.forClass(Integer.class); when(mockDcOps.scaleUp(any(), eq(kbNamespace), dcScaleUpNameCaptor.capture(), dcScaleUpReplicasCaptor.capture(), anyLong())).thenReturn(Future.succeededFuture()); ArgumentCaptor<String> dcScaleDownNameCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Integer> dcScaleDownReplicasCaptor = ArgumentCaptor.forClass(Integer.class); when(mockDcOps.scaleDown(any(), eq(kbNamespace), dcScaleDownNameCaptor.capture(), dcScaleDownReplicasCaptor.capture(), anyLong())).thenReturn(Future.succeededFuture()); ArgumentCaptor<PodDisruptionBudget> pdbCaptor = ArgumentCaptor.forClass(PodDisruptionBudget.class); when(mockPdbOps.reconcile(any(), anyString(), any(), pdbCaptor.capture())).thenReturn(Future.succeededFuture()); when(mockCmOps.reconcile(any(), anyString(), any(), any())).thenReturn(Future.succeededFuture(ReconcileResult.created(new ConfigMap()))); // Mock CM get when(mockBridgeOps.get(kbNamespace, kbName)).thenReturn(kb); ConfigMap metricsCm = new ConfigMapBuilder().withNewMetadata() .withName(KafkaBridgeResources.metricsAndLogConfigMapName(kbName)) .withNamespace(kbNamespace) .endMetadata() .withData(Collections.singletonMap(MetricsModel.CONFIG_MAP_KEY, METRICS_CONFIG)) .build(); when(mockCmOps.get(kbNamespace, KafkaBridgeResources.metricsAndLogConfigMapName(kbName))).thenReturn(metricsCm); // Mock CM patch Set<String> metricsCms = TestUtils.set(); doAnswer(invocation -> { metricsCms.add(invocation.getArgument(1)); return Future.succeededFuture(); }).when(mockCmOps).reconcile(any(), eq(kbNamespace), anyString(), any()); KafkaBridgeAssemblyOperator ops = new KafkaBridgeAssemblyOperator(vertx, new PlatformFeaturesAvailability(true, kubernetesVersion), new MockCertManager(), new PasswordGenerator(10, "a", "a"), supplier, ResourceUtils.dummyClusterOperatorConfig(VERSIONS)); Checkpoint async = context.checkpoint(); ops.createOrUpdate(new Reconciliation("test-trigger", KafkaBridge.RESOURCE_KIND, kbNamespace, kbName), kb) .onComplete(context.succeeding(v -> context.verify(() -> { KafkaBridgeCluster compareTo = KafkaBridgeCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kb, SHARED_ENV_PROVIDER); // Verify service List<Service> capturedServices = serviceCaptor.getAllValues(); assertThat(capturedServices, hasSize(1)); Service service = capturedServices.get(0); assertThat(service.getMetadata().getName(), is(KafkaBridgeResources.serviceName(kbName))); assertThat(service, is(compareTo.generateService())); // Verify Deployment List<Deployment> capturedDc = dcCaptor.getAllValues(); assertThat(capturedDc, hasSize(1)); Deployment dc = capturedDc.get(0); assertThat(dc.getMetadata().getName(), is(compareTo.getComponentName())); assertThat(dc, is(compareTo.generateDeployment(Collections.singletonMap(Annotations.ANNO_STRIMZI_AUTH_HASH, "0"), true, null, null))); // Verify PodDisruptionBudget List<PodDisruptionBudget> capturedPdb = pdbCaptor.getAllValues(); assertThat(capturedPdb, hasSize(1)); PodDisruptionBudget pdb = capturedPdb.get(0); assertThat(pdb.getMetadata().getName(), is(compareTo.getComponentName())); assertThat(pdb, is(compareTo.generatePodDisruptionBudget())); // Verify scaleDown / scaleUp were not called assertThat(dcScaleDownNameCaptor.getAllValues(), hasSize(1)); assertThat(dcScaleUpNameCaptor.getAllValues(), hasSize(1)); // No metrics config => no CMs created verify(mockCmOps, never()).createOrUpdate(any(), any()); async.flag(); }))); }
public static Configuration loadConfiguration() { return loadConfiguration(new Configuration()); }
@Test void testInvalidConfiguration() { assertThatThrownBy(() -> GlobalConfiguration.loadConfiguration(tmpDir.getAbsolutePath())) .isInstanceOf(IllegalConfigurationException.class); }
public static IOException maybeExtractIOException( String path, Throwable thrown, String message) { if (thrown == null) { return null; } // walk down the chain of exceptions to find the innermost. Throwable cause = getInnermostThrowable(thrown.getCause(), thrown); // see if this is an http channel exception HttpChannelEOFException channelException = maybeExtractChannelException(path, message, cause); if (channelException != null) { return channelException; } // not a channel exception, not an IOE. if (!(cause instanceof IOException)) { return null; } // the cause can be extracted to an IOE. // rather than just return it, we try to preserve the stack trace // of the outer exception. // as a new instance is created through reflection, the // class of the returned instance will be that of the innermost, // unless no suitable constructor is available. final IOException ioe = (IOException) cause; return wrapWithInnerIOE(path, message, thrown, ioe); }
@Test public void testConnectExceptionExtraction() throws Throwable { intercept(ConnectException.class, "top", () -> { throw maybeExtractIOException("p1", sdkException("top", sdkException("middle", new ConnectException("bottom"))), null); }); }
public static <S, T> RemoteIterator<T> mappingRemoteIterator( RemoteIterator<S> iterator, FunctionRaisingIOE<? super S, T> mapper) { return new MappingRemoteIterator<>(iterator, mapper); }
@Test public void testMapping() throws Throwable { CountdownRemoteIterator countdown = new CountdownRemoteIterator(100); RemoteIterator<Integer> it = mappingRemoteIterator( countdown, i -> i); verifyInvoked(it, 100, c -> counter++); assertCounterValue(100); extractStatistics(it); assertStringValueContains(it, "CountdownRemoteIterator"); close(it); countdown.assertCloseCount(1); }
public static String toJavaIdentifierString(String className) { // replace invalid characters with '_' return CharMatcher.forPredicate(Character::isJavaIdentifierPart).negate() .replaceFrom(className, '_'); }
@Test public void testToJavaIdentifierString() { assertEquals(toJavaIdentifierString("HelloWorld"), "HelloWorld"); assertEquals(toJavaIdentifierString("Hello$World"), "Hello$World"); assertEquals(toJavaIdentifierString("Hello#World"), "Hello_World"); assertEquals(toJavaIdentifierString("A^B^C"), "A_B_C"); }
@Override public GetClusterNodeAttributesResponse getClusterNodeAttributes( GetClusterNodeAttributesRequest request) throws YarnException, IOException { if (request == null) { routerMetrics.incrGetClusterNodeAttributesFailedRetrieved(); String msg = "Missing getClusterNodeAttributes request."; RouterAuditLogger.logFailure(user.getShortUserName(), GET_CLUSTERNODEATTRIBUTES, UNKNOWN, TARGET_CLIENT_RM_SERVICE, msg); RouterServerUtil.logAndThrowException(msg, null); } long startTime = clock.getTime(); ClientMethod remoteMethod = new ClientMethod("getClusterNodeAttributes", new Class[] {GetClusterNodeAttributesRequest.class}, new Object[] {request}); Collection<GetClusterNodeAttributesResponse> clusterNodeAttributesResponses = null; try { clusterNodeAttributesResponses = invokeConcurrent(remoteMethod, GetClusterNodeAttributesResponse.class); } catch (Exception ex) { routerMetrics.incrGetClusterNodeAttributesFailedRetrieved(); String msg = "Unable to get cluster node attributes due to exception."; RouterAuditLogger.logFailure(user.getShortUserName(), GET_CLUSTERNODEATTRIBUTES, UNKNOWN, TARGET_CLIENT_RM_SERVICE, msg); RouterServerUtil.logAndThrowException(msg, ex); } long stopTime = clock.getTime(); routerMetrics.succeededGetClusterNodeAttributesRetrieved(stopTime - startTime); RouterAuditLogger.logSuccess(user.getShortUserName(), GET_CLUSTERNODEATTRIBUTES, TARGET_CLIENT_RM_SERVICE); return RouterYarnClientUtils.mergeClusterNodeAttributesResponse(clusterNodeAttributesResponses); }
@Test public void testClusterNodeAttributes() throws Exception { LOG.info("Test FederationClientInterceptor : Get ClusterNodeAttributes request."); // null request LambdaTestUtils.intercept(YarnException.class, "Missing getClusterNodeAttributes request.", () -> interceptor.getClusterNodeAttributes(null)); // normal request GetClusterNodeAttributesResponse response = interceptor.getClusterNodeAttributes(GetClusterNodeAttributesRequest.newInstance()); Assert.assertNotNull(response); Set<NodeAttributeInfo> nodeAttributeInfos = response.getNodeAttributes(); Assert.assertNotNull(nodeAttributeInfos); Assert.assertEquals(4, nodeAttributeInfos.size()); NodeAttributeInfo nodeAttributeInfo1 = NodeAttributeInfo.newInstance(NodeAttributeKey.newInstance("GPU"), NodeAttributeType.STRING); Assert.assertTrue(nodeAttributeInfos.contains(nodeAttributeInfo1)); NodeAttributeInfo nodeAttributeInfo2 = NodeAttributeInfo.newInstance(NodeAttributeKey.newInstance("OS"), NodeAttributeType.STRING); Assert.assertTrue(nodeAttributeInfos.contains(nodeAttributeInfo2)); }
@Override public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility( TypeSerializerSnapshot<T> oldSerializerSnapshot) { if (!(oldSerializerSnapshot instanceof AvroSerializerSnapshot)) { return TypeSerializerSchemaCompatibility.incompatible(); } AvroSerializerSnapshot<?> oldAvroSerializerSnapshot = (AvroSerializerSnapshot<?>) oldSerializerSnapshot; return resolveSchemaCompatibility(oldAvroSerializerSnapshot.schema, schema); }
@Test void removingAnOptionalFieldsIsCompatibleAsIs() { assertThat( AvroSerializerSnapshot.resolveSchemaCompatibility( FIRST_REQUIRED_LAST_OPTIONAL, FIRST_NAME)) .is(isCompatibleAfterMigration()); }
@Override public V fetch(final K key, final long time) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlyWindowStore<K, V>> stores = provider.stores(storeName, windowStoreType); for (final ReadOnlyWindowStore<K, V> windowStore : stores) { try { final V result = windowStore.fetch(key, time); if (result != null) { return result; } } catch (final InvalidStateStoreException e) { throw new InvalidStateStoreException( "State store is not available anymore and may have been migrated to another instance; " + "please re-discover its location from the state metadata."); } } return null; }
@Test public void shouldNotGetValuesFromOtherStores() { otherUnderlyingStore.put("some-key", "some-value", 0L); underlyingWindowStore.put("some-key", "my-value", 1L); final List<KeyValue<Long, String>> results = StreamsTestUtils.toList(windowStore.fetch("some-key", ofEpochMilli(0L), ofEpochMilli(2L))); assertEquals(Collections.singletonList(new KeyValue<>(1L, "my-value")), results); }
public static boolean isDubboProxyName(String name) { return name.startsWith(ALIBABA_DUBBO_PROXY_NAME_PREFIX) || name.startsWith(APACHE_DUBBO_PROXY_NAME_PREFIX) || name.contains(DUBBO_3_X_PARTIAL_PROXY_NAME); }
@Test public void testIsNotDubboProxyName() { assertFalse(DubboUtil.isDubboProxyName(ArrayList.class.getName())); }
public AppNamespace findPublicAppNamespace(String namespaceName) { List<AppNamespace> appNamespaces = appNamespaceRepository.findByNameAndIsPublic(namespaceName, true); if (CollectionUtils.isEmpty(appNamespaces)) { return null; } return appNamespaces.get(0); }
@Test @Sql(scripts = "/sql/appnamespaceservice/init-appnamespace.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/sql/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) public void testFindPublicAppNamespace() { List<AppNamespace> appNamespaceList = appNamespaceService.findPublicAppNamespaces(); Assert.assertNotNull(appNamespaceList); Assert.assertEquals(5, appNamespaceList.size()); }
public static boolean isNumber(String text) { final int startPos = findStartPosition(text); if (startPos < 0) { return false; } for (int i = startPos; i < text.length(); i++) { char ch = text.charAt(i); if (!Character.isDigit(ch)) { return false; } } return true; }
@Test @DisplayName("Tests that isNumber returns false for floats") void isNumberFloats() { assertFalse(ObjectHelper.isNumber("12.34")); assertFalse(ObjectHelper.isNumber("-12.34")); assertFalse(ObjectHelper.isNumber("1.0")); assertFalse(ObjectHelper.isNumber("0.0")); }
@Override public void filter(ContainerRequestContext requestContext) { if (isInternalRequest(requestContext)) { log.trace("Skipping authentication for internal request"); return; } try { log.debug("Authenticating request"); BasicAuthCredentials credentials = new BasicAuthCredentials(requestContext.getHeaderString(AUTHORIZATION)); LoginContext loginContext = new LoginContext( CONNECT_LOGIN_MODULE, null, new BasicAuthCallBackHandler(credentials), configuration); loginContext.login(); setSecurityContextForRequest(requestContext, credentials); } catch (LoginException | ConfigException e) { // Log at debug here in order to avoid polluting log files whenever someone mistypes their credentials log.debug("Request failed authentication", e); requestContext.abortWith( Response.status(Response.Status.UNAUTHORIZED) .entity("User cannot access the resource.") .build()); } }
@Test public void testUnknownCredentialsFile() { JaasBasicAuthFilter jaasBasicAuthFilter = setupJaasFilter("KafkaConnect", "/tmp/testcrednetial"); ContainerRequestContext requestContext = setMock("Basic", "user", "password"); jaasBasicAuthFilter.filter(requestContext); verify(requestContext).abortWith(any(Response.class)); verify(requestContext, atLeastOnce()).getMethod(); verify(requestContext).getHeaderString(JaasBasicAuthFilter.AUTHORIZATION); }
@Override public InetSocketAddress resolve(ServerWebExchange exchange) { List<String> xForwardedValues = extractXForwardedValues(exchange); if (!xForwardedValues.isEmpty()) { int index = Math.max(0, xForwardedValues.size() - maxTrustedIndex); return new InetSocketAddress(xForwardedValues.get(index), 0); } return defaultRemoteIpResolver.resolve(exchange); }
@Test public void trustAllFallsBackOnEmptyHeader() { ServerWebExchange exchange = buildExchange(remoteAddressOnlyBuilder().header("X-Forwarded-For", "")); InetSocketAddress address = trustAll.resolve(exchange); assertThat(address.getHostName()).isEqualTo("0.0.0.0"); }
public TaskAcknowledgeResult acknowledgeCoordinatorState( OperatorInfo coordinatorInfo, @Nullable ByteStreamStateHandle stateHandle) { synchronized (lock) { if (disposed) { return TaskAcknowledgeResult.DISCARDED; } final OperatorID operatorId = coordinatorInfo.operatorId(); OperatorState operatorState = operatorStates.get(operatorId); // sanity check for better error reporting if (!notYetAcknowledgedOperatorCoordinators.remove(operatorId)) { return operatorState != null && operatorState.getCoordinatorState() != null ? TaskAcknowledgeResult.DUPLICATE : TaskAcknowledgeResult.UNKNOWN; } if (operatorState == null) { operatorState = new OperatorState( operatorId, coordinatorInfo.currentParallelism(), coordinatorInfo.maxParallelism()); operatorStates.put(operatorId, operatorState); } if (stateHandle != null) { operatorState.setCoordinatorState(stateHandle); } return TaskAcknowledgeResult.SUCCESS; } }
@Test void testAcknowledgeUnknownCoordinator() throws Exception { final PendingCheckpoint checkpoint = createPendingCheckpointWithCoordinators(new TestingOperatorInfo()); final TaskAcknowledgeResult ack = checkpoint.acknowledgeCoordinatorState(new TestingOperatorInfo(), null); assertThat(TaskAcknowledgeResult.UNKNOWN).isEqualTo(ack); }
public IterableOfProtosFluentAssertion<M> ignoringRepeatedFieldOrder() { return usingConfig(config.ignoringRepeatedFieldOrder()); }
@Test public void testFormatDiff() { expectFailureWhenTesting() .that(listOf(message1)) .ignoringRepeatedFieldOrder() .containsExactly(message2); expectThatFailure() .factValue("diff") .isEqualTo( "Differences were found:\n" + "modified: o_int: 3 -> 1\n" + "added: r_string[0]: \"foo\"\n" + "added: r_string[1]: \"bar\"\n" + "deleted: r_string[0]: \"baz\"\n" + "deleted: r_string[1]: \"qux\"\n"); }
@Override public String getContextualName(DubboClientContext context) { return super.getContextualName(context.getInvocation()); }
@Test void testGetContextualName() { RpcInvocation invocation = new RpcInvocation(); Invoker<?> invoker = ObservationConventionUtils.getMockInvokerWithUrl(); invocation.setMethodName("testMethod"); invocation.setServiceName("com.example.TestService"); DubboClientContext context = new DubboClientContext(invoker, invocation); DefaultDubboClientObservationConvention convention = new DefaultDubboClientObservationConvention(); String contextualName = convention.getContextualName(context); Assertions.assertEquals("com.example.TestService/testMethod", contextualName); }
@Override public short getTypeCode() { return MessageType.TYPE_REG_RM; }
@Test public void getTypeCode() { RegisterRMRequest registerRMRequest = new RegisterRMRequest(); assertThat(MessageType.TYPE_REG_RM).isEqualTo(registerRMRequest.getTypeCode()); }
public static synchronized RealtimeSegmentStatsHistory deserialzeFrom(File inFile) throws IOException, ClassNotFoundException { if (inFile.exists()) { try (FileInputStream is = new FileInputStream(inFile); ObjectInputStream obis = new CustomObjectInputStream(is)) { RealtimeSegmentStatsHistory history = (RealtimeSegmentStatsHistory) (obis.readObject()); history.normalize(); return history; } } else { return new RealtimeSegmentStatsHistory(inFile.getAbsolutePath()); } }
@Test public void testMultiThreadedUse() throws Exception { final int numThreads = 8; final int numIterations = 10; final long avgSleepTimeMs = 300; Thread[] threads = new Thread[numThreads]; final String tmpDir = System.getProperty("java.io.tmpdir"); File serializedFile = new File(tmpDir, STATS_FILE_NAME); FileUtils.deleteQuietly(serializedFile); serializedFile.deleteOnExit(); RealtimeSegmentStatsHistory statsHistory = RealtimeSegmentStatsHistory.deserialzeFrom(serializedFile); for (int i = 0; i < numThreads; i++) { threads[i] = new Thread(new StatsUpdater(statsHistory, numIterations, avgSleepTimeMs)); threads[i].start(); } for (int i = 0; i < numThreads; i++) { threads[i].join(); } FileUtils.deleteQuietly(serializedFile); }
public static OsInfo getOsInfo() { return Singleton.get(OsInfo.class); }
@Test public void getOsInfoTest() { final OsInfo osInfo = SystemUtil.getOsInfo(); assertNotNull(osInfo); Console.log(osInfo.getName()); }
public synchronized String get() { ConfidentialStore cs = ConfidentialStore.get(); if (secret == null || cs != lastCS) { lastCS = cs; try { byte[] payload = load(); if (payload == null) { payload = cs.randomBytes(length / 2); store(payload); } secret = Util.toHexString(payload).substring(0, length); } catch (IOException e) { throw new Error("Failed to load the key: " + getId(), e); } } return secret; }
@Test public void hexStringShouldProduceHexString() { HexStringConfidentialKey key = new HexStringConfidentialKey("test", 8); assertTrue(key.get().matches("[A-Fa-f0-9]{8}")); }
@Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { return inject(statement, new TopicProperties.Builder()); }
@Test public void shouldPassThroughWithClauseToBuilderForCreateAs() { // Given: givenStatement("CREATE STREAM x WITH (kafka_topic='topic') AS SELECT * FROM SOURCE;"); final CreateSourceAsProperties props = ((CreateAsSelect) statement.getStatement()) .getProperties(); // When: injector.inject(statement, builder); // Then: verify(builder).withWithClause( props.getKafkaTopic(), props.getPartitions(), props.getReplicas(), props.getRetentionInMillis() ); }
public SearchQuery parse(String encodedQueryString) { if (Strings.isNullOrEmpty(encodedQueryString) || "*".equals(encodedQueryString)) { return new SearchQuery(encodedQueryString); } final var queryString = URLDecoder.decode(encodedQueryString, StandardCharsets.UTF_8); final Matcher matcher = querySplitterMatcher(requireNonNull(queryString).trim()); final ImmutableMultimap.Builder<String, FieldValue> builder = ImmutableMultimap.builder(); final ImmutableSet.Builder<String> disallowedKeys = ImmutableSet.builder(); while (matcher.find()) { final String entry = matcher.group(); if (!entry.contains(":")) { builder.put(withPrefixIfNeeded(defaultField), createFieldValue(defaultFieldKey.getFieldType(), entry, false)); continue; } final Iterator<String> entryFields = FIELD_VALUE_SPLITTER.splitToList(entry).iterator(); checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); final String key = entryFields.next(); // Skip if there are no valid k/v pairs. (i.e. "action:") if (!entryFields.hasNext()) { continue; } final boolean negate = key.startsWith("-"); final String cleanKey = key.replaceFirst("^-", ""); final String value = entryFields.next(); VALUE_SPLITTER.splitToList(value).forEach(v -> { if (!dbFieldMapping.containsKey(cleanKey)) { disallowedKeys.add(cleanKey); } final SearchQueryField translatedKey = dbFieldMapping.get(cleanKey); if (translatedKey != null) { builder.put(withPrefixIfNeeded(translatedKey.getDbField()), createFieldValue(translatedKey.getFieldType(), v, negate)); } else { builder.put(withPrefixIfNeeded(defaultField), createFieldValue(defaultFieldKey.getFieldType(), v, negate)); } }); checkArgument(!entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); } return new SearchQuery(queryString, builder.build(), disallowedKeys.build()); }
@Test void booleanValuesSupported() { final SearchQueryParser parser = new SearchQueryParser("name", Map.of( "name", SearchQueryField.create("title", SearchQueryField.Type.STRING), "gone", SearchQueryField.create("disabled", SearchQueryField.Type.BOOLEAN) ) ); final SearchQuery searchQuery = parser.parse("gone:true"); assertEquals("gone:true", searchQuery.getQueryString()); final Multimap<String, SearchQueryParser.FieldValue> queryMap = searchQuery.getQueryMap(); assertThat(queryMap.keySet().size()).isEqualTo(1); assertThat(queryMap.keySet()).containsOnly("disabled"); //properly renamed assertThat(queryMap.get("disabled")) .containsOnly(new SearchQueryParser.FieldValue( true, //boolean true instead of "true" string! SearchQueryOperators.EQUALS, //equals instead of reqexp! false) ); }
@Inject public FileMergeCacheManager( CacheConfig cacheConfig, FileMergeCacheConfig fileMergeCacheConfig, CacheStats stats, ExecutorService cacheFlushExecutor, ExecutorService cacheRemovalExecutor, ScheduledExecutorService cacheSizeCalculateExecutor) { requireNonNull(cacheConfig, "directory is null"); this.cacheFlushExecutor = cacheFlushExecutor; this.cacheRemovalExecutor = cacheRemovalExecutor; this.cacheSizeCalculateExecutor = cacheSizeCalculateExecutor; this.cache = CacheBuilder.newBuilder() .maximumSize(fileMergeCacheConfig.getMaxCachedEntries()) .expireAfterAccess(fileMergeCacheConfig.getCacheTtl().toMillis(), MILLISECONDS) .removalListener(new CacheRemovalListener()) .recordStats() .build(); this.stats = requireNonNull(stats, "stats is null"); this.baseDirectory = new Path(cacheConfig.getBaseDirectory()); checkArgument(fileMergeCacheConfig.getMaxInMemoryCacheSize().toBytes() >= 0, "maxInflightBytes is negative"); this.maxInflightBytes = fileMergeCacheConfig.getMaxInMemoryCacheSize().toBytes(); File target = new File(baseDirectory.toUri()); if (!target.exists()) { try { Files.createDirectories(target.toPath()); } catch (IOException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "cannot create cache directory " + target, e); } } else { File[] files = target.listFiles(); if (files == null) { return; } this.cacheRemovalExecutor.submit(() -> Arrays.stream(files).forEach(file -> { try { Files.delete(file.toPath()); } catch (IOException e) { // ignore } })); } this.cacheSizeCalculateExecutor.scheduleAtFixedRate( () -> { try { cacheScopeFiles.keySet().forEach(cacheIdentifier -> cacheScopeSizeInBytes.put(cacheIdentifier, getCacheScopeSizeInBytes(cacheIdentifier))); cacheScopeSizeInBytes.keySet().removeIf(key -> !cacheScopeFiles.containsKey(key)); } catch (Throwable t) { log.error(t, "Error calculating cache size"); } }, 0, 15, TimeUnit.SECONDS); }
@Test(invocationCount = 10) public void testStress() throws ExecutionException, InterruptedException { CacheConfig cacheConfig = new CacheConfig().setBaseDirectory(cacheDirectory); FileMergeCacheConfig fileMergeCacheConfig = new FileMergeCacheConfig().setCacheTtl(new Duration(10, MILLISECONDS)); CacheManager cacheManager = fileMergeCacheManager(cacheConfig, fileMergeCacheConfig); stressTest(data, (position, buffer, offset, length) -> readFully(cacheManager, NO_CACHE_CONSTRAINTS, position, buffer, offset, length)); }
public static long getSeed(String streamId, long masterSeed) { MessageDigest md5 = md5Holder.get(); md5.reset(); //'/' : make sure that we don't get the same str from ('11',0) and ('1',10) // We could have fed the bytes of masterSeed one by one to md5.update() // instead String str = streamId + '/' + masterSeed; byte[] digest = md5.digest(str.getBytes(StandardCharsets.UTF_8)); // Create a long from the first 8 bytes of the digest // This is fine as MD5 has the avalanche property. // Paranoids could have XOR folded the other 8 bytes in too. long seed = 0; for (int i=0; i<8; i++) { seed = (seed<<8) + ((int)digest[i]+128); } return seed; }
@Test public void testSeedGeneration() { long masterSeed1 = 42; long masterSeed2 = 43; assertTrue("Deterministic seeding", getSeed("stream1", masterSeed1) == getSeed("stream1", masterSeed1)); assertTrue("Deterministic seeding", getSeed("stream2", masterSeed2) == getSeed("stream2", masterSeed2)); assertTrue("Different streams", getSeed("stream1", masterSeed1) != getSeed("stream2", masterSeed1)); assertTrue("Different master seeds", getSeed("stream1", masterSeed1) != getSeed("stream1", masterSeed2)); }
public int accumulateSum(int... nums) { LOGGER.info("Source module {}", VERSION); var sum = 0; for (final var num : nums) { sum += num; } return sum; }
@Test void testAccumulateSum() { assertEquals(0, source.accumulateSum(-1, 0, 1)); }
@Override public String getProcessNamespace(String fingerprint) { return CachedDigestUtils.sha256Hex(fingerprint + agentIdentifier.getUuid() + workingDirectory); }
@Test public void shouldReturnDigestOfMaterialFingerprintConcatinatedWithAgentUUID() { AgentIdentifier agentIdentifier = mock(AgentIdentifier.class); String uuid = "agent-uuid"; when(agentIdentifier.getUuid()).thenReturn(uuid); String fingerprint = "material-fingerprint"; String workingDirectory = "working-folder-full-path"; AgentSubprocessExecutionContext execCtx = new AgentSubprocessExecutionContext(agentIdentifier, workingDirectory); String workspaceName = execCtx.getProcessNamespace(fingerprint); assertThat(workspaceName, is(CachedDigestUtils.sha256Hex(fingerprint + uuid + workingDirectory))); assertThat(workspaceName.length(), is(64)); }
@Override public int start(int from) { Assert.notNull(this.text, "Text to find must be not null!"); final int limit = getValidEndIndex(); if(negative){ for (int i = from; i > limit; i--) { if (NumberUtil.equals(c, text.charAt(i), caseInsensitive)) { return i; } } } else{ for (int i = from; i < limit; i++) { if (NumberUtil.equals(c, text.charAt(i), caseInsensitive)) { return i; } } } return -1; }
@Test public void negativeStartTest(){ int start = new CharFinder('a').setText("cba123").setNegative(true).start(2); assertEquals(2, start); start = new CharFinder('2').setText("cba123").setNegative(true).start(2); assertEquals(-1, start); start = new CharFinder('c').setText("cba123").setNegative(true).start(2); assertEquals(0, start); }
public static List<Term> parse(Map<String, Object> map) { if (MapUtils.isEmpty(map)) { return Collections.emptyList(); } List<Term> terms = new ArrayList<>(map.size()); for (Map.Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); boolean isOr = false; Term term = new Term(); //嵌套 if (key.startsWith("$nest") || (isOr = key.startsWith("$orNest"))) { @SuppressWarnings("all") List<Term> nest = value instanceof Map ? parse(((Map<String, Object>) value)) : parse(String.valueOf(value)); term.setTerms(nest); } //普通 else { if (key.startsWith("$or$")) { isOr = true; key = key.substring(4); } term.setColumn(key); term.setValue(value); } if (isOr) { term.setType(Term.Type.or); } terms.add(term); } return terms; }
@Test public void testChinese() { { List<Term> terms = TermExpressionParser.parse("name = 我"); assertEquals(terms.get(0).getTermType(), TermType.eq); assertEquals(terms.get(0).getValue(),"我"); } { List<Term> terms = TermExpressionParser.parse("name like %我%"); assertEquals(terms.get(0).getTermType(), TermType.like); assertEquals(terms.get(0).getValue(),"%我%"); } }
public static boolean isValidDateFormatToStringDate( String dateFormat, String dateString ) { String detectedDateFormat = detectDateFormat( dateString ); if ( ( dateFormat != null ) && ( dateFormat.equals( detectedDateFormat ) ) ) { return true; } return false; }
@Test public void testIsValidDateFormatToStringDateLocale() { assertTrue( DateDetector.isValidDateFormatToStringDate( SAMPLE_DATE_FORMAT_US, SAMPLE_DATE_STRING_US, LOCALE_en_US ) ); assertFalse( DateDetector.isValidDateFormatToStringDate( null, SAMPLE_DATE_STRING, LOCALE_en_US ) ); assertFalse( DateDetector.isValidDateFormatToStringDate( SAMPLE_DATE_FORMAT_US, null, LOCALE_en_US ) ); assertTrue( DateDetector.isValidDateFormatToStringDate( SAMPLE_DATE_FORMAT_US, SAMPLE_DATE_STRING_US, null ) ); }
public BitList<Invoker<T>> getInvokers() { return invokers; }
@Test void tagRouterRuleParseTest() { String tagRouterRuleConfig = "---\n" + "force: false\n" + "runtime: true\n" + "enabled: false\n" + "priority: 1\n" + "key: demo-provider\n" + "tags:\n" + " - name: tag1\n" + " addresses: null\n" + " - name: tag2\n" + " addresses: [\"30.5.120.37:20880\"]\n" + " - name: tag3\n" + " addresses: []\n" + " - name: tag4\n" + " addresses: ~\n" + "..."; TagRouterRule tagRouterRule = TagRuleParser.parse(tagRouterRuleConfig); TagStateRouter<?> router = Mockito.mock(TagStateRouter.class); Mockito.when(router.getInvokers()).thenReturn(BitList.emptyList()); tagRouterRule.init(router); // assert tags assert tagRouterRule.getKey().equals("demo-provider"); assert tagRouterRule.getPriority() == 1; assert tagRouterRule.getTagNames().contains("tag1"); assert tagRouterRule.getTagNames().contains("tag2"); assert tagRouterRule.getTagNames().contains("tag3"); assert tagRouterRule.getTagNames().contains("tag4"); // assert addresses assert tagRouterRule.getAddresses().contains("30.5.120.37:20880"); assert tagRouterRule.getTagnameToAddresses().get("tag1") == null; assert tagRouterRule.getTagnameToAddresses().get("tag2").size() == 1; assert tagRouterRule.getTagnameToAddresses().get("tag3") == null; assert tagRouterRule.getTagnameToAddresses().get("tag4") == null; assert tagRouterRule.getAddresses().size() == 1; }
@Override public AssertionResult getResult(SampleResult response) { // no error as default AssertionResult result = new AssertionResult(getName()); result.setFailure(false); result.setFailureMessage(""); byte[] responseData = null; Document doc = null; try { if (isScopeVariable()){ String inputString=getThreadContext().getVariables().get(getVariableName()); if (!StringUtils.isEmpty(inputString)) { responseData = inputString.getBytes(StandardCharsets.UTF_8); } } else { responseData = response.getResponseData(); } if (responseData == null || responseData.length == 0) { return result.setResultForNull(); } if(log.isDebugEnabled()) { log.debug("Validation is set to {}, Whitespace is set to {}, Tolerant is set to {}", isValidating(), isWhitespace(), isTolerant()); } boolean isXML = JOrphanUtils.isXML(responseData); doc = XPathUtil.makeDocument(new ByteArrayInputStream(responseData), isValidating(), isWhitespace(), isNamespace(), isTolerant(), isQuiet(), showWarnings() , reportErrors(), isXML , isDownloadDTDs()); } catch (SAXException e) { log.debug("Caught sax exception.", e); result.setError(true); result.setFailureMessage("SAXException: " + e.getMessage()); return result; } catch (IOException e) { log.warn("Cannot parse result content.", e); result.setError(true); result.setFailureMessage("IOException: " + e.getMessage()); return result; } catch (ParserConfigurationException e) { log.warn("Cannot parse result content.", e); result.setError(true); result.setFailureMessage("ParserConfigurationException: " + e.getMessage()); return result; } catch (TidyException e) { result.setError(true); result.setFailureMessage(e.getMessage()); return result; } if (doc == null || doc.getDocumentElement() == null) { result.setError(true); result.setFailureMessage("Document is null, probably not parsable"); return result; } XPathUtil.computeAssertionResult(result, doc, getXPathString(), isNegated()); return result; }
@Test public void testAssertionBlankResult() throws Exception { result.setResponseData(" ", null); AssertionResult res = assertion.getResult(result); testLog.debug("isError() {} isFailure() {}", res.isError(), res.isFailure()); testLog.debug("failure message: {}", res.getFailureMessage()); assertTrue(res.getFailureMessage().indexOf("Premature end of file") > 0); assertTrue(res.isError(), "Should be an error"); assertFalse(res.isFailure(), "Should not be a failure"); }
static void unTarUsingJava(File inFile, File untarDir, boolean gzipped) throws IOException { InputStream inputStream = null; TarArchiveInputStream tis = null; try { if (gzipped) { inputStream = new GZIPInputStream(Files.newInputStream(inFile.toPath())); } else { inputStream = Files.newInputStream(inFile.toPath()); } inputStream = new BufferedInputStream(inputStream); tis = new TarArchiveInputStream(inputStream); for (TarArchiveEntry entry = tis.getNextTarEntry(); entry != null;) { unpackEntries(tis, entry, untarDir); entry = tis.getNextTarEntry(); } } finally { IOUtils.cleanupWithLogger(LOG, tis, inputStream); } }
@Test(expected = IOException.class) public void testCreateArbitrarySymlinkUsingJava() throws IOException { final File simpleTar = new File(del, FILE); OutputStream os = new FileOutputStream(simpleTar); File rootDir = new File("tmp"); try (TarArchiveOutputStream tos = new TarArchiveOutputStream(os)) { tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); // Create arbitrary dir File arbitraryDir = new File(rootDir, "arbitrary-dir/"); Verify.mkdirs(arbitraryDir); // We will tar from the tar-root lineage File tarRoot = new File(rootDir, "tar-root/"); File symlinkRoot = new File(tarRoot, "dir1/"); Verify.mkdirs(symlinkRoot); // Create Symbolic Link to an arbitrary dir java.nio.file.Path symLink = Paths.get(symlinkRoot.getPath(), "sl"); Files.createSymbolicLink(symLink, arbitraryDir.toPath().toAbsolutePath()); // Put entries in tar file putEntriesInTar(tos, tarRoot); putEntriesInTar(tos, new File(symLink.toFile(), "dir-outside-tar-root/")); tos.close(); // Untar using Java File untarFile = new File(rootDir, "extracted"); FileUtil.unTarUsingJava(simpleTar, untarFile, false); } finally { FileUtils.deleteDirectory(rootDir); } }
@Override public void execute(Context context) { editionProvider.get().ifPresent(edition -> { if (!edition.equals(EditionProvider.Edition.COMMUNITY)) { return; } Map<String, Integer> filesPerLanguage = reportReader.readMetadata().getNotAnalyzedFilesByLanguageMap() .entrySet() .stream() .filter(entry -> entry.getValue() > 0) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); if (filesPerLanguage.isEmpty()) { return; } ceTaskMessages.add(constructMessage(filesPerLanguage)); computeMeasures(filesPerLanguage); }); }
@Test public void adds_warning_and_measures_in_SQ_community_edition_if_there_are_c_files() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); reportReader.setMetadata(ScannerReport.Metadata.newBuilder() .putNotAnalyzedFilesByLanguage("C", 10) .build()); underTest.execute(new TestComputationStepContext()); verify(ceTaskMessages, times(1)).add(argumentCaptor.capture()); List<CeTaskMessages.Message> messages = argumentCaptor.getAllValues(); assertThat(messages).extracting(CeTaskMessages.Message::getText).containsExactly( "10 unanalyzed C files were detected in this project during the last analysis. C cannot be analyzed with your current SonarQube edition. Please" + " consider <a target=\"_blank\" href=\"https://www.sonarsource.com/plans-and-pricing/developer/?referrer=sonarqube-cpp\">upgrading to Developer" + " Edition</a> to find Bugs, Code Smells, Vulnerabilities and Security Hotspots in this file."); assertThat(measureRepository.getAddedRawMeasure(PROJECT_REF, UNANALYZED_C_KEY).get().getIntValue()).isEqualTo(10); assertThat(measureRepository.getAddedRawMeasure(PROJECT_REF, UNANALYZED_CPP_KEY)).isEmpty(); }
public SecretStore load(SecureConfig secureConfig) { return doIt(MODE.LOAD, secureConfig); }
@Test public void testAlternativeImplementationInvalid() { SecureConfig secureConfig = new SecureConfig(); secureConfig.add("keystore.classname", "junk".toCharArray()); assertThrows(SecretStoreException.ImplementationNotFoundException.class, () -> { secretStoreFactory.load(secureConfig); }); }
public Properties getProperties() { return properties; }
@Test public void testUriWithSslEnabledPassword() throws SQLException { PrestoDriverUri parameters = createDriverUri("presto://localhost:8080/blackhole?SSL=true&SSLTrustStorePath=truststore.jks&SSLTrustStorePassword=password"); assertUriPortScheme(parameters, 8080, "https"); Properties properties = parameters.getProperties(); assertEquals(properties.getProperty(SSL_TRUST_STORE_PATH.getKey()), "truststore.jks"); assertEquals(properties.getProperty(SSL_TRUST_STORE_PASSWORD.getKey()), "password"); }
static Map<String, String> toMap(List<Settings.Setting> settingsList) { Map<String, String> result = new LinkedHashMap<>(); for (Settings.Setting s : settingsList) { // we need the "*.file.suffixes" and "*.file.patterns" properties for language detection // see DefaultLanguagesRepository.populateFileSuffixesAndPatterns() if (!s.getInherited() || s.getKey().endsWith(".file.suffixes") || s.getKey().endsWith(".file.patterns")) { switch (s.getValueOneOfCase()) { case VALUE: result.put(s.getKey(), s.getValue()); break; case VALUES: result.put(s.getKey(), s.getValues().getValuesList().stream().map(StringEscapeUtils::escapeCsv).collect(Collectors.joining(","))); break; case FIELDVALUES: convertPropertySetToProps(result, s); break; default: if (!s.getKey().endsWith(".secured")) { throw new IllegalStateException("Unknown property value for " + s.getKey()); } } } } return result; }
@Test public void should_always_load_language_detection_properties() { assertThat(AbstractSettingsLoader.toMap(List.of( Setting.newBuilder() .setInherited(false) .setKey("sonar.xoo.file.suffixes") .setValues(Values.newBuilder().addValues(".xoo")).build(), Setting.newBuilder() .setInherited(false) .setKey("sonar.xoo.file.patterns") .setValues(Values.newBuilder().addValues("Xoofile")).build() ))).containsExactly( entry("sonar.xoo.file.suffixes", ".xoo"), entry("sonar.xoo.file.patterns", "Xoofile") ); }
public static boolean testURLPassesExclude(String url, String exclude) { // If the url doesn't decode to UTF-8 then return false, it could be trying to get around our rules with nonstandard encoding // If the exclude rule includes a "?" character, the url must exactly match the exclude rule. // If the exclude rule does not contain the "?" character, we chop off everything starting at the first "?" // in the URL and then the resulting url must exactly match the exclude rule. If the exclude ends with a "*" // (wildcard) character, and wildcards are allowed in excludes, then the URL is allowed if it exactly // matches everything before the * and there are no ".." even encoded ones characters after the "*". String decodedUrl = null; try { decodedUrl = URLDecoder.decode(url, "UTF-8"); } catch (Exception e) { return false; } if (exclude.endsWith("*") && ALLOW_WILDCARDS_IN_EXCLUDES.getValue()) { if (url.startsWith(exclude.substring(0, exclude.length()-1))) { // Now make sure that there are no ".." characters in the rest of the URL. if (!decodedUrl.contains("..")) { return true; } } } else if (exclude.contains("?")) { if (url.equals(exclude)) { return true; } } else { int paramIndex = url.indexOf("?"); if (paramIndex != -1) { url = url.substring(0, paramIndex); } if (url.equals(exclude)) { return true; } } return false; }
@Test public void pathTraversalDetectedWhenWildcardsNotAllowed() throws Exception { AuthCheckFilter.ALLOW_WILDCARDS_IN_EXCLUDES.setValue(false); assertFalse(AuthCheckFilter.testURLPassesExclude("setup/setup-/../../log.jsp?log=info&mode=asc&lines=All","setup/setup-*")); assertFalse(AuthCheckFilter.testURLPassesExclude("setup/setup-/%2E%2E/%2E%2E/log.jsp?log=info&mode=asc&lines=All","setup/setup-*")); assertFalse(AuthCheckFilter.testURLPassesExclude("setup/setup-s/%u002e%u002e/%u002e%u002e/log.jsp?log=info&mode=asc&lines=All", "setup/setup-*")); }
public static String parseInstanceIdFromEndpoint(String endpoint) { if (StringUtils.isEmpty(endpoint)) { return null; } return endpoint.substring(endpoint.lastIndexOf("/") + 1, endpoint.indexOf('.')); }
@Test public void testParseInstanceIdFromEndpoint() { assertThat(NameServerAddressUtils.parseInstanceIdFromEndpoint(endpoint3)).isEqualTo( "MQ_INST_123456789_BXXUzaee"); assertThat(NameServerAddressUtils.parseInstanceIdFromEndpoint(endpoint4)).isEqualTo( "MQ_INST_123456789_BXXUzaee"); }
@Override protected void validateDataImpl(TenantId tenantId, TbResource resource) { validateString("Resource title", resource.getTitle()); if (resource.getTenantId() == null) { resource.setTenantId(TenantId.SYS_TENANT_ID); } if (!resource.getTenantId().isSysTenantId()) { if (!tenantService.tenantExists(resource.getTenantId())) { throw new DataValidationException("Resource is referencing to non-existent tenant!"); } } if (resource.getResourceType() == null) { throw new DataValidationException("Resource type should be specified!"); } if (resource.getData() != null) { validateResourceSize(resource.getTenantId(), resource.getId(), resource.getData().length); } if (StringUtils.isEmpty(resource.getFileName())) { throw new DataValidationException("Resource file name should be specified!"); } if (StringUtils.containsAny(resource.getFileName(), "/", "\\")) { throw new DataValidationException("File name contains forbidden symbols"); } if (StringUtils.isEmpty(resource.getResourceKey())) { throw new DataValidationException("Resource key should be specified!"); } }
@Test void testValidateNameInvocation() { TbResource resource = new TbResource(); resource.setTitle("rss"); resource.setResourceType(ResourceType.PKCS_12); resource.setFileName("cert.pem"); resource.setResourceKey("19_1.0"); resource.setTenantId(tenantId); validator.validateDataImpl(tenantId, resource); verify(validator).validateString("Resource title", resource.getTitle()); }
@Override public SelLong assignOps(SelOp op, SelType rhs) { SelTypeUtil.checkTypeMatch(this.type(), rhs.type()); long another = ((SelLong) rhs).val; switch (op) { case ASSIGN: this.val = another; // direct assignment return this; case ADD_ASSIGN: this.val += another; return this; case SUB_ASSIGN: this.val -= another; return this; case MUL_ASSIGN: this.val *= another; return this; case DIV_ASSIGN: this.val /= another; return this; case MOD_ASSIGN: this.val %= another; return this; default: throw new UnsupportedOperationException( "int/Integer/long/Long DO NOT support assignment operation " + op); } }
@Test(expected = UnsupportedOperationException.class) public void testInvalidAssignOpType() { orig.assignOps(SelOp.EQUAL, orig); }
@Deprecated public String javaUnbox(Schema schema) { return javaUnbox(schema, false); }
@Test void javaUnboxDateTime() throws Exception { SpecificCompiler compiler = createCompiler(); Schema dateSchema = LogicalTypes.date().addToSchema(Schema.create(Schema.Type.INT)); Schema timeSchema = LogicalTypes.timeMillis().addToSchema(Schema.create(Schema.Type.INT)); Schema timestampSchema = LogicalTypes.timestampMillis().addToSchema(Schema.create(Schema.Type.LONG)); // Date/time types should always use upper level java classes, even though // their underlying representations are primitive types assertEquals("java.time.LocalDate", compiler.javaUnbox(dateSchema, false), "Should use java.time.LocalDate for date type"); assertEquals("java.time.LocalTime", compiler.javaUnbox(timeSchema, false), "Should use java.time.LocalTime for time-millis type"); assertEquals("java.time.Instant", compiler.javaUnbox(timestampSchema, false), "Should use java.time.Instant for timestamp-millis type"); }
@Bean public MetaDataHandler divideMetaDataHandler() { return new DivideMetaDataHandler(); }
@Test public void testDivideMetaDataHandler() { applicationContextRunner.run(context -> { MetaDataHandler handler = context.getBean("divideMetaDataHandler", MetaDataHandler.class); assertNotNull(handler); } ); }
@Override public void merge(ColumnStatisticsObj aggregateColStats, ColumnStatisticsObj newColStats) { LOG.debug("Merging statistics: [aggregateColStats:{}, newColStats: {}]", aggregateColStats, newColStats); LongColumnStatsDataInspector aggregateData = longInspectorFromStats(aggregateColStats); LongColumnStatsDataInspector newData = longInspectorFromStats(newColStats); Long lowValue = mergeLowValue(getLowValue(aggregateData), getLowValue(newData)); if (lowValue != null) { aggregateData.setLowValue(lowValue); } Long highValue = mergeHighValue(getHighValue(aggregateData), getHighValue(newData)); if (highValue != null) { aggregateData.setHighValue(highValue); } aggregateData.setNumNulls(mergeNumNulls(aggregateData.getNumNulls(), newData.getNumNulls())); NumDistinctValueEstimator oldNDVEst = aggregateData.getNdvEstimator(); NumDistinctValueEstimator newNDVEst = newData.getNdvEstimator(); List<NumDistinctValueEstimator> ndvEstimatorsList = Arrays.asList(oldNDVEst, newNDVEst); aggregateData.setNumDVs(mergeNumDistinctValueEstimator(aggregateColStats.getColName(), ndvEstimatorsList, aggregateData.getNumDVs(), newData.getNumDVs())); aggregateData.setNdvEstimator(ndvEstimatorsList.get(0)); KllHistogramEstimator oldKllEst = aggregateData.getHistogramEstimator(); KllHistogramEstimator newKllEst = newData.getHistogramEstimator(); aggregateData.setHistogramEstimator(mergeHistogramEstimator(aggregateColStats.getColName(), oldKllEst, newKllEst)); aggregateColStats.getStatsData().setLongStats(aggregateData); }
@Test public void testMergeNullWithNonNullValues() { ColumnStatisticsObj aggrObj = createColumnStatisticsObj(new ColStatsBuilder<>(long.class) .low(null) .high(null) .numNulls(0) .numDVs(0) .build()); ColumnStatisticsObj newObj = createColumnStatisticsObj(new ColStatsBuilder<>(long.class) .low(1L) .high(3L) .numNulls(4) .numDVs(2) .hll(1, 3, 3) .kll(1, 3, 3) .build()); merger.merge(aggrObj, newObj); ColumnStatisticsData expectedColumnStatisticsData = new ColStatsBuilder<>(long.class) .low(1L) .high(3L) .numNulls(4) .numDVs(2) .hll(1, 3, 3) .kll(1, 3, 3) .build(); assertEquals(expectedColumnStatisticsData, aggrObj.getStatsData()); }
void visit(final PathItem.HttpMethod method, final Operation operation, final PathItem pathItem) { if (filter.accept(operation.getOperationId())) { final String methodName = method.name().toLowerCase(); emitter.emit(methodName, path); emit("id", operation.getOperationId()); emit("description", operation.getDescription()); Set<String> operationLevelConsumes = new LinkedHashSet<>(); if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) { operationLevelConsumes.addAll(operation.getRequestBody().getContent().keySet()); } emit("consumes", operationLevelConsumes); Set<String> operationLevelProduces = new LinkedHashSet<>(); if (operation.getResponses() != null) { for (ApiResponse response : operation.getResponses().values()) { if (response.getContent() != null) { operationLevelProduces.addAll(response.getContent().keySet()); } } ApiResponse response = operation.getResponses().get(ApiResponses.DEFAULT); if (response != null && response.getContent() != null) { operationLevelProduces.addAll(response.getContent().keySet()); } } emit("produces", operationLevelProduces); if (ObjectHelper.isNotEmpty(operation.getParameters())) { operation.getParameters().forEach(this::emit); } if (ObjectHelper.isNotEmpty(pathItem.getParameters())) { pathItem.getParameters().forEach(this::emit); } emitOperation(operation); emitter.emit("to", destinationGenerator.generateDestinationFor(operation)); } }
@Test public void shouldEmitCodeForOas32ParameterInPath() { final Builder method = MethodSpec.methodBuilder("configure"); final MethodBodySourceCodeEmitter emitter = new MethodBodySourceCodeEmitter(method); final OperationVisitor<?> visitor = new OperationVisitor<>( emitter, new OperationFilter(), "/path/{param}", new DefaultDestinationGenerator(), null); final OpenAPI document = new OpenAPI(); final Paths paths = new Paths(); final PathItem path = new PathItem(); paths.addPathItem("/path/{param}", path); final Operation operation = new Operation(); final Parameter parameter = new Parameter(); parameter.setName("param"); parameter.setIn("path"); path.addParametersItem(parameter); document.setPaths(paths); visitor.visit(PathItem.HttpMethod.GET, operation, path); assertThat(method.build().toString()).isEqualTo("void configure() {\n" + " get(\"/path/{param}\")\n" + " .param()\n" + " .name(\"param\")\n" + " .type(org.apache.camel.model.rest.RestParamType.path)\n" + " .required(true)\n" + " .endParam()\n" + " .to(\"direct:rest1\")\n" + " }\n"); }
@Override public String forDisplay() { return value; }
@Test public void shouldReturnStringValueForReporting() { assertThat(argument.forDisplay(), is("test")); }
public int getCheckUserAccessToQueueFailedRetrieved() { return numCheckUserAccessToQueueFailedRetrieved.value(); }
@Test public void testCheckUserAccessToQueueRetrievedFailed() { long totalBadBefore = metrics.getCheckUserAccessToQueueFailedRetrieved(); badSubCluster.getCheckUserAccessToQueueFailed(); Assert.assertEquals(totalBadBefore + 1, metrics.getCheckUserAccessToQueueFailedRetrieved()); }
public void processVerstrekkingAanAfnemer(VerstrekkingAanAfnemer verstrekkingAanAfnemer){ if (logger.isDebugEnabled()) logger.debug("Processing verstrekkingAanAfnemer: {}", marshallElement(verstrekkingAanAfnemer)); Afnemersbericht afnemersbericht = afnemersberichtRepository.findByOnzeReferentie(verstrekkingAanAfnemer.getReferentieId()); if(mismatch(verstrekkingAanAfnemer, afnemersbericht)){ digidXClient.remoteLogBericht(Log.NO_RELATION_TO_SENT_MESSAGE, verstrekkingAanAfnemer, afnemersbericht); return; } switch (verstrekkingAanAfnemer.getGebeurtenissoort().getNaam()) { case "Null" -> { logger.info("Start processing Null message"); dglResponseService.processNullMessage(verstrekkingAanAfnemer.getGebeurtenisinhoud().getNull(), afnemersbericht); digidXClient.remoteLogWithoutRelatingToAccount(Log.MESSAGE_PROCESSED, "Null"); } case "Ag01" -> { logger.info("Start processing Ag01 message"); dglResponseService.processAg01(verstrekkingAanAfnemer.getGebeurtenisinhoud().getAg01(), afnemersbericht); digidXClient.remoteLogBericht(Log.MESSAGE_PROCESSED, verstrekkingAanAfnemer, afnemersbericht); } case "Ag31" -> { logger.info("Start processing Ag31 message"); dglResponseService.processAg31(verstrekkingAanAfnemer.getGebeurtenisinhoud().getAg31(), afnemersbericht); digidXClient.remoteLogBericht(Log.MESSAGE_PROCESSED, verstrekkingAanAfnemer, afnemersbericht); } case "Af01" -> { logger.info("Start processing Af01 message"); dglResponseService.processAf01(verstrekkingAanAfnemer.getGebeurtenisinhoud().getAf01(), afnemersbericht); digidXClient.remoteLogBericht(Log.MESSAGE_PROCESSED, verstrekkingAanAfnemer, afnemersbericht); } case "Af11" -> { logger.info("Start processing Af11 message"); dglResponseService.processAf11(verstrekkingAanAfnemer.getGebeurtenisinhoud().getAf11(), afnemersbericht); digidXClient.remoteLogWithoutRelatingToAccount(Log.MESSAGE_PROCESSED, "Af11"); } case "Gv01" -> { logger.info("Start processing Gv01 message"); Gv01 gv01 = verstrekkingAanAfnemer.getGebeurtenisinhoud().getGv01(); dglResponseService.processGv01(gv01); String bsn = CategorieUtil.findBsnOudeWaarde(gv01.getCategorie()); if (bsn == null) { bsn = CategorieUtil.findBsn(gv01.getCategorie()); } digidXClient.remoteLogSpontaneVerstrekking(Log.MESSAGE_PROCESSED, "Gv01", gv01.getANummer(), bsn); } case "Ng01" -> { logger.info("Start processing Ng01 message"); Ng01 ng01 = verstrekkingAanAfnemer.getGebeurtenisinhoud().getNg01(); dglResponseService.processNg01(ng01); digidXClient.remoteLogSpontaneVerstrekking(Log.MESSAGE_PROCESSED, "Ng01", CategorieUtil.findANummer(ng01.getCategorie()), ""); } case "Wa11" -> { logger.info("Start processing Wa11 message"); dglResponseService.processWa11(verstrekkingAanAfnemer.getGebeurtenisinhoud().getWa11()); } } }
@Test public void testProcessAf01(){ String testBsn = "SSSSSSSSS"; Af01 testAf01 = TestDglMessagesUtil.createTestAf01(testBsn); VerstrekkingInhoudType inhoudType = new VerstrekkingInhoudType(); inhoudType.setAf01(testAf01); GeversioneerdType type = new GeversioneerdType(); type.setNaam("Af01"); when(verstrekkingAanAfnemer.getReferentieId()).thenReturn("referentieId"); when(afnemersberichtRepository.findByOnzeReferentie("referentieId")).thenReturn(afnemersbericht); when(verstrekkingAanAfnemer.getGebeurtenissoort()).thenReturn(type); when(verstrekkingAanAfnemer.getGebeurtenisinhoud()).thenReturn(inhoudType); when(afnemersbericht.getBsn()).thenReturn(testBsn); classUnderTest.processVerstrekkingAanAfnemer(verstrekkingAanAfnemer); verify(dglResponseService, times(1)).processAf01(testAf01, afnemersbericht); }
public static RawPrivateTransaction decode(final String hexTransaction) { final byte[] transaction = Numeric.hexStringToByteArray(hexTransaction); final TransactionType transactionType = getPrivateTransactionType(transaction); if (transactionType == TransactionType.EIP1559) { return decodePrivateTransaction1559(transaction); } return decodeLegacyPrivateTransaction(transaction); }
@Test public void testDecodingSigned() throws Exception { final BigInteger nonce = BigInteger.ZERO; final BigInteger gasPrice = BigInteger.ONE; final BigInteger gasLimit = BigInteger.TEN; final String to = "0x0add5355"; final RawPrivateTransaction rawTransaction = RawPrivateTransaction.createTransaction( nonce, gasPrice, gasLimit, to, "", MOCK_ENCLAVE_KEY, MOCK_PRIVATE_FOR, RESTRICTED); final String privateKey = "8f2a55949038a9610f50fb23b5883af3b4ecb3c3bb792cbcefbd1542c692be63"; final Credentials credentials = Credentials.create(privateKey); final byte[] encodedMessage = PrivateTransactionEncoder.signMessage(rawTransaction, credentials); final String hexMessage = Numeric.toHexString(encodedMessage); final RawPrivateTransaction result = PrivateTransactionDecoder.decode(hexMessage); assertNotNull(result); assertEquals(nonce, result.getNonce()); assertEquals(gasPrice, result.getGasPrice()); assertEquals(gasLimit, result.getGasLimit()); assertEquals(to, result.getTo()); assertEquals("", result.getData()); assertEquals(MOCK_ENCLAVE_KEY, result.getPrivateFrom()); assertEquals(MOCK_PRIVATE_FOR, result.getPrivateFor().get()); assertEquals(RESTRICTED, result.getRestriction()); assertTrue(result instanceof SignedRawPrivateTransaction); final SignedRawPrivateTransaction signedResult = (SignedRawPrivateTransaction) result; assertNotNull(signedResult.getSignatureData()); Sign.SignatureData signatureData = signedResult.getSignatureData(); final byte[] encodedTransaction = PrivateTransactionEncoder.encode(rawTransaction); final BigInteger key = Sign.signedMessageToKey(encodedTransaction, signatureData); assertEquals(key, credentials.getEcKeyPair().getPublicKey()); assertEquals(credentials.getAddress(), signedResult.getFrom()); signedResult.verify(credentials.getAddress()); assertNull(signedResult.getChainId()); }
protected Request buildRequest(String url, String sender, String data) throws JsonProcessingException { if (sender == null || !WalletUtils.isValidAddress(sender)) { throw new EnsResolutionException("Sender address is null or not valid"); } if (data == null) { throw new EnsResolutionException("Data is null"); } if (!url.contains("{sender}")) { throw new EnsResolutionException("Url is not valid, sender parameter is not exist"); } // URL expansion String href = url.replace("{sender}", sender).replace("{data}", data); Request.Builder builder = new Request.Builder().url(href); if (url.contains("{data}")) { return builder.get().build(); } else { EnsGatewayRequestDTO requestDTO = new EnsGatewayRequestDTO(data); ObjectMapper om = ObjectMapperFactory.getObjectMapper(); return builder.post(RequestBody.create(om.writeValueAsString(requestDTO), JSON)) .addHeader("Content-Type", "application/json") .build(); } }
@Test void buildRequestWhenPostSuccessTest() throws IOException { String url = "https://example.com/gateway/{sender}.json"; String sender = "0x226159d592E2b063810a10Ebf6dcbADA94Ed68b8"; String data = "0xd5fa2b00"; okhttp3.Request request = ensResolver.buildRequest(url, sender, data); assertNotNull(request); assertNotNull(request.url()); assertNotNull(request.body()); assertEquals("POST", request.method()); assertEquals( "https://example.com/gateway/0x226159d592E2b063810a10Ebf6dcbADA94Ed68b8.json", request.url().url().toString()); }
@Override public ScalarOperator visitCaseWhenOperator(CaseWhenOperator operator, Void context) { return shuttleIfUpdate(operator); }
@Test void visitCaseWhenOperator() { CaseWhenOperator operator = new CaseWhenOperator(INT, null, null, ImmutableList.of()); { ScalarOperator newOperator = shuttle.visitCaseWhenOperator(operator, null); assertEquals(operator, newOperator); } { ScalarOperator newOperator = shuttle2.visitCaseWhenOperator(operator, null); assertEquals(operator, newOperator); } }
@Override public void getConfig(StorServerConfig.Builder builder) { super.getConfig(builder); provider.getConfig(builder); }
@Test void testPortOverride() { StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder(); DistributorCluster cluster = parse("<cluster id=\"storage\" distributor-base-port=\"14065\">" + " <redundancy>3</redundancy>" + " <documents/>" + " <group>" + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" + " </group>" + "</cluster>"); cluster.getChildren().get("0").getConfig(builder); StorCommunicationmanagerConfig config = new StorCommunicationmanagerConfig(builder); assertEquals(14066, config.rpcport()); }
public ExitStatus(Options options) { this.options = options; }
@Test void with_passed_scenarios() { createRuntime(); bus.send(testCaseFinishedWithStatus(Status.PASSED)); assertThat(exitStatus.exitStatus(), is(equalTo((byte) 0x0))); }
@Override public void execute(ComputationStep.Context context) { new PathAwareCrawler<>( FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) .buildFor( Iterables.concat(NewLinesAndConditionsCoverageFormula.from(newLinesRepository, reportReader), FORMULAS))) .visit(treeRootHolder.getRoot()); }
@Test public void no_measure_for_PROJECT_component() { treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, ROOT_REF).build()); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.isEmpty()).isTrue(); }
@ApiOperation("更新功能按钮资源") @PutMapping("/{actionId}") public ApiResult update(@PathVariable Long actionId, @Validated @RequestBody ActionForm actionForm){ actionForm.setActionId(actionId); baseActionService.updateAction(actionForm); return ApiResult.success(); }
@Test void update() { }
public void triggerRun() { call( new PostRequest(path()) ); }
@Test public void triggerRun_whenTriggered_shouldNotFail() { assertThatNoException().isThrownBy(() ->gitlabSynchronizationRunService.triggerRun()); }
@Override public CompletableFuture<String> triggerSavepoint( @Nullable String targetDirectory, boolean cancelJob, SavepointFormatType formatType) { return state.tryCall( StateWithExecutionGraph.class, stateWithExecutionGraph -> { if (isAnyOutputBlocking(stateWithExecutionGraph.getExecutionGraph())) { return FutureUtils.<String>completedExceptionally( new CheckpointException( CheckpointFailureReason.BLOCKING_OUTPUT_EXIST)); } return stateWithExecutionGraph.triggerSavepoint( targetDirectory, cancelJob, formatType); }, "triggerSavepoint") .orElse( FutureUtils.completedExceptionally( new CheckpointException( "The Flink job is currently not executing.", CheckpointFailureReason.TRIGGER_CHECKPOINT_FAILURE))); }
@Test void testStopWithSavepointFailsInIllegalState() throws Exception { final AdaptiveScheduler scheduler = new AdaptiveSchedulerBuilder( createJobGraph(), mainThreadExecutor, EXECUTOR_RESOURCE.getExecutor()) .build(); assertThatFuture( scheduler.triggerSavepoint( "some directory", false, SavepointFormatType.CANONICAL)) .eventuallyFailsWith(ExecutionException.class) .withCauseInstanceOf(CheckpointException.class); }
@Deprecated public static String getJwt(JwtClaims claims) throws JoseException { String jwt; RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey( jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName()); // A JWT is a JWS and/or a JWE with JSON claims as the payload. // In this example it is a JWS nested inside a JWE // So we first create a JsonWebSignature object. JsonWebSignature jws = new JsonWebSignature(); // The payload of the JWS is JSON content of the JWT Claims jws.setPayload(claims.toJson()); // The JWT is signed using the sender's private key jws.setKey(privateKey); // Get provider from security config file, it should be two digit // And the provider id will set as prefix for keyid in the token header, for example: 05100 // if there is no provider id, we use "00" for the default value String provider_id = ""; if (jwtConfig.getProviderId() != null) { provider_id = jwtConfig.getProviderId(); if (provider_id.length() == 1) { provider_id = "0" + provider_id; } else if (provider_id.length() > 2) { logger.error("provider_id defined in the security.yml file is invalid; the length should be 2"); provider_id = provider_id.substring(0, 2); } } jws.setKeyIdHeaderValue(provider_id + jwtConfig.getKey().getKid()); // Set the signature algorithm on the JWT/JWS that will integrity protect the claims jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256); // Sign the JWS and produce the compact serialization, which will be the inner JWT/JWS // representation, which is a string consisting of three dot ('.') separated // base64url-encoded parts in the form Header.Payload.Signature jwt = jws.getCompactSerialization(); return jwt; }
@Test public void longlivedCcPetstoreScpString() throws Exception { JwtClaims claims = ClaimsUtil.getTestCcClaimsScopeScp("f7d42348-c647-4efb-a52d-4c5787421e73", "write:pets read:pets"); claims.setExpirationTimeMinutesInTheFuture(5256000); String jwt = JwtIssuer.getJwt(claims, long_kid, KeyUtil.deserializePrivateKey(long_key, KeyUtil.RSA)); System.out.println("***Long lived token for portal lightapi***: " + jwt); }
public String readWPString(int length) throws IOException { char[] chars = new char[length]; for (int i = 0; i < length; i++) { int c = in.read(); if (c == -1) { throw new EOFException(); } chars[i] = (char) c; } return new String(chars); }
@Test public void testReadString() throws Exception { try (WPInputStream wpInputStream = emptyWPStream()) { wpInputStream.readWPString(10); fail("should have thrown EOF"); } catch (EOFException e) { //swallow } }
public static <T, R> CheckedFunction0<R> andThen(CheckedFunction0<T> function, CheckedFunction2<T, Throwable, R> handler) { return () -> { try { return handler.apply(function.apply(), null); } catch (Throwable throwable) { return handler.apply(null, throwable); } }; }
@Test public void shouldRecoverFromResult() throws Throwable { CheckedFunction0<String> callable = () -> "Wrong Result"; CheckedFunction0<String> callableWithRecovery = VavrCheckedFunctionUtils.andThen(callable, (result, ex) -> { if(result.equals("Wrong Result")){ return "Bla"; } return result; }); String result = callableWithRecovery.apply(); assertThat(result).isEqualTo("Bla"); }
public String run() throws IOException { Process process = new ProcessBuilder(mCommand).redirectErrorStream(true).start(); BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.defaultCharset())); try { // read the output of the command StringBuilder output = new StringBuilder(); String line = inReader.readLine(); while (line != null) { output.append(line); output.append("\n"); line = inReader.readLine(); } // wait for the process to finish and check the exit code int exitCode = process.waitFor(); if (exitCode != 0) { throw new ShellUtils.ExitCodeException(exitCode, output.toString()); } return output.toString(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } finally { // close the input stream try { // JDK 7 tries to automatically drain the input streams for us // when the process exits, but since close is not synchronized, // it creates a race if we close the stream first and the same // fd is recycled. the stream draining thread will attempt to // drain that fd!! it may block, OOM, or cause bizarre behavior // see: https://bugs.openjdk.java.net/browse/JDK-8024521 // issue is fixed in build 7u60 InputStream stdout = process.getInputStream(); synchronized (stdout) { inReader.close(); } } catch (IOException e) { LOG.warn(String.format("Error while closing the input stream of process %s: %s", process, e.getMessage())); } process.destroy(); } }
@Test public void execCommandFail() throws Exception { mExceptionRule.expect(ShellUtils.ExitCodeException.class); // run a command that guarantees to fail String[] cmd = new String[]{"bash", "-c", "false"}; String result = new ShellCommand(cmd).run(); assertEquals("false\n", result); }
public String doGetConfig(HttpServletRequest request, HttpServletResponse response, String dataId, String group, String tenant, String tag, String isNotify, String clientIp) throws IOException, ServletException { return doGetConfig(request, response, dataId, group, tenant, tag, isNotify, clientIp, false); }
@Test void testDoGetConfigNotExist() throws Exception { // if lockResult equals 0,cache item not exist. configCacheServiceMockedStatic.when(() -> ConfigCacheService.tryConfigReadLock(anyString())).thenReturn(0); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); String actualValue = configServletInner.doGetConfig(request, response, "test", "test", "test", "test", "true", "localhost"); assertEquals(HttpServletResponse.SC_NOT_FOUND + "", actualValue); configCacheServiceMockedStatic.when(() -> ConfigCacheService.getContentCache(GroupKey2.getKey("test", "test", "test"))) .thenReturn(new CacheItem(GroupKey2.getKey("test", "test", "test"))); // if lockResult less than 0 configCacheServiceMockedStatic.when(() -> ConfigCacheService.tryConfigReadLock(anyString())).thenReturn(-1); actualValue = configServletInner.doGetConfig(request, response, "test", "test", "test", "test", "true", "localhost"); assertEquals(HttpServletResponse.SC_CONFLICT + "", actualValue); }
public void tick() { // The main loop does two primary things: 1) drive the group membership protocol, responding to rebalance events // as they occur, and 2) handle external requests targeted at the leader. All the "real" work of the herder is // performed in this thread, which keeps synchronization straightforward at the cost of some operations possibly // blocking up this thread (especially those in callbacks due to rebalance events). try { // if we failed to read to end of log before, we need to make sure the issue was resolved before joining group // Joining and immediately leaving for failure to read configs is exceedingly impolite if (!canReadConfigs) { if (readConfigToEnd(workerSyncTimeoutMs)) { canReadConfigs = true; } else { return; // Safe to return and tick immediately because readConfigToEnd will do the backoff for us } } log.debug("Ensuring group membership is still active"); String stageDescription = "ensuring membership in the cluster"; member.ensureActive(() -> new TickThreadStage(stageDescription)); completeTickThreadStage(); // Ensure we're in a good state in our group. If not restart and everything should be setup to rejoin if (!handleRebalanceCompleted()) return; } catch (WakeupException e) { // May be due to a request from another thread, or might be stopping. If the latter, we need to check the // flag immediately. If the former, we need to re-run the ensureActive call since we can't handle requests // unless we're in the group. log.trace("Woken up while ensure group membership is still active"); return; } if (fencedFromConfigTopic) { if (isLeader()) { // We were accidentally fenced out, possibly by a zombie leader try { log.debug("Reclaiming write privileges for config topic after being fenced out"); try (TickThreadStage stage = new TickThreadStage("reclaiming write privileges for the config topic")) { configBackingStore.claimWritePrivileges(); } fencedFromConfigTopic = false; log.debug("Successfully reclaimed write privileges for config topic after being fenced out"); } catch (Exception e) { log.warn("Unable to claim write privileges for config topic. Will backoff and possibly retry if still the leader", e); backoff(CONFIG_TOPIC_WRITE_PRIVILEGES_BACKOFF_MS); return; } } else { log.trace("Relinquished write privileges for config topic after being fenced out, since worker is no longer the leader of the cluster"); // We were meant to be fenced out because we fell out of the group and a new leader was elected fencedFromConfigTopic = false; } } long now = time.milliseconds(); if (checkForKeyRotation(now)) { log.debug("Distributing new session key"); keyExpiration = Long.MAX_VALUE; try { SessionKey newSessionKey = new SessionKey(keyGenerator.generateKey(), now); writeToConfigTopicAsLeader( "writing a new session key to the config topic", () -> configBackingStore.putSessionKey(newSessionKey) ); } catch (Exception e) { log.info("Failed to write new session key to config topic; forcing a read to the end of the config topic before possibly retrying", e); canReadConfigs = false; return; } } // Process any external requests // TODO: Some of these can be performed concurrently or even optimized away entirely. // For example, if three different connectors are slated to be restarted, it's fine to // restart all three at the same time instead. // Another example: if multiple configurations are submitted for the same connector, // the only one that actually has to be written to the config topic is the // most-recently one. Long scheduledTick = null; while (true) { final DistributedHerderRequest next = peekWithoutException(); if (next == null) { break; } else if (now >= next.at) { currentRequest = requests.pollFirst(); } else { scheduledTick = next.at; break; } runRequest(next.action(), next.callback()); } // Process all pending connector restart requests processRestartRequests(); if (scheduledRebalance < Long.MAX_VALUE) { scheduledTick = scheduledTick != null ? Math.min(scheduledTick, scheduledRebalance) : scheduledRebalance; rebalanceResolved = false; log.debug("Scheduled rebalance at: {} (now: {} scheduledTick: {}) ", scheduledRebalance, now, scheduledTick); } if (isLeader() && internalRequestValidationEnabled() && keyExpiration < Long.MAX_VALUE) { scheduledTick = scheduledTick != null ? Math.min(scheduledTick, keyExpiration) : keyExpiration; log.debug("Scheduled next key rotation at: {} (now: {} scheduledTick: {}) ", keyExpiration, now, scheduledTick); } // Process any configuration updates AtomicReference<Set<String>> connectorConfigUpdatesCopy = new AtomicReference<>(); AtomicReference<Set<String>> connectorTargetStateChangesCopy = new AtomicReference<>(); AtomicReference<Set<ConnectorTaskId>> taskConfigUpdatesCopy = new AtomicReference<>(); boolean shouldReturn; if (member.currentProtocolVersion() == CONNECT_PROTOCOL_V0) { shouldReturn = updateConfigsWithEager(connectorConfigUpdatesCopy, connectorTargetStateChangesCopy); // With eager protocol we should return immediately if needsReconfigRebalance has // been set to retain the old workflow if (shouldReturn) { return; } if (connectorConfigUpdatesCopy.get() != null) { processConnectorConfigUpdates(connectorConfigUpdatesCopy.get()); } if (connectorTargetStateChangesCopy.get() != null) { processTargetStateChanges(connectorTargetStateChangesCopy.get()); } } else { shouldReturn = updateConfigsWithIncrementalCooperative(connectorConfigUpdatesCopy, connectorTargetStateChangesCopy, taskConfigUpdatesCopy); if (connectorConfigUpdatesCopy.get() != null) { processConnectorConfigUpdates(connectorConfigUpdatesCopy.get()); } if (connectorTargetStateChangesCopy.get() != null) { processTargetStateChanges(connectorTargetStateChangesCopy.get()); } if (taskConfigUpdatesCopy.get() != null) { processTaskConfigUpdatesWithIncrementalCooperative(taskConfigUpdatesCopy.get()); } if (shouldReturn) { return; } } // Let the group take any actions it needs to try { long nextRequestTimeoutMs = scheduledTick != null ? Math.max(scheduledTick - time.milliseconds(), 0L) : Long.MAX_VALUE; log.trace("Polling for group activity; will wait for {}ms or until poll is interrupted by " + "either config backing store updates or a new external request", nextRequestTimeoutMs); String pollDurationDescription = scheduledTick != null ? "for up to " + nextRequestTimeoutMs + "ms or " : ""; String stageDescription = "polling the group coordinator " + pollDurationDescription + "until interrupted"; member.poll(nextRequestTimeoutMs, () -> new TickThreadStage(stageDescription)); completeTickThreadStage(); // Ensure we're in a good state in our group. If not restart and everything should be setup to rejoin handleRebalanceCompleted(); } catch (WakeupException e) { // FIXME should not be WakeupException log.trace("Woken up while polling for group activity"); // Ignore. Just indicates we need to check the exit flag, for requested actions, etc. } }
@Test public void testConnectorPausedRunningTaskOnly() { // even if we don't own the connector, we should still propagate target state // changes to the worker so that tasks will transition correctly when(herder.connectorType(anyMap())).thenReturn(ConnectorType.SOURCE); when(member.memberId()).thenReturn("member"); when(member.currentProtocolVersion()).thenReturn(CONNECT_PROTOCOL_V0); // join expectRebalance(1, Collections.emptyList(), singletonList(TASK0)); expectConfigRefreshAndSnapshot(SNAPSHOT); expectMemberPoll(); when(worker.startSourceTask(eq(TASK0), any(), any(), any(), eq(herder), eq(TargetState.STARTED))).thenReturn(true); herder.tick(); // join // handle the state change expectMemberEnsureActive(); when(configBackingStore.snapshot()).thenReturn(SNAPSHOT_PAUSED_CONN1); ArgumentCaptor<Callback<TargetState>> onPause = ArgumentCaptor.forClass(Callback.class); doAnswer(invocation -> { onPause.getValue().onCompletion(null, TargetState.PAUSED); return null; }).when(worker).setTargetState(eq(CONN1), eq(TargetState.PAUSED), onPause.capture()); configUpdateListener.onConnectorTargetStateChange(CONN1); // state changes to paused herder.tick(); // apply state change verify(worker).setTargetState(eq(CONN1), eq(TargetState.PAUSED), any(Callback.class)); verifyNoMoreInteractions(worker, member, configBackingStore, statusBackingStore); }
public SendResult putMessageToRemoteBroker(MessageExtBrokerInner messageExt, String brokerNameToSend) { if (this.brokerController.getBrokerConfig().getBrokerName().equals(brokerNameToSend)) { // not remote broker return null; } final boolean isTransHalfMessage = TransactionalMessageUtil.buildHalfTopic().equals(messageExt.getTopic()); MessageExtBrokerInner messageToPut = messageExt; if (isTransHalfMessage) { messageToPut = TransactionalMessageUtil.buildTransactionalMessageFromHalfMessage(messageExt); } final TopicPublishInfo topicPublishInfo = this.brokerController.getTopicRouteInfoManager().tryToFindTopicPublishInfo(messageToPut.getTopic()); if (null == topicPublishInfo || !topicPublishInfo.ok()) { LOG.warn("putMessageToRemoteBroker: no route info of topic {} when escaping message, msgId={}", messageToPut.getTopic(), messageToPut.getMsgId()); return null; } final MessageQueue mqSelected; if (StringUtils.isEmpty(brokerNameToSend)) { mqSelected = topicPublishInfo.selectOneMessageQueue(this.brokerController.getBrokerConfig().getBrokerName()); messageToPut.setQueueId(mqSelected.getQueueId()); brokerNameToSend = mqSelected.getBrokerName(); if (this.brokerController.getBrokerConfig().getBrokerName().equals(brokerNameToSend)) { LOG.warn("putMessageToRemoteBroker failed, remote broker not found. Topic: {}, MsgId: {}, Broker: {}", messageExt.getTopic(), messageExt.getMsgId(), brokerNameToSend); return null; } } else { mqSelected = new MessageQueue(messageExt.getTopic(), brokerNameToSend, messageExt.getQueueId()); } final String brokerAddrToSend = this.brokerController.getTopicRouteInfoManager().findBrokerAddressInPublish(brokerNameToSend); if (null == brokerAddrToSend) { LOG.warn("putMessageToRemoteBroker failed, remote broker address not found. Topic: {}, MsgId: {}, Broker: {}", messageExt.getTopic(), messageExt.getMsgId(), brokerNameToSend); return null; } final long beginTimestamp = System.currentTimeMillis(); try { final SendResult sendResult = this.brokerController.getBrokerOuterAPI().sendMessageToSpecificBroker( brokerAddrToSend, brokerNameToSend, messageToPut, this.getProducerGroup(messageToPut), SEND_TIMEOUT); if (null != sendResult && SendStatus.SEND_OK.equals(sendResult.getSendStatus())) { return sendResult; } else { LOG.error("Escaping failed! cost {}ms, Topic: {}, MsgId: {}, Broker: {}", System.currentTimeMillis() - beginTimestamp, messageExt.getTopic(), messageExt.getMsgId(), brokerNameToSend); } } catch (RemotingException | MQBrokerException e) { LOG.error(String.format("putMessageToRemoteBroker exception, MsgId: %s, RT: %sms, Broker: %s", messageToPut.getMsgId(), System.currentTimeMillis() - beginTimestamp, mqSelected), e); } catch (InterruptedException e) { LOG.error(String.format("putMessageToRemoteBroker interrupted, MsgId: %s, RT: %sms, Broker: %s", messageToPut.getMsgId(), System.currentTimeMillis() - beginTimestamp, mqSelected), e); Thread.currentThread().interrupt(); } return null; }
@Test public void testPutMessageToRemoteBroker_specificBrokerName_equals() throws Exception { escapeBridge.putMessageToRemoteBroker(new MessageExtBrokerInner(), BROKER_NAME); verify(topicRouteInfoManager, times(0)).tryToFindTopicPublishInfo(anyString()); }
public MetricsBuilder protocol(String protocol) { this.protocol = protocol; return getThis(); }
@Test void protocol() { MetricsBuilder builder = MetricsBuilder.newBuilder(); builder.protocol("test"); Assertions.assertEquals("test", builder.build().getProtocol()); }
List<String> liveKeysAsOrderedList() { return new ArrayList<String>(liveMap.keySet()); }
@Test public void empty0() { long now = 3000; tracker.removeStaleComponents(now); assertEquals(0, tracker.liveKeysAsOrderedList().size()); assertEquals(0, tracker.getComponentCount()); }
@NonNull @Override public String getId() { return ID; }
@Test public void getRepositoriesWithoutCredentialId() throws IOException, UnirestException { createCredential(BitbucketServerScm.ID); Map repoResp = new RequestBuilder(baseUrl) .crumb(crumb) .status(200) .jwtToken(getJwtToken(j.jenkins, authenticatedUser.getId(), authenticatedUser.getId())) .post("/organizations/jenkins/scm/"+BitbucketServerScm.ID+"/organizations/TESTP/repositories/?apiUrl="+apiUrl) .build(Map.class); List repos = (List) ((Map)repoResp.get("repositories")).get("items"); assertEquals(2, repos.size()); assertEquals("empty-repo-test", ((Map)repos.get(0)).get("name")); assertEquals("empty-repo-test", ((Map)repos.get(0)).get("description")); assertTrue((Boolean) ((Map)repos.get(0)).get("private")); assertNull(((Map)repos.get(0)).get("defaultBranch")); assertEquals("pipeline-demo-test", ((Map)repos.get(1)).get("name")); assertEquals("pipeline-demo-test", ((Map)repos.get(1)).get("description")); assertTrue((Boolean) ((Map)repos.get(1)).get("private")); assertEquals("master",((Map)repos.get(1)).get("defaultBranch")); }
@JsonIgnore public ValidationResult validate(@Nullable EventDefinitionDto oldEventDefinitionDto, EventDefinitionConfiguration eventDefinitionConfiguration) { final ValidationResult validation = new ValidationResult(); if (title().isEmpty()) { validation.addError(FIELD_TITLE, "Event Definition title cannot be empty."); } try { validation.addAll(config().validate()); validation.addAll(config().validate( Optional.ofNullable(oldEventDefinitionDto).map(EventDefinitionDto::config).orElse(null), eventDefinitionConfiguration)); } catch (UnsupportedOperationException e) { validation.addError(FIELD_CONFIG, "Event Definition config type cannot be empty."); } for (Map.Entry<String, EventFieldSpec> fieldSpecEntry : fieldSpec().entrySet()) { final String fieldName = fieldSpecEntry.getKey(); if (!Message.validKey(fieldName)) { validation.addError(FIELD_FIELD_SPEC, "Event Definition field_spec contains invalid message field \"" + fieldName + "\"." + " Valid message field characters are: a-z, A-Z, 0-9, ., -, and @. No spaces are allowed."); } } if (keySpec().stream().anyMatch(key -> !fieldSpec().containsKey(key))) { validation.addError(FIELD_KEY_SPEC, "Event Definition key_spec can only contain fields defined in field_spec."); } return validation; }
@Test public void testValidEventDefinition() { final ValidationResult validationResult = validate(testSubject); assertThat(validationResult.failed()).isFalse(); assertThat(validationResult.getErrors().size()).isEqualTo(0); }
@Override public boolean assign(final Map<ProcessId, ClientState> clients, final Set<TaskId> allTaskIds, final Set<TaskId> statefulTaskIds, final AssignmentConfigs configs) { final int numStandbyReplicas = configs.numStandbyReplicas(); final Set<String> rackAwareAssignmentTags = new HashSet<>(tagsFunction.apply(configs)); final Map<TaskId, Integer> tasksToRemainingStandbys = computeTasksToRemainingStandbys( numStandbyReplicas, statefulTaskIds ); final Map<String, Set<String>> tagKeyToValues = new HashMap<>(); final Map<TagEntry, Set<ProcessId>> tagEntryToClients = new HashMap<>(); fillClientsTagStatistics(clients, tagEntryToClients, tagKeyToValues); final ConstrainedPrioritySet standbyTaskClientsByTaskLoad = createLeastLoadedPrioritySetConstrainedByAssignedTask(clients); final Map<TaskId, ProcessId> pendingStandbyTasksToClientId = new HashMap<>(); for (final TaskId statefulTaskId : statefulTaskIds) { for (final Map.Entry<ProcessId, ClientState> entry : clients.entrySet()) { final ProcessId clientId = entry.getKey(); final ClientState clientState = entry.getValue(); if (clientState.activeTasks().contains(statefulTaskId)) { assignStandbyTasksToClientsWithDifferentTags( numStandbyReplicas, standbyTaskClientsByTaskLoad, statefulTaskId, clientId, rackAwareAssignmentTags, clients, tasksToRemainingStandbys, tagKeyToValues, tagEntryToClients, pendingStandbyTasksToClientId ); } } } if (!tasksToRemainingStandbys.isEmpty()) { assignPendingStandbyTasksToLeastLoadedClients(clients, numStandbyReplicas, standbyTaskClientsByTaskLoad, tasksToRemainingStandbys); } // returning false, because standby task assignment will never require a follow-up probing rebalance. return false; }
@Test public void shouldDistributeStandbyTasksOnLeastLoadedClientsWhenClientsAreNotOnDifferentTagDimensions() { final Map<ProcessId, ClientState> clientStates = mkMap( mkEntry(PID_1, createClientStateWithCapacity(PID_1, 3, mkMap(mkEntry(CLUSTER_TAG, CLUSTER_1), mkEntry(ZONE_TAG, ZONE_1)), TASK_0_0)), mkEntry(PID_2, createClientStateWithCapacity(PID_2, 3, mkMap(mkEntry(CLUSTER_TAG, CLUSTER_1), mkEntry(ZONE_TAG, ZONE_1)), TASK_0_1)), mkEntry(PID_3, createClientStateWithCapacity(PID_3, 3, mkMap(mkEntry(CLUSTER_TAG, CLUSTER_1), mkEntry(ZONE_TAG, ZONE_1)), TASK_0_2)), mkEntry(PID_4, createClientStateWithCapacity(PID_4, 3, mkMap(mkEntry(CLUSTER_TAG, CLUSTER_1), mkEntry(ZONE_TAG, ZONE_1)), TASK_1_0)) ); final Set<TaskId> allActiveTasks = findAllActiveTasks(clientStates); final AssignmentConfigs assignmentConfigs = newAssignmentConfigs(1, CLUSTER_TAG, ZONE_TAG); standbyTaskAssignor.assign(clientStates, allActiveTasks, allActiveTasks, assignmentConfigs); assertTotalNumberOfStandbyTasksEqualsTo(clientStates, 4); assertEquals(1, clientStates.get(PID_1).standbyTaskCount()); assertEquals(1, clientStates.get(PID_2).standbyTaskCount()); assertEquals(1, clientStates.get(PID_3).standbyTaskCount()); assertEquals(1, clientStates.get(PID_4).standbyTaskCount()); }
public static boolean isValidRule(GatewayFlowRule rule) { if (rule == null || StringUtil.isBlank(rule.getResource()) || rule.getResourceMode() < 0 || rule.getGrade() < 0 || rule.getCount() < 0 || rule.getBurst() < 0 || rule.getControlBehavior() < 0) { return false; } if (rule.getControlBehavior() == RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER && rule.getMaxQueueingTimeoutMs() < 0) { return false; } if (rule.getIntervalSec() <= 0) { return false; } GatewayParamFlowItem item = rule.getParamItem(); if (item != null) { return isValidParamItem(item); } return true; }
@Test public void testIsValidRule() { GatewayFlowRule bad1 = new GatewayFlowRule(); GatewayFlowRule bad2 = new GatewayFlowRule("abc") .setIntervalSec(0); GatewayFlowRule bad3 = new GatewayFlowRule("abc") .setParamItem(new GatewayParamFlowItem() .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)); GatewayFlowRule bad4 = new GatewayFlowRule("abc") .setParamItem(new GatewayParamFlowItem() .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM) .setFieldName("p") .setPattern("def") .setMatchStrategy(-1) ); GatewayFlowRule good1 = new GatewayFlowRule("abc"); GatewayFlowRule good2 = new GatewayFlowRule("abc") .setParamItem(new GatewayParamFlowItem().setParseStrategy(0)); GatewayFlowRule good3 = new GatewayFlowRule("abc") .setParamItem(new GatewayParamFlowItem() .setMatchStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER) .setFieldName("Origin") .setPattern("def")); assertFalse(GatewayRuleManager.isValidRule(bad1)); assertFalse(GatewayRuleManager.isValidRule(bad2)); assertFalse(GatewayRuleManager.isValidRule(bad3)); assertFalse(GatewayRuleManager.isValidRule(bad4)); assertTrue(GatewayRuleManager.isValidRule(good1)); assertTrue(GatewayRuleManager.isValidRule(good2)); assertTrue(GatewayRuleManager.isValidRule(good3)); }
@Override protected FailureAnalysis analyze(Throwable rootFailure, ConfigDataMissingEnvironmentPostProcessor.ImportException cause) { String description; if (cause.missingPrefix) { description = "The spring.config.import property is missing a " + PolarisConfigDataLocationResolver.PREFIX + " entry"; } else { description = "No spring.config.import property has been defined"; } String action = "\t1. Add a spring.config.import=polaris property to your configuration.\n" + "\t2. If configuration is not required add spring.config.import=optional:polaris instead.\n" + "\t3. If you still want use bootstrap.yml, " + "you can add <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bootstrap</artifactId> dependency for compatible upgrade."; return new FailureAnalysis(description, action, cause); }
@Test public void failureAnalyzerTest() { SpringApplication app = mock(SpringApplication.class); MockEnvironment environment = new MockEnvironment(); PolarisConfigDataMissingEnvironmentPostProcessor processor = new PolarisConfigDataMissingEnvironmentPostProcessor(); assertThatThrownBy(() -> processor.postProcessEnvironment(environment, app)) .isInstanceOf(PolarisConfigDataMissingEnvironmentPostProcessor.ImportException.class); Throwable throwable = catchThrowable(() -> processor.postProcessEnvironment(environment, app)); PolarisImportExceptionFailureAnalyzer failureAnalyzer = new PolarisImportExceptionFailureAnalyzer(); FailureAnalysis analyze = failureAnalyzer.analyze(throwable); assertThat(StringUtils.isNotBlank(analyze.getAction())).isTrue(); }
@Override public TenantDO getTenantByName(String name) { return tenantMapper.selectByName(name); }
@Test public void testGetTenantByName() { // mock 数据 TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setName("芋道")); tenantMapper.insert(dbTenant);// @Sql: 先插入出一条存在的数据 // 调用 TenantDO result = tenantService.getTenantByName("芋道"); // 校验存在 assertPojoEquals(result, dbTenant); }
public void setNeedClientAuth(Boolean needClientAuth) { this.needClientAuth = needClientAuth; }
@Test public void testSetNeedClientAuth() throws Exception { configuration.setNeedClientAuth(true); configuration.configure(configurable); assertTrue(configurable.isNeedClientAuth()); }
protected CompletableFuture<Void> scheduleJob(final Instant runAt, @Nullable final byte[] jobData) { return Mono.fromFuture(() -> scheduleJob(buildRunAtAttribute(runAt), runAt.plus(jobExpiration), jobData)) .retryWhen(Retry.backoff(8, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4))) .toFuture() .thenRun(() -> Metrics.counter(SCHEDULE_JOB_COUNTER_NAME, SCHEDULER_NAME_TAG, getSchedulerName()).increment()); }
@Test void scheduleJob() { final TestJobScheduler scheduler = new TestJobScheduler(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), DynamoDbExtensionSchema.Tables.SCHEDULED_JOBS.tableName(), Clock.fixed(CURRENT_TIME, ZoneId.systemDefault())); assertDoesNotThrow(() -> scheduler.scheduleJob(scheduler.buildRunAtAttribute(CURRENT_TIME, 0L), CURRENT_TIME, null).join()); final CompletionException completionException = assertThrows(CompletionException.class, () -> scheduler.scheduleJob(scheduler.buildRunAtAttribute(CURRENT_TIME, 0L), CURRENT_TIME, null).join(), "Scheduling multiple jobs with identical sort keys should fail"); assertInstanceOf(ConditionalCheckFailedException.class, completionException.getCause()); }
public InetSocketAddress updateConnectAddr( String hostProperty, String addressProperty, String defaultAddressValue, InetSocketAddress addr) { final String host = get(hostProperty); final String connectHostPort = getTrimmed(addressProperty, defaultAddressValue); if (host == null || host.isEmpty() || connectHostPort == null || connectHostPort.isEmpty()) { //not our case, fall back to original logic return updateConnectAddr(addressProperty, addr); } final String connectHost = connectHostPort.split(":")[0]; // Create connect address using client address hostname and server port. return updateConnectAddr(addressProperty, NetUtils.createSocketAddrForHost( connectHost, addr.getPort())); }
@Test public void testUpdateSocketAddress() throws IOException { InetSocketAddress addr = NetUtils.createSocketAddrForHost("host", 1); InetSocketAddress connectAddr = conf.updateConnectAddr("myAddress", addr); assertEquals(connectAddr.getHostName(), addr.getHostName()); addr = new InetSocketAddress(1); connectAddr = conf.updateConnectAddr("myAddress", addr); assertEquals(connectAddr.getHostName(), InetAddress.getLocalHost().getHostName()); }
@Override public Map<String, FailoverData> getFailoverData() { if (Boolean.parseBoolean(switchParams.get(FAILOVER_MODE_PARAM))) { return serviceMap; } return new ConcurrentHashMap<>(0); }
@Test void testGetFailoverDataForFailoverDisabled() { Map<String, FailoverData> actual = dataSource.getFailoverData(); assertTrue(actual.isEmpty()); }
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 testFromKRaftDualWritingToKRaftPostMigration() { Kafka kafka = new KafkaBuilder(KAFKA) .editMetadata() .addToAnnotations(Annotations.ANNO_STRIMZI_IO_KRAFT, "migration") .endMetadata() .withNewStatus() .withKafkaMetadataState(KRaftDualWriting) .endStatus() .build(); KafkaMetadataStateManager kafkaMetadataStateManager = new KafkaMetadataStateManager(Reconciliation.DUMMY_RECONCILIATION, kafka); assertEquals(kafkaMetadataStateManager.computeNextMetadataState(kafka.getStatus()), KRaftPostMigration); }
@Override public List<ProductCategoryDO> getCategoryList(ProductCategoryListReqVO listReqVO) { return productCategoryMapper.selectList(listReqVO); }
@Test public void testGetCategoryList() { // mock 数据 ProductCategoryDO dbCategory = randomPojo(ProductCategoryDO.class, o -> { // 等会查询到 o.setName("奥特曼"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setParentId(PARENT_ID_NULL); }); productCategoryMapper.insert(dbCategory); // 测试 name 不匹配 productCategoryMapper.insert(cloneIgnoreId(dbCategory, o -> o.setName("奥特块"))); // 测试 status 不匹配 productCategoryMapper.insert(cloneIgnoreId(dbCategory, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); // 测试 parentId 不匹配 productCategoryMapper.insert(cloneIgnoreId(dbCategory, o -> o.setParentId(3333L))); // 准备参数 ProductCategoryListReqVO reqVO = new ProductCategoryListReqVO(); reqVO.setName("特曼"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); reqVO.setParentId(PARENT_ID_NULL); // 调用 List<ProductCategoryDO> list = productCategoryService.getCategoryList(reqVO); List<ProductCategoryDO> all = productCategoryService.getCategoryList(new ProductCategoryListReqVO()); // 断言 assertEquals(1, list.size()); assertEquals(4, all.size()); assertPojoEquals(dbCategory, list.get(0)); }
@Override public int compare(Object o1, Object o2) { if (o1 == null && o2 == null) { return 0; // o1 == o2 } if (o1 == null) { return -1; // o1 < o2 } if (o2 == null) { return 1; // o1 > o2 } return nonNullCompare(o1, o2); }
@Test public void noNulls() { assertTrue("no Nulls", cmp.compare(1, 2) == 42); }
@Override public void clean() { COUNTER_MAP.clear(); GAUGE_MAP.clear(); HISTOGRAM_MAP.clear(); }
@Test public void testClean() throws Exception { prometheusMetricsRegister.clean(); Field field1 = prometheusMetricsRegister.getClass().getDeclaredField("COUNTER_MAP"); field1.setAccessible(true); Map<String, Counter> map1 = (Map<String, Counter>) field1.get(prometheusMetricsRegister); Assertions.assertTrue(CollectionUtils.isEmpty(map1)); Field field2 = prometheusMetricsRegister.getClass().getDeclaredField("GAUGE_MAP"); field2.setAccessible(true); Map<String, Gauge> map2 = (Map<String, Gauge>) field2.get(prometheusMetricsRegister); Assertions.assertTrue(CollectionUtils.isEmpty(map2)); Field field3 = prometheusMetricsRegister.getClass().getDeclaredField("HISTOGRAM_MAP"); field3.setAccessible(true); Map<String, Histogram> map3 = (Map<String, Histogram>) field3.get(prometheusMetricsRegister); Assertions.assertTrue(CollectionUtils.isEmpty(map3)); }
@Override public List<? extends Instance> listInstances(String namespaceId, String groupName, String serviceName, String clusterName) throws NacosException { Service service = Service.newService(namespaceId, groupName, serviceName); if (!ServiceManager.getInstance().containSingleton(service)) { throw new NacosException(NacosException.NOT_FOUND, String.format("service %s@@%s is not found!", groupName, serviceName)); } if (!serviceStorage.getClusters(service).contains(clusterName)) { throw new NacosException(NacosException.NOT_FOUND, "cluster " + clusterName + " is not found!"); } ServiceInfo serviceInfo = serviceStorage.getData(service); ServiceInfo result = ServiceUtil.selectInstances(serviceInfo, clusterName); return result.getHosts(); }
@Test void testListInstancesNonExistService() throws NacosException { assertThrows(NacosException.class, () -> { catalogServiceV2Impl.listInstances("A", "BB", "CC", "DD"); }); }
@CheckForNull @Override public Set<Path> branchChangedFiles(String targetBranchName, Path rootBaseDir) { return Optional.ofNullable((branchChangedFilesWithFileMovementDetection(targetBranchName, rootBaseDir))) .map(GitScmProvider::extractAbsoluteFilePaths) .orElse(null); }
@Test public void branchChangedFiles_should_not_fail_with_patience_diff_algo() throws IOException { Path gitConfig = worktree.resolve(".git").resolve("config"); Files.write(gitConfig, "[diff]\nalgorithm = patience\n".getBytes(StandardCharsets.UTF_8)); Repository repo = FileRepositoryBuilder.create(worktree.resolve(".git").toFile()); git = new Git(repo); assertThat(newScmProvider().branchChangedFiles("main", worktree)).isNull(); }
public static DatabaseType getProtocolType(final DatabaseConfiguration databaseConfig, final ConfigurationProperties props) { Optional<DatabaseType> configuredDatabaseType = findConfiguredDatabaseType(props); if (configuredDatabaseType.isPresent()) { return configuredDatabaseType.get(); } Collection<DataSource> dataSources = getDataSources(databaseConfig).values(); return dataSources.isEmpty() ? getDefaultStorageType() : getStorageType(dataSources.iterator().next()); }
@Test void assertGetProtocolTypeFromDataSource() throws SQLException { DataSource datasource = mockDataSource(TypedSPILoader.getService(DatabaseType.class, "PostgreSQL")); DatabaseConfiguration databaseConfig = new DataSourceProvidedDatabaseConfiguration(Collections.singletonMap("foo_ds", datasource), Collections.singleton(new FixtureRuleConfiguration())); assertThat(DatabaseTypeEngine.getProtocolType(databaseConfig, new ConfigurationProperties(new Properties())), instanceOf(PostgreSQLDatabaseType.class)); assertThat(DatabaseTypeEngine.getProtocolType(Collections.singletonMap("foo_db", databaseConfig), new ConfigurationProperties(new Properties())), instanceOf(PostgreSQLDatabaseType.class)); }
@Override public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { if (hazelcastInstance instanceof HazelcastInstanceImpl impl) { instance = impl; localMember = instance.node.address.equals(address); logger = instance.node.getLogger(this.getClass().getName()); } }
@Test public void testSetHazelcastInstance() { MemberImpl member = new MemberImpl(address, MemberVersion.of("3.8.0"), true); assertNull(member.getLogger()); member.setHazelcastInstance(hazelcastInstance); assertNotNull(member.getLogger()); }
@Override public List<String> splitAndEvaluate() { try (ReflectContext context = new ReflectContext(JAVA_CLASSPATH)) { if (Strings.isNullOrEmpty(inlineExpression)) { return Collections.emptyList(); } return flatten(evaluate(context, GroovyUtils.split(handlePlaceHolder(inlineExpression)))); } }
@Test void assertEvaluateForExpressionPlaceHolder() { List<String> expected = createInlineExpressionParser("t_$->{[\"new$->{1+2}\",'old']}_order_$->{1..2}").splitAndEvaluate(); assertThat(expected.size(), is(4)); assertThat(expected, hasItems("t_new3_order_1", "t_new3_order_2", "t_old_order_1", "t_old_order_2")); }
public Iterable<InputChannel> inputChannels() { return () -> new Iterator<InputChannel>() { private final Iterator<Map<InputChannelInfo, InputChannel>> mapIterator = inputChannels.values().iterator(); private Iterator<InputChannel> iterator = null; @Override public boolean hasNext() { return (iterator != null && iterator.hasNext()) || mapIterator.hasNext(); } @Override public InputChannel next() { if ((iterator == null || !iterator.hasNext()) && mapIterator.hasNext()) { iterator = mapIterator.next().values().iterator(); } if (iterator == null || !iterator.hasNext()) { return null; } return iterator.next(); } }; }
@Test void testSingleInputGateInfo() { final int numSingleInputGates = 2; final int numInputChannels = 3; for (int i = 0; i < numSingleInputGates; i++) { final SingleInputGate gate = new SingleInputGateBuilder() .setSingleInputGateIndex(i) .setNumberOfChannels(numInputChannels) .build(); int channelCounter = 0; for (InputChannel inputChannel : gate.inputChannels()) { InputChannelInfo channelInfo = inputChannel.getChannelInfo(); assertThat(channelInfo.getGateIdx()).isEqualTo(i); assertThat(channelInfo.getInputChannelIdx()).isEqualTo(channelCounter++); } } }