focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public synchronized void patchConnectorConfig(String connName, Map<String, String> configPatch, Callback<Created<ConnectorInfo>> callback) { try { ConnectorInfo connectorInfo = connectorInfo(connName); if (connectorInfo == null) { callback.onCompletion(new N...
@Test public void testPatchConnectorConfigNotFound() { initialize(false); Map<String, String> connConfigPatch = new HashMap<>(); connConfigPatch.put("foo1", "baz1"); Callback<Herder.Created<ConnectorInfo>> patchCallback = mock(Callback.class); herder.patchConnectorConfig(CON...
public static LocalDateTime parse(CharSequence text) { return parse(text, (DateTimeFormatter) null); }
@Test public void parseTest4() { final LocalDateTime localDateTime = LocalDateTimeUtil.parse("2020-01-23T12:23:56"); assertEquals("2020-01-23T12:23:56", localDateTime.toString()); }
public String generateRedirectUrl(String artifact, String transactionId, String sessionId, BvdStatus status) throws SamlSessionException, UnsupportedEncodingException { final var samlSession = findSamlSessionByArtifactOrTransactionId(artifact, transactionId); if (CANCELLED.equals(status)) s...
@Test void redirectWithWrongArtifact() { when(samlSessionRepositoryMock.findByArtifact(anyString())).thenReturn(Optional.empty()); Exception exception = assertThrows(SamlSessionException.class, () -> assertionConsumerServiceUrlService.generateRedirectUrl("IncorrectArtifact", null, "...
@Override public void flush() throws IOException { if(log.isWarnEnabled()) { log.warn(String.format("Flush stream %s", proxy)); } this.flush(true); }
@Test public void testFlush() throws Exception { final ByteArrayOutputStream proxy = new ByteArrayOutputStream(20); final MemorySegementingOutputStream out = new MemorySegementingOutputStream(proxy, 32768); final byte[] content = RandomUtils.nextBytes(40500); out.write(content, 0, 32...
@Override public CompletableFuture<SchemaVersion> putSchemaIfAbsent(String schemaId, SchemaData schema, SchemaCompatibilityStrategy strategy) { try { SchemaDataValidator.va...
@Test public void testPutSchemaIfAbsentWithBadSchemaData() { String schemaId = "test-schema-id"; SchemaCompatibilityStrategy strategy = SchemaCompatibilityStrategy.FULL; CompletableFuture<SchemaVersion> future = new CompletableFuture<>(); when(underlyingService.putSchemaIfAbsent(eq(s...
@Override public Timestamp getValue() { return value; }
@Test public void getValue() { RubyTimeStampGauge gauge = new RubyTimeStampGauge("bar", RUBY_TIMESTAMP); assertThat(gauge.getValue()).isEqualTo(RUBY_TIMESTAMP.getTimestamp()); assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_RUBYTIMESTAMP); //Null initialize gauge = ne...
@SuppressWarnings("rawtypes") @Override @SneakyThrows(ReflectiveOperationException.class) public Map<String, Class<?>> getYamlShortcuts() { Collection<YamlRuleConfigurationSwapper> swappers = ShardingSphereServiceLoader.getServiceInstances(YamlRuleConfigurationSwapper.class); Map<String, Cla...
@Test void assertGetYamlShortcuts() { Map<String, Class<?>> actual = new YamlRuleConfigurationShortcuts().getYamlShortcuts(); assertThat(actual.size(), is(1)); assertTrue(actual.containsKey("!FIXTURE")); }
public static ParamType getSchemaFromType(final Type type) { return getSchemaFromType(type, JAVA_TO_ARG_TYPE); }
@Test public void shouldGetGenericSchemaFromType() throws NoSuchMethodException { // Given: final Type genericType = getClass().getMethod("genericType").getGenericReturnType(); // When: final ParamType returnType = UdfUtil.getSchemaFromType(genericType); // Then: MatcherAssert.assertThat(ret...
@Override public RedisClusterNode clusterGetNodeForSlot(int slot) { Iterable<RedisClusterNode> res = clusterGetNodes(); for (RedisClusterNode redisClusterNode : res) { if (redisClusterNode.isMaster() && redisClusterNode.getSlotRange().contains(slot)) { return redisCluster...
@Test public void testClusterGetNodeForSlot() { RedisClusterNode node1 = connection.clusterGetNodeForSlot(1); RedisClusterNode node2 = connection.clusterGetNodeForSlot(16000); assertThat(node1.getId()).isNotEqualTo(node2.getId()); }
static void closeStateManager(final Logger log, final String logPrefix, final boolean closeClean, final boolean eosEnabled, final ProcessorStateManager stateMgr, ...
@Test public void testCloseStateManagerWithStateStoreWipeOutRethrowWrappedIOException() { final File unknownFile = new File("/unknown/path"); final InOrder inOrder = inOrder(stateManager, stateDirectory); when(stateManager.taskId()).thenReturn(taskId); when(stateDirectory.lock(taskId...
@Override public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException { if (metric == null) { throw new NullPointerException("metric == null"); } return metric; }
@Test public void registerNullMetric() { MetricRegistry registry = new NoopMetricRegistry(); assertThatNullPointerException() .isThrownBy(() -> registry.register("any_name", null)) .withMessage("metric == null"); }
@Nullable static String channelName(@Nullable Destination destination) { if (destination == null) return null; boolean isQueue = isQueue(destination); try { if (isQueue) { return ((Queue) destination).getQueueName(); } else { return ((Topic) destination).getTopicName(); } ...
@Test void channelName_queueAndTopic_null() { assertThat(MessageParser.channelName(null)).isNull(); }
@Override public void validateJoinRequest(JoinMessage joinMessage) { // check joining member's major.minor version is same as current cluster version's major.minor numbers MemberVersion memberVersion = joinMessage.getMemberVersion(); Version clusterVersion = node.getClusterService().getClust...
@Test public void test_joinRequestFails_whenPreviousMinorVersion() { assumeTrue("Minor version is 0", nodeVersion.getMinor() > 0); MemberVersion nextMinorVersion = MemberVersion.of(nodeVersion.getMajor(), nodeVersion.getMinor() - 1, nodeVersion.getPatch()); JoinRequest joinRe...
@Deprecated @Restricted(DoNotUse.class) public static String resolve(ConfigurationContext context, String toInterpolate) { return context.getSecretSourceResolver().resolve(toInterpolate); }
@Test public void resolve_JsonWithSpaceInKey() { String input = "{ \"abc def\": 1, \"b\": 2 }"; environment.set("FOO", input); String output = resolve("${json:abc def:${FOO}}"); assertThat(output, equalTo("1")); }
public static boolean notEqualWithinTolerance(double left, double right, double tolerance) { if (Doubles.isFinite(left) && Doubles.isFinite(right)) { return Math.abs(left - right) > Math.abs(tolerance); } else { return false; } }
@Test public void floatNotEquals() { assertThat(notEqualWithinTolerance(1.3f, 1.3f, 0.00000000000001f)).isFalse(); assertThat(notEqualWithinTolerance(1.3f, 1.3f, 0.0f)).isFalse(); assertThat( notEqualWithinTolerance(0.0f, 1.0f + 2.0f - 3.0f, 0.00000000000000000000000000000001f)) .isFal...
public static List<ParameterMarkerExpressionSegment> getParameterMarkerExpressions(final Collection<ExpressionSegment> expressions) { List<ParameterMarkerExpressionSegment> result = new ArrayList<>(); extractParameterMarkerExpressions(result, expressions); return result; }
@Test void assertGetParameterMarkerExpressionsFromTypeCastExpression() { ParameterMarkerExpressionSegment expected = new ParameterMarkerExpressionSegment(0, 0, 1, ParameterMarkerType.DOLLAR); Collection<ExpressionSegment> input = Collections.singleton(new TypeCastExpression(0, 0, "$2::varchar", expe...
@Override public List<PartitionInfo> getPartitions(Table table, List<String> partitionNames) { Map<String, Partition> partitionMap = Maps.newHashMap(); IcebergTable icebergTable = (IcebergTable) table; PartitionsTable partitionsTable = (PartitionsTable) MetadataTableUtils. cr...
@Test public void testGetPartitions2() { mockedNativeTableG.newAppend().appendFile(FILE_B_5).commit(); IcebergHiveCatalog icebergHiveCatalog = new IcebergHiveCatalog(CATALOG_NAME, new Configuration(), DEFAULT_CONFIG); CachingIcebergCatalog cachingIcebergCatalog = new CachingIcebergCatalog(C...
@Override public DdlCommand create( final String sqlExpression, final DdlStatement ddlStatement, final SessionConfig config ) { return FACTORIES .getOrDefault(ddlStatement.getClass(), (statement, cf, ci) -> { throw new KsqlException( "Unable to find ddl command ...
@Test public void shouldCreateStreamCommandWithSingleValueWrappingFromOverridesNotConfig() { // Given: givenCommandFactories(); ksqlConfig = new KsqlConfig(ImmutableMap.of( KsqlConfig.KSQL_WRAP_SINGLE_VALUES, true )); final ImmutableMap<String, Object> overrides = ImmutableMap.of( ...
@Override public void resolve(ConcurrentJobModificationException e) { final List<Job> concurrentUpdatedJobs = e.getConcurrentUpdatedJobs(); final List<ConcurrentJobModificationResolveResult> failedToResolve = concurrentUpdatedJobs .stream() .map(this::resolve) ...
@Test void concurrentStateChangeFromProcessingToDeletedIsAllowedAndInterruptsThread() { final Job job1 = aJobInProgress().build(); final Job job2 = aJobInProgress().build(); final Thread job1Thread = mock(Thread.class); final Thread job2Thread = mock(Thread.class); when(sto...
@Override public Result run(GoPluginDescriptor pluginDescriptor, Map<String, List<String>> extensionsInfoOfPlugin) { final ValidationResult validationResult = validate(pluginDescriptor, extensionsInfoOfPlugin); return new Result(validationResult.hasError(), validationResult.toErrorMessage()); }
@Test void shouldAddErrorAndReturnValidationResultWhenPluginRequiredExtensionIsNotSupportedByGoCD() { final PluginPostLoadHook.Result validationResult = pluginExtensionsAndVersionValidator.run(descriptor, Map.of("some-invalid-extension", List.of("2.0"))); assertThat(validationResult.isAFailure()).i...
@Override public URL getLocalArtifactUrl(DependencyJar dependency) { String depShortName = dependency.getShortName(); String pathStr = properties.getProperty(depShortName); if (pathStr != null) { if (pathStr.indexOf(File.pathSeparatorChar) != -1) { throw new IllegalArgumentException( ...
@Test public void whenMissingFromProperties_shouldDelegate() throws Exception { DependencyResolver resolver = new PropertiesDependencyResolver(propsFile("nothing", new File("interesting")), mock); when(mock.getLocalArtifactUrl(exampleDep)).thenReturn(new URL("file:///path/3")); URL url = resolver...
@ApiOperation(value = "Delete a user’s info", tags = { "Users" }, code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the user was found and the info for the given key has been deleted. Response body is left empty intentionally."), @ApiResponse(code = 404, messa...
@Test public void testDeleteUserInfo() throws Exception { User savedUser = null; try { User newUser = identityService.newUser("testuser"); newUser.setFirstName("Fred"); newUser.setLastName("McDonald"); newUser.setEmail("no-reply@flowable.org"); ...
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { final List<Path> deleted = new ArrayList<Path>(); for(Map.Entry<Path, TransferStatus> entry : files.entrySet()) { boolean skip = false;...
@Test public void testDeleteDirectory() throws Exception { final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)); new DAVDirectoryFeature(session).mkdir(test, new TransferStatus()); assertTrue...
public static Interval of(String interval, TimeRange timeRange) { switch (timeRange.type()) { case TimeRange.KEYWORD: return timestampInterval(interval); case TimeRange.ABSOLUTE: return ofAbsoluteRange(interval, (AbsoluteRange)timeRange); case TimeRange.RELATI...
@Test public void approximatesAutoIntervalWithScalingIfAbsoluteRangeAndBeyondLimits() { final AbsoluteRange absoluteRange = AbsoluteRange.create( DateTime.parse("2019-12-02T12:50:23Z"), DateTime.parse("2019-12-02T14:50:23Z") ); final Interval interval = Appro...
public static String toString(InputStream input, String encoding) throws IOException { return (null == encoding) ? toString(new InputStreamReader(input, Constants.ENCODE)) : toString(new InputStreamReader(input, encoding)); }
@Test void testToStringV2() { try { Reader reader = new CharArrayReader("test".toCharArray()); String actualValue = MD5Util.toString(reader); assertEquals("test", actualValue); } catch (IOException e) { System.out.println(e.toString()); ...
@Override public final void restore() throws Exception { restoreInternal(); }
@Test void testSubTaskInitializationMetrics() throws Exception { StreamTaskMailboxTestHarnessBuilder<Integer> builder = new StreamTaskMailboxTestHarnessBuilder<>( OneInputStreamTask::new, BasicTypeInfo.INT_TYPE_INFO) .addInput(BasicType...
@SuppressWarnings("ReturnValueIgnored") void startStreams() { getWorkStream.get(); getDataStream.get(); commitWorkStream.get(); workCommitter.get().start(); // *stream.get() is all memoized in a threadsafe manner. started.set(true); }
@Test public void testStartStream_onlyStartsStreamsOnceConcurrent() throws InterruptedException { long itemBudget = 1L; long byteBudget = 1L; WindmillStreamSender windmillStreamSender = newWindmillStreamSender( GetWorkBudget.builder().setBytes(byteBudget).setItems(itemBudget).build())...
@Override public void serialize(Asn1OutputStream out, byte[] obj) { out.write(0); out.write(obj); }
@Test public void shouldSerialize() { assertArrayEquals( new byte[] { 0, 1, 2, 3 }, serialize(new BitStringToByteArrayConverter(), byte[].class, new byte[] { 1, 2, 3 }) ); }
@Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } if (this == o) { return true; } NamingListenerInvoker that = (NamingListenerInvoker) o; return Objects.equals(listener,...
@Test public void testEquals() { EventListener listener1 = mock(EventListener.class); EventListener listener2 = mock(EventListener.class); NamingListenerInvoker invoker1 = new NamingListenerInvoker(listener1); NamingListenerInvoker invoker2 = new NamingListenerInvoker(listener1); ...
public static ExpressionTree parseFilterTree(String filter) throws MetaException { return PartFilterParser.parseFilter(filter); }
@Test public void testParseFilterWithInvalidTimestampWithType() { MetaException exception = assertThrows(MetaException.class, () -> PartFilterExprUtil.parseFilterTree("(j = TIMESTAMP'2023-06-02 99:35:00')")); assertTrue(exception.getMessage().contains("Error parsing partition filter")); }
public String normalizeNamespace(String appId, String namespaceName) { AppNamespace appNamespace = appNamespaceServiceWithCache.findByAppIdAndNamespace(appId, namespaceName); if (appNamespace != null) { return appNamespace.getName(); } appNamespace = appNamespaceServiceWithCache.findPublicNamespa...
@Test public void testNormalizeNamespaceWithPrivateNamespace() throws Exception { String someAppId = "someAppId"; String someNamespaceName = "someNamespaceName"; String someNormalizedNamespaceName = "someNormalizedNamespaceName"; AppNamespace someAppNamespace = mock(AppNamespace.class); when(some...
@Override public void execute(Exchange exchange) throws SmppException { DataSm dataSm = createDataSm(exchange); if (log.isDebugEnabled()) { log.debug("Sending a data short message for exchange id '{}'...", exchange.getExchangeId()); } DataSmResult result; try { ...
@Test public void execute() throws Exception { Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "DataSm"); exchange.getIn().setHeader(SmppConstants.SERVICE_TYPE, "XXX"); exchange.getIn().setHe...
public SmppCommand createSmppCommand(SMPPSession session, Exchange exchange) { SmppCommandType commandType = SmppCommandType.fromExchange(exchange); return commandType.createCommand(session, configuration); }
@Test public void createSmppQuerySmCommand() { SMPPSession session = new SMPPSession(); Exchange exchange = new DefaultExchange(new DefaultCamelContext()); exchange.getIn().setHeader(SmppConstants.COMMAND, "QuerySm"); SmppCommand command = binding.createSmppCommand(session, exchange...
public static <T> void invokeAll(List<Callable<T>> callables, long timeoutMs) throws TimeoutException, ExecutionException { ExecutorService service = Executors.newCachedThreadPool(); try { invokeAll(service, callables, timeoutMs); } finally { service.shutdownNow(); } }
@Test public void invokeAllPropagatesExceptionWithTimeout() throws Exception { int numTasks = 5; final AtomicInteger id = new AtomicInteger(); List<Callable<Void>> tasks = new ArrayList<>(); final Exception testException = new Exception("test message"); for (int i = 0; i < numTasks; i++) { t...
@Override public void init(File dataFile, @Nullable Set<String> fieldsToRead, @Nullable RecordReaderConfig recordReaderConfig) throws IOException { File parquetFile = RecordReaderUtils.unpackIfRequired(dataFile, EXTENSION); if (recordReaderConfig != null && ((ParquetRecordReaderConfig) recordReaderConfi...
@Test public void testParquetAvroRecordReader() throws IOException { ParquetAvroRecordReader avroRecordReader = new ParquetAvroRecordReader(); avroRecordReader.init(_dataFile, null, new ParquetRecordReaderConfig()); testReadParquetFile(avroRecordReader, SAMPLE_RECORDS_SIZE); }
@Override public Optional<Language> find(String languageKey) { return Optional.ofNullable(languagesByKey.get(languageKey)); }
@Test public void find_by_other_key_returns_absent() { LanguageRepositoryImpl languageRepository = new LanguageRepositoryImpl(SOME_LANGUAGE); Optional<Language> language = languageRepository.find(ANY_KEY); assertThat(language).isEmpty(); }
@Override public HttpResponseOutputStream<File> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final String location = new StoregateWriteFeature(session, fileid).start(file, status); final MultipartOutputStream proxy = new Multipar...
@Test public void testWriteZeroLength() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session); final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir( new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random()), ...
@Override public boolean contains(Object o) { for (M member : members) { if (selector.select(member) && o.equals(member)) { return true; } } return false; }
@Test public void testDoesNotContainNonMatchingMemberWhenLiteMembersSelected() { Collection<MemberImpl> collection = new MemberSelectingCollection<>(members, LITE_MEMBER_SELECTOR); assertFalse(collection.contains(dataMember)); }
@Override public S3ClientBuilder createBuilder(S3Options s3Options) { return createBuilder(S3Client.builder(), s3Options); }
@Test public void testEmptyOptions() { DefaultS3ClientBuilderFactory.createBuilder(builder, s3Options); verifyNoInteractions(builder); }
@VisibleForTesting RowExpression getScopedCanonical(RowExpression expression, Predicate<VariableReferenceExpression> variableScope) { RowExpression canonicalIndex = canonicalMap.get(expression); if (canonicalIndex == null) { return null; } return getCanonical(filter(e...
@Test public void testEqualityGeneration() { EqualityInference.Builder builder = new EqualityInference.Builder(METADATA); builder.addEquality(variable("a1"), add("b", "c")); // a1 = b + c builder.addEquality(variable("e1"), add("b", "d")); // e1 = b + d addEquality("c", "d", buil...
@Override public int getMaxParallelism() { return parallelismInfo.getMaxParallelism(); }
@Test void testConfiguredMaxParallelismIsRespected() throws Exception { final int configuredMaxParallelism = 12; final int defaultMaxParallelism = 13; final ExecutionJobVertex ejv = createDynamicExecutionJobVertex( -1, configuredMaxParallelism, default...
@Override public boolean assign(final Map<ProcessId, ClientState> clients, final Set<TaskId> allTaskIds, final Set<TaskId> statefulTaskIds, final AssignmentConfigs configs) { final int numStandbyReplicas = configs.numStandbyReplic...
@Test public void shouldNotAssignStandbyTasksIfThereAreNoEnoughClients() { final Map<ProcessId, ClientState> clientStates = mkMap( mkEntry(PID_1, createClientStateWithCapacity(PID_1, 3, mkMap(mkEntry(CLUSTER_TAG, CLUSTER_1), mkEntry(ZONE_TAG, ZONE_1)), TASK_0_0)) ); final Set<Ta...
public IdChain get(IdChain key) { return mapping.get(key); }
@Test public void test() { IdChain key = new IdChain(10005L, 10006L, 10005L, 10007L, 10008L); Assert.assertTrue(key.equals(src)); Assert.assertEquals(src, key); IdChain val = fileMapping.get(key); Assert.assertNotNull(val); Assert.assertEquals(dest, val); Lon...
@SuppressWarnings("unchecked") public String uploadFile( String parentPath, String name, InputStream inputStream, String mediaType, Date modified, String description) throws IOException, InvalidTokenException, DestinationMemoryFullException { String url; try { U...
@Test public void testUploadFileNotFound() { server.enqueue( new MockResponse() .setResponseCode(404) .setHeader("Content-Type", "application/json") .setBody( "{\"error\":{\"code\":\"NotFound\",\"message\":\"File not found\"},\"requestId\":\"bad2465e-300...
@Override public boolean equals(Object other) { return super.equals(other); }
@Test public void equalsTest(){ RollbackRule rollbackRuleByClass = new NoRollbackRule(Exception.class); RollbackRule otherRollbackRuleByClass = new NoRollbackRule(Exception.class); Assertions.assertEquals(rollbackRuleByClass, otherRollbackRuleByClass); RollbackRule rollbackRuleByName...
@Override public String toString() { return String.format("Repeatedly.forever(%s)", subTriggers.get(REPEATED)); }
@Test public void testToString() { TriggerStateMachine trigger = RepeatedlyStateMachine.forever(StubTriggerStateMachine.named("innerTrigger")); assertEquals("Repeatedly.forever(innerTrigger)", trigger.toString()); }
@Override public String toString() { if (str == null) str = attributeSelector.toStringBuilder() .append("/Value[@number=\"") .append(valueIndex + 1) .append("\"]") .toString(); return str; }
@Test public void testToString() { ItemPointer ip = new ItemPointer(Tag.RequestAttributesSequence, 0); ValueSelector vs = new ValueSelector(Tag.StudyInstanceUID, null, 0, ip); assertEquals(XPATH, vs.toString()); }
public RetryableException() { super(); }
@Test public void testRetryableException() { Assertions.assertThrowsExactly(RetryableException.class, () -> { throw new RetryableException(); }); Assertions.assertThrowsExactly(RetryableException.class, () -> { throw new RetryableException("error"); }); ...
@Override public @Nullable String getFilename() { if (!isDirectory()) { return key.substring(key.lastIndexOf('/') + 1); } if ("/".equals(key)) { return null; } String keyWithoutTrailingSlash = key.substring(0, key.length() - 1); return keyWithoutTrailingSlash.substring(keyWithoutTr...
@Test public void testGetFilename() { assertNull(S3ResourceId.fromUri("s3://my_bucket/").getFilename()); assertEquals("abc", S3ResourceId.fromUri("s3://my_bucket/abc").getFilename()); assertEquals("abc", S3ResourceId.fromUri("s3://my_bucket/abc/").getFilename()); assertEquals("def", S3ResourceId.fromU...
@Override public V fetch(final K key, final long time) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlyWindowStore<K, V>> stores = provider.stores(storeName, windowStoreType); for (final ReadOnlyWindowStore<K, V> windowStore : stores) { try { ...
@Test public void shouldReturnEmptyIteratorIfNoData() { try (final WindowStoreIterator<String> iterator = windowStore.fetch("my-key", ofEpochMilli(0L), ofEpochMilli(25L))) { assertFalse(iterator.hasNext()); } }
@Override public Processor<KIn, VIn, KOut, VOut> get() { return new KStreamFlatTransformProcessor<>(transformerSupplier.get()); }
@Test public void shouldGetFlatTransformProcessor() { @SuppressWarnings("unchecked") final org.apache.kafka.streams.kstream.TransformerSupplier<Number, Number, Iterable<KeyValue<Integer, Integer>>> transformerSupplier = mock(org.apache.kafka.streams.kstream.TransformerSupplier.class); ...
public void stop() { try { sharedHealthState.clearMine(); } catch (HazelcastInstanceNotActiveException | RetryableHazelcastException e) { LOG.debug("Hazelcast is not active anymore", e); } }
@Test void stop_whenCalled_hasNoEffect() { underTest.stop(); verify(sharedHealthState).clearMine(); verifyNoInteractions(executorService, nodeHealthProvider); }
@Override public Map<String, String> requestParameters() { return unmodifiableMap(requestParameters); }
@Test public void shouldReturnUnmodifiableRequestParams() throws Exception { DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest("extension", "1.0", "request-name"); Map<String, String> requestParameters = request.requestParameters(); try { requestParameters.put("ne...
public String createULID(Message message) { checkTimestamp(message.getTimestamp().getMillis()); try { return createULID(message.getTimestamp().getMillis(), message.getSequenceNr()); } catch (Exception e) { LOG.error("Exception while creating ULID.", e); return...
@Test public void simpleGenerate() { final MessageULIDGenerator generator = new MessageULIDGenerator(new ULID()); final long ts = Tools.nowUTC().getMillis(); ULID.Value parsedULID = ULID.parseULID(generator.createULID(ts, 123)); assertThat(extractSequenceNr(parsedULID)).isEqualTo(...
public boolean registerConsumer(final String group, final ClientChannelInfo clientChannelInfo, ConsumeType consumeType, MessageModel messageModel, ConsumeFromWhere consumeFromWhere, final Set<SubscriptionData> subList, boolean isNotifyConsumerIdsChangedEnable) { return registerConsumer(group, cl...
@Test public void registerConsumerTest() { register(); final Set<SubscriptionData> subList = new HashSet<>(); SubscriptionData subscriptionData = new SubscriptionData(TOPIC, "*"); subList.add(subscriptionData); consumerManager.registerConsumer(GROUP, clientChannelInfo, Consum...
public int doWork() { final long nowNs = nanoClock.nanoTime(); trackTime(nowNs); int workCount = 0; workCount += processTimers(nowNs); if (!asyncClientCommandInFlight) { workCount += clientCommandAdapter.receive(); } workCount += drainComm...
@Test void shouldRemoveSingleCounter() { final long registrationId = driverProxy.addCounter( COUNTER_TYPE_ID, counterKeyAndLabel, COUNTER_KEY_OFFSET, COUNTER_KEY_LENGTH, counterKeyAndLabel, COUNTER_LABEL_OFFSET, COUNTER_...
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity", "checkstyle:methodlength"}) void planMigrations(int partitionId, PartitionReplica[] oldReplicas, PartitionReplica[] newReplicas, MigrationDecisionCallback callback) { assert oldReplicas.length == newReplicas.leng...
@Test public void test_SHIFT_DOWN_withNullNonNullKeepReplicaIndex() throws UnknownHostException { final PartitionReplica[] oldReplicas = { new PartitionReplica(new Address("localhost", 5701), uuids[0]), new PartitionReplica(new Address("localhost", 5702), uuids[1]), ...
@RequestMapping(value = "", method = RequestMethod.POST) public ResponseEntity<String> postCluster(@RequestParam(required = false) String product, @RequestParam(required = false) String cluster, @RequestParam(name = "ips") String ips) { //1. prepare the storage name for product and clus...
@Test void testPostCluster() throws Exception { mockMvc.perform(post("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList") .param("ips", "192.168.3.1,192.168.3.2")).andExpect(status().isOk()); }
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromStrin...
@Test void testForwardedInvalidTargetFieldType2() { String[] forwardedFields = {"f2.*->*"}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); assertThatThrownBy( () -> SemanticPropUtil.getSemanticPropsSingleFromStr...
public void reportMeasurement(final long durationNs) { if (!maxCycleTime.isClosed()) { maxCycleTime.proposeMaxOrdered(durationNs); if (durationNs > cycleTimeThresholdNs) { cycleTimeThresholdExceededCount.incrementOrdered(); } }...
@Test void reportMeasurementIsANoOpIfMaxCounterIsClosed() { final AtomicCounter maxCycleTime = mock(AtomicCounter.class); when(maxCycleTime.isClosed()).thenReturn(true); final AtomicCounter cycleTimeThresholdExceededCount = mock(AtomicCounter.class); final DutyCycleStallTracker d...
@Override public KeyValueIterator<K, V> reverseAll() { final NextIteratorFunction<K, V, ReadOnlyKeyValueStore<K, V>> nextIteratorFunction = new NextIteratorFunction<K, V, ReadOnlyKeyValueStore<K, V>>() { @Override public KeyValueIterator<K, V> apply(final ReadOnlyKeyValueStore<K, V> ...
@Test public void shouldThrowInvalidStoreExceptionOnReverseAllDuringRebalance() { assertThrows(InvalidStateStoreException.class, () -> rebalancing().reverseAll()); }
@Override public void executeUpdate(final UnregisterStorageUnitStatement sqlStatement, final ContextManager contextManager) { if (!sqlStatement.isIfExists()) { checkExisted(sqlStatement.getStorageUnitNames()); } checkInUsed(sqlStatement); try { contextManager....
@Test void assertExecuteUpdateSuccess() throws SQLException { when(database.getRuleMetaData().getInUsedStorageUnitNameAndRulesMap()).thenReturn(Collections.emptyMap()); UnregisterStorageUnitStatement sqlStatement = new UnregisterStorageUnitStatement(Collections.singleton("foo_ds"), false, false); ...
void appendMergeClause(StringBuilder sb) { sb.append("MERGE INTO "); dialect.quoteIdentifier(sb, jdbcTable.getExternalNameList()); sb.append(' '); appendFieldNames(sb, jdbcTable.dbFieldNames()); }
@Test void appendMergeClause() { H2UpsertQueryBuilder builder = new H2UpsertQueryBuilder(table, dialect); StringBuilder sb = new StringBuilder(); builder.appendMergeClause(sb); String mergeClause = sb.toString(); assertThat(mergeClause).isEqualTo("MERGE INTO \"table1\" (\"fi...
@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()) ...
@Test void testMixedPeriodConversion() { final RelativeRange result = converter.apply(Period.hours(1).plusMinutes(10).plusSeconds(7)); verifyResult(result, 4207); }
@Udf public <T> List<T> except( @UdfParameter(description = "Array of values") final List<T> left, @UdfParameter(description = "Array of exceptions") final List<T> right) { if (left == null || right == null) { return null; } final Set<T> distinctRightValues = new HashSet<>(right); fi...
@Test public void shouldDistinctValuesForEmptyExceptionArray() { final List<String> input1 = Arrays.asList("foo", "foo", "bar", "foo"); final List<String> input2 = Arrays.asList(); final List<String> result = udf.except(input1, input2); assertThat(result, contains("foo", "bar")); }
@Udf public boolean check(@UdfParameter(description = "The input JSON string") final String input) { if (input == null) { return false; } try { return !UdfJsonMapper.parseJson(input).isMissingNode(); } catch (KsqlFunctionException e) { return false; } }
@Test public void shouldNotInterpretNull() { assertFalse(udf.check(null)); }
@Override public ObjectNode encode(Criterion criterion, CodecContext context) { EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context); return encoder.encode(); }
@Test public void matchIPSrcTest() { Criterion criterion = Criteria.matchIPSrc(ipPrefix4); ObjectNode result = criterionCodec.encode(criterion, context); assertThat(result, matchesCriterion(criterion)); }
@Override protected void registerMetadata(final MetaDataRegisterDTO metaDataDTO) { MetaDataService metaDataService = getMetaDataService(); MetaDataDO exist = metaDataService.findByPath(metaDataDTO.getPath()); metaDataService.saveOrUpdateMetaData(exist, metaDataDTO); }
@Test public void testRegisterMetadata() { MetaDataDO metaDataDO = MetaDataDO.builder().build(); when(metaDataService.findByPath(any())).thenReturn(metaDataDO); MetaDataRegisterDTO metaDataDTO = MetaDataRegisterDTO.builder().build(); shenyuClientRegisterMotanService.registerMetadata(...
@Override public Collection<SchemaMetaData> load(final MetaDataLoaderMaterial material) throws SQLException { try (Connection connection = material.getDataSource().getConnection()) { Collection<String> schemaNames = SchemaMetaDataLoader.loadSchemaNames(connection, TypedSPILoader.getService(Datab...
@Test void assertLoadWithoutTables() throws SQLException { DataSource dataSource = mockDataSource(); ResultSet schemaResultSet = mockSchemaMetaDataResultSet(); when(dataSource.getConnection().getMetaData().getSchemas()).thenReturn(schemaResultSet); ResultSet tableResultSet = mockTabl...
public ConfigTransformerResult transform(Map<String, String> configs) { Map<String, Map<String, Set<String>>> keysByProvider = new HashMap<>(); Map<String, Map<String, Map<String, String>>> lookupsByProvider = new HashMap<>(); // Collect the variables from the given configs that need transforma...
@Test public void testReplaceMultipleVariablesWithoutPathInValue() { ConfigTransformerResult result = configTransformer.transform(Collections.singletonMap(MY_KEY, "first ${test:testKey}; second ${test:testKey}")); Map<String, String> data = result.data(); assertEquals("first testResultNoPath...
MethodSpec buildFunction(AbiDefinition functionDefinition) throws ClassNotFoundException { return buildFunction(functionDefinition, true); }
@Test public void testBuildFunctionConstantMultiDynamicArrayRawListReturn() throws Exception { AbiDefinition functionDefinition = new AbiDefinition( true, Arrays.asList(new NamedType("param", "uint8[][]")), "functionName...
@Override public void execute(Context context) { try (StreamWriter<ProjectDump.Plugin> writer = dumpWriter.newStreamWriter(DumpElement.PLUGINS)) { Collection<PluginInfo> plugins = pluginRepository.getPluginInfos(); for (PluginInfo plugin : plugins) { ProjectDump.Plugin.Builder builder = Proje...
@Test public void export_zero_plugins() { when(pluginRepository.getPluginInfos()).thenReturn(Collections.emptyList()); underTest.execute(new TestComputationStepContext()); assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.PLUGINS)).isEmpty(); assertThat(logTester.logs(Level.DEBUG)).contains("0 ...
@Bean public ShenyuClientRegisterRepository shenyuClientRegisterRepository(final ShenyuRegisterCenterConfig config) { return ShenyuClientRegisterRepositoryFactory.newInstance(config); }
@Test public void testShenyuClientRegisterRepository() { MockedStatic<RegisterUtils> registerUtilsMockedStatic = mockStatic(RegisterUtils.class); registerUtilsMockedStatic.when(() -> RegisterUtils.doLogin(any(), any(), any())).thenReturn(Optional.ofNullable("token")); applicationContextRunne...
private List<Configserver> getConfigServers(DeployState deployState, TreeConfigProducer<AnyConfigProducer> parent, Element adminE) { Element configserversE = XML.getChild(adminE, "configservers"); if (configserversE == null) { Element adminserver = XML.getChild(adminE, "adminserver"); ...
@Test void adminWithConfigserversElement() { Admin admin = buildAdmin(servicesConfigservers()); assertEquals(1, admin.getConfigservers().size()); }
public void setContract(@Nullable Produce contract) { this.contract = contract; setStoredContract(contract); handleContractState(); }
@Test public void cabbageContractOnionHarvestableAndPotatoHarvestable() { final long unixNow = Instant.now().getEpochSecond(); // Get the two allotment patches final FarmingPatch patch1 = farmingGuildPatches.get(Varbits.FARMING_4773); final FarmingPatch patch2 = farmingGuildPatches.get(Varbits.FARMING_4774);...
public void addObjectSink(final ObjectSink objectSink) { this.sink = this.sink.addObjectSink( objectSink, this.alphaNodeHashingThreshold, this.alphaNodeRangeIndexThreshold ); }
@Test public void testAddObjectSink() throws Exception { final MockObjectSource source = new MockObjectSource( 15 ); // We need to re-assign this var each time the sink changes references final Field field = ObjectSource.class.getDeclaredField( "sink" ); field.setAccessible( true );...
public static List<String> shellSplit(CharSequence string) { List<String> tokens = new ArrayList<>(); if ( string == null ) { return tokens; } boolean escaping = false; char quoteChar = ' '; boolean quoting = false; StringBuilder current = new StringBu...
@Test public void whitespacesOnlyYeildsEmptyArgs() { assertTrue(StringUtils.shellSplit(" \t \n").isEmpty()); }
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testMemoryPercentageCpuAbsolute() throws Exception { expectMissingResource("cpu"); parseResourceConfigValue("50% memory, 2 vcores"); }
public void logOnNewLeadershipTerm( final int memberId, final long logLeadershipTermId, final long nextLeadershipTermId, final long nextTermBaseLogPosition, final long nextLogPosition, final long leadershipTermId, final long termBaseLogPosition, final long...
@Test void logOnNewLeadershipTerm() { final int offset = align(22, ALIGNMENT); logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, offset); final long logLeadershipTermId = 434; final long nextLeadershipTermId = 2561; final long nextTermBaseLogPosition = 2562; fina...
public List<String> build() { return switch (dialect.getId()) { case Oracle.ID -> forOracle(tableName); case H2.ID, PostgreSql.ID -> singletonList("drop table if exists " + tableName); case MsSql.ID -> // "if exists" is supported only since MSSQL 2016. singletonList("drop table " +...
@Test public void drop_tables_on_h2() { assertThat(new DropTableBuilder(new H2(), "issues") .build()).containsOnly("drop table if exists issues"); }
public static Method getGenericAccessor(Class<?> clazz, String field) { LOG.trace( "getGenericAccessor({}, {})", clazz, field ); AccessorCacheKey accessorCacheKey = new AccessorCacheKey( clazz.getClassLoader(), clazz.getCanonicalName(), field ); return accessorCache.computeIfAb...
@Test void getGenericAccessor() throws NoSuchMethodException { Method expectedAccessor = TestPojo.class.getMethod("getAProperty"); assertThat(EvalHelper.getGenericAccessor(TestPojo.class, "aProperty")).as("getGenericAccessor should work on Java bean accessors.").isEqualTo(expectedAccessor); ...
@Override public AttributeResource getAttrValue(ResName resName) { AttributeResource attributeResource = items.get(resName); // This hack allows us to look up attributes from downstream dependencies, see comment in // org.robolectric.shadows.ShadowThemeTest.obtainTypedArrayFromDependencyLibrary() // ...
@Test public void getAttrValue_willReturnTrimmedAttributeValues() throws Exception { StyleData styleData = new StyleData( "library.resource", "Theme_MyApp", "Theme_Material", asList( new AttributeResource(myLibSearchViewStyle, "\n lib_value "...
@Override public void onStateElection(Job job, JobState newState) { if (isNotFailed(newState) || isJobNotFoundException(newState) || isProblematicExceptionAndMustNotRetry(newState) || maxAmountOfRetriesReached(job)) return; job.scheduleAt(now().plusSeconds(getSecondsToAdd(job)), String....
@Test void retryFilterDoesNotScheduleJobAgainIfTheExceptionIsProblematic() { final Job job = aFailedJob().withState(new FailedState("a message", problematicConfigurationException("big problem"))).build(); applyDefaultJobFilter(job); int beforeVersion = job.getJobStates().size(); ret...
public static String SHA256(String data) { return SHA256(data.getBytes()); }
@Test public void testSHA256() throws Exception { String biezhiSHA256 = "8fcbefd5c7a6c81165f587e46bffd821214a6fc1bc3842309f3aef6938e627a7"; Assert.assertEquals( biezhiSHA256, EncryptKit.SHA256("biezhi") ); Assert.assertEquals( biezhiSHA...
public void serialize() throws KettleException { String xml = MetaXmlSerializer.serialize( from( stepMetaInterface ) ); //.encryptedFields( encryptedFields ) ); rep.saveStepAttribute( idTrans, idStep, REPO_TAG, xml ); }
@Test public void testSerialize() throws KettleException { String serialized = serialize( from( stepMeta ) ); RepoSerializer .builder() .repo( repo ) .stepId( stepId ) .transId( transId ) .stepMeta( stepMeta ) .serialize(); verify( repo, times( 1 ) ) .saveStepAt...
@Nullable @Override public Message decode(@Nonnull final RawMessage rawMessage) { final GELFMessage gelfMessage = new GELFMessage(rawMessage.getPayload(), rawMessage.getRemoteAddress()); final String json = gelfMessage.getJSON(decompressSizeLimit, charset); final JsonNode node; ...
@Test public void decodeFailsWithBlankShortMessage() throws Exception { final String json = "{" + "\"version\": \"1.1\"," + "\"host\": \"example.org\"," + "\"short_message\": \" \"" + "}"; final RawMessage rawMessage = new RawMessa...
@Override public V setValue(V value) { throw new UnsupportedOperationException(); }
@Test(expected = UnsupportedOperationException.class) public void givenNewEntry_whenSetValue_thenThrowUnsupportedOperationException() { CachedQueryEntry<Object, Object> entry = createEntry("key"); entry.setValue(new Object()); }
public static long getInitialSeedUniquifier() { // Use the value set via the setter. long initialSeedUniquifier = ThreadLocalRandom.initialSeedUniquifier; if (initialSeedUniquifier != 0) { return initialSeedUniquifier; } synchronized (ThreadLocalRandom.class) { ...
@Test public void getInitialSeedUniquifierPreservesInterrupt() { try { Thread.currentThread().interrupt(); assertTrue(Thread.currentThread().isInterrupted(), "Assert that thread is interrupted before invocation of getInitialSeedUniquifier()"); ThreadLo...
@Override public Object getObject(final int columnIndex) throws SQLException { return mergeResultSet.getValue(columnIndex, Object.class); }
@Test void assertGetObjectWithBlob() throws SQLException { Blob result = mock(Blob.class); when(mergeResultSet.getValue(1, Blob.class)).thenReturn(result); assertThat(shardingSphereResultSet.getObject(1, Blob.class), is(result)); }
@Override public void removeDevice(DeviceId deviceId) { checkNotNull(deviceId, DEVICE_ID_NULL); DeviceEvent event = store.removeDevice(deviceId); if (event != null) { log.info("Device {} administratively removed", deviceId); } }
@Test public void removeDevice() { connectDevice(DID1, SW1); connectDevice(DID2, SW2); assertEquals("incorrect device count", 2, service.getDeviceCount()); assertEquals("incorrect available device count", 2, service.getAvailableDeviceCount()); admin.removeDevice(DID1); ...
@Override protected boolean notExist() { return Stream.of(DefaultPathConstants.PLUGIN_PARENT, DefaultPathConstants.APP_AUTH_PARENT, DefaultPathConstants.META_DATA, DefaultPathConstants.PROXY_SELECTOR, DefaultPathConstants.DISCOVERY_UPSTREAM).no...
@Test public void testNotExist() throws Exception { EtcdDataChangedInit etcdDataChangedInit = new EtcdDataChangedInit(etcdClient); assertNotNull(etcdDataChangedInit); when(etcdClient.exists(DefaultPathConstants.PLUGIN_PARENT)).thenReturn(true); boolean pluginExist = etcdDataChangedI...
@VisibleForTesting static void writeFileConservatively(Path file, String content) throws IOException { if (Files.exists(file)) { String oldContent = new String(Files.readAllBytes(file), StandardCharsets.UTF_8); if (oldContent.equals(content)) { return; } } Files.createDirectories...
@Test public void testWriteFileConservatively_noWriteIfUnchanged() throws IOException { Path file = temporaryFolder.newFile().toPath(); Files.write(file, "some content".getBytes(StandardCharsets.UTF_8)); FileTime fileTime = Files.getLastModifiedTime(file); PluginConfigurationProcessor.writeFileConser...
public static boolean isMatchWithPrefix(final byte[] candidate, final byte[] expected, final int prefixLength) { if (candidate.length != expected.length) { return false; } if (candidate.length == 4) { final int mask = prefixLengthToIpV4Mask(prefixLeng...
@Test void shouldMatchIfAllBytesMatch() { final byte[] a = { 'a', 'b', 'c', 'd' }; final byte[] b = { 'a', 'b', 'c', 'd' }; assertTrue(isMatchWithPrefix(a, b, 32)); }
@Override public String convert(IAccessEvent accessEvent) { if (!isStarted()) { return "INACTIVE_REQUEST_PARAM_CONV"; } // This call should be safe, because the request map is cached beforehand final String[] paramArray = accessEvent.getRequestParameterMap().get(key); ...
@Test void testConvertOneParameter() throws Exception { Mockito.when(httpServletRequest.getParameterValues("name")).thenReturn(new String[]{"Alice"}); Mockito.when(httpServletRequest.getParameterNames()) .thenReturn(Collections.enumeration(Collections.singleton("name"))); //...
@GetMapping(value = "/node/self") @Secured(action = ActionTypes.READ, resource = "nacos/admin", signType = SignType.CONSOLE) public Result<Member> self() { return Result.success(nacosClusterOperationService.self()); }
@Test void testSelf() { Member self = new Member(); when(nacosClusterOperationService.self()).thenReturn(self); Result<Member> result = nacosClusterControllerV2.self(); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); assertEquals(self, result.getData());...
public List<BookDto> getAllBooks() { List<BookDto> books = Collections.emptyList(); try { AuditDto audit = null; Call<List<BookDto>> callBookResponse = libraryClient.getAllBooks("all"); Response<List<BookDto>> allBooksResponse = callBookResponse.execute(); ...
@Test @DisplayName("Successful getAllBooks call") public void getAllBooksTest() throws Exception { String booksResponse = getBooksResponse("/response/getAllBooks.json"); List<BookDto> bookDtoList = new ObjectMapper().readValue(booksResponse, new TypeReference<>() { ...
public void generate() throws IOException { packageNameByTypes.clear(); generatePackageInfo(); generateTypeStubs(); generateMessageHeaderStub(); for (final List<Token> tokens : ir.messages()) { final Token msgToken = tokens.get(0); final List<...
@Test void shouldGenerateGetFixedLengthStringUsingAppendable() throws Exception { final UnsafeBuffer buffer = new UnsafeBuffer(new byte[4096]); final StringBuilder result = new StringBuilder(); generator().generate(); final Object encoder = wrap(buffer, compileCarEncoder().getDe...
@Udf public Integer abs(@UdfParameter final Integer val) { return (val == null) ? null : Math.abs(val); }
@Test public void shouldHandleNull() { assertThat(udf.abs((Integer) null), is(nullValue())); assertThat(udf.abs((Long)null), is(nullValue())); assertThat(udf.abs((Double)null), is(nullValue())); assertThat(udf.abs((BigDecimal) null), is(nullValue())); }
@Override public boolean mayHaveMergesPending(String bucketSpace, int contentNodeIndex) { if (!stats.hasUpdatesFromAllDistributors()) { return true; } ContentNodeStats nodeStats = stats.getStats().getNodeStats(contentNodeIndex); if (nodeStats != null) { Conten...
@Test void valid_bucket_space_stats_can_have_no_merges_pending() { Fixture f = Fixture.fromBucketsPending(0); assertFalse(f.mayHaveMergesPending("default", 1)); }
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { // Must split otherwise 413 Request Entity Too Large is returned for(List<Path> partition : new Partition<>(new ArrayList<>(files.keySet()), ...
@Test public void testDeleteFolder() throws Exception { final DriveFileIdProvider fileid = new DriveFileIdProvider(session); final Path directory = new DriveDirectoryFeature(session, fileid).mkdir(new Path(DriveHomeFinderService.MYDRIVE_FOLDER, new AlphanumericRandomStringService().r...