focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public boolean matches(String matchUrl) { if (url.equals(matchUrl)) return true; Iterator<UrlPathPart> iter1 = new MatchUrl(matchUrl).pathParts.iterator(); Iterator<UrlPathPart> iter2 = pathParts.iterator(); while (iter1.hasNext() && iter2.hasNext()) if (!iter1.next().matche...
@Test void testNoMatchWithParams() { boolean matches = new MatchUrl("/api/jobs/enqueued/wrong").matches("/api/jobs/:state/test"); assertThat(matches).isFalse(); }
@Override public List<String> getGroups(String userName) throws IOException { return new ArrayList(getUnixGroups(userName)); }
@Test public void testGetGroupsNotResolvable() throws Exception { TestGroupNotResolvable mapping = new TestGroupNotResolvable(); List<String> groups = mapping.getGroups("user"); assertTrue(groups.size() == 2); assertTrue(groups.contains("abc")); assertTrue(groups.contains("def")); }
@Override public boolean containsSlot(AllocationID allocationId) { return registeredSlots.containsKey(allocationId); }
@Test void testContainsSlot() { final DefaultAllocatedSlotPool slotPool = new DefaultAllocatedSlotPool(); final AllocatedSlot allocatedSlot = createAllocatedSlot(null); slotPool.addSlots(Collections.singleton(allocatedSlot), 0); assertThat(slotPool.containsSlot(allocatedSlot.getAll...
@Override public RemoteData.Builder serialize() { final RemoteData.Builder remoteBuilder = RemoteData.newBuilder(); remoteBuilder.addDataObjectStrings(value.toStorageData()); remoteBuilder.addDataLongs(getTimeBucket()); remoteBuilder.addDataStrings(entityId); remoteBuilder.a...
@Test public void testSerialize() { function.accept(MeterEntity.newService("service-test", Layer.GENERAL), HTTP_CODE_COUNT_1); MinLabeledFunction function2 = new MinLabeledFunctionInst(); function2.deserialize(function.serialize().build()); assertThat(function2.getEntityId()).isEqu...
public Optional<Long> validateAndGetTimestamp(final ExternalServiceCredentials credentials) { final String[] parts = requireNonNull(credentials).password().split(DELIMITER); final String timestampSeconds; final String actualSignature; // making sure password format matches our expectations based on the...
@Test public void testValidateValid() throws Exception { assertEquals(standardGenerator.validateAndGetTimestamp(standardCredentials).orElseThrow(), TIME_SECONDS); }
@Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return criterionValue1.isGreaterThan(criterionValue2); }
@Test public void betterThan() { AnalysisCriterion criterion = getCriterion(); assertTrue(criterion.betterThan(numOf(6), numOf(3))); assertFalse(criterion.betterThan(numOf(4), numOf(7))); }
@Override public void export(RegisterTypeEnum registerType) { if (this.exported) { return; } if (getScopeModel().isLifeCycleManagedExternally()) { // prepare model for reference getScopeModel().getDeployer().prepare(); } else { // ensu...
@Test void testMethodConfigWithConfiguredArgumentIndex() { ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>(); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); service.setProtocol(new ProtocolConfig() { { setName...
public static String extractArgumentsFromAttributeName(String attributeNameWithArguments) { int start = StringUtil.lastIndexOf(attributeNameWithArguments, '['); int end = StringUtil.lastIndexOf(attributeNameWithArguments, ']'); if (start > 0 && end > 0 && end > start) { return attrib...
@Test(expected = IllegalArgumentException.class) public void extractArgument_wrongArguments_noArgument() { extractArgumentsFromAttributeName("car.wheel["); }
public Result waitForCondition(Config config, Supplier<Boolean>... conditionCheck) { return finishOrTimeout( config, conditionCheck, () -> jobIsDoneOrFinishing(config.project(), config.region(), config.jobId())); }
@Test public void testWaitForConditionJobFinished() throws IOException { when(client.getJobStatus(any(), any(), any())) .thenReturn(JobState.RUNNING) .thenReturn(JobState.CANCELLED); Result result = new PipelineOperator(client).waitForCondition(DEFAULT_CONFIG, () -> false); assertThat(re...
@Override public ServiceInstance doChoose(String serviceName, List<ServiceInstance> instances) { final int index = Math.abs(position.incrementAndGet()); return instances.get(index % instances.size()); }
@Test public void doChoose() { int port1 = 9999; int port2 = 8888; String serviceName = "round"; final List<ServiceInstance> serviceInstances = Arrays .asList(CommonUtils.buildInstance(serviceName, port1), CommonUtils.buildInstance(serviceName, port2)); final ...
@Bean @ConditionalOnBean(ShenyuThreadPoolExecutor.class) public ShenyuThreadPoolExecutorDestructor shenyuThreadPoolExecutorDestructor() { return new ShenyuThreadPoolExecutorDestructor(); }
@Test public void testShenyuThreadPoolExecutorDestructor() { ShenyuThreadPoolConfiguration.ShenyuThreadPoolExecutorDestructor shenyuThreadPoolExecutorDestructor = shenyuThreadPoolConfiguration.shenyuThreadPoolExecutorDestructor(); SpringBeanUtils.getInstance().setApplicationContext(m...
@Override public List<ServiceDefinition> getServices(String name) { final Lookup lookup = cache.computeIfAbsent(name, this::createLookup); final Record[] records = lookup.run(); List<ServiceDefinition> services; if (Objects.nonNull(records) && lookup.getResult() == Lookup.SUCCESSFUL...
@Test void testServiceDiscovery() throws IOException { DnsConfiguration configuration = new DnsConfiguration(); try (DnsServiceDiscovery discovery = new DnsServiceDiscovery(configuration)) { configuration.setDomain("jabber.com"); configuration.setProto("_tcp"); ...
public TurnServerOptions getRoutingFor( @Nonnull final UUID aci, @Nonnull final Optional<InetAddress> clientAddress, final int instanceLimit ) { try { return getRoutingForInner(aci, clientAddress, instanceLimit); } catch(Exception e) { logger.error("Failed to perform routing", e)...
@Test public void testLimitReturnsPreferredProtocolAndPrioritizesPerformance() throws UnknownHostException { when(performanceTable.getDatacentersFor(any(), any(), any(), any())) .thenReturn(List.of("dc-performance3", "dc-performance2", "dc-performance1")); assertThat(router().getRoutingFor(aci, Optio...
@Override public ShadowRule build(final ShadowRuleConfiguration ruleConfig, final String databaseName, final DatabaseType protocolType, final ResourceMetaData resourceMetaData, final Collection<ShardingSphereRule> builtRules, final ComputeNodeInstanceContext computeNodeInstanceContext) {...
@SuppressWarnings({"rawtypes", "unchecked"}) @Test void assertBuild() { ShadowRuleConfiguration ruleConfig = new ShadowRuleConfiguration(); DatabaseRuleBuilder builder = OrderedSPILoader.getServices(DatabaseRuleBuilder.class, Collections.singleton(ruleConfig)).get(ruleConfig); assertThat...
@Override public FilterScope getFilterScope() { return filterScope; }
@Test public void getFilterScope_always_returns_the_same_instance() { String fieldName = randomAlphabetic(12); boolean sticky = RANDOM.nextBoolean(); SimpleFieldTopAggregationDefinition underTest = new SimpleFieldTopAggregationDefinition(fieldName, sticky); Set<TopAggregationDefinition.FilterScope> f...
public static boolean isKeepAlive(HttpMessage message) { return !message.headers().containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true) && (message.protocolVersion().isKeepAliveDefault() || message.headers().containsValue(HttpHeaderNames.CONNECTION, HttpHeaderVa...
@Test public void testKeepAliveIfConnectionHeaderAbsent() { HttpMessage http11Message = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http:localhost/http_1_1"); assertTrue(HttpUtil.isKeepAlive(http11Message)); HttpMessage http10Message = new DefaultHttpRequest(Ht...
public static String decoratorPathWithSlash(final String contextPath) { return StringUtils.endsWith(contextPath, AdminConstants.URI_SLASH_SUFFIX) ? contextPath : contextPath + AdminConstants.URI_SLASH_SUFFIX; }
@Test public void testDecoratorPathWithSlash() { String uri = PathUtils.decoratorPathWithSlash(URI); assertThat(uri, is(URI + AdminConstants.URI_SLASH_SUFFIX)); uri = PathUtils.decoratorContextPath(URI_SLASH); assertThat(uri, is(URI + AdminConstants.URI_SLASH_SUFFIX)); }
public static ObjectInspector create(@Nullable Schema schema) { if (schema == null) { return IcebergRecordObjectInspector.empty(); } return TypeUtil.visit(schema, new IcebergObjectInspector()); }
@Test public void testIcebergObjectInspector() { ObjectInspector oi = IcebergObjectInspector.create(schema); Assert.assertNotNull(oi); Assert.assertEquals(ObjectInspector.Category.STRUCT, oi.getCategory()); StructObjectInspector soi = (StructObjectInspector) oi; // binary StructField binaryF...
@CanIgnoreReturnValue public final Ordered containsAtLeastEntriesIn(Multimap<?, ?> expectedMultimap) { checkNotNull(expectedMultimap, "expectedMultimap"); checkNotNull(actual); ListMultimap<?, ?> missing = difference(expectedMultimap, actual); // TODO(kak): Possible enhancement: Include "[1 copy]" if...
@Test public void containsAtLeastEntriesIn() { ImmutableListMultimap<Integer, String> actual = ImmutableListMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four"); ImmutableSetMultimap<Integer, String> expected = ImmutableSetMultimap.of(3, "one", 3, "six", 3, "two", 4, "five"); a...
protected <T> T initialize(T proxy) throws HibernateException { if (!Hibernate.isInitialized(proxy)) { Hibernate.initialize(proxy); } return proxy; }
@Test void initializesProxies() throws Exception { final LazyInitializer initializer = mock(LazyInitializer.class); when(initializer.isUninitialized()).thenReturn(true); final HibernateProxy proxy = mock(HibernateProxy.class); doCallRealMethod().when(proxy).asHibernateProxy(); ...
@Override public void processElement(StreamRecord<T> element) throws Exception { writer.write(element.getValue()); }
@TestTemplate public void testTableWithoutSnapshot() throws Exception { try (OneInputStreamOperatorTestHarness<RowData, WriteResult> testHarness = createIcebergStreamWriter()) { assertThat(testHarness.extractOutputValues()).isEmpty(); } // Even if we closed the iceberg stream writer, there's...
@Override public void define(WebService.NewController controller) { controller.createAction(VALIDATE_ACTION) .setDescription("Check credentials.") .setSince("3.3") .setHandler(ServletFilterHandler.INSTANCE) .setResponseExample(Resources.getResource(this.getClass(), "example-validate.json")...
@Test public void define_shouldDefineWS() { String controllerKey = "foo"; WebService.Context context = new WebService.Context(); WebService.NewController newController = context.createController(controllerKey); underTest.define(newController); newController.done(); WebService.Action validate ...
public ValidationResult validate(final Map<String, InternalTopicConfig> topicConfigs) { log.info("Starting to validate internal topics {}.", topicConfigs.keySet()); final long now = time.milliseconds(); final long deadline = now + retryTimeoutMs; final ValidationResult validationResult...
@Test public void shouldReportMultipleMisconfigurationsForSameTopic() { final long retentionMs = 1000; final long shorterRetentionMs = 900; final Map<String, String> windowedChangelogConfig = windowedChangelogConfig(shorterRetentionMs); windowedChangelogConfig.put(TopicConfig.RETENTI...
public static Validator parses(final Function<String, ?> parser) { return (name, val) -> { if (val != null && !(val instanceof String)) { throw new IllegalArgumentException("validator should only be used with STRING defs"); } try { parser.apply((String)val); } catch (final Ex...
@Test(expected = IllegalArgumentException.class) public void shouldThrowOnNonStringFromParse() { // Given: final Validator validator = ConfigValidators.parses(parser); // When: validator.ensureValid("propName", 10); }
void removeFactMapping(FactMapping toRemove) { factMappings.remove(toRemove); }
@Test public void removeFactMapping() { FactMapping retrieved = modelDescriptor.addFactMapping(factIdentifier, expressionIdentifier); modelDescriptor.removeFactMapping(retrieved); assertThat(modelDescriptor.getUnmodifiableFactMappings()).doesNotContain(retrieved); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { return this.list(directory, listener, String.valueOf(Path.DELIMITER)); }
@Test public void testDirectory() throws Exception { final Path bucket = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); final Path directory = new S3DirectoryFeature(s...
@Override public ListenableFuture<?> spill(Iterator<Page> pageIterator) { requireNonNull(pageIterator, "pageIterator is null"); checkNoSpillInProgress(); spillInProgress = executor.submit(() -> writePages(pageIterator)); return spillInProgress; }
@Test public void testSpill() throws Exception { assertSpill(false, false); }
@Override public List<String> getMountPoints(final String str) throws IOException { verifyMountTable(); String path = RouterAdmin.normalizeFileSystemPath(str); if (isTrashPath(path)) { path = subtractTrashCurrentPath(path); } readLock.lock(); try { String from = path; String ...
@Test public void testTrailingSlashInInputPath() throws IOException { // Check mount points beneath the path with trailing slash. getMountPoints(true); }
@Override public boolean dropNamespace(Namespace namespace) { if (!isValidateNamespace(namespace)) { return false; } try { clients.run( client -> { client.dropDatabase( namespace.level(0), false /* deleteData */, false /* i...
@Test public void dropNamespace() { Namespace namespace = Namespace.of("dbname_drop"); TableIdentifier identifier = TableIdentifier.of(namespace, "table"); Schema schema = getTestSchema(); catalog.createNamespace(namespace, META); catalog.createTable(identifier, schema); Map<String, String> n...
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); List<AclEntry> foundAclSpecEntries = ...
@Test(expected=AclException.class) public void testMergeAclEntriesInputTooLarge() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, OTHER, NONE)) .build(); me...
@Override public boolean remove(long key1, int key2) { return super.remove0(key1, key2); }
@Test public void testRemove() { final long key1 = randomKey(); final int key2 = randomKey(); insert(key1, key2); assertTrue(hsa.remove(key1, key2)); assertFalse(hsa.remove(key1, key2)); }
public EventTimer getEventTimer(String eventName) { EventTimer eventTimer; synchronized (mTrackTimer) { eventTimer = mTrackTimer.get(eventName); mTrackTimer.remove(eventName); } return eventTimer; }
@Test public void getEventTimer() { mInstance.addEventTimer("EventTimer", new EventTimer(TimeUnit.SECONDS, 10000L)); Assert.assertNotNull(mInstance.getEventTimer("EventTimer")); }
public long getWorkerTabletNum(String workerIpPort) { try { WorkerInfo workerInfo = client.getWorkerInfo(serviceId, workerIpPort); return workerInfo.getTabletNum(); } catch (StarClientException e) { LOG.info("Failed to get worker tablet num from starMgr, Error: {}.", ...
@Test public void testGetWorkerTabletNum() throws StarClientException { String serviceId = "1"; String workerIpPort = "127.0.0.1:8093"; long workerId = 20000L; int expectedTabletNum = 10086; Deencapsulation.setField(starosAgent, "serviceId", serviceId); WorkerInfo wor...
@Override public Map<String, Collection<String>> getDataSourceMapper() { Map<String, Collection<String>> result = new HashMap<>(dataSourceGroupRules.size(), 1F); for (ReadwriteSplittingDataSourceGroupRule each : dataSourceGroupRules) { result.put(each.getName(), each.getReadwriteSplittin...
@Test void assertGetDataSourceMapper() { Map<String, Collection<String>> actual = new ReadwriteSplittingDataSourceMapperRuleAttribute(Collections.singleton(createDataSourceGroupRule())).getDataSourceMapper(); Map<String, Collection<String>> expected = Collections.singletonMap("readwrite", Arrays.asL...
public static void validateImageInDaemonConf(Map<String, Object> conf) { List<String> allowedImages = getAllowedImages(conf, true); if (allowedImages.isEmpty()) { LOG.debug("{} is not configured; skip image validation", DaemonConfig.STORM_OCI_ALLOWED_IMAGES); } else { Str...
@Test public void validateImageInDaemonConfWrongPattern() { assertThrows(IllegalArgumentException.class, () -> { Map<String, Object> conf = new HashMap<>(); List<String> allowedImages = new ArrayList<>(); allowedImages.add("*"); conf.put(DaemonConfig.STORM_OCI...
public static String nameOf(String group, String plural, String name) { if (StringUtils.isBlank(group)) { return String.join("/", plural, name); } return String.join(".", plural, group) + "/" + name; }
@Test void testNameOf() { String s = MeterUtils.nameOf("content.halo.run", "posts", "fake-post"); assertThat(s).isEqualTo("posts.content.halo.run/fake-post"); }
@Override public void execute(ComputationStep.Context context) { DuplicationVisitor visitor = new DuplicationVisitor(); new DepthTraversalTypeAwareCrawler(visitor).visit(treeRootHolder.getReportTreeRoot()); context.getStatistics().add("duplications", visitor.count); }
@Test public void loads_duplication_with_otherFileRef_as_inProject_duplication() { reportReader.putDuplications(FILE_1_REF, createDuplication(singleLineTextRange(LINE), createInProjectDuplicate(FILE_2_REF, LINE + 1))); TestComputationStepContext context = new TestComputationStepContext(); underTest.execu...
@Override public Set<String> getNames() { return unmodifiableSet(probeInstances.values().stream() .map(probeInstance -> probeInstance.descriptor.metricString()) .collect(Collectors.toSet())); }
@Test public void getNames() { Set<String> metrics = new HashSet<>(); metrics.add("first"); metrics.add("second"); metrics.add("third"); Set<String> expected = new HashSet<>(); expected.add("[metric=first]"); expected.add("[metric=second]"); expected....
@Override public Long time(RedisClusterNode node) { RedisClient entry = getEntry(node); RFuture<Long> f = executorService.readAsync(entry, LongCodec.INSTANCE, RedisCommands.TIME_LONG); return syncFuture(f); }
@Test public void testTime() { RedisClusterNode master = getFirstMaster(); Long time = connection.time(master); assertThat(time).isGreaterThan(1000); }
@Override public String method() { return DubboParser.method(invocation); }
@Test void method() { when(invocation.getMethodName()).thenReturn("sayHello"); assertThat(request.method()).isEqualTo("sayHello"); }
@Override public AppendFiles appendManifest(ManifestFile manifest) { Preconditions.checkArgument( !manifest.hasExistingFiles(), "Cannot append manifest with existing files"); Preconditions.checkArgument( !manifest.hasDeletedFiles(), "Cannot append manifest with deleted files"); Preconditio...
@TestTemplate public void testAppendManifestCleanup() throws IOException { // inject 5 failures TestTables.TestTableOperations ops = table.ops(); ops.failCommits(5); ManifestFile manifest = writeManifest(FILE_A, FILE_B); AppendFiles append = table.newAppend().appendManifest(manifest); Snapsho...
public int startWithRunStrategy( @NotNull WorkflowInstance instance, @NotNull RunStrategy runStrategy) { return withMetricLogError( () -> withRetryableTransaction( conn -> { final long nextInstanceId = getLatestInstanceId(conn, instan...
@Test public void testStartWorkflowInstanceWithSameUuid() { wfi.setWorkflowUuid("8a0bd56f-745f-4a2c-b81b-1b2f89127e73"); int res = runStrategyDao.startWithRunStrategy(wfi, Defaults.DEFAULT_RUN_STRATEGY); assertEquals(0, res); assertEquals(1, wfi.getWorkflowInstanceId()); assertEquals(1, wfi.getWor...
@Override public List<Operation> parse(String statement) { CalciteParser parser = calciteParserSupplier.get(); FlinkPlannerImpl planner = validatorSupplier.get(); Optional<Operation> command = EXTENDED_PARSER.parse(statement); if (command.isPresent()) { return Collection...
@Test void testPartialParseWithStatementSet() { assertThatThrownBy( () -> parser.parse( "Execute Statement Set Begin insert into A select * from B")) .isInstanceOf(SqlParserEOFException.class); ...
public static MaterializedDataPredicates differenceDataPredicates( MaterializedDataPredicates baseTablePredicatesInfo, MaterializedDataPredicates viewPredicatesInfo, Map<String, String> viewToBaseTablePredicatesKeyMap) { return differenceDataPredicates(baseTablePredicates...
@Test public void testDifferenceDataPredicates() { TestingTypeManager typeManager = new TestingTypeManager(); TestingSemiTransactionalHiveMetastore testMetastore = TestingSemiTransactionalHiveMetastore.create(); List<String> keys = ImmutableList.of("ds"); Column dsColumn = new C...
public static <T> T retry(Callable<T> callable, int retries) { return retry(callable, retries, Collections.emptyList()); }
@Test(expected = HazelcastException.class) public void retryNonRetryableKeywords() throws Exception { // given given(callable.call()).willThrow(new HazelcastException(NON_RETRYABLE_KEYWORDS)).willThrow(new RuntimeException()); // when String result = RetryUtils.retry(cal...
public boolean deleteTenantCapacity(final String tenant) { try { TenantCapacityMapper tenantCapacityMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.TENANT_CAPACITY); PreparedStatementCreator preparedStatementCreator = connection ...
@Test void testDeleteTenantCapacity() { when(jdbcTemplate.update(any(PreparedStatementCreator.class))).thenReturn(1); assertTrue(service.deleteTenantCapacity("test")); //mock get connection fail when(jdbcTemplate.update(any(PreparedStatementCreator.class))).thenThro...
@Override public Object evaluateUnsafe(EvaluationContext context) { final Object idxObj = this.index.evaluateUnsafe(context); final Object indexable = indexableObject.evaluateUnsafe(context); if (idxObj == null || indexable == null) { return null; } if (idxObj in...
@Test public void accessIterable() { final Iterable<Integer> iterable = () -> new AbstractIterator<Integer>() { private boolean done = false; @Override protected Integer computeNext() { if (done) { return endOfData(); }...
@Udf public <T extends Comparable<? super T>> List<T> arraySortDefault(@UdfParameter( description = "The array to sort") final List<T> input) { return arraySortWithDirection(input, "ASC"); }
@Test public void shouldSortDoubles() { final List<Double> input = Arrays.asList(Double.valueOf(1.1), Double.valueOf(3.1), Double.valueOf(-1.1)); final List<Double> output = udf.arraySortDefault(input); assertThat(output, contains(Double.valueOf(-1.1), Double.valueOf(1.1), Double.valueOf(3.1))); ...
@Override public void close() throws IOException { IOException ioeFromFlush = null; try { flush(); } catch (IOException e) { ioeFromFlush = e; throw e; } finally { try { this.out.close(); } catch (IOException e) { // If there was an Exception during flush(...
@Test public void testCloseWhenFlushThrowingIOException() throws Exception { MockOutputStream out = new MockOutputStream(); SyncableDataOutputStream sdos = new SyncableDataOutputStream(out); out.flushThrowIOE = true; LambdaTestUtils.intercept(IOException.class, "An IOE from flush", () -> sdos.close())...
public String buildRealData(final ConditionData condition, final ServerWebExchange exchange) { return ParameterDataFactory.builderData(condition.getParamType(), condition.getParamName(), exchange); }
@Test public void testBuildRealDataHostBranch() { conditionData.setParamType(ParamTypeEnum.HOST.getName()); assertEquals("localhost", abstractMatchStrategy.buildRealData(conditionData, exchange)); }
protected JavaRDD<GenericRecord> maybeAppendKafkaOffsets(JavaRDD<ConsumerRecord<Object, Object>> kafkaRDD) { if (this.shouldAddOffsets) { AvroConvertor convertor = new AvroConvertor(schemaProvider.getSourceSchema()); return kafkaRDD.map(convertor::withKafkaFieldsAppended); } else { return kafk...
@Test public void testAppendKafkaOffsets() throws IOException { UtilitiesTestBase.Helpers.saveStringsToDFS( new String[] {dataGen.generateGenericRecord().getSchema().toString()}, hoodieStorage(), SCHEMA_PATH); ConsumerRecord<Object, Object> recordConsumerRecord = new ConsumerRecord<Obj...
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { try { session.getClient().putDirectory(folder.getAbsolute()); return folder; } catch(MantaException e) { throw new MantaExceptionMappingService().map("...
@Test public void testMkdir() throws Exception { final Path target = new MantaDirectoryFeature(session).mkdir(randomDirectory(), null); final PathAttributes found = new MantaAttributesFinderFeature(session).find(target); assertNotEquals(Permission.EMPTY, found.getPermission()); new M...
public static <T extends Serializable> SerializableCoder<T> of(TypeDescriptor<T> type) { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) type.getRawType(); return new SerializableCoder<>(clazz, type); }
@Test public void coderChecksForEquals() throws Exception { SerializableCoder.of(ProperEquals.class); expectedLogs.verifyNotLogged("Can't verify serialized elements of type"); }
@Override public synchronized void addAggregateFunctionFactory( final AggregateFunctionFactory aggregateFunctionFactory) { final String functionName = aggregateFunctionFactory.getName().toUpperCase(); validateFunctionName(functionName); if (udfs.containsKey(functionName)) { throw new KsqlExce...
@Test public void shouldThrowOnInvalidUdafFunctionName() { // Given: when(udafFactory.getName()).thenReturn("i am invalid"); // When: final Exception e = assertThrows( KsqlException.class, () -> functionRegistry.addAggregateFunctionFactory(udafFactory) ); // Then: assertT...
public static < EventTypeT, EventKeyTypeT, ResultTypeT, StateTypeT extends MutableState<EventTypeT, ResultTypeT>> OrderedEventProcessor<EventTypeT, EventKeyTypeT, ResultTypeT, StateTypeT> create( OrderedProcessingHandler<EventTypeT, EventKeyTypeT, StateTypeT, Resu...
@Test public void testProcessingOfTheLastInput() throws CannotProvideCoderException { Event[] events = { Event.create(0, "id-1", "a"), Event.create(1, "id-1", "b"), Event.create(2, "id-1", StringEventExaminer.LAST_INPUT) }; Collection<KV<String, OrderedProcessingStatus>> expectedStatuse...
@Override public void configure(final Map<String, ?> config) { configure( config, new Options(), org.rocksdb.LRUCache::new, org.rocksdb.WriteBufferManager::new ); }
@Test public void shouldFailIfConfiguredTwiceFromSameInstance() { // Given: rocksDBConfig.configure(CONFIG_PROPS); // Expect: // When: final Exception e = assertThrows( IllegalStateException.class, () -> rocksDBConfig.configure(CONFIG_PROPS) ); // Then: assertThat(e.g...
@Override public String generateSqlType(Dialect dialect) { return switch (dialect.getId()) { case PostgreSql.ID, H2.ID -> "INTEGER"; case MsSql.ID -> "INT"; case Oracle.ID -> "NUMBER(38,0)"; default -> throw new IllegalArgumentException("Unsupported dialect id " + dialect.getId()); }; ...
@Test public void generateSqlType_for_MsSql() { assertThat(underTest.generateSqlType(new MsSql())).isEqualTo("INT"); }
static void finish(TracingFilter filter, DubboRequest request, @Nullable Result result, @Nullable Throwable error, Span span) { if (request instanceof RpcClientRequest) { filter.clientHandler.handleReceive( new DubboClientResponse((DubboClientRequest) request, result, error), span); } else { ...
@Test void finish_result_but_null_error_DubboServerRequest() { Span span = tracing.tracer().nextSpan().kind(SERVER).start(); FinishSpan.finish(filter, serverRequest, mock(Result.class), null, span); testSpanHandler.takeRemoteSpan(SERVER); }
@VisibleForTesting WxMpService getWxMpService(Integer userType) { // 第一步,查询 DB 的配置项,获得对应的 WxMpService 对象 SocialClientDO client = socialClientMapper.selectBySocialTypeAndUserType( SocialTypeEnum.WECHAT_MP.getType(), userType); if (client != null && Objects.equals(client.getSta...
@Test public void testGetWxMpService_clientDisable() { // 准备参数 Integer userType = randomPojo(UserTypeEnum.class).getValue(); // mock 数据 SocialClientDO client = randomPojo(SocialClientDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()) .setUserType(userTyp...
public void setFilePath(String filePath) { if (filePath == null) { throw new IllegalArgumentException("File path cannot be null."); } // TODO The job-submission web interface passes empty args (and thus empty // paths) to compute the preview graph. The following is a workaro...
@Test void testSetPathNullPath() { assertThatThrownBy(() -> new DummyFileInputFormat().setFilePath((Path) null)) .isInstanceOf(IllegalArgumentException.class); }
@Override @SneakyThrows public <T> T parseObject(String text, Class<T> clazz) { JavaType javaType = MAPPER.getTypeFactory().constructType(clazz); return MAPPER.readValue(text, javaType); }
@Test public void testParseObject() { // normal json to boolean Assertions.assertEquals(true, JACKSON_HANDLER.parseObject("true", Boolean.class)); // normal json to double Assertions.assertEquals(0.01, JACKSON_HANDLER.parseObject("0.01", Double.class)); // normal json to inte...
public VersionRange<T> intersectionWith(VersionRange<T> that) { if (this.isAll()) return that; if (that.isAll()) return this; if (!isOverlappedBy(that)) return empty(); T newMinimum; if (this.minimum == null) newMinimum = that.min...
@Test public void testIntersectionWith() { assertIntersectionWith(all(), all(), all()); assertIntersectionWith(all(), empty(), empty()); assertIntersectionWith(all(), VersionNumber.between("10", "20"), VersionNumber.between("10", "20")); assertIntersectionWith(all(), VersionNumber.at...
public boolean test(final IndexRange indexRange, final Set<Stream> validStreams) { // If index range is incomplete, check the prefix against the valid index sets. if (indexRange.streamIds() == null) { return validStreams.stream() .map(Stream::getIn...
@Test public void emptyStreamsShouldNotMatchAnything() { final IndexRange indexRange = mock(IndexRange.class); assertThat(toTest.test(indexRange, Collections.emptySet())).isFalse(); }
public Optional<Set<String>> subscribedTopics() { return subscribedTopics; }
@Test public void testSubscribedTopics() { // not able to compute it for a newly created group assertEquals(Optional.empty(), group.subscribedTopics()); JoinGroupRequestProtocolCollection protocols = new JoinGroupRequestProtocolCollection(); protocols.add(new JoinGroupRequestProtoco...
public Result runExtractor(String value) { final Matcher matcher = pattern.matcher(value); final boolean found = matcher.find(); if (!found) { return null; } final int start = matcher.groupCount() > 0 ? matcher.start(1) : -1; final int end = matcher.groupCou...
@Test public void testReplacementWithNoMatchAndDefaultReplacement() throws Exception { final Message message = messageFactory.createMessage("Test", "source", Tools.nowUTC()); final RegexReplaceExtractor extractor = new RegexReplaceExtractor( metricRegistry, "id", ...
@SuppressWarnings("unchecked") @Override public <S extends StateStore> S getStateStore(final String name) { final StateStore store = stateManager.getGlobalStore(name); return (S) getReadWriteStore(store); }
@Test public void shouldNotAllowCloseForKeyValueStore() { when(stateManager.getGlobalStore(GLOBAL_KEY_VALUE_STORE_NAME)).thenReturn(mock(KeyValueStore.class)); final StateStore store = globalContext.getStateStore(GLOBAL_KEY_VALUE_STORE_NAME); try { store.close(); fail...
@Override public NamespacedMetric namespace(final String... key) { final IRubyObject[] rubyfiedKeys = Stream.of(key) .map(this::getSymbol) .toArray(IRubyObject[]::new); return new NamespacedMetricImpl( this.threadContext, this.metrics.namespace(this.t...
@Test public void testNamespace() { final NamespacedMetric metrics = this.getInstance().namespace("test"); final NamespacedMetric namespaced = metrics.namespace("abcdef"); assertThat(namespaced.namespaceName()).containsExactly("test", "abcdef"); final NamespacedMetric namespaced2 =...
@Override public void write(T record) { recordConsumer.startMessage(); try { messageWriter.writeTopLevelMessage(record); } catch (RuntimeException e) { Message m = (record instanceof Message.Builder) ? ((Message.Builder) record).build() : (Message) record; LOG.error("Cannot write message...
@Test public void testSimplestMessage() throws Exception { RecordConsumer readConsumerMock = Mockito.mock(RecordConsumer.class); ProtoWriteSupport<TestProtobuf.InnerMessage> instance = createReadConsumerInstance(TestProtobuf.InnerMessage.class, readConsumerMock); TestProtobuf.InnerMessage.Builder...
public static boolean loadRules(List<DegradeRule> rules) { try { return currentProperty.updateValue(rules); } catch (Throwable e) { RecordLog.error("[DefaultCircuitBreakerRuleManager] Unexpected error when loading default rules", e); return false; } }
@Test public void testLoadRules() { DegradeRule rule = mock(DegradeRule.class); List<DegradeRule> ruleList = new ArrayList<DegradeRule>(); ruleList.add(rule); assertTrue(DefaultCircuitBreakerRuleManager.loadRules(ruleList)); assertFalse(DefaultCircuitBreakerRuleManager.loadRu...
@Override public void onChange(Job job) { sendObject(job); if (job.hasState(SUCCEEDED) || job.hasState(FAILED) || job.hasState(DELETED)) { close(); } }
@Test void sseConnectionIsClosedIfJobStateIsDeleted() throws IOException { JobSseExchange jobSseExchange = new JobSseExchange(httpExchange, storageProvider, new JacksonJsonMapper()); jobSseExchange.onChange(aDeletedJob().build()); verify(storageProvider).removeJobStorageOnChangeListener(jo...
public Searcher searcher() { return new Searcher(); }
@Test void require_that_multi_term_queries_are_supported() { ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder(); IndexableFeatureConjunction c1 = indexableConj( conj( feature("a").inSet("1"), feature("b").inSet("3"))); ...
@Override public <OUT> ProcessConfigurableAndNonKeyedPartitionStream<OUT> process( OneInputStreamProcessFunction<T, OUT> processFunction) { validateStates( processFunction.usesStates(), new HashSet<>( Arrays.asList( ...
@Test void testProcess() throws Exception { ExecutionEnvironmentImpl env = StreamTestUtils.getEnv(); NonKeyedPartitionStreamImpl<Integer> stream = new NonKeyedPartitionStreamImpl<>( env, new TestingTransformation<>("t1", Types.INT, 1)); stream.process(...
@Override public int getOrder() { return PluginEnum.WEB_SOCKET.getCode(); }
@Test public void getOrderTest() { assertEquals(PluginEnum.WEB_SOCKET.getCode(), webSocketPlugin.getOrder()); }
public static RDA fit(double[][] x, int[] y, Properties params) { double alpha = Double.parseDouble(params.getProperty("smile.rda.alpha", "0.9")); double[] priori = Strings.parseDoubleArray(params.getProperty("smile.rda.priori")); double tol = Double.parseDouble(params.getProperty("smile.rda.tol...
@Test public void testPenDigits() { System.out.println("Pen Digits"); MathEx.setSeed(19650218); // to get repeatable results. ClassificationValidations<RDA> result = CrossValidation.classification(10, PenDigits.x, PenDigits.y, (x, y) -> RDA.fit(x, y, 0.9)); System.o...
public static BlockLease newLease(Block block, Closer... closers) { return new ClosingBlockLease(block, closers); }
@Test public void testArrayAllocations() { CountingArrayAllocator allocator = new CountingArrayAllocator(); assertEquals(allocator.getBorrowedArrayCount(), 0); int[] array = allocator.borrowIntArray(1); try (BlockLease ignored = newLease(dummyBlock, () -> allocator.returnArray(a...
@Override public Iterable<TimerData> timersIterable() { FluentIterable<Timer> allTimers = FluentIterable.from(workItem.getTimers().getTimersList()); FluentIterable<Timer> eventTimers = allTimers.filter(IS_WATERMARK); FluentIterable<Timer> nonEventTimers = allTimers.filter(Predicates.not(IS_WATERMARK)); ...
@Test public void testTimerOrdering() throws Exception { Windmill.WorkItem workItem = Windmill.WorkItem.newBuilder() .setKey(SERIALIZED_KEY) .setWorkToken(17) .setTimers( Windmill.TimerBundle.newBuilder() .addTimers( ...
public static String getSchemasPath(final String databaseName) { return String.join("/", getDatabaseNamePath(databaseName), SCHEMAS_NODE); }
@Test void assertGetSchemasPath() { assertThat(ShardingSphereDataNode.getSchemasPath("db_name"), is("/statistics/databases/db_name/schemas")); }
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromStrin...
@Test void forExpression() { String inputExpression = "for item in order.items return item.price * item.quantity"; BaseNode forbase = parse( inputExpression ); assertThat( forbase).isInstanceOf(ForExpressionNode.class); assertThat( forbase.getText()).isEqualTo(inputExpression); ...
public static void rewind(Buffer buffer) { buffer.rewind(); }
@Test public void testRewind() { ByteBuffer byteBuffer = ByteBuffer.allocate(4); byteBuffer.putInt(1); Assertions.assertDoesNotThrow(() -> BufferUtils.rewind(byteBuffer)); }
public synchronized V get(final K key, final Supplier<V> valueSupplier, final Consumer<V> expireCallback) { final var value = cache.get(key); if (value != null) { value.updateDeadline(); return value.value; } final var newValue = new ExpirableValue<>(valueSupplie...
@Test public void testExpire() throws InterruptedException { final var cache = new SimpleCache<Integer, Integer>(executor, 500L, 5); final var expiredValues = Collections.synchronizedSet(new HashSet<Integer>()); final var allKeys = IntStream.range(0, 5).boxed().collect(Collectors.toSet()); ...
public List<MavenArtifact> searchSha1(String sha1) throws IOException, TooManyRequestsException { if (null == sha1 || !sha1.matches("^[0-9A-Fa-f]{40}$")) { throw new IllegalArgumentException("Invalid SHA1 format"); } if (cache != null) { final List<MavenArtifact> cached =...
@Test(expected = IOException.class) public void testMissingSha1() throws Exception { try { searcher.searchSha1("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); } catch (IOException ex) { //we hit a failure state on the CI Assume.assumeFalse(StringUtils.contains(ex...
@Nullable DockerCredentialHelper getCredentialHelperFor(String registry) { List<Predicate<String>> registryMatchers = getRegistryMatchersFor(registry); Map.Entry<String, String> firstCredHelperMatch = findFirstInMapByKey(dockerConfigTemplate.getCredHelpers(), registryMatchers); if (firstCredHelpe...
@Test public void testGetCredentialHelperFor_withSuffix() throws URISyntaxException, IOException { Path json = Paths.get(Resources.getResource("core/json/dockerconfig.json").toURI()); DockerConfig dockerConfig = new DockerConfig(JsonTemplateMapper.readJsonFromFile(json, DockerConfigTemplate.class)); ...
@Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) { String value = way.getTag("hgv:conditional", ""); int index = value.indexOf("@"); Hgv hgvValue = index > 0 && conditionalWeightToTons(value) == 3.5 ? Hgv.find(value.substring(...
@Test public void testConditionalTags() { EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1); ReaderWay readerWay = new ReaderWay(1); readerWay.setTag("highway", "primary"); readerWay.setTag("hgv:conditional", "no @ (weight > 3.5)"); parser.handleWayTags(edgeId, edgeIntA...
public void removeSelectData(final SelectorData selectorData) { Optional.ofNullable(selectorData).ifPresent(data -> { final List<SelectorData> selectorDataList = SELECTOR_MAP.get(data.getPluginName()); synchronized (SELECTOR_MAP) { Optional.ofNullable(selectorDataList).if...
@Test public void testRemoveSelectData() throws NoSuchFieldException, IllegalAccessException { SelectorData selectorData = SelectorData.builder().id("1").pluginName(mockPluginName1).build(); ConcurrentHashMap<String, List<SelectorData>> selectorMap = getFieldByName(selectorMapStr); selectorM...
public Optional<Long> validateAndGetTimestamp(final ExternalServiceCredentials credentials) { final String[] parts = requireNonNull(credentials).password().split(DELIMITER); final String timestampSeconds; final String actualSignature; // making sure password format matches our expectations based on the...
@Test public void testValidateWithExpiration() throws Exception { final long elapsedSeconds = 10000; clock.incrementSeconds(elapsedSeconds); assertEquals(standardGenerator.validateAndGetTimestamp(standardCredentials, elapsedSeconds + 1).orElseThrow(), TIME_SECONDS); assertTrue(standardGenerator.valid...
void downloadInterpreter( InterpreterInstallationRequest request, DependencyResolver dependencyResolver, Path interpreterDir, ServiceCallback<String> serviceCallback) { try { LOGGER.info("Start to download a dependency: {}", request.getName()); if (null != serviceCallback) { ...
@Test void downloadInterpreter() throws IOException { final String interpreterName = "test-interpreter"; String artifactName = "junit:junit:4.11"; Path specificInterpreterPath = Files.createDirectory(Paths.get(interpreterDir.toString(), interpreterName)); DependencyResolver dependencyResolver ...
public <T> void resolve(T resolvable) { ParamResolver resolver = this; if (ParamScope.class.isAssignableFrom(resolvable.getClass())) { ParamScope newScope = (ParamScope) resolvable; resolver = newScope.applyOver(resolver); } resolveStringLeaves(resolvable, resolve...
@Test public void shouldResolveCollections() { PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("cruise", "dev", "ant"); pipelineConfig.setLabelTemplate("2.1-${COUNT}-#{foo}-bar-#{bar}"); HgMaterialConfig materialConfig = MaterialConfigsMother.hgMaterialConfig("http:...
@Override public void process() { if (realVideoObject == null) { realVideoObject = new RealVideoObject(); } realVideoObject.process(); }
@Test void processDoesNotThrowException() { assertDoesNotThrow(() -> new VideoObjectProxy().process(), "Process method should not throw any exception"); }
@Override public void createTable(ObjectPath tablePath, CatalogBaseTable table, boolean ignoreIfExists) throws TableAlreadyExistException, DatabaseNotExistException, CatalogException { checkNotNull(tablePath, "Table path cannot be null"); checkNotNull(table, "Table cannot be null"); if (!databaseEx...
@Test public void testCreateHoodieTableWithWrongTableType() { HashMap<String,String> properties = new HashMap<>(); properties.put(FactoryUtil.CONNECTOR.key(), "hudi"); properties.put("table.type","wrong type"); CatalogTable table = new CatalogTableImpl(schema, properties, "hudi table"); ...
@Udf public <T> List<T> remove( @UdfParameter(description = "Array of values") final List<T> array, @UdfParameter(description = "Value to remove") final T victim) { if (array == null) { return null; } return array.stream() .filter(el -> !Objects.equals(el, victim)) .coll...
@Test public void shouldReturnNullForNullInputs() { final List<Long> input1 = null; final Long input2 = null; final List<Long> result = udf.remove(input1, input2); assertThat(result, is(nullValue())); }
public FEELFnResult<Boolean> invoke(@ParameterName( "point1" ) Comparable point1, @ParameterName( "point2" ) Comparable point2) { if ( point1 == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point1", "cannot be null")); } if ( point2 == null ) { ...
@Test void invokeParamsCantBeCompared() { FunctionTestUtil.assertResultError( coincidesFunction.invoke("a", BigDecimal.valueOf(2) ), InvalidParametersEvent.class ); }
@Override public Thread newThread(Runnable runnable) { String name = mPrefix + mThreadNum.getAndIncrement(); Thread ret = new Thread(mGroup, runnable, name, 0); ret.setDaemon(mDaemon); return ret; }
@Test void testPrefixAndDaemon() { NamedThreadFactory factory = new NamedThreadFactory("prefix", true); Thread t = factory.newThread(Mockito.mock(Runnable.class)); assertThat(t.getName(), allOf(containsString("prefix-"), containsString("-thread-"))); assertTrue(t.isDaemon()); }
@VisibleForTesting static PhotoModel toCommonPhoto(Photo p, String albumId) { Preconditions.checkArgument( !Strings.isNullOrEmpty(p.getOriginalSize().getSource()), "Photo [" + p.getId() + "] has a null authUrl"); return new PhotoModel( p.getTitle(), p.getOriginalSize().getSourc...
@Test public void toCommonPhoto() { Photo photo = FlickrTestUtils.initializePhoto(PHOTO_TITLE, FETCHABLE_URL, PHOTO_DESCRIPTION, MEDIA_TYPE); PhotoModel photoModel = FlickrPhotosExporter.toCommonPhoto(photo, ALBUM_ID); assertThat(photoModel.getAlbumId()).isEqualTo(ALBUM_ID); assertThat(photoM...
@Override public void symlink(final Path file, final String target) throws BackgroundException { try { Files.createSymbolicLink(session.toPath(file), session.toPath(target)); } catch(IOException e) { throw new LocalExceptionMappingService().map("Cannot create {0}", e,...
@Test public void testSymlink() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); assumeTrue(session.isPosixFilesystem()); session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new Disab...
public static synchronized void registerProvider(ZuulBlockFallbackProvider provider) { AssertUtil.notNull(provider, "fallback provider cannot be null"); String route = provider.getRoute(); if ("*".equals(route) || route == null) { defaultFallbackProvider = provider; } else { ...
@Test public void testRegisterProvider() throws Exception { MyNullResponseFallBackProvider myNullResponseFallBackProvider = new MyNullResponseFallBackProvider(); ZuulBlockFallbackManager.registerProvider(myNullResponseFallBackProvider); Assert.assertEquals(myNullResponseFallBackProvider.getR...
static File resolveTempDir(Properties p) { return new File(Optional.ofNullable(p.getProperty("sonar.path.temp")).orElse("temp")); }
@Test public void resolveTempDir_reads_relative_temp_dir_location_from_sonar_path_temp() { String tempDirPath = "blablabl"; Properties properties = new Properties(); properties.put("sonar.path.temp", tempDirPath); File file = Shutdowner.resolveTempDir(properties); assertThat(file).isEqualTo(new F...
public void start() { this.lock.lock(); try { if (this.destroyed) { return; } if (!this.stopped) { return; } this.stopped = false; if (this.running) { return; } ...
@Test public void testStartTrigger() throws Exception { assertEquals(0, this.timer.counter.get()); this.timer.start(); Thread.sleep(1000); assertEquals(20, this.timer.counter.get(), 3); }
@SuppressWarnings("unused") // Required for automatic type inference public static <K> Builder0<K> forClass(final Class<K> type) { return new Builder0<>(); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowIfHandlerSupplierThrows2() { HandlerMaps.forClass(BaseType.class).withArgTypes(String.class, Integer.class) .put(LeafTypeA.class, () -> { throw new RuntimeException("Boom"); }) .build(); }
public static <T> T waitWithLogging( Logger log, String prefix, String action, CompletableFuture<T> future, Deadline deadline, Time time ) throws Throwable { log.info("{}Waiting for {}", prefix, action); try { T result = time.waitForFuture(...
@Test public void testWaitWithLogging() throws Throwable { ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1); CompletableFuture<Integer> future = new CompletableFuture<>(); executorService.schedule(() -> future.complete(123), 1000, TimeUnit.NANOSECONDS); a...
@Override public void visit(final File f, final String _relativePath) throws IOException { int mode = IOUtils.mode(f); // On Windows, the elements of relativePath are separated by // back-slashes (\), but Zip files need to have their path elements separated // by forward-slashes (/)...
@Issue("JENKINS-9942") @Test public void backwardsSlashesOnWindows() throws IOException { // create foo/bar/baz/Test.txt Path baz = tmp.newFolder().toPath().resolve("foo").resolve("bar").resolve("baz"); Files.createDirectories(baz); Path tmpFile = baz.resolve("Test.txt"); ...