focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public String requestMessageForCheckConnectionToPackage(PackageConfiguration packageConfiguration, RepositoryConfiguration repositoryConfiguration) { Map configuredValues = new LinkedHashMap(); configuredValues.put("repository-configuration", jsonResultMessageHandler.configurationToMap(repositoryConfiguration)); configuredValues.put("package-configuration", jsonResultMessageHandler.configurationToMap(packageConfiguration)); return GSON.toJson(configuredValues); }
@Test public void shouldBuildRequestBodyForCheckPackageConnectionRequest() throws Exception { String requestMessage = messageHandler.requestMessageForCheckConnectionToPackage(packageConfiguration, repositoryConfiguration); assertThat(requestMessage, is("{\"repository-configuration\":{\"key-one\":{\"value\":\"value-one\"},\"key-two\":{\"value\":\"value-two\"}},\"package-configuration\":{\"key-three\":{\"value\":\"value-three\"},\"key-four\":{\"value\":\"value-four\"}}}")); }
@VisibleForTesting void validateDictTypeUnique(Long id, String type) { if (StrUtil.isEmpty(type)) { return; } DictTypeDO dictType = dictTypeMapper.selectByType(type); if (dictType == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的字典类型 if (id == null) { throw exception(DICT_TYPE_TYPE_DUPLICATE); } if (!dictType.getId().equals(id)) { throw exception(DICT_TYPE_TYPE_DUPLICATE); } }
@Test public void testValidateDictTypeUnique_valueDuplicateForCreate() { // 准备参数 String type = randomString(); // mock 数据 dictTypeMapper.insert(randomDictTypeDO(o -> o.setType(type))); // 调用,校验异常 assertServiceException(() -> dictTypeService.validateDictTypeUnique(null, type), DICT_TYPE_TYPE_DUPLICATE); }
@Override public void subscribe(final Subscriber<? super Row> subscriber) { if (polling) { throw new IllegalStateException("Cannot set subscriber if polling"); } synchronized (this) { subscribing = true; super.subscribe(subscriber); } }
@Test public void shouldDeliverBufferedRowsOnError() throws Exception { // Given givenPublisherAcceptsOneRow(); subscribe(); handleQueryResultError(); // When subscription.request(1); // Then assertThatEventually(() -> subscriberReceivedRow, is(true)); assertThatEventually(() -> subscriberFailed, is(true)); }
public static Optional<ConnectorPageSource> createHivePageSource( Set<HiveRecordCursorProvider> cursorProviders, Set<HiveBatchPageSourceFactory> pageSourceFactories, Configuration configuration, ConnectorSession session, HiveFileSplit fileSplit, OptionalInt tableBucketNumber, Storage storage, TupleDomain<HiveColumnHandle> effectivePredicate, List<HiveColumnHandle> hiveColumns, Map<String, HiveColumnHandle> predicateColumns, List<HivePartitionKey> partitionKeys, DateTimeZone hiveStorageTimeZone, TypeManager typeManager, SchemaTableName tableName, List<HiveColumnHandle> partitionKeyColumnHandles, List<Column> tableDataColumns, Map<String, String> tableParameters, int partitionDataColumnCount, TableToPartitionMapping tableToPartitionMapping, Optional<BucketConversion> bucketConversion, boolean s3SelectPushdownEnabled, HiveFileContext hiveFileContext, RowExpression remainingPredicate, boolean isPushdownFilterEnabled, RowExpressionService rowExpressionService, Optional<EncryptionInformation> encryptionInformation, Optional<byte[]> rowIdPartitionComponent) { List<HiveColumnHandle> allColumns; if (isPushdownFilterEnabled) { Set<String> columnNames = hiveColumns.stream().map(HiveColumnHandle::getName).collect(toImmutableSet()); List<HiveColumnHandle> additionalColumns = predicateColumns.values().stream() .filter(column -> !columnNames.contains(column.getName())) .collect(toImmutableList()); allColumns = ImmutableList.<HiveColumnHandle>builder() .addAll(hiveColumns) .addAll(additionalColumns) .build(); } else { allColumns = hiveColumns; } List<ColumnMapping> columnMappings = ColumnMapping.buildColumnMappings( partitionKeys, allColumns, bucketConversion.map(BucketConversion::getBucketColumnHandles).orElse(ImmutableList.of()), tableToPartitionMapping, fileSplit, tableBucketNumber); Set<Integer> outputIndices = hiveColumns.stream() .map(HiveColumnHandle::getHiveColumnIndex) .collect(toImmutableSet()); // Finds the non-synthetic columns. List<ColumnMapping> regularAndInterimColumnMappings = ColumnMapping.extractRegularAndInterimColumnMappings(columnMappings); Optional<BucketAdaptation> bucketAdaptation = bucketConversion.map(conversion -> toBucketAdaptation( conversion, regularAndInterimColumnMappings, tableBucketNumber, ColumnMapping::getIndex, isLegacyTimestampBucketing(session))); if (isUseRecordPageSourceForCustomSplit(session) && shouldUseRecordReaderFromInputFormat(configuration, storage, fileSplit.getCustomSplitInfo())) { return getPageSourceFromCursorProvider( cursorProviders, configuration, session, fileSplit, storage, effectivePredicate, hiveStorageTimeZone, typeManager, tableName, partitionKeyColumnHandles, tableDataColumns, tableParameters, partitionDataColumnCount, tableToPartitionMapping, s3SelectPushdownEnabled, remainingPredicate, isPushdownFilterEnabled, rowExpressionService, allColumns, columnMappings, outputIndices, regularAndInterimColumnMappings, bucketAdaptation); } for (HiveBatchPageSourceFactory pageSourceFactory : pageSourceFactories) { Optional<? extends ConnectorPageSource> pageSource = pageSourceFactory.createPageSource( configuration, session, fileSplit, storage, tableName, tableParameters, toColumnHandles(regularAndInterimColumnMappings, true), effectivePredicate, hiveStorageTimeZone, hiveFileContext, encryptionInformation, rowIdPartitionComponent); if (pageSource.isPresent()) { HivePageSource hivePageSource = new HivePageSource( columnMappings, bucketAdaptation, hiveStorageTimeZone, typeManager, pageSource.get(), fileSplit.getPath(), rowIdPartitionComponent); if (isPushdownFilterEnabled) { return Optional.of(new FilteringPageSource( columnMappings, effectivePredicate, remainingPredicate, typeManager, rowExpressionService, session, outputIndices, hivePageSource)); } return Optional.of(hivePageSource); } } return getPageSourceFromCursorProvider( cursorProviders, configuration, session, fileSplit, storage, effectivePredicate, hiveStorageTimeZone, typeManager, tableName, partitionKeyColumnHandles, tableDataColumns, tableParameters, partitionDataColumnCount, tableToPartitionMapping, s3SelectPushdownEnabled, remainingPredicate, isPushdownFilterEnabled, rowExpressionService, allColumns, columnMappings, outputIndices, regularAndInterimColumnMappings, bucketAdaptation); }
@Test public void testUseRecordReaderWithInputFormatAnnotationAndCustomSplit() { StorageFormat storageFormat = StorageFormat.create(ParquetHiveSerDe.class.getName(), HoodieParquetInputFormat.class.getName(), ""); Storage storage = new Storage(storageFormat, "test", Optional.empty(), true, ImmutableMap.of(), ImmutableMap.of()); Map<String, String> customSplitInfo = ImmutableMap.of( CUSTOM_FILE_SPLIT_CLASS_KEY, HoodieRealtimeFileSplit.class.getName(), HUDI_BASEPATH_KEY, "/test/file.parquet", HUDI_DELTA_FILEPATHS_KEY, "/test/.file_100.log", HUDI_MAX_COMMIT_TIME_KEY, "100"); HiveRecordCursorProvider recordCursorProvider = new MockHiveRecordCursorProvider(); HiveBatchPageSourceFactory hiveBatchPageSourceFactory = new MockHiveBatchPageSourceFactory(); HiveFileSplit fileSplit = new HiveFileSplit( "/test/", 0, 100, 200, Instant.now().toEpochMilli(), Optional.empty(), customSplitInfo, 0); Optional<ConnectorPageSource> pageSource = HivePageSourceProvider.createHivePageSource( ImmutableSet.of(recordCursorProvider), ImmutableSet.of(hiveBatchPageSourceFactory), new Configuration(), new TestingConnectorSession(new HiveSessionProperties( new HiveClientConfig().setUseRecordPageSourceForCustomSplit(true), new OrcFileWriterConfig(), new ParquetFileWriterConfig(), new CacheConfig()).getSessionProperties()), fileSplit, OptionalInt.empty(), storage, TupleDomain.none(), ImmutableList.of(), ImmutableMap.of(), ImmutableList.of(), DateTimeZone.UTC, new TestingTypeManager(), new SchemaTableName("test", "test"), ImmutableList.of(), ImmutableList.of(), ImmutableMap.of(), 0, TableToPartitionMapping.empty(), Optional.empty(), false, null, null, false, null, Optional.empty(), Optional.empty()); assertTrue(pageSource.isPresent()); assertTrue(pageSource.get() instanceof RecordPageSource); }
public Service getService() { return service; }
@Test void testGetService() { TestService service = mock(TestService.class); ServiceBean serviceBean = new ServiceBean(null, service); Service beanService = serviceBean.getService(); MatcherAssert.assertThat(beanService, not(nullValue())); }
public static String formatExpression(final Expression expression) { return formatExpression(expression, FormatOptions.of(s -> false)); }
@Test public void shouldFormatCastToStruct() { // Given: final Cast cast = new Cast( new StringLiteral("foo"), new Type(SqlStruct.builder() .field("field", SqlTypes.STRING).build()) ); // When: final String result = ExpressionFormatter.formatExpression(cast, FormatOptions.none()); // Then: assertThat(result, equalTo("CAST('foo' AS STRUCT<`field` STRING>)")); }
public static long readUnsignedIntLittleEndian(byte[] data, int index) { long result = (long) (data[index] & 0xFF) | (long) ((data[index + 1] & 0xFF) << 8) | (long) ((data[index + 2] & 0xFF) << 16) | (long) ((data[index + 3] & 0xFF) << 24); return result; }
@Test public void testReadUnsignedIntLittleEndian() { Assert.assertEquals(0L, ByteHelper.readUnsignedIntLittleEndian(new byte[] {0, 0, 0, 0}, 0)); }
public static int markProtocolType(int source, SerializeType type) { return (type.getCode() << 24) | (source & 0x00FFFFFF); }
@Test public void testMarkProtocolType_JSONProtocolType() { int source = 261; SerializeType type = SerializeType.JSON; byte[] result = new byte[4]; int x = RemotingCommand.markProtocolType(source, type); result[0] = (byte) (x >> 24); result[1] = (byte) (x >> 16); result[2] = (byte) (x >> 8); result[3] = (byte) x; assertThat(result).isEqualTo(new byte[] {0, 0, 1, 5}); }
@Override public Object execute(String command, byte[]... args) { for (Method method : this.getClass().getDeclaredMethods()) { if (method.getName().equalsIgnoreCase(command) && Modifier.isPublic(method.getModifiers()) && (method.getParameterTypes().length == args.length)) { try { Object t = execute(method, args); if (t instanceof String) { return ((String) t).getBytes(); } return t; } catch (IllegalArgumentException e) { if (isPipelined()) { throw new RedisPipelineException(e); } throw new InvalidDataAccessApiUsageException(e.getMessage(), e); } } } throw new UnsupportedOperationException(); }
@Test public void testExecute() { Long s = (Long) connection.execute("ttl", "key".getBytes()); assertThat(s).isEqualTo(-2); connection.execute("flushDb"); }
void reload() throws IOException { clear(); load(); }
@Test public void testReload() throws IOException { UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE); String user1 = "user1"; File directory1 = mapper.putIfAbsent(user1, true); mapper.reload(); assertThat(mapper.isMapped(user1), is(true)); assertThat(mapper.getConvertedUserIds(), hasSize(1)); }
public static List<String> split(String path) { // String[] pathelements = path.split("/"); List<String> dirs = new ArrayList<String>(pathelements.length); for (String pathelement : pathelements) { if (!pathelement.isEmpty()) { dirs.add(pathelement); } } return dirs; }
@Test public void testSplittingEmpty() throws Throwable { assertEquals(0, split("").size()); assertEquals(0, split("/").size()); assertEquals(0, split("///").size()); }
public static SerdeFeatures buildValueFeatures( final LogicalSchema schema, final Format valueFormat, final SerdeFeatures explicitFeatures, final KsqlConfig ksqlConfig ) { final boolean singleColumn = schema.value().size() == 1; final ImmutableSet.Builder<SerdeFeature> builder = ImmutableSet.builder(); getValueWrapping(singleColumn, valueFormat, explicitFeatures, ksqlConfig) .ifPresent(builder::add); return SerdeFeatures.from(builder.build()); }
@Test public void shouldNotGetSingleValueWrappingFromConfigForMultiFields() { // Given: ksqlConfig = new KsqlConfig(ImmutableMap.of( KsqlConfig.KSQL_WRAP_SINGLE_VALUES, false )); // When: final SerdeFeatures result = SerdeFeaturesFactory.buildValueFeatures( MULTI_FIELD_SCHEMA, JSON, SerdeFeatures.of(), ksqlConfig ); // Then: assertThat(result.findAny(SerdeFeatures.WRAPPING_FEATURES), is(Optional.empty())); }
CodeEmitter<T> emit(final Parameter parameter) { emitter.emit("param"); emit("name", parameter.getName()); final String parameterType = parameter.getIn(); if (ObjectHelper.isNotEmpty(parameterType)) { emit("type", RestParamType.valueOf(parameterType)); } if (!"body".equals(parameterType)) { final Schema schema = parameter.getSchema(); if (schema != null) { final String dataType = schema.getType(); if (ObjectHelper.isNotEmpty(dataType)) { emit("dataType", dataType); } emit("allowableValues", asStringList(schema.getEnum())); final StyleEnum style = parameter.getStyle(); if (ObjectHelper.isNotEmpty(style)) { if (style.equals(StyleEnum.FORM)) { // Guard against null explode value // See: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#fixed-fields-10 if (Boolean.FALSE.equals(parameter.getExplode())) { emit("collectionFormat", CollectionFormat.csv); } else { emit("collectionFormat", CollectionFormat.multi); } } } if (ObjectHelper.isNotEmpty(schema.getDefault())) { final String value = StringHelper.removeLeadingAndEndingQuotes(schema.getDefault().toString()); emit("defaultValue", value); } if ("array".equals(dataType) && schema.getItems() != null) { emit("arrayType", schema.getItems().getType()); } } } if (parameter.getRequired() != null) { emit("required", parameter.getRequired()); } else { emit("required", Boolean.FALSE); } emit("description", parameter.getDescription()); emitter.emit("endParam"); return emitter; }
@Test public void shouldEmitCodeForOas3ParameterWithDefaultValue() { final Builder method = MethodSpec.methodBuilder("configure"); final MethodBodySourceCodeEmitter emitter = new MethodBodySourceCodeEmitter(method); final OperationVisitor<?> visitor = new OperationVisitor<>(emitter, null, null, null, null); final Parameter parameter = new Parameter(); parameter.setName("param"); parameter.setIn("path"); Schema schema = new Schema(); schema.setDefault("default"); parameter.setSchema(schema); visitor.emit(parameter); assertThat(method.build().toString()).isEqualTo("void configure() {\n" + " param()\n" + " .name(\"param\")\n" + " .type(org.apache.camel.model.rest.RestParamType.path)\n" + " .defaultValue(\"default\")\n" + " .required(true)\n" + " .endParam()\n" + " }\n"); }
public static Criterion matchInPort(PortNumber port) { return new PortCriterion(port, Type.IN_PORT); }
@Test public void testMatchInPortMethod() { PortNumber p1 = portNumber(1); Criterion matchInPort = Criteria.matchInPort(p1); PortCriterion portCriterion = checkAndConvert(matchInPort, Criterion.Type.IN_PORT, PortCriterion.class); assertThat(portCriterion.port(), is(equalTo(p1))); }
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testNewCombiningNoFetch() throws Exception { GroupingState<Integer, Integer> value = underTestNewKey.state(NAMESPACE, COMBINING_ADDR); assertThat(value.isEmpty().read(), Matchers.is(true)); assertThat(value.read(), Matchers.is(Sum.ofIntegers().identity())); assertThat(value.isEmpty().read(), Matchers.is(false)); // Shouldn't need to read from windmill for this. Mockito.verifyZeroInteractions(mockReader); }
@VisibleForTesting StreamingEngineConnectionState getCurrentConnections() { return connections.get(); }
@Test public void testStreamsStartCorrectly() throws InterruptedException { long items = 10L; long bytes = 10L; int numBudgetDistributionsExpected = 1; TestGetWorkBudgetDistributor getWorkBudgetDistributor = spy(new TestGetWorkBudgetDistributor(numBudgetDistributionsExpected)); fanOutStreamingEngineWorkProvider = newStreamingEngineClient( GetWorkBudget.builder().setItems(items).setBytes(bytes).build(), getWorkBudgetDistributor, noOpProcessWorkItemFn()); String workerToken = "workerToken1"; String workerToken2 = "workerToken2"; WorkerMetadataResponse firstWorkerMetadata = WorkerMetadataResponse.newBuilder() .setMetadataVersion(1) .addWorkEndpoints(metadataResponseEndpoint(workerToken)) .addWorkEndpoints(metadataResponseEndpoint(workerToken2)) .putAllGlobalDataEndpoints(DEFAULT) .build(); getWorkerMetadataReady.await(); fakeGetWorkerMetadataStub.injectWorkerMetadata(firstWorkerMetadata); waitForWorkerMetadataToBeConsumed(getWorkBudgetDistributor); StreamingEngineConnectionState currentConnections = fanOutStreamingEngineWorkProvider.getCurrentConnections(); assertEquals(2, currentConnections.windmillConnections().size()); assertEquals(2, currentConnections.windmillStreams().size()); Set<String> workerTokens = currentConnections.windmillConnections().values().stream() .map(WindmillConnection::backendWorkerToken) .collect(Collectors.toSet()); assertTrue(workerTokens.contains(workerToken)); assertTrue(workerTokens.contains(workerToken2)); verify(getWorkBudgetDistributor, atLeast(1)) .distributeBudget( any(), eq(GetWorkBudget.builder().setItems(items).setBytes(bytes).build())); verify(streamFactory, times(2)) .createDirectGetWorkStream( any(), eq(getWorkRequest(0, 0)), any(), any(), any(), any(), eq(noOpProcessWorkItemFn())); verify(streamFactory, times(2)).createGetDataStream(any(), any()); verify(streamFactory, times(2)).createCommitWorkStream(any(), any()); }
public List<File> getFiles( File file, String filters, boolean useCache ) throws FileException { try { FileProvider<File> fileProvider = providerService.get( file.getProvider() ); List<File> files; if ( fileCache.containsKey( file ) && useCache ) { files = fileCache.getFiles( file ).stream() .filter( f -> f instanceof Directory || ( f instanceof RepositoryFile && ( (RepositoryFile) f ).passesTypeFilter( filters ) ) || org.pentaho.di.plugins.fileopensave.api.providers.Utils.matches( f.getName(), filters ) ) .collect( Collectors.toList() ); } else { files = fileProvider.getFiles( file, filters, space ); fileCache.setFiles( file, files ); } fileListener.ifPresent( listener -> files.stream().map( this::toLookupInfo ).forEach( listener::onFileLoaded ) ); return files; } catch ( InvalidFileProviderException e ) { return Collections.emptyList(); } }
@Test public void testGetFilesCache() throws FileException { TestDirectory testDirectory = new TestDirectory(); testDirectory.setPath( "/" ); List<File> files = fileController.getFiles( testDirectory, null, true ); Assert.assertEquals( 8, files.size() ); Assert.assertTrue( fileController.fileCache.containsKey( testDirectory ) ); Assert.assertEquals( 8, fileController.fileCache.getFiles( testDirectory ).size() ); }
@Override public VersionedKeyValueStore<K, V> build() { final KeyValueStore<Bytes, byte[]> store = storeSupplier.get(); if (!(store instanceof VersionedBytesStore)) { throw new IllegalStateException("VersionedBytesStoreSupplier.get() must return an instance of VersionedBytesStore"); } return new MeteredVersionedKeyValueStore<>( maybeWrapLogging((VersionedBytesStore) store), // no caching layer for versioned stores storeSupplier.metricsScope(), time, keySerde, valueSerde); }
@Test public void shouldHaveChangeLoggingStoreWhenLoggingEnabled() { setUp(); final VersionedKeyValueStore<String, String> store = builder .withLoggingEnabled(Collections.emptyMap()) .build(); assertThat(store, instanceOf(MeteredVersionedKeyValueStore.class)); final StateStore next = ((WrappedStateStore) store).wrapped(); assertThat(next, instanceOf(ChangeLoggingVersionedKeyValueBytesStore.class)); assertThat(((WrappedStateStore) next).wrapped(), equalTo(inner)); }
public static ExecutableStage forGrpcPortRead( QueryablePipeline pipeline, PipelineNode.PCollectionNode inputPCollection, Set<PipelineNode.PTransformNode> initialNodes) { checkArgument( !initialNodes.isEmpty(), "%s must contain at least one %s.", GreedyStageFuser.class.getSimpleName(), PipelineNode.PTransformNode.class.getSimpleName()); // Choose the environment from an arbitrary node. The initial nodes may not be empty for this // subgraph to make any sense, there has to be at least one processor node // (otherwise the stage is gRPC Read -> gRPC Write, which doesn't do anything). Environment environment = getStageEnvironment(pipeline, initialNodes); ImmutableSet.Builder<PipelineNode.PTransformNode> fusedTransforms = ImmutableSet.builder(); fusedTransforms.addAll(initialNodes); Set<SideInputReference> sideInputs = new LinkedHashSet<>(); Set<UserStateReference> userStates = new LinkedHashSet<>(); Set<TimerReference> timers = new LinkedHashSet<>(); Set<PipelineNode.PCollectionNode> fusedCollections = new LinkedHashSet<>(); Set<PipelineNode.PCollectionNode> materializedPCollections = new LinkedHashSet<>(); Queue<PipelineNode.PCollectionNode> fusionCandidates = new ArrayDeque<>(); for (PipelineNode.PTransformNode initialConsumer : initialNodes) { fusionCandidates.addAll(pipeline.getOutputPCollections(initialConsumer)); sideInputs.addAll(pipeline.getSideInputs(initialConsumer)); userStates.addAll(pipeline.getUserStates(initialConsumer)); timers.addAll(pipeline.getTimers(initialConsumer)); } while (!fusionCandidates.isEmpty()) { PipelineNode.PCollectionNode candidate = fusionCandidates.poll(); if (fusedCollections.contains(candidate) || materializedPCollections.contains(candidate)) { // This should generally mean we get to a Flatten via multiple paths through the graph and // we've already determined what to do with the output. LOG.debug( "Skipping fusion candidate {} because it is {} in this {}", candidate, fusedCollections.contains(candidate) ? "fused" : "materialized", ExecutableStage.class.getSimpleName()); continue; } PCollectionFusibility fusibility = canFuse(pipeline, candidate, environment, fusedCollections); switch (fusibility) { case MATERIALIZE: materializedPCollections.add(candidate); break; case FUSE: // All of the consumers of the candidate PCollection can be fused into this stage. Do so. fusedCollections.add(candidate); fusedTransforms.addAll(pipeline.getPerElementConsumers(candidate)); for (PipelineNode.PTransformNode consumer : pipeline.getPerElementConsumers(candidate)) { // The outputs of every transform fused into this stage must be either materialized or // themselves fused away, so add them to the set of candidates. fusionCandidates.addAll(pipeline.getOutputPCollections(consumer)); sideInputs.addAll(pipeline.getSideInputs(consumer)); } break; default: throw new IllegalStateException( String.format( "Unknown type of %s %s", PCollectionFusibility.class.getSimpleName(), fusibility)); } } return ImmutableExecutableStage.ofFullComponents( pipeline.getComponents(), environment, inputPCollection, sideInputs, userStates, timers, fusedTransforms.build(), materializedPCollections, ExecutableStage.DEFAULT_WIRE_CODER_SETTINGS); }
@Test public void differentEnvironmentsThrows() { // (impulse.out) -> read -> read.out --> go -> go.out // \ // -> py -> py.out // read.out can't be fused with both 'go' and 'py', so we should refuse to create this stage QueryablePipeline p = QueryablePipeline.forPrimitivesIn( partialComponents .toBuilder() .putTransforms( "read", PTransform.newBuilder() .setSpec( FunctionSpec.newBuilder() .setUrn(PTransformTranslation.PAR_DO_TRANSFORM_URN) .build()) .putInputs("input", "impulse.out") .putOutputs("output", "read.out") .build()) .putPcollections( "read.out", PCollection.newBuilder().setUniqueName("read.out").build()) .putTransforms( "goTransform", PTransform.newBuilder() .putInputs("input", "read.out") .putOutputs("output", "go.out") .setSpec( FunctionSpec.newBuilder() .setUrn(PTransformTranslation.PAR_DO_TRANSFORM_URN) .setPayload( ParDoPayload.newBuilder() .setDoFn(FunctionSpec.newBuilder()) .build() .toByteString())) .setEnvironmentId("go") .build()) .putPcollections("go.out", PCollection.newBuilder().setUniqueName("go.out").build()) .putTransforms( "pyTransform", PTransform.newBuilder() .putInputs("input", "read.out") .putOutputs("output", "py.out") .setSpec( FunctionSpec.newBuilder() .setUrn(PTransformTranslation.ASSIGN_WINDOWS_TRANSFORM_URN) .setPayload( WindowIntoPayload.newBuilder() .setWindowFn(FunctionSpec.newBuilder()) .build() .toByteString())) .setEnvironmentId("py") .build()) .putPcollections("py.out", PCollection.newBuilder().setUniqueName("py.out").build()) .putEnvironments("go", Environments.createDockerEnvironment("go")) .putEnvironments("py", Environments.createDockerEnvironment("py")) .build()); Set<PTransformNode> differentEnvironments = p.getPerElementConsumers( PipelineNode.pCollection( "read.out", PCollection.newBuilder().setUniqueName("read.out").build())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("go"); thrown.expectMessage("py"); thrown.expectMessage("same"); GreedyStageFuser.forGrpcPortRead( p, PipelineNode.pCollection( "read.out", PCollection.newBuilder().setUniqueName("read.out").build()), differentEnvironments); }
@GetMapping("/list") @TpsControl(pointName = "NamingServiceListQuery", name = "HttpNamingServiceListQuery") @Secured(action = ActionTypes.READ) public ObjectNode list(HttpServletRequest request) throws Exception { final int pageNo = NumberUtils.toInt(WebUtils.required(request, "pageNo")); final int pageSize = NumberUtils.toInt(WebUtils.required(request, "pageSize")); String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID); String groupName = WebUtils.optional(request, CommonParams.GROUP_NAME, Constants.DEFAULT_GROUP); String selectorString = WebUtils.optional(request, "selector", StringUtils.EMPTY); ObjectNode result = JacksonUtils.createEmptyJsonNode(); Collection<String> serviceNameList = getServiceOperator().listService(namespaceId, groupName, selectorString); result.put("count", serviceNameList.size()); result.replace("doms", JacksonUtils.transferToJsonNode(ServiceUtil.pageServiceName(pageNo, pageSize, serviceNameList))); return result; }
@Test void testList() throws Exception { Mockito.when(serviceOperatorV2.listService(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Collections.singletonList("DEFAULT_GROUP@@providers:com.alibaba.nacos.controller.test:1")); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); servletRequest.addParameter("pageNo", "1"); servletRequest.addParameter("pageSize", "10"); ObjectNode objectNode = serviceController.list(servletRequest); assertEquals(1, objectNode.get("count").asInt()); }
public ImmutableList<Replacement> format( SnippetKind kind, String source, List<Range<Integer>> ranges, int initialIndent, boolean includeComments) throws FormatterException { RangeSet<Integer> rangeSet = TreeRangeSet.create(); for (Range<Integer> range : ranges) { rangeSet.add(range); } if (includeComments) { if (kind != SnippetKind.COMPILATION_UNIT) { throw new IllegalArgumentException( "comment formatting is only supported for compilation units"); } return formatter.getFormatReplacements(source, ranges); } SnippetWrapper wrapper = snippetWrapper(kind, source, initialIndent); ranges = offsetRanges(ranges, wrapper.offset); String replacement = formatter.formatSource(wrapper.contents.toString(), ranges); replacement = replacement.substring( wrapper.offset, replacement.length() - (wrapper.contents.length() - wrapper.offset - source.length())); return toReplacements(source, replacement).stream() .filter(r -> rangeSet.encloses(r.getReplaceRange())) .collect(toImmutableList()); }
@Test public void compilation() throws FormatterException { String input = "/** a\nb*/\nclass Test {\n}"; List<Replacement> replacements = new SnippetFormatter() .format( SnippetKind.COMPILATION_UNIT, input, ImmutableList.of(Range.closedOpen(input.indexOf("class"), input.length())), 4, false); assertThat(replacements).containsExactly(Replacement.create(22, 23, "")); }
@Override public List<String> validateText(String text, List<String> tags) { Assert.isTrue(ENABLED, "敏感词功能未开启,请将 ENABLED 设置为 true"); // 无标签时,默认所有 if (CollUtil.isEmpty(tags)) { return defaultSensitiveWordTrie.validate(text); } // 有标签的情况 Set<String> result = new HashSet<>(); tags.forEach(tag -> { SimpleTrie trie = tagSensitiveWordTries.get(tag); if (trie == null) { return; } result.addAll(trie.validate(text)); }); return new ArrayList<>(result); }
@Test public void testValidateText_noTag() { testInitLocalCache(); // 准备参数 String text = "你是傻瓜,你是笨蛋"; // 调用 List<String> result = sensitiveWordService.validateText(text, null); // 断言 assertEquals(Arrays.asList("傻瓜", "笨蛋"), result); // 准备参数 String text2 = "你是傻瓜,你是笨蛋,你是白"; // 调用 List<String> result2 = sensitiveWordService.validateText(text2, null); // 断言 assertEquals(Arrays.asList("傻瓜", "笨蛋","白"), result2); }
public CompletableFuture<InetSocketAddress> resolveAndCheckTargetAddress(String hostAndPort) { int pos = hostAndPort.lastIndexOf(':'); String host = hostAndPort.substring(0, pos); int port = Integer.parseInt(hostAndPort.substring(pos + 1)); if (!isPortAllowed(port)) { return FutureUtil.failedFuture( new TargetAddressDeniedException("Given port in '" + hostAndPort + "' isn't allowed.")); } else if (!isHostAllowed(host)) { return FutureUtil.failedFuture( new TargetAddressDeniedException("Given host in '" + hostAndPort + "' isn't allowed.")); } else { return NettyFutureUtil.toCompletableFuture( inetSocketAddressResolver.resolve(InetSocketAddress.createUnresolved(host, port))) .thenCompose(resolvedAddress -> { CompletableFuture<InetSocketAddress> result = new CompletableFuture<>(); if (isIPAddressAllowed(resolvedAddress)) { result.complete(resolvedAddress); } else { result.completeExceptionally(new TargetAddressDeniedException( "The IP address of the given host and port '" + hostAndPort + "' isn't allowed.")); } return result; }); } }
@Test public void shouldSupportHostNamePattern() throws Exception { BrokerProxyValidator brokerProxyValidator = new BrokerProxyValidator( createMockedAddressResolver("1.2.3.4"), "*.mydomain" , "1.2.0.0/16" , "6650"); brokerProxyValidator.resolveAndCheckTargetAddress("myhost.mydomain:6650").get(); }
@Override protected String ruleHandler() { return new WebSocketRuleHandle().toJson(); }
@Test public void testRuleHandler() { assertEquals(new WebSocketRuleHandle().toJson(), shenyuClientRegisterWebSocketService.ruleHandler()); }
@Override public RecordCursor cursor() { return new ExampleRecordCursor(columnHandles, byteSource); }
@Test public void testCursorSimple() { RecordSet recordSet = new ExampleRecordSet(new ExampleSplit("test", "schema", "table", dataUri), ImmutableList.of( new ExampleColumnHandle("test", "text", createUnboundedVarcharType(), 0), new ExampleColumnHandle("test", "value", BIGINT, 1))); RecordCursor cursor = recordSet.cursor(); assertEquals(cursor.getType(0), createUnboundedVarcharType()); assertEquals(cursor.getType(1), BIGINT); Map<String, Long> data = new LinkedHashMap<>(); while (cursor.advanceNextPosition()) { data.put(cursor.getSlice(0).toStringUtf8(), cursor.getLong(1)); assertFalse(cursor.isNull(0)); assertFalse(cursor.isNull(1)); } assertEquals(data, ImmutableMap.<String, Long>builder() .put("ten", 10L) .put("eleven", 11L) .put("twelve", 12L) .build()); }
@Override public void run() { try (DbSession dbSession = dbClient.openSession(false)) { List<CeActivityDto> recentSuccessfulTasks = getRecentSuccessfulTasks(dbSession); Collection<String> entityUuids = recentSuccessfulTasks.stream() .map(CeActivityDto::getEntityUuid) .toList(); List<EntityDto> entities = dbClient.entityDao().selectByUuids(dbSession, entityUuids); Map<String, String> entityUuidAndKeys = entities.stream() .collect(Collectors.toMap(EntityDto::getUuid, EntityDto::getKey)); reportObservedDurationForTasks(recentSuccessfulTasks, entityUuidAndKeys); } lastUpdatedTimestamp = system.now(); }
@Test public void run_given5SuccessfulTasks_observeDurationFor5Tasks() { RecentTasksDurationTask task = new RecentTasksDurationTask(dbClient, metrics, config, system); List<CeActivityDto> recentTasks = createTasks(5, 0); when(entityDao.selectByUuids(any(), any())).thenReturn(createEntityDtos(5)); when(ceActivityDao.selectNewerThan(any(), anyLong())).thenReturn(recentTasks); task.run(); verify(metrics, times(5)).observeComputeEngineTaskDuration(anyLong(), any(), any()); }
@Override public double getValue(double quantile) { if (quantile < 0.0 || quantile > 1.0 || Double.isNaN( quantile )) { throw new IllegalArgumentException(quantile + " is not in [0..1]"); } if (values.length == 0) { return 0.0; } final double pos = quantile * (values.length + 1); final int index = (int) pos; if (index < 1) { return values[0]; } if (index >= values.length) { return values[values.length - 1]; } final double lower = values[index - 1]; final double upper = values[index]; return lower + (pos - floor(pos)) * (upper - lower); }
@Test public void smallQuantilesAreTheFirstValue() throws Exception { assertThat(snapshot.getValue(0.0)) .isEqualTo(1, offset(0.1)); }
public static FlinkPod loadPodFromTemplateFile( FlinkKubeClient kubeClient, File podTemplateFile, String mainContainerName) { final KubernetesPod pod = kubeClient.loadPodFromTemplateFile(podTemplateFile); final List<Container> otherContainers = new ArrayList<>(); Container mainContainer = null; if (null != pod.getInternalResource().getSpec()) { for (Container container : pod.getInternalResource().getSpec().getContainers()) { if (mainContainerName.equals(container.getName())) { mainContainer = container; } else { otherContainers.add(container); } } pod.getInternalResource().getSpec().setContainers(otherContainers); } else { // Set an empty spec for pod template pod.getInternalResource().setSpec(new PodSpecBuilder().build()); } if (mainContainer == null) { LOG.info( "Could not find main container {} in pod template, using empty one to initialize.", mainContainerName); mainContainer = new ContainerBuilder().build(); } return new FlinkPod(pod.getInternalResource(), mainContainer); }
@Test void testLoadPodFromTemplateWithNoMainContainerShouldReturnEmptyMainContainer() { final FlinkPod flinkPod = KubernetesUtils.loadPodFromTemplateFile( flinkKubeClient, KubernetesPodTemplateTestUtils.getPodTemplateFile(), "nonExistMainContainer"); assertThat(flinkPod.getMainContainer()).isEqualTo(EMPTY_POD.getMainContainer()); assertThat(flinkPod.getPodWithoutMainContainer().getSpec().getContainers()).hasSize(2); }
public static int getRandomPort() { return RND_PORT_START + ThreadLocalRandom.current().nextInt(RND_PORT_RANGE); }
@Test void testGetRandomPort() { assertThat(NetUtils.getRandomPort(), greaterThanOrEqualTo(30000)); assertThat(NetUtils.getRandomPort(), greaterThanOrEqualTo(30000)); assertThat(NetUtils.getRandomPort(), greaterThanOrEqualTo(30000)); }
@Override public String doLayout(ILoggingEvent event) { StringWriter output = new StringWriter(); try (JsonWriter json = new JsonWriter(output)) { json.beginObject(); if (!"".equals(nodeName)) { json.name("nodename").value(nodeName); } json.name("process").value(processKey); for (Map.Entry<String, String> entry : event.getMDCPropertyMap().entrySet()) { if (entry.getValue() != null && !exclusions.contains(entry.getKey())) { json.name(entry.getKey()).value(entry.getValue()); } } json .name("timestamp").value(DATE_FORMATTER.format(Instant.ofEpochMilli(event.getTimeStamp()))) .name("severity").value(event.getLevel().toString()) .name("logger").value(event.getLoggerName()) .name("message").value(NEWLINE_REGEXP.matcher(event.getFormattedMessage()).replaceAll("\r")); IThrowableProxy tp = event.getThrowableProxy(); if (tp != null) { json.name("stacktrace").beginArray(); int nbOfTabs = 0; while (tp != null) { printFirstLine(json, tp, nbOfTabs); render(json, tp, nbOfTabs); tp = tp.getCause(); nbOfTabs++; } json.endArray(); } json.endObject(); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("BUG - fail to create JSON", e); } output.write(System.lineSeparator()); return output.toString(); }
@Test public void test_simple_log_with_hostname() { LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the message", null, new Object[0]); LogbackJsonLayout underTestWithNodeName = new LogbackJsonLayout("web", "my-nodename"); String log = underTestWithNodeName.doLayout(event); JsonLog json = new Gson().fromJson(log, JsonLog.class); assertThat(json.process).isEqualTo("web"); assertThat(json.timestamp).isEqualTo(DATE_FORMATTER.format(Instant.ofEpochMilli(event.getTimeStamp()))); assertThat(json.severity).isEqualTo("WARN"); assertThat(json.logger).isEqualTo("the.logger"); assertThat(json.message).isEqualTo("the message"); assertThat(json.stacktrace).isNull(); assertThat(json.fromMdc).isNull(); assertThat(json.nodename).isEqualTo("my-nodename"); }
@Udf(description = "Converts a number of milliseconds since 1970-01-01 00:00:00 UTC/GMT into the" + " string representation of the timestamp in the given format. Single quotes in the" + " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'." + " The system default time zone is used when no time zone is explicitly provided." + " The format pattern should be in the format expected" + " by java.time.format.DateTimeFormatter") public String timestampToString( @UdfParameter( description = "Milliseconds since" + " January 1, 1970, 00:00:00 UTC/GMT.") final long epochMilli, @UdfParameter( description = "The format pattern should be in the format expected by" + " java.time.format.DateTimeFormatter.") final String formatPattern) { if (formatPattern == null) { return null; } try { final Timestamp timestamp = new Timestamp(epochMilli); final DateTimeFormatter formatter = formatters.get(formatPattern); return timestamp.toInstant() .atZone(ZoneId.systemDefault()) .format(formatter); } catch (final ExecutionException | RuntimeException e) { throw new KsqlFunctionException("Failed to format timestamp " + epochMilli + " with formatter '" + formatPattern + "': " + e.getMessage(), e); } }
@Test public void testTimeZoneInLocalTime() { // Given: final long timestamp = 1534353043000L; // When: final String localTime = udf.timestampToString(timestamp, "yyyy-MM-dd HH:mm:ss zz"); // Then: final String expected = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zz") .format(new Date(timestamp)); assertThat(localTime, is(expected)); }
public String[] getCoderNames(String codecName) { String[] coderNames = coderNameMap.get(codecName); return coderNames; }
@Test public void testGetCoderNames() { String[] coderNames = CodecRegistry.getInstance(). getCoderNames(ErasureCodeConstants.RS_CODEC_NAME); assertEquals(2, coderNames.length); assertEquals(NativeRSRawErasureCoderFactory.CODER_NAME, coderNames[0]); assertEquals(RSRawErasureCoderFactory.CODER_NAME, coderNames[1]); coderNames = CodecRegistry.getInstance(). getCoderNames(ErasureCodeConstants.RS_LEGACY_CODEC_NAME); assertEquals(1, coderNames.length); assertEquals(RSLegacyRawErasureCoderFactory.CODER_NAME, coderNames[0]); coderNames = CodecRegistry.getInstance(). getCoderNames(ErasureCodeConstants.XOR_CODEC_NAME); assertEquals(2, coderNames.length); assertEquals(NativeXORRawErasureCoderFactory.CODER_NAME, coderNames[0]); assertEquals(XORRawErasureCoderFactory.CODER_NAME, coderNames[1]); }
public URL getSignature(String base, Map<String, String> queryParams) { // Add the RTM specific query params to the map for signing Map<String, String> modifiedParams = new HashMap<>(); modifiedParams.putAll(queryParams); modifiedParams.put("api_key", appCredentials.getKey()); modifiedParams.put("auth_token", authToken); List<String> orderedKeys = modifiedParams.keySet().stream().collect(Collectors.toList()); Collections.sort(orderedKeys); List<String> queryParamStrings = new ArrayList<>(); StringBuilder resultBuilder = new StringBuilder(); resultBuilder.append(appCredentials.getSecret()); for (String key : orderedKeys) { // trim all keys and values from whitespace - We don't want to escape all whitespace values, // because the RTM endpoint will generate the signature with the unescaped whitespace and // compare that to the signature generated. String k = key.trim(); String v = modifiedParams.get(key).trim(); resultBuilder.append(k).append(v); queryParamStrings.add(k + "=" + v); } try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] thedigest = md.digest(resultBuilder.toString().getBytes(StandardCharsets.UTF_8)); String signature = BaseEncoding.base16().encode(thedigest).toLowerCase(); return new URL(base + "?" + String.join("&", queryParamStrings) + "&api_sig=" + signature); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Couldn't find MD5 hash", e); } catch (MalformedURLException e) { throw new IllegalArgumentException("Couldn't parse authUrl", e); } }
@Test public void signatureTest() throws Exception { String base = "http://example.com"; Map<String, String> queryParams = ImmutableMap.of("yxz", "foo", "feg", "bar", "abc", "baz"); URL expected = new URL( base + "?abc=baz&api_key=BANANAS1&auth_token=BANANAS3&feg=bar&yxz=foo&api_sig=b48f0dd1a18179b3068b16728e214561"); assertThat(SIGNATURE_GENERATOR.getSignature(base, queryParams)).isEqualTo(expected); }
public abstract void filter(Metadata metadata) throws TikaException;
@Test public void testCaptureGroupOverwrite() throws Exception { TikaConfig config = getConfig("TIKA-4133-capture-group-overwrite.xml"); Metadata metadata = new Metadata(); metadata.set(TikaCoreProperties.TIKA_CONTENT, "quick brown fox"); metadata.set(Metadata.CONTENT_TYPE, "text/html; charset=UTF-8"); MetadataFilter filter = config.getMetadataFilter(); filter.filter(metadata); assertEquals("quick brown fox", metadata.get(TikaCoreProperties.TIKA_CONTENT)); assertEquals("text/html", metadata.get(Metadata.CONTENT_TYPE)); // now test that a single match overwrites all the values metadata.set(Metadata.CONTENT_TYPE, "text/html; charset=UTF-8"); metadata.add(TikaCoreProperties.TIKA_CONTENT.toString(), "text/html; charset=UTF-8"); metadata.add(TikaCoreProperties.TIKA_CONTENT.toString(), "text/plain; charset=UTF-8"); metadata.add(TikaCoreProperties.TIKA_CONTENT.toString(), "application/pdf; charset=UTF-8"); filter.filter(metadata); assertEquals(1, metadata.getValues(Metadata.CONTENT_TYPE).length); assertEquals("text/html", metadata.get(Metadata.CONTENT_TYPE)); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Target target = getTarget(request); if (target == Target.Other) { chain.doFilter(request, response); return; } HttpServletRequest httpRequest = (HttpServletRequest) request; if (isRateLimited(httpRequest, target)) { incrementStats(target); if (serverConfig.isRateLimiterEnabled()) { ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } } chain.doFilter(request, response); }
@Test public void testCustomClientShedding() throws Exception { // Custom clients will go up to the window limit whenRequest(FULL_FETCH, CUSTOM_CLIENT); filter.doFilter(request, response, filterChain); filter.doFilter(request, response, filterChain); verify(filterChain, times(2)).doFilter(request, response); // Now we hit the limit long rateLimiterCounter = EurekaMonitors.RATE_LIMITED.getCount(); filter.doFilter(request, response, filterChain); assertEquals("Expected rate limiter counter increase", rateLimiterCounter + 1, EurekaMonitors.RATE_LIMITED.getCount()); verify(response, times(1)).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); }
public void start() { if (isPeriodicMaterializeEnabled) { if (!started) { started = true; LOG.info("Task {} starts periodic materialization", subtaskName); scheduleNextMaterialization(initialDelay); } } else { LOG.info("Task {} disable periodic materialization", subtaskName); } }
@Test void testInitialDelay() { ManuallyTriggeredScheduledExecutorService scheduledExecutorService = new ManuallyTriggeredScheduledExecutorService(); long periodicMaterializeDelay = 10_000L; try (PeriodicMaterializationManager test = new PeriodicMaterializationManager( new SyncMailboxExecutor(), newDirectExecutorService(), "test", (message, exception) -> {}, MaterializationTarget.NO_OP, new ChangelogMaterializationMetricGroup( UnregisteredMetricGroups.createUnregisteredOperatorMetricGroup()), true, periodicMaterializeDelay, 0, "subtask-0", scheduledExecutorService)) { test.start(); assertThat( getOnlyElement( scheduledExecutorService .getAllScheduledTasks() .iterator()) .getDelay(MILLISECONDS)) .as( String.format( "task for initial materialization should be scheduled with a 0..%d delay", periodicMaterializeDelay)) .isLessThanOrEqualTo(periodicMaterializeDelay); } }
@Override public void resetConfigStats(RedisClusterNode node) { RedisClient entry = getEntry(node); RFuture<Void> f = executorService.writeAsync(entry, StringCodec.INSTANCE, RedisCommands.CONFIG_RESETSTAT); syncFuture(f); }
@Test public void testResetConfigStats() { RedisClusterNode master = getFirstMaster(); connection.resetConfigStats(master); }
public boolean start( WorkflowSummary workflowSummary, Step step, StepRuntimeSummary runtimeSummary) { StepRuntime.Result result = getStepRuntime(runtimeSummary.getType()) .start(workflowSummary, step, cloneSummary(runtimeSummary)); runtimeSummary.mergeRuntimeUpdate(result.getTimeline(), result.getArtifacts()); switch (result.getState()) { case CONTINUE: case DONE: runtimeSummary.markExecuting(tracingManager); return result.shouldPersist(); case USER_ERROR: markTerminatedWithMetric( runtimeSummary, result.getState(), getUserErrorStatus(runtimeSummary)); return false; case PLATFORM_ERROR: markTerminatedWithMetric( runtimeSummary, result.getState(), getPlatformErrorStatus(runtimeSummary)); return false; case FATAL_ERROR: markTerminatedWithMetric( runtimeSummary, result.getState(), StepInstance.Status.FATALLY_FAILED); return false; case STOPPED: markTerminatedWithMetric(runtimeSummary, result.getState(), StepInstance.Status.STOPPED); return false; case TIMED_OUT: markTerminatedWithMetric(runtimeSummary, result.getState(), StepInstance.Status.TIMED_OUT); return false; default: throw new MaestroInternalError( "Entered an unexpected result state [%s] for step %s when starting", result.getState(), runtimeSummary.getIdentity()); } }
@Test public void testStart() { StepRuntimeSummary summary = StepRuntimeSummary.builder() .type(StepType.NOOP) .stepRetry(StepInstance.StepRetry.from(Defaults.DEFAULT_RETRY_POLICY)) .build(); boolean ret = runtimeManager.start(workflowSummary, null, summary); assertTrue(ret); assertEquals(StepInstance.Status.RUNNING, summary.getRuntimeState().getStatus()); assertNotNull(summary.getRuntimeState().getExecuteTime()); assertNotNull(summary.getRuntimeState().getModifyTime()); assertEquals(1, summary.getPendingRecords().size()); assertEquals( StepInstance.Status.NOT_CREATED, summary.getPendingRecords().get(0).getOldStatus()); assertEquals(StepInstance.Status.RUNNING, summary.getPendingRecords().get(0).getNewStatus()); assertEquals(artifact, summary.getArtifacts().get("test-artifact")); assertTrue(summary.getTimeline().isEmpty()); }
public CatalogueTreeSortStrategy getStrategy(String strategyName) { CatalogueTreeSortStrategy catalogueTreeSortStrategy = Safes.of(catalogueTreeSortStrategyMap).get(strategyName); if (Objects.isNull(catalogueTreeSortStrategy)) { log.warn("Strategy {} is not defined. Use DefaultStrategy", strategyName); catalogueTreeSortStrategy = Safes.of(catalogueTreeSortStrategyMap).get(CatalogueSortConstant.STRATEGY_DEFAULT); } if (Objects.isNull(catalogueTreeSortStrategy)) { throw new BusException(StrUtil.format("Strategy {} is not defined.", strategyName)); } return catalogueTreeSortStrategy; }
@Test public void getStrategyTest2() { when(catalogueTreeSortStrategyMap.get(anyString())).thenAnswer(invocationOnMock -> { String strategy = invocationOnMock.getArgument(0); return mockCatalogueTreeSortStrategyMap.get(strategy); }); CatalogueTreeSortStrategy strategy = catalogueTreeSortFactoryTest.getStrategy("first_letter"); assertEquals(catalogueTreeSortFirstLetterStrategy, strategy); }
@Override public Long createJobLog(Long jobId, LocalDateTime beginTime, String jobHandlerName, String jobHandlerParam, Integer executeIndex) { JobLogDO log = JobLogDO.builder().jobId(jobId).handlerName(jobHandlerName) .handlerParam(jobHandlerParam).executeIndex(executeIndex) .beginTime(beginTime).status(JobLogStatusEnum.RUNNING.getStatus()).build(); jobLogMapper.insert(log); return log.getId(); }
@Test public void testCreateJobLog() { // 准备参数 JobLogDO reqVO = randomPojo(JobLogDO.class, o -> o.setExecuteIndex(1)); // 调用 Long id = jobLogService.createJobLog(reqVO.getJobId(), reqVO.getBeginTime(), reqVO.getHandlerName(), reqVO.getHandlerParam(), reqVO.getExecuteIndex()); // 断言 assertNotNull(id); // 校验记录的属性是否正确 JobLogDO job = jobLogMapper.selectById(id); assertEquals(JobLogStatusEnum.RUNNING.getStatus(), job.getStatus()); }
@Override public long getMin() { if (values.length == 0) { return 0; } return values[0]; }
@Test public void calculatesTheMinimumValue() { assertThat(snapshot.getMin()) .isEqualTo(1); }
public static ObjectInputDecoder createDecoder(Type type, TypeManager typeManager) { String base = type.getTypeSignature().getBase(); switch (base) { case UnknownType.NAME: return o -> o; case BIGINT: return o -> (Long) o; case INTEGER: return o -> ((Long) o).intValue(); case SMALLINT: return o -> ((Long) o).shortValue(); case TINYINT: return o -> ((Long) o).byteValue(); case BOOLEAN: return o -> (Boolean) o; case DATE: return DateTimeUtils::createDate; case DECIMAL: if (Decimals.isShortDecimal(type)) { final int scale = ((DecimalType) type).getScale(); return o -> HiveDecimal.create(BigInteger.valueOf((long) o), scale); } else if (Decimals.isLongDecimal(type)) { final int scale = ((DecimalType) type).getScale(); return o -> HiveDecimal.create(Decimals.decodeUnscaledValue((Slice) o), scale); } break; case REAL: return o -> intBitsToFloat(((Number) o).intValue()); case DOUBLE: return o -> ((Double) o); case TIMESTAMP: return o -> new Timestamp(((long) o)); case VARBINARY: return o -> ((Slice) o).getBytes(); case VARCHAR: return o -> ((Slice) o).toStringUtf8(); case CHAR: return o -> ((Slice) o).toStringUtf8(); case ROW: return RowObjectInputDecoder.create(((RowType) type), typeManager); case ARRAY: return ArrayObjectInputDecoder.create(((ArrayType) type), typeManager); case MAP: return MapObjectInputDecoder.create(((MapType) type), typeManager); } throw unsupportedType(type); }
@Test public void testSliceObjectDecoders() { ObjectInputDecoder decoder; decoder = createDecoder(VARBINARY, typeManager); assertTrue(decoder.decode(Slices.wrappedBuffer(new byte[] {12, 34, 56})) instanceof byte[]); decoder = createDecoder(VARCHAR, typeManager); assertTrue(decoder.decode(Slices.utf8Slice("test_varchar")) instanceof String); decoder = createDecoder(createCharType(10), typeManager); assertTrue(decoder.decode(Slices.utf8Slice("test_char")) instanceof String); }
@Override public Mono<Void> execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) { initCacheConfig(); final String pluginName = named(); PluginData pluginData = BaseDataCache.getInstance().obtainPluginData(pluginName); // early exit if (Objects.isNull(pluginData) || !pluginData.getEnabled()) { return chain.execute(exchange); } final String path = getRawPath(exchange); List<SelectorData> selectors = BaseDataCache.getInstance().obtainSelectorData(pluginName); if (CollectionUtils.isEmpty(selectors)) { return handleSelectorIfNull(pluginName, exchange, chain); } SelectorData selectorData = obtainSelectorDataCacheIfEnabled(path); // handle Selector if (Objects.nonNull(selectorData) && StringUtils.isBlank(selectorData.getId())) { return handleSelectorIfNull(pluginName, exchange, chain); } if (Objects.isNull(selectorData)) { selectorData = trieMatchSelector(exchange, pluginName, path); if (Objects.isNull(selectorData)) { selectorData = defaultMatchSelector(exchange, selectors, path); if (Objects.isNull(selectorData)) { return handleSelectorIfNull(pluginName, exchange, chain); } } } printLog(selectorData, pluginName); if (!selectorData.getContinued()) { // if continued, not match rules return doExecute(exchange, chain, selectorData, defaultRuleData(selectorData)); } List<RuleData> rules = BaseDataCache.getInstance().obtainRuleData(selectorData.getId()); if (CollectionUtils.isEmpty(rules)) { return handleRuleIfNull(pluginName, exchange, chain); } if (selectorData.getType() == SelectorTypeEnum.FULL_FLOW.getCode()) { //get last RuleData rule = rules.get(rules.size() - 1); printLog(rule, pluginName); return doExecute(exchange, chain, selectorData, rule); } // lru map as L1 cache,the cache is enabled by default. // if the L1 cache fails to hit, using L2 cache based on trie cache. // if the L2 cache fails to hit, execute default strategy. RuleData ruleData = obtainRuleDataCacheIfEnabled(path); if (Objects.nonNull(ruleData) && Objects.isNull(ruleData.getId())) { return handleRuleIfNull(pluginName, exchange, chain); } if (Objects.isNull(ruleData)) { // L1 cache not exist data, try to get data through trie cache ruleData = trieMatchRule(exchange, selectorData, path); // trie cache fails to hit, execute default strategy if (Objects.isNull(ruleData)) { ruleData = defaultMatchRule(exchange, rules, path); if (Objects.isNull(ruleData)) { return handleRuleIfNull(pluginName, exchange, chain); } } } printLog(ruleData, pluginName); return doExecute(exchange, chain, selectorData, ruleData); }
@Test public void executeSelectorDataIsNullTest() { BaseDataCache.getInstance().cachePluginData(pluginData); BaseDataCache.getInstance().cacheSelectData(selectorData); StepVerifier.create(testShenyuPlugin.execute(exchange, shenyuPluginChain)).expectSubscription().verifyComplete(); verify(shenyuPluginChain).execute(exchange); }
public static void d(String tag, String message, Object... args) { sLogger.d(tag, message, args); }
@Test public void debug() { String tag = "TestTag"; String message = "Test message"; LogManager.d(tag, message); verify(logger).d(tag, message); }
@Override public AppResponse process(Flow flow, AppRequest body) { if (appSession.getRdaSessionStatus().equals("VERIFIED")) { ((ActivationFlow) flow).activateApp(appAuthenticator, appSession, RDA); digidClient.remoteLog("1219", Map.of(lowerUnderscore(ACCOUNT_ID), appSession.getAccountId(), lowerUnderscore(DEVICE_NAME), appAuthenticator.getDeviceName())); return new StatusResponse("SUCCESS"); } return new NokResponse(); }
@Test void processAppSessionVerified(){ mockedAppSession.setRdaSessionStatus("VERIFIED"); AppResponse appResponse = finalizeRda.process(mockedFlow, mockedAbstractAppRequest); verify(mockedFlow, times(1)).activateApp(mockedAppAuthenticator, mockedAppSession, "rda"); verify(digidClientMock, times(1)).remoteLog("1219", Map.of(lowerUnderscore(ACCOUNT_ID), mockedAppSession.getAccountId(), lowerUnderscore(DEVICE_NAME), mockedAppAuthenticator.getDeviceName())); assertTrue(appResponse instanceof StatusResponse); assertEquals("SUCCESS", ((StatusResponse)appResponse).getStatus()); }
@Override public RelativeRange apply(final Period period) { if (period != null) { return RelativeRange.Builder.builder() .from(period.withYears(0).withMonths(0).plusDays(period.getYears() * 365).plusDays(period.getMonths() * 30).toStandardSeconds().getSeconds()) .build(); } else { return null; } }
@Test void testMinuteConversion() { final RelativeRange result = converter.apply(Period.minutes(30)); verifyResult(result, 1800); }
public boolean parse(final String s) { if (StringUtils.isEmpty(s) || StringUtils.isBlank(s)) { return false; } final String[] tmps = Utils.parsePeerId(s); if (tmps.length < 2 || tmps.length > 4) { return false; } try { final int port = Integer.parseInt(tmps[1]); this.endpoint = new Endpoint(tmps[0], port); switch (tmps.length) { case 3: this.idx = Integer.parseInt(tmps[2]); break; case 4: if (tmps[2].equals("")) { this.idx = 0; } else { this.idx = Integer.parseInt(tmps[2]); } this.priority = Integer.parseInt(tmps[3]); break; default: break; } this.str = null; return true; } catch (final Exception e) { LOG.error("Parse peer from string failed: {}.", s, e); return false; } }
@Test public void testToStringPeerIdFalse() { final PeerId serverId = new PeerId(); assertFalse(serverId.parse(null)); assertFalse(serverId.parse("")); assertFalse(serverId.parse(" ")); }
public static <T> RestResponse<T> toRestResponse( final ResponseWithBody resp, final String path, final Function<ResponseWithBody, T> mapper ) { final int statusCode = resp.getResponse().statusCode(); return statusCode == OK.code() ? RestResponse.successful(statusCode, mapper.apply(resp)) : createErrorResponse(path, resp); }
@Test public void shouldCreateRestResponseFromUnauthorizedResponse() { // Given: when(httpClientResponse.statusCode()).thenReturn(UNAUTHORIZED.code()); // When: final RestResponse<KsqlEntityList> restResponse = KsqlClientUtil.toRestResponse(response, PATH, mapper); // Then: assertThat("is erroneous", restResponse.isErroneous()); assertThat(restResponse.getStatusCode(), is(UNAUTHORIZED.code())); assertThat(restResponse.getErrorMessage().getMessage(), containsString("Could not authenticate successfully with the supplied credential")); }
@SuppressWarnings("unchecked") @Override public OUT[] extract(Object in) { OUT[] output = (OUT[]) Array.newInstance(clazz, order.length); for (int i = 0; i < order.length; i++) { output[i] = (OUT) Array.get(in, this.order[i]); } return output; }
@Test void testStringArray() { // check single field extraction for (int i = 0; i < testStringArray.length; i++) { String[] tmp = {testStringArray[i]}; arrayEqualityCheck( tmp, new FieldsFromArray<>(String.class, i).extract(testStringArray)); } // check reverse order String[] reverseOrder = new String[testStringArray.length]; for (int i = 0; i < testStringArray.length; i++) { reverseOrder[i] = testStringArray[testStringArray.length - i - 1]; } arrayEqualityCheck( reverseOrder, new FieldsFromArray<>(String.class, 4, 3, 2, 1, 0).extract(testStringArray)); // check picking fields and reorder String[] crazyOrder = {testStringArray[4], testStringArray[1], testStringArray[2]}; arrayEqualityCheck( crazyOrder, new FieldsFromArray<>(String.class, 4, 1, 2).extract(testStringArray)); }
static ValueExtractor instantiateExtractor(AttributeConfig config, ClassLoader classLoader) { ValueExtractor extractor = null; if (classLoader != null) { try { extractor = instantiateExtractorWithConfigClassLoader(config, classLoader); } catch (IllegalArgumentException ex) { // cached back-stage, initialised lazily since it's not a common case Logger.getLogger(ExtractorHelper.class) .warning("Could not instantiate extractor with the config class loader", ex); } } if (extractor == null) { extractor = instantiateExtractorWithClassForName(config, classLoader); } return extractor; }
@Test public void instantiate_extractor() { // GIVEN AttributeConfig config = new AttributeConfig("iq", "com.hazelcast.query.impl.getters.ExtractorHelperTest$IqExtractor"); // WHEN ValueExtractor extractor = instantiateExtractor(config); // THEN assertThat(extractor).isInstanceOf(IqExtractor.class); }
public static void onFail(final ServerMemberManager manager, final Member member) { // To avoid null pointer judgments, pass in one NONE_EXCEPTION onFail(manager, member, ExceptionUtil.NONE_EXCEPTION); }
@Test void testMemberOnFailWhenConnectRefused() { final Member remote = buildMember(); mockMemberAddressInfos.add(remote.getAddress()); remote.setFailAccessCnt(1); MemberUtil.onFail(memberManager, remote, new ConnectException(MemberUtil.TARGET_MEMBER_CONNECT_REFUSE_ERRMSG)); assertEquals(2, remote.getFailAccessCnt()); assertEquals(NodeState.DOWN, remote.getState()); assertTrue(mockMemberAddressInfos.isEmpty()); verify(memberManager).notifyMemberChange(remote); }
@Override public void setConfiguration(final Path file, final PasswordCallback prompt, final VersioningConfiguration configuration) throws BackgroundException { final Path container = containerService.getContainer(file); try { final Storage.Buckets.Patch request = session.getClient().buckets().patch(container.getName(), new Bucket().setVersioning(new Bucket.Versioning().setEnabled(configuration.isEnabled()))); if(containerService.getContainer(file).attributes().getCustom().containsKey(GoogleStorageAttributesFinderFeature.KEY_REQUESTER_PAYS)) { request.setUserProject(session.getHost().getCredentials().getUsername()); } request.execute(); cache.remove(container); } catch(IOException e) { throw new GoogleStorageExceptionMappingService().map("Failure to write attributes of {0}", e, container); } }
@Test public void testSetConfiguration() throws Exception { final Path container = new Path(new AsciiRandomStringService().random().toLowerCase(Locale.ROOT), EnumSet.of(Path.Type.directory, Path.Type.volume)); new GoogleStorageDirectoryFeature(session).mkdir(container, new TransferStatus()); final Versioning feature = new GoogleStorageVersioningFeature(session); feature.setConfiguration(container, new DisabledLoginCallback(), new VersioningConfiguration(true, false)); assertTrue(feature.getConfiguration(container).isEnabled()); new GoogleStorageDeleteFeature(session).delete(Collections.<Path>singletonList(container), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
static boolean isReady(@Nullable CompletableFuture<?> future) { return (future != null) && future.isDone() && !future.isCompletedExceptionally() && (future.join() != null); }
@Test(dataProvider = "unsuccessful") public void isReady_fails(CompletableFuture<Integer> future) { assertThat(Async.isReady(future)).isFalse(); }
@SuppressWarnings({"unchecked", "rawtypes"}) public static int compareTo(final Comparable thisValue, final Comparable otherValue, final OrderDirection orderDirection, final NullsOrderType nullsOrderType, final boolean caseSensitive) { if (null == thisValue && null == otherValue) { return 0; } if (null == thisValue) { return NullsOrderType.FIRST == nullsOrderType ? -1 : 1; } if (null == otherValue) { return NullsOrderType.FIRST == nullsOrderType ? 1 : -1; } if (!caseSensitive && thisValue instanceof String && otherValue instanceof String) { return compareToCaseInsensitiveString((String) thisValue, (String) otherValue, orderDirection); } return OrderDirection.ASC == orderDirection ? thisValue.compareTo(otherValue) : -thisValue.compareTo(otherValue); }
@Test void assertCompareToWhenSecondValueIsNullForOrderByAscAndNullsLast() { assertThat(CompareUtils.compareTo(1, null, OrderDirection.ASC, NullsOrderType.LAST, caseSensitive), is(-1)); }
public static SkillChallengeClue forText(String text, String rawText) { for (SkillChallengeClue clue : CLUES) { if (rawText.equalsIgnoreCase(clue.returnText)) { clue.setChallengeCompleted(true); return clue; } else if (text.equals(clue.rawChallenge)) { clue.setChallengeCompleted(false); return clue; } } return null; }
@Test public void forTextEmptyString() { assertNull(SkillChallengeClue.forText("", "")); }
public PushConnection remove(final String clientId) { final PushConnection pc = clientPushConnectionMap.remove(clientId); return pc; }
@Test void testRemove() { pushConnectionRegistry.put("clientId1", pushConnection); assertEquals(pushConnection, pushConnectionRegistry.remove("clientId1")); assertNull(pushConnectionRegistry.get("clientId1")); }
@Override public String getName() { return _name; }
@Test public void testBigDecimalSerDeTransformFunction() { ExpressionContext expression = RequestContextUtils.getExpression(String.format("bigDecimalToBytes(%s)", BIG_DECIMAL_SV_COLUMN)); TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap); assertTrue(transformFunction instanceof ScalarTransformFunctionWrapper); assertEquals(transformFunction.getName(), "bigDecimalToBytes"); byte[][] expectedBytesValues = new byte[NUM_ROWS][]; for (int i = 0; i < NUM_ROWS; i++) { expectedBytesValues[i] = BigDecimalUtils.serialize(_bigDecimalSVValues[i]); } testTransformFunction(transformFunction, expectedBytesValues); expression = RequestContextUtils.getExpression( String.format("bytesToBigDecimal(bigDecimalToBytes(%s))", BIG_DECIMAL_SV_COLUMN)); transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap); assertTrue(transformFunction instanceof ScalarTransformFunctionWrapper); assertEquals(transformFunction.getName(), "bytesToBigDecimal"); testTransformFunction(transformFunction, _bigDecimalSVValues); }
@Override public MapperResult findConfigInfo4PageFetchRows(MapperContext context) { final String tenant = (String) context.getWhereParameter(FieldConstant.TENANT_ID); final String dataId = (String) context.getWhereParameter(FieldConstant.DATA_ID); final String group = (String) context.getWhereParameter(FieldConstant.GROUP_ID); final String appName = (String) context.getWhereParameter(FieldConstant.APP_NAME); final String content = (String) context.getWhereParameter(FieldConstant.CONTENT); final String[] tagArr = (String[]) context.getWhereParameter(FieldConstant.TAG_ARR); List<Object> paramList = new ArrayList<>(); StringBuilder where = new StringBuilder(" WHERE "); final String sql = "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a LEFT JOIN " + "config_tags_relation b ON a.id=b.id"; where.append(" a.tenant_id=? "); paramList.add(tenant); if (StringUtils.isNotBlank(dataId)) { where.append(" AND a.data_id=? "); paramList.add(dataId); } if (StringUtils.isNotBlank(group)) { where.append(" AND a.group_id=? "); paramList.add(group); } if (StringUtils.isNotBlank(appName)) { where.append(" AND a.app_name=? "); paramList.add(appName); } if (!StringUtils.isBlank(content)) { where.append(" AND a.content LIKE ? "); paramList.add(content); } where.append(" AND b.tag_name IN ("); for (int i = 0; i < tagArr.length; i++) { if (i != 0) { where.append(", "); } where.append('?'); paramList.add(tagArr[i]); } where.append(") "); return new MapperResult(sql + where + " LIMIT " + context.getStartRow() + "," + context.getPageSize(), paramList); }
@Test void testFindConfigInfo4PageFetchRows() { context.putWhereParameter(FieldConstant.DATA_ID, "dataID1"); context.putWhereParameter(FieldConstant.GROUP_ID, "groupID1"); context.putWhereParameter(FieldConstant.APP_NAME, "AppName1"); context.putWhereParameter(FieldConstant.CONTENT, "Content1"); MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfo4PageFetchRows(context); assertEquals("SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info " + "a LEFT JOIN config_tags_relation b ON a.id=b.id " + "WHERE a.tenant_id=? AND a.data_id=? AND a.group_id=? AND a.app_name=? AND a.content LIKE ? " + " AND b.tag_name IN (?, ?, ?, ?, ?) LIMIT " + startRow + "," + pageSize, mapperResult.getSql()); List<Object> list = CollectionUtils.list(tenantId); list.add("dataID1"); list.add("groupID1"); list.add("AppName1"); list.add("Content1"); list.addAll(Arrays.asList(tagArr)); assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); }
@Override public byte[] retrieveSecret(SecretIdentifier identifier) { if (identifier != null && identifier.getKey() != null && !identifier.getKey().isEmpty()) { try { lock.lock(); loadKeyStore(); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBE"); KeyStore.SecretKeyEntry secretKeyEntry = (KeyStore.SecretKeyEntry) keyStore.getEntry(identifier.toExternalForm(), protectionParameter); //not found if (secretKeyEntry == null) { LOGGER.debug("requested secret {} not found", identifier.toExternalForm()); return null; } PBEKeySpec passwordBasedKeySpec = (PBEKeySpec) factory.getKeySpec(secretKeyEntry.getSecretKey(), PBEKeySpec.class); //base64 encoded char[] char[] base64secret = passwordBasedKeySpec.getPassword(); byte[] secret = SecretStoreUtil.base64Decode(base64secret); passwordBasedKeySpec.clearPassword(); LOGGER.debug("retrieved secret {}", identifier.toExternalForm()); return secret; } catch (Exception e) { throw new SecretStoreException.RetrievalException(identifier, e); } finally { releaseLock(lock); } } return null; }
@Test public void retrieveMissingSecret() { assertThat(keyStore.retrieveSecret(new SecretIdentifier("does-not-exist"))).isNull(); }
public static File[] getPathFiles(String path) throws FileNotFoundException { URL url = ResourceUtils.class.getClassLoader().getResource(path); if (url == null) { throw new FileNotFoundException("path not found: " + path); } return Arrays.stream(Objects.requireNonNull(new File(url.getPath()).listFiles(), "No files in " + path)) .filter(File::isFile).toArray(File[]::new); }
@Test public void testGetPathFilesNotFound() { assertThrows(FileNotFoundException.class, () -> ResourceUtils.getPathFiles("doesn't exist")); }
@Override public PageResult<OAuth2AccessTokenDO> getAccessTokenPage(OAuth2AccessTokenPageReqVO reqVO) { return oauth2AccessTokenMapper.selectPage(reqVO); }
@Test public void testGetAccessTokenPage() { // mock 数据 OAuth2AccessTokenDO dbAccessToken = randomPojo(OAuth2AccessTokenDO.class, o -> { // 等会查询到 o.setUserId(10L); o.setUserType(1); o.setClientId("test_client"); o.setExpiresTime(LocalDateTime.now().plusDays(1)); }); oauth2AccessTokenMapper.insert(dbAccessToken); // 测试 userId 不匹配 oauth2AccessTokenMapper.insert(cloneIgnoreId(dbAccessToken, o -> o.setUserId(20L))); // 测试 userType 不匹配 oauth2AccessTokenMapper.insert(cloneIgnoreId(dbAccessToken, o -> o.setUserType(2))); // 测试 userType 不匹配 oauth2AccessTokenMapper.insert(cloneIgnoreId(dbAccessToken, o -> o.setClientId("it_client"))); // 测试 expireTime 不匹配 oauth2AccessTokenMapper.insert(cloneIgnoreId(dbAccessToken, o -> o.setExpiresTime(LocalDateTimeUtil.now()))); // 准备参数 OAuth2AccessTokenPageReqVO reqVO = new OAuth2AccessTokenPageReqVO(); reqVO.setUserId(10L); reqVO.setUserType(1); reqVO.setClientId("test"); // 调用 PageResult<OAuth2AccessTokenDO> pageResult = oauth2TokenService.getAccessTokenPage(reqVO); // 断言 assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getList().size()); assertPojoEquals(dbAccessToken, pageResult.getList().get(0)); }
void checkFlow(ResourceWrapper resource, Context context, DefaultNode node, int count, boolean prioritized) throws BlockException { checker.checkFlow(ruleProvider, resource, context, node, count, prioritized); }
@Test @SuppressWarnings("unchecked") public void testCheckFlowPass() throws Exception { FlowRuleChecker checker = mock(FlowRuleChecker.class); FlowSlot flowSlot = new FlowSlot(checker); Context context = mock(Context.class); DefaultNode node = mock(DefaultNode.class); doCallRealMethod().when(checker).checkFlow(any(Function.class), any(ResourceWrapper.class), any(Context.class), any(DefaultNode.class), anyInt(), anyBoolean()); String resA = "resAK"; String resB = "resBK"; FlowRule rule1 = new FlowRule(resA).setCount(10); FlowRule rule2 = new FlowRule(resB).setCount(10); // Here we only load rules for resA. FlowRuleManager.loadRules(Collections.singletonList(rule1)); when(checker.canPassCheck(eq(rule1), any(Context.class), any(DefaultNode.class), anyInt(), anyBoolean())) .thenReturn(true); when(checker.canPassCheck(eq(rule2), any(Context.class), any(DefaultNode.class), anyInt(), anyBoolean())) .thenReturn(false); flowSlot.checkFlow(new StringResourceWrapper(resA, EntryType.IN), context, node, 1, false); flowSlot.checkFlow(new StringResourceWrapper(resB, EntryType.IN), context, node, 1, false); }
@Override public Set<TopicAnomaly> topicAnomalies() { LOG.info("Start to detect topic replication factor anomaly."); Cluster cluster = _kafkaCruiseControl.kafkaCluster(); Set<String> topicsToCheck; if (_topicExcludedFromCheck.pattern().isEmpty()) { topicsToCheck = new HashSet<>(cluster.topics()); } else { topicsToCheck = new HashSet<>(); cluster.topics().stream().filter(topic -> !_topicExcludedFromCheck.matcher(topic).matches()).forEach(topicsToCheck::add); } refreshTopicMinISRCache(); if (!topicsToCheck.isEmpty()) { maybeRetrieveAndCacheTopicMinISR(topicsToCheck); Map<Short, Set<TopicReplicationFactorAnomalyEntry>> badTopicsByDesiredRF = populateBadTopicsByDesiredRF(topicsToCheck, cluster); if (!badTopicsByDesiredRF.isEmpty()) { return Collections.singleton(createTopicReplicationFactorAnomaly(badTopicsByDesiredRF, _targetReplicationFactor)); } } return Collections.emptySet(); }
@Test public void testAnomalyDetection() throws InterruptedException, ExecutionException, TimeoutException { KafkaCruiseControl mockKafkaCruiseControl = mockKafkaCruiseControl(); AdminClient mockAdminClient = mockAdminClient((short) 1); TopicReplicationFactorAnomalyFinder anomalyFinder = new TopicReplicationFactorAnomalyFinder(mockKafkaCruiseControl, TARGET_TOPIC_REPLICATION_FACTOR, TOPIC_REPLICATION_FACTOR_MARGIN, mockAdminClient); Set<TopicAnomaly> topicAnomalies = anomalyFinder.topicAnomalies(); assertEquals(1, topicAnomalies.size()); EasyMock.verify(mockKafkaCruiseControl, mockAdminClient); }
@SuppressWarnings("unchecked") public static <T extends Throwable> T wrap(Throwable throwable, Class<T> wrapThrowable) { if (wrapThrowable.isInstance(throwable)) { return (T) throwable; } return ReflectUtil.newInstance(wrapThrowable, throwable); }
@Test public void wrapTest() { IORuntimeException e = ExceptionUtil.wrap(new IOException(), IORuntimeException.class); assertNotNull(e); }
@Override public int compare(final List<String> o1, final List<String> o2) { if (o1.size() < o2.size()) { return -1; } else if (o1.size() > o2.size()) { return 1; } else { int index = 0; while (index < o1.size()) { String item1 = o1.get(index); String item2 = o2.get(index++); final int comparisonResult = item1.compareToIgnoreCase(item2); if (comparisonResult != 0) { return comparisonResult; } } return 0; } }
@Test void testEmptyListIsSmallerThanListWithElements() { assertTrue(toTest.compare(List.of(), List.of("mum")) < 0); assertTrue(toTest.compare(List.of("mum", "Dad"), List.of()) > 0); }
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { handleFetchSuccess(fetchTarget, data, clientResponse); } }, (fetchTarget, data, error) -> { synchronized (Fetcher.this) { handleFetchFailure(fetchTarget, data, error); } }); return fetchRequests.size(); }
@Test public void testFetchedRecordsRaisesOnSerializationErrors() { // raise an exception from somewhere in the middle of the fetch response // so that we can verify that our position does not advance after raising ByteArrayDeserializer deserializer = new ByteArrayDeserializer() { int i = 0; @Override public byte[] deserialize(String topic, byte[] data) { if (i++ % 2 == 1) { // Should be blocked on the value deserialization of the first record. assertEquals("value-1", new String(data, StandardCharsets.UTF_8)); throw new SerializationException(); } return data; } }; buildFetcher(deserializer, deserializer); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 1); client.prepareResponse(matchesOffset(tidp0, 1), fullFetchResponse(tidp0, records, Errors.NONE, 100L, 0)); assertEquals(1, sendFetches()); consumerClient.poll(time.timer(0)); for (int i = 0; i < 2; i++) { // The fetcher should throw a Deserialization error assertThrows(SerializationException.class, this::collectFetch); // the position should not advance since no data has been returned assertEquals(1, subscriptions.position(tp0).offset); } }
public Optional<UpdateCenter> getUpdateCenter(boolean refreshUpdateCenter) { Optional<UpdateCenter> updateCenter = centerClient.getUpdateCenter(refreshUpdateCenter); if (updateCenter.isPresent()) { org.sonar.api.utils.Version fullVersion = sonarQubeVersion.get(); org.sonar.api.utils.Version semanticVersion = org.sonar.api.utils.Version.create(fullVersion.major(), fullVersion.minor(), fullVersion.patch()); return Optional.of(updateCenter.get().setInstalledSonarVersion(Version.create(semanticVersion.toString())).registerInstalledPlugins( installedPluginReferentialFactory.getInstalledPluginReferential()) .setDate(centerClient.getLastRefreshDate())); } return Optional.empty(); }
@Test public void return_absent_update_center() { UpdateCenterClient updateCenterClient = mock(UpdateCenterClient.class); when(updateCenterClient.getUpdateCenter(anyBoolean())).thenReturn(Optional.empty()); underTest = new UpdateCenterMatrixFactory(updateCenterClient, mock(SonarQubeVersion.class), mock(InstalledPluginReferentialFactory.class)); Optional<UpdateCenter> updateCenter = underTest.getUpdateCenter(false); assertThat(updateCenter).isEmpty(); }
public JmxCollector register() { return register(PrometheusRegistry.defaultRegistry); }
@Test public void testEnumValue() throws Exception { JmxCollector jc = new JmxCollector( "\n---\nrules:\n- pattern: `org.bean.enum<type=StateMetrics.*>State: RUNNING`\n name: bean_running\n value: 1" .replace('`', '"')) .register(prometheusRegistry); assertEquals(1.0, getSampleValue("bean_running", new String[] {}, new String[] {}), .001); }
@Udf public Map<String, String> splitToMap( @UdfParameter( description = "Separator string and values to join") final String input, @UdfParameter( description = "Separator string and values to join") final String entryDelimiter, @UdfParameter( description = "Separator string and values to join") final String kvDelimiter) { if (input == null || entryDelimiter == null || kvDelimiter == null) { return null; } if (entryDelimiter.isEmpty() || kvDelimiter.isEmpty() || entryDelimiter.equals(kvDelimiter)) { return null; } final Iterable<String> entries = Splitter.on(entryDelimiter).omitEmptyStrings().split(input); return StreamSupport.stream(entries.spliterator(), false) .filter(e -> e.contains(kvDelimiter)) .map(kv -> Splitter.on(kvDelimiter).split(kv).iterator()) .collect(Collectors.toMap( Iterator::next, Iterator::next, (v1, v2) -> v2)); }
@Test public void shouldReturnNullOnNullInputString() { Map<String, String> result = udf.splitToMap(null, "/", ":="); assertThat(result, is(nullValue())); }
@ExecuteOn(TaskExecutors.IO) @Get(uri = "{namespace}/files/directory") @Operation(tags = {"Files"}, summary = "List directory content") public List<FileAttributes> list( @Parameter(description = "The namespace id") @PathVariable String namespace, @Parameter(description = "The internal storage uri") @Nullable @QueryValue URI path ) throws IOException, URISyntaxException { forbiddenPathsGuard(path); NamespaceFile namespaceFile = NamespaceFile.of(namespace, path); if (namespaceFile.isRootDirectory() && !storageInterface.exists(tenantService.resolveTenant(), NamespaceFile.of(namespace).uri())) { storageInterface.createDirectory(tenantService.resolveTenant(), NamespaceFile.of(namespace).uri()); return Collections.emptyList(); } return storageInterface.list(tenantService.resolveTenant(), namespaceFile.uri()); }
@Test void list() throws IOException { String hw = "Hello World"; storageInterface.put(null, toNamespacedStorageUri(NAMESPACE, URI.create("/test/test.txt")), new ByteArrayInputStream(hw.getBytes())); storageInterface.put(null, toNamespacedStorageUri(NAMESPACE, URI.create("/test/test2.txt")), new ByteArrayInputStream(hw.getBytes())); List<FileAttributes> res = List.of(client.toBlocking().retrieve(HttpRequest.GET("/api/v1/namespaces/" + NAMESPACE + "/files/directory"), TestFileAttributes[].class)); assertThat(res.stream().map(FileAttributes::getFileName).toList(), Matchers.containsInAnyOrder("test")); res = List.of(client.toBlocking().retrieve(HttpRequest.GET("/api/v1/namespaces/" + NAMESPACE + "/files/directory?path=/test"), TestFileAttributes[].class)); assertThat(res.stream().map(FileAttributes::getFileName).toList(), Matchers.containsInAnyOrder("test.txt", "test2.txt")); }
public static Path fromString(String path) { return fromString(path, "/"); }
@Test(expected = IllegalArgumentException.class) public void testDoubleDot() { Path.fromString("foo/../bar"); }
@Override public Set<K> keySet() { return keySet(null); }
@Test public void testKeySet() { Map<SimpleKey, SimpleValue> map = redisson.getMap("simple"); map.put(new SimpleKey("1"), new SimpleValue("2")); map.put(new SimpleKey("33"), new SimpleValue("44")); map.put(new SimpleKey("5"), new SimpleValue("6")); assertThat(map.keySet()).containsOnly(new SimpleKey("33"), new SimpleKey("1"), new SimpleKey("5")); }
static boolean unprotectedSetTimes( FSDirectory fsd, INodesInPath iip, long mtime, long atime, boolean force) throws FileNotFoundException { assert fsd.hasWriteLock(); boolean status = false; INode inode = iip.getLastINode(); if (inode == null) { throw new FileNotFoundException("File/Directory " + iip.getPath() + " does not exist."); } int latest = iip.getLatestSnapshotId(); if (mtime >= 0) { inode = inode.setModificationTime(mtime, latest); status = true; } // if the last access time update was within the last precision interval, // then no need to store access time if (atime >= 0 && (status || force || atime > inode.getAccessTime() + fsd.getAccessTimePrecision())) { inode.setAccessTime(atime, latest, fsd.getFSNamesystem().getSnapshotManager(). getSkipCaptureAccessTimeOnlyChange()); status = true; } return status; }
@Test(expected = FileNotFoundException.class) public void testUnprotectedSetTimesFNFE() throws FileNotFoundException { FSDirectory fsd = Mockito.mock(FSDirectory.class); INodesInPath iip = Mockito.mock(INodesInPath.class); when(fsd.hasWriteLock()).thenReturn(Boolean.TRUE); when(iip.getLastINode()).thenReturn(null); FSDirAttrOp.unprotectedSetTimes(fsd, iip, 0, 0, false); }
public static Patch<String> diffInline(String original, String revised) { List<String> origList = new ArrayList<>(); List<String> revList = new ArrayList<>(); for (Character character : original.toCharArray()) { origList.add(character.toString()); } for (Character character : revised.toCharArray()) { revList.add(character.toString()); } Patch<String> patch = DiffUtils.diff(origList, revList); for (AbstractDelta<String> delta : patch.getDeltas()) { delta.getSource().setLines(compressLines(delta.getSource().getLines(), "")); delta.getTarget().setLines(compressLines(delta.getTarget().getLines(), "")); } return patch; }
@Test public void testDiffInline() { final Patch<String> patch = DiffUtils.diffInline("", "test"); assertEquals(1, patch.getDeltas().size()); assertTrue(patch.getDeltas().get(0) instanceof InsertDelta); assertEquals(0, patch.getDeltas().get(0).getSource().getPosition()); assertEquals(0, patch.getDeltas().get(0).getSource().getLines().size()); assertEquals("test", patch.getDeltas().get(0).getTarget().getLines().get(0)); }
public SqlConfig setCatalogPersistenceEnabled(final boolean catalogPersistenceEnabled) { this.catalogPersistenceEnabled = catalogPersistenceEnabled; return this; }
@Test public void testSQLPersistenceEnabledWithoutEELicense() { final Config config = new Config(); config.getSqlConfig().setCatalogPersistenceEnabled(true); assertThatThrownBy(() -> Hazelcast.newHazelcastInstance(config)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("SQL Catalog Persistence requires Hazelcast Enterprise Edition"); }
@Override public <V1, R> KTable<K, R> outerJoin(final KTable<K, V1> other, final ValueJoiner<? super V, ? super V1, ? extends R> joiner) { return outerJoin(other, joiner, NamedInternal.empty()); }
@Test public void shouldThrowNullPointerOnOuterJoinWhenMaterializedIsNull() { assertThrows(NullPointerException.class, () -> table.outerJoin(table, MockValueJoiner.TOSTRING_JOINER, (Materialized) null)); }
@Override public int getColumnLength(final Object value) { return 8; }
@Test void assertGetColumnLength() { assertThat(new PostgreSQLDoubleBinaryProtocolValue().getColumnLength(""), is(8)); }
public static List<String> withRemovedMetricAlias(Collection<String> metrics) { if (metrics.contains(REMOVED_METRIC)) { Set<String> newMetrics = new HashSet<>(metrics); newMetrics.remove(REMOVED_METRIC); newMetrics.add(DEPRECATED_METRIC_REPLACEMENT); return newMetrics.stream().toList(); } else { return new ArrayList<>(metrics); } }
@Test void withRemovedMetricAlias_whenListContainsAccepted_shouldReturnListWithAccepted() { List<String> coreMetrics = List.of("accepted_issues", "blocker_violations", "critical_violations"); List<String> upToDateMetrics = RemovedMetricConverter.withRemovedMetricAlias(coreMetrics); assertThat(upToDateMetrics).containsExactlyInAnyOrder("accepted_issues", "blocker_violations", "critical_violations"); }
@Override public boolean isAutoIncrement(final int column) { Preconditions.checkArgument(1 == column); return true; }
@Test void assertIsAutoIncrement() throws SQLException { assertTrue(actualMetaData.isAutoIncrement(1)); }
@Override public HttpHeaders add(HttpHeaders headers) { if (headers instanceof DefaultHttpHeaders) { this.headers.add(((DefaultHttpHeaders) headers).headers); return this; } else { return super.add(headers); } }
@Test public void addObjects() { final DefaultHttpHeaders headers = newDefaultDefaultHttpHeaders(); headers.add(HEADER_NAME, HeaderValue.THREE.asList()); assertDefaultValues(headers, HeaderValue.THREE); }
@Override public void open(Map<String, Object> config, SinkContext sinkContext) throws Exception { alluxioSinkConfig = AlluxioSinkConfig.load(config); alluxioSinkConfig.validate(); // initialize FileSystem String alluxioMasterHost = alluxioSinkConfig.getAlluxioMasterHost(); int alluxioMasterPort = alluxioSinkConfig.getAlluxioMasterPort(); configuration.set(PropertyKey.MASTER_HOSTNAME, alluxioMasterHost); configuration.set(PropertyKey.MASTER_RPC_PORT, alluxioMasterPort); if (alluxioSinkConfig.getSecurityLoginUser() != null) { configuration.set(PropertyKey.SECURITY_LOGIN_USERNAME, alluxioSinkConfig.getSecurityLoginUser()); } fileSystem = FileSystem.Factory.create(configuration); // initialize alluxio dirs String alluxioDir = alluxioSinkConfig.getAlluxioDir(); fileDirPath = alluxioDir.startsWith("/") ? alluxioDir : "/" + alluxioDir; tmpFileDirPath = fileDirPath + "/tmp"; AlluxioURI alluxioDirPath = new AlluxioURI(fileDirPath); if (!fileSystem.exists(alluxioDirPath)) { fileSystem.createDirectory(alluxioDirPath); } AlluxioURI tmpAlluxioDirPath = new AlluxioURI(tmpFileDirPath); if (!fileSystem.exists(tmpAlluxioDirPath)) { fileSystem.createDirectory(tmpAlluxioDirPath); } recordsNum = 0; recordsToAck = Lists.newArrayList(); tmpFilePath = ""; alluxioState = AlluxioState.WRITE_STARTED; lastRotationTime = System.currentTimeMillis(); rotationRecordsNum = alluxioSinkConfig.getRotationRecords(); rotationInterval = alluxioSinkConfig.getRotationInterval(); }
@Test public void openTest() throws Exception { map.put("filePrefix", "TopicA"); map.put("fileExtension", ".txt"); map.put("lineSeparator", "\n"); map.put("rotationRecords", "100"); String alluxioDir = "/pulsar"; sink = new AlluxioSink(); sink.open(map, mockSinkContext); FileSystem client = cluster.getClient(); AlluxioURI alluxioURI = new AlluxioURI(alluxioDir); Assert.assertTrue(client.exists(alluxioURI)); String alluxioTmpDir = FilenameUtils.concat(alluxioDir, "tmp"); AlluxioURI alluxioTmpURI = new AlluxioURI(alluxioTmpDir); Assert.assertTrue(client.exists(alluxioTmpURI)); sink.close(); }
public boolean isEmpty() { return value == null; }
@Test public void isEmptyTest() { // 这是jdk11 Optional中的新函数,直接照搬了过来 // 判断包裹内元素是否为空,注意并没有判断空字符串的情况 boolean isEmpty = Opt.empty().isEmpty(); assertTrue(isEmpty); }
@Override public void restRequest(RestRequest request, Callback<RestResponse> callback, String routeKey) { this.restRequest(request, new RequestContext(), callback, routeKey); }
@Test public void testRouteLookupClientCallback() throws InterruptedException, ExecutionException, TimeoutException { RouteLookup routeLookup = new SimpleTestRouteLookup(); final D2Client d2Client = new D2ClientBuilder().setZkHosts("localhost:2121").build(); d2Client.start(new FutureCallback<>()); RouteLookupClient routeLookupClient = new RouteLookupClient(d2Client, routeLookup, "WestCoast"); RestRequest dummyRestRequest = new RestRequestBuilder(URI.create("d2://simple_uri")).build(); FutureCallback<RestResponse> futureCallback = new FutureCallback<>(); routeLookupClient.restRequest(dummyRestRequest,futureCallback, "5555"); try { RestResponse response = futureCallback.get(10, TimeUnit.SECONDS); Assert.fail("Unexpected success, request should have thrown a ServiceUnavailableException"); } catch (Exception e) { String message = e.getMessage(); if (!message.contains("_serviceName=simple_uriWestCoast5555Foo")) { Assert.fail("request was not rewritten to point at the d2 service simple_uriWestCoast5555Foo"); } } }
public void setRocketMQMessageListener(RocketMQMessageListener anno) { this.rocketMQMessageListener = anno; this.consumeMode = anno.consumeMode(); this.consumeThreadMax = anno.consumeThreadMax(); this.consumeThreadNumber = anno.consumeThreadNumber(); this.messageModel = anno.messageModel(); this.selectorType = anno.selectorType(); this.selectorExpression = anno.selectorExpression(); this.consumeTimeout = anno.consumeTimeout(); this.maxReconsumeTimes = anno.maxReconsumeTimes(); this.replyTimeout = anno.replyTimeout(); this.tlsEnable = anno.tlsEnable(); this.namespace = anno.namespace(); this.namespaceV2 = anno.namespaceV2(); this.delayLevelWhenNextConsume = anno.delayLevelWhenNextConsume(); this.suspendCurrentQueueTimeMillis = anno.suspendCurrentQueueTimeMillis(); this.awaitTerminationMillisWhenShutdown = Math.max(0, anno.awaitTerminationMillisWhenShutdown()); this.instanceName = anno.instanceName(); }
@Test public void testSetRocketMQMessageListener() { DefaultRocketMQListenerContainer container = new DefaultRocketMQListenerContainer(); RocketMQMessageListener anno = TestRocketMQMessageListener.class.getAnnotation(RocketMQMessageListener.class); container.setRocketMQMessageListener(anno); assertEquals(anno.consumeMode(), container.getConsumeMode()); assertEquals(anno.consumeThreadMax(), container.getConsumeThreadMax()); assertEquals(anno.consumeThreadNumber(), container.getConsumeThreadNumber()); assertEquals(anno.messageModel(), container.getMessageModel()); assertEquals(anno.selectorType(), container.getSelectorType()); assertEquals(anno.selectorExpression(), container.getSelectorExpression()); assertEquals(anno.tlsEnable(), container.getTlsEnable()); assertEquals(anno.namespace(), container.getNamespace()); assertEquals(anno.namespaceV2(), container.getNamespaceV2()); assertEquals(anno.delayLevelWhenNextConsume(), container.getDelayLevelWhenNextConsume()); assertEquals(anno.suspendCurrentQueueTimeMillis(), container.getSuspendCurrentQueueTimeMillis()); assertEquals(anno.instanceName(), container.getInstanceName()); }
@Override public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { try { session.sftp().rename(file.getAbsolute(), renamed.getAbsolute(), status.isExists() ? new HashSet<>(Arrays.asList(RenameFlags.OVERWRITE, RenameFlags.NATIVE)) : Collections.singleton(RenameFlags.NATIVE)); // Copy original file attributes return renamed.withAttributes(file.attributes()); } catch(IOException e) { throw new SFTPExceptionMappingService().map("Cannot rename {0}", e, file); } }
@Test public void testMove() throws Exception { final Path workdir = new SFTPHomeDirectoryService(session).find(); final Path test = new SFTPTouchFeature(session).touch(new Path(workdir, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)), new TransferStatus()); assertEquals(TransferStatus.UNKNOWN_LENGTH, test.attributes().getSize()); final Path target = new SFTPMoveFeature(session).move(test, new Path(workdir, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)), new TransferStatus(), new Delete.DisabledCallback(), new DisabledConnectionCallback()); assertFalse(new SFTPFindFeature(session).find(test)); assertTrue(new SFTPFindFeature(session).find(target)); assertEquals(test.attributes(), target.attributes()); new SFTPDeleteFeature(session).delete(Collections.<Path>singletonList(target), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
public static TrustManager[] trustManager(boolean needAuth, String trustCertPath) { if (needAuth) { try { return trustCertPath == null ? null : buildSecureTrustManager(trustCertPath); } catch (SSLException e) { LOGGER.warn("degrade trust manager as build failed, " + "will trust all certs."); return trustAll; } } else { return trustAll; } }
@Test void testTrustManagerSuccess() throws CertificateException { URL url = SelfTrustManagerTest.class.getClassLoader().getResource("test-tls-cert.pem"); String path = url.getPath(); TrustManager[] actual = SelfTrustManager.trustManager(true, path); assertNotNull(actual); assertEquals(1, actual.length); assertTrue(actual[0] instanceof X509TrustManager); assertFalse(actual[0].getClass().getCanonicalName().startsWith("com.alibaba.nacos")); X509TrustManager x509TrustManager = (X509TrustManager) actual[0]; X509Certificate[] certificates = x509TrustManager.getAcceptedIssuers(); assertNotNull(certificates); x509TrustManager.checkClientTrusted(certificates, "a"); x509TrustManager.checkServerTrusted(certificates, "b"); }
public String getSlotInfo() { StringBuilder sb = new StringBuilder(); int index = this.index + 1; for (int i = 0; i < slotCount; i++) { if (i > 0) { sb.append(' '); } sb.append(this.data[(i + index) % slotCount].get()); } return sb.toString(); }
@Test void testGetSlotInfo() { SimpleFlowData simpleFlowData = new SimpleFlowData(5, 10000); simpleFlowData.incrementAndGet(); simpleFlowData.incrementAndGet(); simpleFlowData.incrementAndGet(); assertEquals("0 0 0 0 3", simpleFlowData.getSlotInfo()); }
public static <K, V> AsMap<K, V> asMap() { return new AsMap<>(false); }
@Test @Category(ValidatesRunner.class) public void testMapSideInputWithNullValuesCatchesDuplicates() { final PCollectionView<Map<String, Integer>> view = pipeline .apply( "CreateSideInput", Create.of(KV.of("a", (Integer) null), KV.of("a", (Integer) null)) .withCoder( KvCoder.of(StringUtf8Coder.of(), NullableCoder.of(VarIntCoder.of())))) .apply(View.asMap()); PCollection<KV<String, Integer>> output = pipeline .apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) .apply( "OutputSideInputs", ParDo.of( new DoFn<String, KV<String, Integer>>() { @ProcessElement public void processElement(ProcessContext c) { c.output( KV.of( c.element(), c.sideInput(view) .getOrDefault(c.element().substring(0, 1), 0))); } }) .withSideInputs(view)); PAssert.that(output) .containsInAnyOrder(KV.of("apple", 1), KV.of("banana", 3), KV.of("blackberry", 3)); // As long as we get an error, be flexible with how a runner surfaces it thrown.expect(Exception.class); pipeline.run(); }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LinkParameter {\n"); sb.append("}"); return sb.toString(); }
@Test public void testToString() { LinkParameter linkParameter = new LinkParameter(); linkParameter.setValue("foo"); Assert.assertEquals(linkParameter.toString(), "class LinkParameter {\n}"); }
@Operation(summary = "registerUser", description = "REGISTER_USER_NOTES") @Parameters({ @Parameter(name = "userName", description = "USER_NAME", required = true, schema = @Schema(implementation = String.class)), @Parameter(name = "userPassword", description = "USER_PASSWORD", required = true, schema = @Schema(implementation = String.class)), @Parameter(name = "repeatPassword", description = "REPEAT_PASSWORD", required = true, schema = @Schema(implementation = String.class)), @Parameter(name = "email", description = "EMAIL", required = true, schema = @Schema(implementation = String.class)), }) @PostMapping("/register") @ResponseStatus(HttpStatus.OK) @ApiException(CREATE_USER_ERROR) public Result<Object> registerUser(@RequestParam(value = "userName") String userName, @RequestParam(value = "userPassword") String userPassword, @RequestParam(value = "repeatPassword") String repeatPassword, @RequestParam(value = "email") String email) throws Exception { userName = ParameterUtils.handleEscapes(userName); userPassword = ParameterUtils.handleEscapes(userPassword); repeatPassword = ParameterUtils.handleEscapes(repeatPassword); email = ParameterUtils.handleEscapes(email); Result<Object> verifyRet = usersService.verifyUserName(userName); if (verifyRet.getCode() != Status.SUCCESS.getCode()) { return verifyRet; } Map<String, Object> result = usersService.registerUser(userName, userPassword, repeatPassword, email); return returnDataList(result); }
@Test public void testRegisterUser() throws Exception { MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("userName", "user_test"); paramsMap.add("userPassword", "123456qwe?"); paramsMap.add("repeatPassword", "123456qwe?"); paramsMap.add("email", "[email protected]"); MvcResult mvcResult = mockMvc.perform(post("/users/register") .header(SESSION_ID, sessionId) .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); }
private void fail(final ChannelHandlerContext ctx, int length) { fail(ctx, String.valueOf(length)); }
@Test public void testTooLongLine2AndEmitLastLine() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new LenientLineBasedFrameDecoder(16, false, false, true)); assertFalse(ch.writeInbound(copiedBuffer("12345678901234567", CharsetUtil.US_ASCII))); try { ch.writeInbound(copiedBuffer("890\r\nfirst\r\n", CharsetUtil.US_ASCII)); fail(); } catch (Exception e) { assertThat(e, is(instanceOf(TooLongFrameException.class))); } ByteBuf buf = ch.readInbound(); ByteBuf buf2 = copiedBuffer("first\r\n", CharsetUtil.US_ASCII); assertThat(buf, is(buf2)); assertThat(ch.finish(), is(false)); buf.release(); buf2.release(); }
@Override public TListTableStatusResult listTableStatus(TGetTablesParams params) throws TException { LOG.debug("get list table request: {}", params); TListTableStatusResult result = new TListTableStatusResult(); List<TTableStatus> tablesResult = Lists.newArrayList(); result.setTables(tablesResult); PatternMatcher matcher = null; boolean caseSensitive = CaseSensibility.TABLE.getCaseSensibility(); if (params.isSetPattern()) { try { matcher = PatternMatcher.createMysqlPattern(params.getPattern(), caseSensitive); } catch (SemanticException e) { throw new TException("Pattern is in bad format " + params.getPattern()); } } Database db = GlobalStateMgr.getCurrentState().getDb(params.db); long limit = params.isSetLimit() ? params.getLimit() : -1; UserIdentity currentUser; if (params.isSetCurrent_user_ident()) { currentUser = UserIdentity.fromThrift(params.current_user_ident); } else { currentUser = UserIdentity.createAnalyzedUserIdentWithIp(params.user, params.user_ip); } if (db != null) { Locker locker = new Locker(); locker.lockDatabase(db, LockType.READ); try { boolean listingViews = params.isSetType() && TTableType.VIEW.equals(params.getType()); List<Table> tables = listingViews ? db.getViews() : db.getTables(); OUTER: for (Table table : tables) { try { Authorizer.checkAnyActionOnTableLikeObject(currentUser, null, params.db, table); } catch (AccessDeniedException e) { continue; } if (!PatternMatcher.matchPattern(params.getPattern(), table.getName(), matcher, caseSensitive)) { continue; } TTableStatus status = new TTableStatus(); status.setName(table.getName()); status.setType(table.getMysqlType()); status.setEngine(table.getEngine()); status.setComment(table.getComment()); status.setCreate_time(table.getCreateTime()); status.setLast_check_time(table.getLastCheckTime()); if (listingViews) { View view = (View) table; String ddlSql = view.getInlineViewDef(); ConnectContext connectContext = new ConnectContext(); connectContext.setQualifiedUser(AuthenticationMgr.ROOT_USER); connectContext.setCurrentUserIdentity(UserIdentity.ROOT); connectContext.setCurrentRoleIds(Sets.newHashSet(PrivilegeBuiltinConstants.ROOT_ROLE_ID)); try { List<TableName> allTables = view.getTableRefs(); for (TableName tableName : allTables) { Table tbl = db.getTable(tableName.getTbl()); if (tbl != null) { try { Authorizer.checkAnyActionOnTableLikeObject(currentUser, null, db.getFullName(), tbl); } catch (AccessDeniedException e) { continue OUTER; } } } } catch (SemanticException e) { // ignore semantic exception because view maybe invalid } status.setDdl_sql(ddlSql); } tablesResult.add(status); // if user set limit, then only return limit size result if (limit > 0 && tablesResult.size() >= limit) { break; } } } finally { locker.unLockDatabase(db, LockType.READ); } } return result; }
@Test public void testListTableStatus() throws TException { FrontendServiceImpl impl = new FrontendServiceImpl(exeEnv); TListTableStatusResult result = impl.listTableStatus(buildListTableStatusParam()); Assert.assertEquals(7, result.tables.size()); }
@Override public void monitor(RedisServer master) { connection.sync(RedisCommands.SENTINEL_MONITOR, master.getName(), master.getHost(), master.getPort().intValue(), master.getQuorum().intValue()); }
@Test public void testMonitor() { Collection<RedisServer> masters = connection.masters(); RedisServer master = masters.iterator().next(); master.setName(master.getName() + ":"); connection.monitor(master); }
public static boolean isCarVin(CharSequence value) { return isMatchRegex(CAR_VIN, value); }
@Test public void isCarVinTest() { assertTrue(Validator.isCarVin("LSJA24U62JG269225")); assertTrue(Validator.isCarVin("LDC613P23A1305189")); assertFalse(Validator.isCarVin("LOC613P23A1305189")); assertTrue(Validator.isCarVin("LSJA24U62JG269225")); //标准分类1 assertTrue(Validator.isCarVin("LDC613P23A1305189")); //标准分类1 assertTrue(Validator.isCarVin("LBV5S3102ESJ25655")); //标准分类1 assertTrue(Validator.isCarVin("LBV5S3102ESJPE655")); //标准分类2 assertFalse(Validator.isCarVin("LOC613P23A1305189")); //错误示例 }
public abstract byte[] encode(MutableSpan input);
@Test void span_noRemoteServiceName_JSON_V2() { clientSpan.remoteServiceName(null); assertThat(new String(encoder.encode(clientSpan), UTF_8)) .isEqualTo( "{\"traceId\":\"7180c278b62e8f6a216a2aea45d08fc9\",\"parentId\":\"6b221d5bc9e6496c\",\"id\":\"5b4185666d50f68b\",\"kind\":\"CLIENT\",\"name\":\"get\",\"timestamp\":1472470996199000,\"duration\":207000,\"localEndpoint\":{\"serviceName\":\"frontend\",\"ipv4\":\"127.0.0.1\"},\"remoteEndpoint\":{\"ipv4\":\"192.168.99.101\",\"port\":9000},\"annotations\":[{\"timestamp\":1472470996238000,\"value\":\"foo\"},{\"timestamp\":1472470996403000,\"value\":\"bar\"}],\"tags\":{\"clnt/finagle.version\":\"6.45.0\",\"http.path\":\"/api\"}}"); }
public static FromMatchesFilter create(Jid address) { return new FromMatchesFilter(address, address != null ? address.hasNoResource() : false) ; }
@Test public void autoCompareMatchingBaseJid() { FromMatchesFilter filter = FromMatchesFilter.create(BASE_JID1); Stanza packet = StanzaBuilder.buildMessage().build(); packet.setFrom(BASE_JID1); assertTrue(filter.accept(packet)); packet.setFrom(FULL_JID1_R1); assertTrue(filter.accept(packet)); packet.setFrom(FULL_JID1_R2); assertTrue(filter.accept(packet)); packet.setFrom(BASE_JID2); assertFalse(filter.accept(packet)); packet.setFrom(FULL_JID2); assertFalse(filter.accept(packet)); packet.setFrom(BASE_JID3); assertFalse(filter.accept(packet)); }
@Override public boolean isAuthenticationRequired(SubjectConnectionReference conn) { Subject subject = conn.getSubject(); if (subject.isAuthenticated()) { //already authenticated: return false; } //subject is not authenticated. Authentication is required by default for all accounts other than //the anonymous user (if enabled) or the vm account (if enabled) if (isAnonymousAccessAllowed()) { if (isAnonymousAccount(subject)) { return false; } } if (!isVmConnectionAuthenticationRequired()) { if (isSystemAccount(subject)) { return false; } } return true; }
@Test public void testIsAuthenticationRequiredWhenSystemConnectionDoesNotRequireAuthenticationAndNotSystemAccount() { Subject subject = new SubjectAdapter() { @Override public PrincipalCollection getPrincipals() { return new SimplePrincipalCollection("foo", "iniRealm"); } }; SubjectConnectionReference sc = new SubjectConnectionReference(new ConnectionContext(), new ConnectionInfo(), new DefaultEnvironment(), subject); assertTrue(policy.isAuthenticationRequired(sc)); }
public static <T> TypeSerializer<T> wrapIfNullIsNotSupported( @Nonnull TypeSerializer<T> originalSerializer, boolean padNullValueIfFixedLen) { return checkIfNullSupported(originalSerializer) ? originalSerializer : wrap(originalSerializer, padNullValueIfFixedLen); }
@Test void testWrappingNeeded() { assertThat(nullableSerializer) .isInstanceOf(NullableSerializer.class) .isEqualTo( NullableSerializer.wrapIfNullIsNotSupported( nullableSerializer, isPaddingNullValue())); }
public void resolveDcMetadata(SamlRequest samlRequest) throws DienstencatalogusException { final DcMetadataResponse metadataFromDc = dienstencatalogusClient.retrieveMetadataFromDc(samlRequest); if (samlRequest instanceof AuthenticationRequest) { dcMetadataResponseMapper.dcMetadataToAuthenticationRequest((AuthenticationRequest) samlRequest, metadataFromDc, samlRequest.getServiceEntityId()); } else { dcMetadataResponseMapper.dcMetadataToSamlRequest(samlRequest, metadataFromDc); } }
@Test public void resolveSamlRequestDcMetadataTest() throws DienstencatalogusException { when(dienstencatalogusClientMock.retrieveMetadataFromDc(any(SamlRequest.class))).thenReturn(stubDcResponse()); SamlRequest request = new ArtifactResolveRequest(); request.setConnectionEntityId(CONNECTION_ENTITY_ID); request.setServiceEntityId(SERVICE_ENTITY_ID); dcMetadataService.resolveDcMetadata(request); assertEquals("federation1", request.getFederationName()); assertEquals(1, request.getLegacyWebserviceId()); assertEquals("serviceUUID", request.getServiceUuid()); assertEquals("permissionQuestion", request.getPermissionQuestion()); assertNotNull(request.getConnectionEntity()); assertNotNull(request.getServiceEntity()); }
public static String getProperty(String propertyName, String envName) { return System.getenv().getOrDefault(envName, System.getProperty(propertyName)); }
@Test void getProperty() { System.setProperty("nacos.test", "google"); String property = PropertyUtils.getProperty("nacos.test", "xx"); assertEquals("google", property); }