focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public byte[] serialize(PendingSplitsCheckpoint<T> checkpoint) throws IOException { checkArgument( checkpoint.getClass() == PendingSplitsCheckpoint.class, "Cannot serialize subclasses of PendingSplitsCheckpoint"); // optimization: the splits lazily cache their own serialized form if (checkpoint.serializedFormCache != null) { return checkpoint.serializedFormCache; } final SimpleVersionedSerializer<T> splitSerializer = this.splitSerializer; // stack cache final Collection<T> splits = checkpoint.getSplits(); final Collection<Path> processedPaths = checkpoint.getAlreadyProcessedPaths(); final ArrayList<byte[]> serializedSplits = new ArrayList<>(splits.size()); final ArrayList<byte[]> serializedPaths = new ArrayList<>(processedPaths.size()); int totalLen = 16; // four ints: magic, version of split serializer, count splits, count paths for (T split : splits) { final byte[] serSplit = splitSerializer.serialize(split); serializedSplits.add(serSplit); totalLen += serSplit.length + 4; // 4 bytes for the length field } for (Path path : processedPaths) { final byte[] serPath = path.toString().getBytes(StandardCharsets.UTF_8); serializedPaths.add(serPath); totalLen += serPath.length + 4; // 4 bytes for the length field } final byte[] result = new byte[totalLen]; final ByteBuffer byteBuffer = ByteBuffer.wrap(result).order(ByteOrder.LITTLE_ENDIAN); byteBuffer.putInt(VERSION_1_MAGIC_NUMBER); byteBuffer.putInt(splitSerializer.getVersion()); byteBuffer.putInt(serializedSplits.size()); byteBuffer.putInt(serializedPaths.size()); for (byte[] splitBytes : serializedSplits) { byteBuffer.putInt(splitBytes.length); byteBuffer.put(splitBytes); } for (byte[] pathBytes : serializedPaths) { byteBuffer.putInt(pathBytes.length); byteBuffer.put(pathBytes); } assert byteBuffer.remaining() == 0; // optimization: cache the serialized from, so we avoid the byte work during repeated // serialization checkpoint.serializedFormCache = result; return result; }
@Test void repeatedSerializationCaches() throws Exception { final PendingSplitsCheckpoint<FileSourceSplit> checkpoint = PendingSplitsCheckpoint.fromCollectionSnapshot( Collections.singletonList(testSplit2())); final byte[] ser1 = new PendingSplitsCheckpointSerializer<>(FileSourceSplitSerializer.INSTANCE) .serialize(checkpoint); final byte[] ser2 = new PendingSplitsCheckpointSerializer<>(FileSourceSplitSerializer.INSTANCE) .serialize(checkpoint); assertThat(ser1).isSameAs(ser2); }
public boolean isMultiThreadingEnabled() { return multiThreadingEnabled; }
@Test public void testIsMultiThreadingEnabled() { TopicConfig topicConfig = new TopicConfig(); assertFalse(topicConfig.isMultiThreadingEnabled()); }
public boolean isCompleteOncePreferredResolved() { return completeOncePreferredResolved; }
@Test void completeOncePreferredResolved() { assertThat(builder.build().isCompleteOncePreferredResolved()).isTrue(); builder.completeOncePreferredResolved(false); assertThat(builder.build().isCompleteOncePreferredResolved()).isFalse(); }
@Override protected Pair<Option<Dataset<Row>>, String> fetchNextBatch(Option<String> lastCkptStr, long sourceLimit) { LOG.info("fetchNextBatch(): Input checkpoint: " + lastCkptStr); MessageBatch messageBatch; try { messageBatch = fetchFileMetadata(); } catch (HoodieException e) { throw e; } catch (Exception e) { throw new HoodieReadFromSourceException("Failed to fetch file metadata from GCS events source", e); } if (messageBatch.isEmpty()) { LOG.info("No new data. Returning empty batch with checkpoint value: " + CHECKPOINT_VALUE_ZERO); return Pair.of(Option.empty(), CHECKPOINT_VALUE_ZERO); } Dataset<String> eventRecords = sparkSession.createDataset(messageBatch.getMessages(), Encoders.STRING()); LOG.info("Returning checkpoint value: " + CHECKPOINT_VALUE_ZERO); StructType sourceSchema = UtilHelpers.getSourceSchema(schemaProvider); if (sourceSchema != null) { return Pair.of(Option.of(sparkSession.read().schema(sourceSchema).json(eventRecords)), CHECKPOINT_VALUE_ZERO); } else { return Pair.of(Option.of(sparkSession.read().json(eventRecords)), CHECKPOINT_VALUE_ZERO); } }
@Test public void shouldReturnEmptyOnNoMessages() { when(pubsubMessagesFetcher.fetchMessages()).thenReturn(Collections.emptyList()); GcsEventsSource source = new GcsEventsSource(props, jsc, sparkSession, null, pubsubMessagesFetcher); Pair<Option<Dataset<Row>>, String> expected = Pair.of(Option.empty(), "0"); Pair<Option<Dataset<Row>>, String> dataAndCheckpoint = source.fetchNextBatch(Option.of("0"), 100); assertEquals(expected, dataAndCheckpoint); }
@Override public OAuth2AccessTokenDO getAccessToken(String accessToken) { // 优先从 Redis 中获取 OAuth2AccessTokenDO accessTokenDO = oauth2AccessTokenRedisDAO.get(accessToken); if (accessTokenDO != null) { return accessTokenDO; } // 获取不到,从 MySQL 中获取 accessTokenDO = oauth2AccessTokenMapper.selectByAccessToken(accessToken); // 如果在 MySQL 存在,则往 Redis 中写入 if (accessTokenDO != null && !DateUtils.isExpired(accessTokenDO.getExpiresTime())) { oauth2AccessTokenRedisDAO.set(accessTokenDO); } return accessTokenDO; }
@Test public void testGetAccessToken() { // mock 数据(访问令牌) OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class) .setExpiresTime(LocalDateTime.now().plusDays(1)); oauth2AccessTokenMapper.insert(accessTokenDO); // 准备参数 String accessToken = accessTokenDO.getAccessToken(); // 调用 OAuth2AccessTokenDO result = oauth2TokenService.getAccessToken(accessToken); // 断言 assertPojoEquals(accessTokenDO, result, "createTime", "updateTime", "deleted", "creator", "updater"); assertPojoEquals(accessTokenDO, oauth2AccessTokenRedisDAO.get(accessToken), "createTime", "updateTime", "deleted", "creator", "updater"); }
public void setName(String name) throws IllegalStateException { if (name != null && name.equals(this.name)) { return; // idempotent naming } if (this.name == null || CoreConstants.DEFAULT_CONTEXT_NAME.equals(this.name)) { this.name = name; } else { throw new IllegalStateException("Context has been already given a name"); } }
@Test public void renameDefault() { context.setName(CoreConstants.DEFAULT_CONTEXT_NAME); context.setName("hello"); }
public B version(String version) { this.version = version; return getThis(); }
@Test void version() { ReferenceBuilder builder = new ReferenceBuilder(); builder.version("version"); Assertions.assertEquals("version", builder.build().getVersion()); }
static boolean isValidComparison( final SqlType left, final ComparisonExpression.Type operator, final SqlType right ) { if (left == null || right == null) { throw nullSchemaException(left, operator, right); } return HANDLERS.stream() .filter(h -> h.handles.test(left.baseType())) .findFirst() .map(h -> h.validator.test(operator, right)) .orElse(false); }
@Test public void shouldAssertTrueForValidComparisons() { // When: int i = 0; int j = 0; for (final SqlType leftType: typesTable) { for (final SqlType rightType: typesTable) { if (expectedResults.get(i).get(j)) { assertThat(ComparisonUtil.isValidComparison(leftType, ComparisonExpression.Type.EQUAL, rightType), is(true)); } j++; } i++; j = 0; } }
public static <T extends Serializable> T ensureSerializable(T value) { return clone(value); }
@Test public void testTranscode() { String stringValue = "hi bob"; int intValue = 42; SerializableByJava testObject = new SerializableByJava(stringValue, intValue); SerializableByJava testCopy = SerializableUtils.ensureSerializable(testObject); assertEquals(stringValue, testCopy.stringValue); assertEquals(intValue, testCopy.intValue); }
static String getAbbreviation(Exception ex, Integer statusCode, String storageErrorMessage) { String result = null; for (RetryReasonCategory retryReasonCategory : rankedReasonCategories) { final String abbreviation = retryReasonCategory.captureAndGetAbbreviation(ex, statusCode, storageErrorMessage); if (abbreviation != null) { result = abbreviation; } } return result; }
@Test public void testEgressLimitRetryReason() { Assertions.assertThat(RetryReason.getAbbreviation(null, HTTP_UNAVAILABLE, EGRESS_OVER_ACCOUNT_LIMIT.getErrorMessage())).isEqualTo( EGRESS_LIMIT_BREACH_ABBREVIATION ); }
@Override public MapSettings setProperty(String key, String value) { return (MapSettings) super.setProperty(key, value); }
@Test public void setStringArrayEscapeCommas() { Settings settings = new MapSettings(definitions); settings.setProperty("multi_values", new String[]{"A,B", "C,D"}); String[] array = settings.getStringArray("multi_values"); assertThat(array).isEqualTo(new String[]{"A,B", "C,D"}); }
public boolean createDataConnection(DataConnectionCatalogEntry dl, boolean replace, boolean ifNotExists) { if (replace) { dataConnectionStorage.put(dl.name(), dl); listeners.forEach(TableListener::onTableChanged); return true; } else { boolean added = dataConnectionStorage.putIfAbsent(dl.name(), dl); if (!added && !ifNotExists) { throw QueryException.error("Data connection already exists: " + dl.name()); } if (!added) { // report only updates to listener listeners.forEach(TableListener::onTableChanged); } return added; } }
@Test public void when_createDataConnection_then_succeeds() { // given DataConnectionCatalogEntry dataConnectionCatalogEntry = dataConnection(); given(relationsStorage.putIfAbsent(dataConnectionCatalogEntry.name(), dataConnectionCatalogEntry)).willReturn(true); // when dataConnectionResolver.createDataConnection(dataConnectionCatalogEntry, false, false); // then verify(relationsStorage).putIfAbsent(eq(dataConnectionCatalogEntry.name()), isA(DataConnectionCatalogEntry.class)); }
public static <F extends Future<Void>> Mono<Void> from(F future) { Objects.requireNonNull(future, "future"); if (future.isDone()) { if (!future.isSuccess()) { return Mono.error(FutureSubscription.wrapError(future.cause())); } return Mono.empty(); } return new ImmediateFutureMono<>(future); }
@Test void testImmediateFutureMonoImmediate() { ImmediateEventExecutor eventExecutor = ImmediateEventExecutor.INSTANCE; Future<Void> promise = eventExecutor.newFailedFuture(new ClosedChannelException()); StepVerifier.create(FutureMono.from(promise)) .expectError(AbortedException.class) .verify(Duration.ofSeconds(30)); }
@ApiOperation(value = "Delete a user", tags = { "Users" }, code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the user was found and has been deleted. Response-body is intentionally empty."), @ApiResponse(code = 404, message = "Indicates the requested user was not found.") }) @DeleteMapping("/identity/users/{userId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteUser(@ApiParam(name = "userId") @PathVariable String userId) { User user = getUserFromRequest(userId); if (restApiInterceptor != null) { restApiInterceptor.deleteUser(user); } identityService.deleteUser(user.getId()); }
@Test public void testDeleteUser() throws Exception { User savedUser = null; try { User newUser = identityService.newUser("testuser"); newUser.setFirstName("Fred"); newUser.setLastName("McDonald"); newUser.setEmail("[email protected]"); identityService.saveUser(newUser); savedUser = newUser; closeResponse(executeRequest(new HttpDelete(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_USER, newUser.getId())), HttpStatus.SC_NO_CONTENT)); // Check if user is deleted assertThat(identityService.createUserQuery().userId(newUser.getId()).count()).isZero(); savedUser = null; } finally { // Delete user after test fails if (savedUser != null) { identityService.deleteUser(savedUser.getId()); } } }
@Override public boolean removeAll(Collection<?> c) { boolean changed = false; for (Object item : c) { changed = items.remove(serializer.encode(item)) || changed; } return changed; }
@Test public void testRemoveAll() throws Exception { //Test for mass removal and change checking Set<Integer> removeSet = Sets.newHashSet(); fillSet(10, set); Set<Integer> duplicateSet = Sets.newHashSet(set); assertFalse("No elements should change.", set.removeAll(removeSet)); assertEquals("Set should not have diverged from the duplicate.", duplicateSet, set); fillSet(5, removeSet); assertTrue("Elements should have been removed.", set.removeAll(removeSet)); assertNotEquals("Duplicate set should no longer be equivalent.", duplicateSet, set); assertEquals("Five elements should have been removed from set.", 5, set.size()); for (Integer item : removeSet) { assertFalse("No element of remove set should remain.", set.contains(item)); } }
public static InternetAddress fromIgnoringZoneId(String address) { return from(address, true); }
@Test public void testFromIgnoringZoneId() { assertInternetAddressEqualsIgnoringZoneId("fe80::641a:cdff:febd:d665", "fe80::641a:cdff:febd:d665%dummy0"); }
@Override public List<ServiceDTO> getServiceInstances(String serviceId) { String configName = SERVICE_ID_TO_CONFIG_NAME.get(serviceId); if (configName == null) { return Collections.emptyList(); } return assembleServiceDTO(serviceId, bizConfig.getValue(configName)); }
@Test public void testGetConfigServiceInstances() { String someUrl = "http://some-host/some-path"; when(bizConfig.getValue(configServiceConfigName)).thenReturn(someUrl); List<ServiceDTO> serviceDTOList = kubernetesDiscoveryService .getServiceInstances(ServiceNameConsts.APOLLO_CONFIGSERVICE); assertEquals(1, serviceDTOList.size()); ServiceDTO serviceDTO = serviceDTOList.get(0); assertEquals(ServiceNameConsts.APOLLO_CONFIGSERVICE, serviceDTO.getAppName()); assertEquals(String.format("%s:%s", ServiceNameConsts.APOLLO_CONFIGSERVICE, someUrl), serviceDTO.getInstanceId()); assertEquals(someUrl, serviceDTO.getHomepageUrl()); }
@Override public void setDefaultValue(Object defaultValue) { if (defaultValue instanceof List) { final List<?> defaultValueList = (List<?>) defaultValue; this.defaultValue = defaultValueList.stream() .filter(o -> o instanceof String) .map(String::valueOf) .collect(Collectors.toList()); } }
@Test public void testSetDefaultValue() throws Exception { final ListField list = new ListField("list", "The List", Collections.emptyList(), "Hello, this is a list", ConfigurationField.Optional.NOT_OPTIONAL); final Object defaultValue1 = list.getDefaultValue(); assertThat(defaultValue1 instanceof List).isTrue(); assertThat(((List) defaultValue1).size()).isEqualTo(0); list.setDefaultValue(ImmutableList.of("Foo", "Bar")); final Object defaultValue2 = list.getDefaultValue(); assertThat(defaultValue2 instanceof List).isTrue(); assertThat(((List) defaultValue2).size()).isEqualTo(2); list.setDefaultValue("Foo"); final Object defaultValue3 = list.getDefaultValue(); assertThat(defaultValue3 instanceof List).isTrue(); assertThat(((List) defaultValue3).size()).isEqualTo(2); list.setDefaultValue(ImmutableList.of(3, "lol")); final Object defaultValue4 = list.getDefaultValue(); assertThat(defaultValue4 instanceof List).isTrue(); final List defaultValue4List = (List) defaultValue4; assertThat(defaultValue4List.size()).isEqualTo(1); assertThat(defaultValue4List.get(0)).isEqualTo("lol"); }
@Override public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument(); EmbeddedDocumentExtractor extractor = EmbeddedDocumentUtil.getEmbeddedDocumentExtractor(context); String mediaType = metadata.get(Metadata.CONTENT_TYPE); if (mediaType != null && mediaType.contains("version=5")) { throw new UnsupportedFormatException("Tika does not yet support rar version 5."); } Archive rar = null; try (TemporaryResources tmp = new TemporaryResources()) { TikaInputStream tis = TikaInputStream.get(stream, tmp, metadata); rar = new Archive(tis.getFile()); if (rar.isEncrypted()) { throw new EncryptedDocumentException(); } //Without this BodyContentHandler does not work xhtml.element("div", " "); FileHeader header = rar.nextFileHeader(); while (header != null && !Thread.currentThread().isInterrupted()) { if (!header.isDirectory()) { Metadata entrydata = PackageParser.handleEntryMetadata(header.getFileName(), header.getCTime(), header.getMTime(), header.getFullUnpackSize(), xhtml); try (InputStream subFile = rar.getInputStream(header)) { if (extractor.shouldParseEmbedded(entrydata)) { extractor.parseEmbedded(subFile, handler, entrydata, true); } } } header = rar.nextFileHeader(); } } catch (RarException e) { throw new TikaException("RarParser Exception", e); } finally { if (rar != null) { rar.close(); } } xhtml.endDocument(); }
@Test public void testEncryptedRar() throws Exception { Parser parser = new RarParser(); try (InputStream input = getResourceAsStream("/test-documents/test-documents-enc.rar")) { Metadata metadata = new Metadata(); ContentHandler handler = new BodyContentHandler(); ParseContext context = new ParseContext(); context.set(PasswordProvider.class, new PasswordProvider() { @Override public String getPassword(Metadata metadata) { return "ApacheTika"; } }); // Note - we don't currently support encrypted RAR // files so we can't check the contents parser.parse(input, handler, metadata, trackingContext); fail("No support yet for Encrypted RAR files"); } catch (EncryptedDocumentException e) { // Good, as expected right now } }
@Override public final void isEqualTo(@Nullable Object other) { @SuppressWarnings("UndefinedEquals") // the contract of this method is to follow Multimap.equals boolean isEqual = Objects.equal(actual, other); if (isEqual) { return; } // Fail but with a more descriptive message: if ((actual instanceof ListMultimap && other instanceof SetMultimap) || (actual instanceof SetMultimap && other instanceof ListMultimap)) { String actualType = (actual instanceof ListMultimap) ? "ListMultimap" : "SetMultimap"; String otherType = (other instanceof ListMultimap) ? "ListMultimap" : "SetMultimap"; failWithoutActual( fact("expected", other), fact("an instance of", otherType), fact("but was", actualCustomStringRepresentationForPackageMembersToCall()), fact("an instance of", actualType), simpleFact( lenientFormat( "a %s cannot equal a %s if either is non-empty", actualType, otherType))); } else if (actual instanceof ListMultimap) { containsExactlyEntriesIn((Multimap<?, ?>) checkNotNull(other)).inOrder(); } else if (actual instanceof SetMultimap) { containsExactlyEntriesIn((Multimap<?, ?>) checkNotNull(other)); } else { super.isEqualTo(other); } }
@Test public void setMultimapIsEqualTo_fails() { ImmutableSetMultimap<String, String> multimapA = ImmutableSetMultimap.<String, String>builder() .putAll("kurt", "kluever", "russell", "cobain") .build(); ImmutableSetMultimap<String, String> multimapB = ImmutableSetMultimap.<String, String>builder().putAll("kurt", "kluever", "russell").build(); expectFailureWhenTestingThat(multimapA).isEqualTo(multimapB); assertFailureKeys("unexpected", "---", "expected", "but was"); assertFailureValue("unexpected", "{kurt=[cobain]}"); assertFailureValue("expected", "{kurt=[kluever, russell]}"); assertFailureValue("but was", "{kurt=[kluever, russell, cobain]}"); }
@Override public URI rewriteURI(URI d2Uri) { String path = d2Uri.getRawPath(); UriBuilder builder = UriBuilder.fromUri(_httpURI); if (path != null) { builder.path(path); } builder.replaceQuery(d2Uri.getRawQuery()); builder.fragment(d2Uri.getRawFragment()); URI rewrittenUri = builder.build(); LOGGER.debug("rewrite uri {} -> {}", d2Uri, rewrittenUri); return rewrittenUri; }
@Test public void testSimpleD2Rewrite() throws URISyntaxException { final URI httpURI = new URIBuilder("http://www.linkedin.com:1234/test").build(); final URI d2URI = new URIBuilder("d2://serviceName/request/query?q=5678").build(); final String expectURL = "http://www.linkedin.com:1234/test/request/query?q=5678"; URIRewriter URIRewriter = new D2URIRewriter(httpURI); URI finalURI = URIRewriter.rewriteURI(d2URI); Assert.assertEquals(finalURI.toString(), expectURL); }
@Override public Mono<Void> apply(final ServerWebExchange exchange, final ShenyuPluginChain shenyuPluginChain, final ParamMappingRuleHandle paramMappingRuleHandle) { return shenyuPluginChain.execute(exchange); }
@Test public void testApply() { when(this.chain.execute(any())).thenReturn(Mono.empty()); StepVerifier.create(defaultOperator.apply(this.exchange, this.chain, new ParamMappingRuleHandle())).expectSubscription().verifyComplete(); }
@GetMapping( path = "/admin/extension/{namespaceName}/{extensionName}", produces = MediaType.APPLICATION_JSON_VALUE ) public ResponseEntity<ExtensionJson> getExtension(@PathVariable String namespaceName, @PathVariable String extensionName) { try { admins.checkAdminUser(); ExtensionJson json; var latest = repositories.findLatestVersion(namespaceName, extensionName, null, false, false); if (latest != null) { json = local.toExtensionVersionJson(latest, null, false); json.allTargetPlatformVersions = repositories.findTargetPlatformsGroupedByVersion(latest.getExtension()); json.active = latest.getExtension().isActive(); } else { var extension = repositories.findExtension(extensionName, namespaceName); if (extension == null) { var error = "Extension not found: " + NamingUtil.toExtensionId(namespaceName, extensionName); throw new ErrorResultException(error, HttpStatus.NOT_FOUND); } json = new ExtensionJson(); json.namespace = extension.getNamespace().getName(); json.name = extension.getName(); json.allVersions = Collections.emptyMap(); json.allTargetPlatformVersions = Collections.emptyList(); json.active = extension.isActive(); } return ResponseEntity.ok(json); } catch (ErrorResultException exc) { return exc.toResponseEntity(ExtensionJson.class); } }
@Test public void testGetInactiveExtension() throws Exception { mockAdminUser(); mockExtension(2, 0, 0).forEach(ev -> { ev.setActive(false); ev.getExtension().setActive(false); }); mockMvc.perform(get("/admin/extension/{namespace}/{extension}", "foobar", "baz") .with(user("admin_user").authorities(new SimpleGrantedAuthority(("ROLE_ADMIN")))) .with(csrf().asHeader())) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { e.namespace = "foobar"; e.name = "baz"; e.version = "2.0.0"; e.active = false; }))); }
@Override public Map<String, Metric> getMetrics() { final Map<String, Metric> gauges = new HashMap<>(); for (final GarbageCollectorMXBean gc : garbageCollectors) { final String name = WHITESPACE.matcher(gc.getName()).replaceAll("-"); gauges.put(name(name, "count"), (Gauge<Long>) gc::getCollectionCount); gauges.put(name(name, "time"), (Gauge<Long>) gc::getCollectionTime); } return Collections.unmodifiableMap(gauges); }
@Test public void hasAGaugeForGcTimes() { final Gauge<Long> gauge = (Gauge<Long>) metrics.getMetrics().get("PS-OldGen.time"); assertThat(gauge.getValue()) .isEqualTo(2L); }
public static Optional<KsqlAuthorizationValidator> create( final KsqlConfig ksqlConfig, final ServiceContext serviceContext, final Optional<KsqlAuthorizationProvider> externalAuthorizationProvider ) { final Optional<KsqlAccessValidator> accessValidator = getAccessValidator( ksqlConfig, serviceContext, externalAuthorizationProvider ); return accessValidator.map(v -> new KsqlAuthorizationValidatorImpl(cacheIfEnabled(ksqlConfig, v))); }
@Test public void shouldReturnEmptyAuthorizationValidatorWhenNoAuthorizationProviderIsFound() { // Given: givenKafkaAuthorizer("", Collections.emptySet()); // When: final Optional<KsqlAuthorizationValidator> validator = KsqlAuthorizationValidatorFactory.create( ksqlConfig, serviceContext, Optional.empty() ); // Then assertThat(validator, is(Optional.empty())); }
public FEELFnResult<Boolean> invoke(@ParameterName( "range" ) Range range, @ParameterName( "point" ) Comparable point) { if ( point == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null")); } if ( range == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "range", "cannot be null")); } try { boolean result = ( range.getLowBoundary() == Range.RangeBoundary.CLOSED && point.compareTo( range.getLowEndPoint() ) == 0 ); return FEELFnResult.ofResult( result ); } catch( Exception e ) { // points are not comparable return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be compared to range")); } }
@Test void invokeParamRangeAndRange() { FunctionTestUtil.assertResult( startedByFunction.invoke( new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ), new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ) ), Boolean.TRUE ); FunctionTestUtil.assertResult( startedByFunction.invoke( new RangeImpl( Range.RangeBoundary.CLOSED, "a", "k", Range.RangeBoundary.CLOSED ), new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ) ), Boolean.TRUE ); FunctionTestUtil.assertResult( startedByFunction.invoke( new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ), new RangeImpl( Range.RangeBoundary.CLOSED, "f", "k", Range.RangeBoundary.CLOSED ) ), Boolean.FALSE ); FunctionTestUtil.assertResult( startedByFunction.invoke( new RangeImpl( Range.RangeBoundary.CLOSED, "a", "k", Range.RangeBoundary.CLOSED ), new RangeImpl( Range.RangeBoundary.OPEN, "a", "f", Range.RangeBoundary.CLOSED ) ), Boolean.FALSE ); }
public String namespace(Namespace ns) { return SLASH.join("v1", prefix, "namespaces", RESTUtil.encodeNamespace(ns)); }
@Test public void testNamespace() { Namespace ns = Namespace.of("ns"); assertThat(withPrefix.namespace(ns)).isEqualTo("v1/ws/catalog/namespaces/ns"); assertThat(withoutPrefix.namespace(ns)).isEqualTo("v1/namespaces/ns"); }
public static Set<String> getTableNameVariations(String tableName) { String rawTableName = extractRawTableName(tableName); String offlineTableName = OFFLINE.tableNameWithType(rawTableName); String realtimeTableName = REALTIME.tableNameWithType(rawTableName); return ImmutableSet.of(rawTableName, offlineTableName, realtimeTableName); }
@Test public void testGetTableNameVariations() { assertEquals(TableNameBuilder.getTableNameVariations("tableAbc"), ImmutableSet.of("tableAbc", "tableAbc_REALTIME", "tableAbc_OFFLINE")); assertEquals(TableNameBuilder.getTableNameVariations("tableAbc_REALTIME"), ImmutableSet.of("tableAbc", "tableAbc_REALTIME", "tableAbc_OFFLINE")); assertEquals(TableNameBuilder.getTableNameVariations("tableAbc_OFFLINE"), ImmutableSet.of("tableAbc", "tableAbc_REALTIME", "tableAbc_OFFLINE")); }
@Override public List<Catalogue> sort(List<Catalogue> catalogueTree, SortTypeEnum sortTypeEnum) { log.debug( "sort catalogue tree based on creation time. catalogueTree: {}, sortTypeEnum: {}", catalogueTree, sortTypeEnum); return recursionSortCatalogues(catalogueTree, sortTypeEnum); }
@Test public void sortAscTest() { SortTypeEnum sortTypeEnum = SortTypeEnum.ASC; List<Catalogue> catalogueTree = Lists.newArrayList(); Catalogue catalogue = new Catalogue(); catalogue.setId(1); catalogue.setCreateTime(LocalDateTime.of(2024, 4, 28, 19, 22, 0)); Catalogue catalogue11 = new Catalogue(); catalogue11.setId(2); catalogue11.setCreateTime(LocalDateTime.of(2024, 4, 28, 20, 22, 0)); Catalogue catalogue12 = new Catalogue(); catalogue12.setId(3); catalogue12.setCreateTime(LocalDateTime.of(2024, 4, 28, 21, 22, 0)); catalogue.setChildren(Lists.newArrayList(catalogue12, catalogue11)); Catalogue catalogue2 = new Catalogue(); catalogue2.setId(4); catalogue2.setCreateTime(LocalDateTime.of(2024, 4, 29, 19, 22, 0)); Catalogue catalogue21 = new Catalogue(); catalogue21.setId(7); catalogue21.setCreateTime(LocalDateTime.of(2024, 4, 29, 21, 22, 0)); Catalogue catalogue22 = new Catalogue(); catalogue22.setId(6); catalogue22.setCreateTime(LocalDateTime.of(2024, 4, 29, 20, 22, 0)); catalogue2.setChildren(Lists.newArrayList(catalogue21, catalogue22)); catalogueTree.add(catalogue2); catalogueTree.add(catalogue); /* input: -- 4 (2024-04-29 19:22:00) -- 7 (2024-04-29 21:22:00) -- 6 (2024-04-29 20:22:00) -- 1 (2024-04-28 19:22:00) -- 3 (2024-04-28 21:22:00) -- 2 (2024-04-28 20:22:00) output: -- 1 (2024-04-28 19:22:00) -- 2 (2024-04-28 20:22:00) -- 3 (2024-04-28 21:22:00) -- 4 (2024-04-29 19:22:00) -- 6 (2024-04-29 20:22:00) -- 7 (2024-04-29 21:22:00) */ List<Catalogue> resultList = catalogueTreeSortCreateTimeStrategyTest.sort(catalogueTree, sortTypeEnum); List<Integer> resultIdList = CategoryTreeSortStrategyTestUtils.breadthTraverse(resultList); assertEquals(Lists.newArrayList(1, 4, 2, 3, 6, 7), resultIdList); }
@Override public void resetLocal() { this.min = Double.POSITIVE_INFINITY; }
@Test void testResetLocal() { DoubleMinimum min = new DoubleMinimum(); double value = 13.57902468; min.add(value); assertThat(min.getLocalValue()).isCloseTo(value, within(0.0)); min.resetLocal(); assertThat(min.getLocalValue()).isCloseTo(Double.POSITIVE_INFINITY, within(0.0)); }
public static BackendExecutorContext getInstance() { return INSTANCE; }
@Test void assertGetInstance() { ContextManager contextManager = mockContextManager(); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); assertThat(BackendExecutorContext.getInstance().getExecutorEngine(), is(BackendExecutorContext.getInstance().getExecutorEngine())); }
@UdafFactory(description = "collect distinct values of a Bigint field into a single Array") public static <T> Udaf<T, List<T>, List<T>> createCollectSetT() { return new Collect<>(); }
@Test public void shouldCollectDistinctTimes() { final Udaf<Time, List<Time>, List<Time>> udaf = CollectSetUdaf.createCollectSetT(); final Time[] values = new Time[] {new Time(1), new Time(2)}; List<Time> runningList = udaf.initialize(); for (final Time i : values) { runningList = udaf.aggregate(i, runningList); } assertThat(runningList, contains(new Time(1), new Time(2))); }
public static BigDecimal cast(final Integer value, final int precision, final int scale) { if (value == null) { return null; } return cast(value.longValue(), precision, scale); }
@Test public void shouldCastDoubleRoundDown() { // When: final BigDecimal decimal = DecimalUtil.cast(1.11, 2, 1); // Then: assertThat(decimal, is(new BigDecimal("1.1"))); }
@Override public Object handle(ProceedingJoinPoint proceedingJoinPoint, RateLimiter rateLimiter, String methodName) throws Throwable { Object returnValue = proceedingJoinPoint.proceed(); if (Flux.class.isAssignableFrom(returnValue.getClass())) { Flux<?> fluxReturnValue = (Flux<?>) returnValue; return fluxReturnValue.transformDeferred(RateLimiterOperator.of(rateLimiter)); } else if (Mono.class.isAssignableFrom(returnValue.getClass())) { Mono<?> monoReturnValue = (Mono<?>) returnValue; return monoReturnValue.transformDeferred(RateLimiterOperator.of(rateLimiter)); } else { logger.error("Unsupported type for Reactor rateLimiter {}", returnValue.getClass().getTypeName()); throw new IllegalArgumentException( "Not Supported type for the rateLimiter in Reactor :" + returnValue.getClass() .getName()); } }
@Test public void testReactorTypes() throws Throwable { RateLimiter rateLimiter = RateLimiter.ofDefaults("test"); when(proceedingJoinPoint.proceed()).thenReturn(Mono.just("Test")); assertThat( reactorRateLimiterAspectExt.handle(proceedingJoinPoint, rateLimiter, "testMethod")) .isNotNull(); when(proceedingJoinPoint.proceed()).thenReturn(Flux.just("Test")); assertThat( reactorRateLimiterAspectExt.handle(proceedingJoinPoint, rateLimiter, "testMethod")) .isNotNull(); }
@Override public void onClose(final int i, final String s, final boolean b) { this.close(); }
@Test public void testOnClose() { shenyuWebsocketClient = spy(shenyuWebsocketClient); doNothing().when(shenyuWebsocketClient).close(); shenyuWebsocketClient.onClose(1, "shenyu-plugin-grpc", true); verify(shenyuWebsocketClient).close(); }
public Version(long version) { this.version = version; }
@Test public void testVersion() { Version version1 = new Version(1); Version version2 = new Version(1); assertTrue(version1.equals(version2)); assertTrue(version1.hashCode() == version2.hashCode()); assertTrue(version1.value() == version2.value()); Version version3 = new Version(2); assertFalse(version1.equals(version3)); assertFalse(version1.hashCode() == version3.hashCode()); assertFalse(version1.value() == version3.value()); }
public String prometheusName(String recordName, String metricName) { String baseName = StringUtils.capitalize(recordName) + StringUtils.capitalize(metricName); String[] parts = SPLIT_PATTERN.split(baseName); String joined = String.join("_", parts).toLowerCase(); return DELIMITERS.matcher(joined).replaceAll("_"); }
@Test public void testNamingWhitespaces() { PrometheusMetricsSink sink = new PrometheusMetricsSink(); String recordName = "JvmMetrics"; String metricName = "GcCount" + "G1 Old Generation"; Assert.assertEquals( "jvm_metrics_gc_count_g1_old_generation", sink.prometheusName(recordName, metricName)); }
public static String sha3_224Hex(String input) { SHA3.DigestSHA3 sha3Digest = new SHA3.Digest224(); byte[] hashBytes = sha3Digest.digest(input.getBytes(StandardCharsets.UTF_8)); return Hex.toHexString(hashBytes); }
@Test void whenCalledOnTheSameInput_sha3_224Hex_returnsTheSameValueAsDigestUtils() { String input = "String to be hashed"; //Apache Commons DigestUtils digest for the string "String to be hashed" String apacheCommonsDigest = "57ead8c5fc5c15ed7bde0550648d06a6aed3cba443ed100a6f5e64f3"; assertEquals(apacheCommonsDigest, DigestUtil.sha3_224Hex(input)); }
public final void isAtMost(int other) { isAtMost((double) other); }
@Test public void isAtMost_int() { expectFailureWhenTestingThat(2.0).isAtMost(1); assertThat(2.0).isAtMost(2); assertThat(2.0).isAtMost(3); }
public HikariDataSource getDataSource() { return ds; }
@Test @Ignore public void testGetSqlServerDataSource() { DataSource ds = SingletonServiceFactory.getBean(SqlServerDataSource.class).getDataSource(); assertNotNull(ds); try(Connection connection = ds.getConnection()){ assertNotNull(connection); } catch (SQLException e) { e.printStackTrace(); } }
public static <T> ZstdCoder<T> of(Coder<T> innerCoder, byte[] dict, int level) { return new ZstdCoder<>(innerCoder, dict, level); }
@Test public void testCoderEquals() throws Exception { // True if coder, dict and level are equal. assertEquals( ZstdCoder.of(ListCoder.of(StringUtf8Coder.of()), null, 0), ZstdCoder.of(ListCoder.of(StringUtf8Coder.of()), null, 0)); assertEquals( ZstdCoder.of(ListCoder.of(ByteArrayCoder.of()), new byte[0], 1), ZstdCoder.of(ListCoder.of(ByteArrayCoder.of()), new byte[0], 1)); // False if coder, dict or level differs. assertNotEquals( ZstdCoder.of(ListCoder.of(StringUtf8Coder.of()), null, 0), ZstdCoder.of(ListCoder.of(ByteArrayCoder.of()), null, 0)); assertNotEquals( ZstdCoder.of(ListCoder.of(StringUtf8Coder.of()), null, 0), ZstdCoder.of(ListCoder.of(StringUtf8Coder.of()), new byte[0], 0)); assertNotEquals( ZstdCoder.of(ListCoder.of(StringUtf8Coder.of()), null, 0), ZstdCoder.of(ListCoder.of(StringUtf8Coder.of()), null, 1)); assertNotEquals( ZstdCoder.of(ListCoder.of(StringUtf8Coder.of()), null, 0), ZstdCoder.of(ListCoder.of(ByteArrayCoder.of()), new byte[0], 1)); }
public static void addTopologyDescriptionMetric(final StreamsMetricsImpl streamsMetrics, final Gauge<String> topologyDescription) { streamsMetrics.addClientLevelMutableMetric( TOPOLOGY_DESCRIPTION, TOPOLOGY_DESCRIPTION_DESCRIPTION, RecordingLevel.INFO, topologyDescription ); }
@Test public void shouldAddTopologyDescriptionMetric() { final String name = "topology-description"; final String description = "The description of the topology executed in the Kafka Streams client"; final String topologyDescription = "thisIsATopologyDescription"; final Gauge<String> topologyDescriptionProvider = (c, n) -> topologyDescription; setUpAndVerifyMutableMetric( name, description, topologyDescriptionProvider, () -> ClientMetrics.addTopologyDescriptionMetric(streamsMetrics, topologyDescriptionProvider) ); }
public static int[] computePhysicalIndices( List<TableColumn> logicalColumns, DataType physicalType, Function<String, String> nameRemapping) { Map<TableColumn, Integer> physicalIndexLookup = computePhysicalIndices(logicalColumns.stream(), physicalType, nameRemapping); return logicalColumns.stream().mapToInt(physicalIndexLookup::get).toArray(); }
@Test void testFieldMappingRowTypeNotMatchingNamesInNestedType() { int[] indices = TypeMappingUtils.computePhysicalIndices( TableSchema.builder() .field("f0", DECIMAL(38, 18)) .field( "f1", ROW( FIELD("logical_f1_0", BIGINT()), FIELD("logical_f1_1", STRING()))) .build() .getTableColumns(), ROW( FIELD("f0", DECIMAL(38, 18)), FIELD( "f1", ROW( FIELD("physical_f1_0", BIGINT()), FIELD("physical_f1_1", STRING())))), Function.identity()); assertThat(indices).isEqualTo(new int[] {0, 1}); }
public abstract Task<Map<K, Try<T>>> taskForBatch(G group, Set<K> keys);
@Test public void testEntriesMissingInReturnedMap() { RecordingTaskStrategy<Integer, Integer, String> strategy = new RecordingTaskStrategy<Integer, Integer, String>(key -> Success.of(String.valueOf(key)), key -> key % 2) { @Override public Task<Map<Integer, Try<String>>> taskForBatch(Integer group, Set<Integer> keys) { return super.taskForBatch(group, keys).andThen(map -> map.remove(1)); } }; _batchingSupport.registerStrategy(strategy); Task<String> task = Task.par(strategy.batchable(0), strategy.batchable(1).recover(e -> "missing"), strategy.batchable(2)) .map("concat", (s0, s1, s2) -> s0 + s1 + s2); String result = runAndWait("TestTaskBatchingStrategy.testEntriesMissingInReturnedMap", task); assertEquals(result, "0missing2"); assertTrue(strategy.getClassifiedKeys().contains(0)); assertTrue(strategy.getClassifiedKeys().contains(1)); assertTrue(strategy.getClassifiedKeys().contains(2)); assertEquals(strategy.getExecutedBatches().size(), 1); assertEquals(strategy.getExecutedSingletons().size(), 1); }
static Set<PipelineOptionSpec> getOptionSpecs( Class<? extends PipelineOptions> optionsInterface, boolean skipHidden) { Iterable<Method> methods = ReflectHelpers.getClosureOfMethodsOnInterface(optionsInterface); Multimap<String, Method> propsToGetters = getPropertyNamesToGetters(methods); ImmutableSet.Builder<PipelineOptionSpec> setBuilder = ImmutableSet.builder(); for (Map.Entry<String, Method> propAndGetter : propsToGetters.entries()) { String prop = propAndGetter.getKey(); Method getter = propAndGetter.getValue(); @SuppressWarnings("unchecked") Class<? extends PipelineOptions> declaringClass = (Class<? extends PipelineOptions>) getter.getDeclaringClass(); if (!PipelineOptions.class.isAssignableFrom(declaringClass)) { continue; } if (skipHidden && declaringClass.isAnnotationPresent(Hidden.class)) { continue; } setBuilder.add(PipelineOptionSpec.of(declaringClass, prop, getter)); } return setBuilder.build(); }
@Test public void testExcludesNonPipelineOptionsMethods() { Set<PipelineOptionSpec> properties = PipelineOptionsReflector.getOptionSpecs(ExtendsNonPipelineOptions.class, true); assertThat(properties, not(hasItem(hasName("foo")))); }
@Override public void callback(CallbackContext context) { try { onCallback(context); } catch (IOException | ExecutionException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException(e); } }
@Test public void callback_whenOrganizationsAreNotDefinedAndUserBelongsToInstallationOrganization_shouldAuthenticateAndRedirect() throws IOException, ExecutionException, InterruptedException { UserIdentity userIdentity = mock(UserIdentity.class); CallbackContext context = mockUserBelongingToOrganization(userIdentity); mockInstallations(); underTest.callback(context); verify(context).authenticate(userIdentity); verify(context).redirectToRequestedPage(); }
public List<ChangeStreamRecord> toChangeStreamRecords( PartitionMetadata partition, ChangeStreamResultSet resultSet, ChangeStreamResultSetMetadata resultSetMetadata) { if (this.isPostgres()) { // In PostgresQL, change stream records are returned as JsonB. return Collections.singletonList( toChangeStreamRecordJson(partition, resultSet.getPgJsonb(0), resultSetMetadata)); } // In GoogleSQL, change stream records are returned as an array of structs. return resultSet.getCurrentRowAsStruct().getStructList(0).stream() .flatMap(struct -> toChangeStreamRecord(partition, struct, resultSetMetadata)) .collect(Collectors.toList()); }
@Test public void testMappingDeleteStructRowToDataChangeRecord() { final DataChangeRecord dataChangeRecord = new DataChangeRecord( "partitionToken", Timestamp.ofTimeSecondsAndNanos(10L, 20), "transactionId", false, "1", "tableName", Arrays.asList( new ColumnType("column1", new TypeCode("{\"code\":\"INT64\"}"), true, 1L), new ColumnType("column2", new TypeCode("{\"code\":\"BYTES\"}"), false, 2L)), Collections.singletonList( new Mod("{\"column1\":\"value1\"}", "{\"column2\":\"oldValue2\"}", null)), ModType.DELETE, ValueCaptureType.OLD_AND_NEW_VALUES, 10L, 2L, "transactionTag", true, null); final Struct jsonFieldsStruct = recordsToStructWithJson(dataChangeRecord); ChangeStreamResultSet resultSet = mock(ChangeStreamResultSet.class); when(resultSet.getCurrentRowAsStruct()).thenReturn(jsonFieldsStruct); assertEquals( Collections.singletonList(dataChangeRecord), mapper.toChangeStreamRecords(partition, resultSet, resultSetMetadata)); }
@Override public void handlerPlugin(final PluginData pluginData) { if (Objects.nonNull(pluginData) && Boolean.TRUE.equals(pluginData.getEnabled())) { MotanRegisterConfig motanRegisterConfig = GsonUtils.getInstance().fromJson(pluginData.getConfig(), MotanRegisterConfig.class); MotanRegisterConfig exist = Singleton.INST.get(MotanRegisterConfig.class); if (Objects.isNull(motanRegisterConfig)) { return; } if (Objects.isNull(exist) || !motanRegisterConfig.equals(exist)) { // If it is null, initialize it ApplicationConfigCache.getInstance().init(motanRegisterConfig); ApplicationConfigCache.getInstance().invalidateAll(); } Singleton.INST.single(MotanRegisterConfig.class, motanRegisterConfig); } }
@Test public void testHandlerPlugin() { pluginData.setEnabled(true); pluginData.setConfig("{\"registerAddress\" : \"127.0.0.1:2181\"}"); motanPluginDataHandler.handlerPlugin(pluginData); Assertions.assertEquals(Singleton.INST.get(MotanRegisterConfig.class).getRegisterAddress(), "127.0.0.1:2181"); }
private AlarmId(DeviceId id, String uniqueIdentifier) { super(id.toString() + ":" + uniqueIdentifier); checkNotNull(id, "device id must not be null"); checkNotNull(uniqueIdentifier, "unique identifier must not be null"); checkArgument(!uniqueIdentifier.isEmpty(), "unique identifier must not be empty"); }
@Test public void testConstruction() { final AlarmId id1 = AlarmId.alarmId(DEVICE_ID, UNIQUE_ID_3); assertEquals(id1.toString(), ID_Z.toString()); final AlarmId idString = AlarmId.alarmId(ID_STRING); assertEquals(id1, idString); }
@Override public DeleteConsumerGroupsResult deleteConsumerGroups(Collection<String> groupIds, DeleteConsumerGroupsOptions options) { SimpleAdminApiFuture<CoordinatorKey, Void> future = DeleteConsumerGroupsHandler.newFuture(groupIds); DeleteConsumerGroupsHandler handler = new DeleteConsumerGroupsHandler(logContext); invokeDriver(handler, future, options.timeoutMs); return new DeleteConsumerGroupsResult(future.all().entrySet().stream() .collect(Collectors.toMap(entry -> entry.getKey().idValue, Map.Entry::getValue))); }
@Test public void testDeleteConsumerGroupsNumRetries() throws Exception { final Cluster cluster = mockCluster(3, 0); final Time time = new MockTime(); final List<String> groupIds = singletonList("groupId"); try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(time, cluster, AdminClientConfig.RETRIES_CONFIG, "0")) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); env.kafkaClient().prepareResponse(prepareFindCoordinatorResponse(Errors.NONE, env.cluster().controller())); final DeletableGroupResultCollection validResponse = new DeletableGroupResultCollection(); validResponse.add(new DeletableGroupResult() .setGroupId("groupId") .setErrorCode(Errors.NOT_COORDINATOR.code())); env.kafkaClient().prepareResponse(new DeleteGroupsResponse( new DeleteGroupsResponseData() .setResults(validResponse) )); env.kafkaClient().prepareResponse(prepareFindCoordinatorResponse(Errors.NONE, env.cluster().controller())); final DeleteConsumerGroupsResult result = env.adminClient().deleteConsumerGroups(groupIds); TestUtils.assertFutureError(result.all(), TimeoutException.class); } }
protected boolean databaseForBothDbInterfacesIsTheSame( DatabaseInterface primary, DatabaseInterface secondary ) { if ( primary == null || secondary == null ) { throw new IllegalArgumentException( "DatabaseInterface shouldn't be null!" ); } if ( primary.getPluginId() == null || secondary.getPluginId() == null ) { return false; } if ( primary.getPluginId().equals( secondary.getPluginId() ) ) { return true; } return primary.getClass().isAssignableFrom( secondary.getClass() ); }
@Test public void databases_WithSameDbConnTypes_AreTheSame() { DatabaseInterface mssqlServerDatabaseMeta = new MSSQLServerDatabaseMeta(); mssqlServerDatabaseMeta.setPluginId( "MSSQL" ); assertTrue( databaseMeta.databaseForBothDbInterfacesIsTheSame( mssqlServerDatabaseMeta, mssqlServerDatabaseMeta ) ); }
@Override public StringBuffer format( Date timestamp, StringBuffer toAppendTo, FieldPosition pos ) { if ( compatibleToSuperPattern ) { return super.format( timestamp, toAppendTo, pos ); } SimpleDateFormat defaultMillisecondDateFormat = new SimpleDateFormat( DEFAULT_MILLISECOND_DATE_FORMAT, Locale.US ); StringBuffer dateBuffer; String nan; if ( timestamp instanceof Timestamp ) { Timestamp tmp = (Timestamp) timestamp; Date date = new Date( tmp.getTime() ); dateBuffer = super.format( date, toAppendTo, pos ); nan = formatNanoseconds( tmp.getNanos() ); } else { dateBuffer = super.format( timestamp, toAppendTo, pos ); String milliseconds = defaultMillisecondDateFormat.format( timestamp ); nan = formatNanoseconds( Integer.valueOf( milliseconds ) * Math.pow( 10, 6 ) ); } int placeholderPosition = replaceHolder( dateBuffer, false ); return dateBuffer.insert( pos.getBeginIndex() + placeholderPosition, nan ); }
@Test public void testFormat() { for ( Locale locale : locales ) { Locale.setDefault( Locale.Category.FORMAT, locale ); tdb = ResourceBundle.getBundle( "org/pentaho/di/core/row/value/timestamp/messages/testdates", locale ); checkFormat( "KETTLE.LONG" ); checkFormat( "LOCALE.DATE", new SimpleTimestampFormat( new SimpleDateFormat().toPattern() ) ); //checkFormat( "LOCALE.TIMESTAMP", new SimpleTimestampFormat( new SimpleDateFormat().toPattern() ) ); checkFormat( "KETTLE" ); checkFormat( "DB.DEFAULT" ); checkFormat( "LOCALE.DEFAULT" ); } }
@Override public Object convert(String value) { if (isNullOrEmpty(value)) { return value; } if (value.contains("=")) { final Map<String, String> fields = new HashMap<>(); Matcher m = PATTERN.matcher(value); while (m.find()) { if (m.groupCount() != 2) { continue; } fields.put(removeQuotes(m.group(1)), removeQuotes(m.group(2))); } return fields; } else { return Collections.emptyMap(); } }
@Test public void testFilterWithKeysIncludingDashOrUnderscore() { TokenizerConverter f = new TokenizerConverter(new HashMap<String, Object>()); @SuppressWarnings("unchecked") Map<String, String> result = (Map<String, String>) f.convert("otters in k-1=v1 k_2=v2 _k3=v3 more otters"); assertThat(result) .hasSize(3) .containsEntry("k-1", "v1") .containsEntry("k_2", "v2") .containsEntry("_k3", "v3"); }
public void draw(List<? extends Pair<Integer, Integer>> coordinateList) { LOGGER.info("Start drawing next frame"); LOGGER.info("Current buffer: " + current + " Next buffer: " + next); frameBuffers[next].clearAll(); coordinateList.forEach(coordinate -> { var x = coordinate.getKey(); var y = coordinate.getValue(); frameBuffers[next].draw(x, y); }); LOGGER.info("Swap current and next buffer"); swap(); LOGGER.info("Finish swapping"); LOGGER.info("Current buffer: " + current + " Next buffer: " + next); }
@Test void testDraw() { try { var scene = new Scene(); var field1 = Scene.class.getDeclaredField("current"); var field2 = Scene.class.getDeclaredField("next"); field1.setAccessible(true); field1.set(scene, 0); field2.setAccessible(true); field2.set(scene, 1); scene.draw(new ArrayList<>()); assertEquals(1, field1.get(scene)); assertEquals(0, field2.get(scene)); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Fail to access private field"); } }
@Override public void deleteState(String key) { ensureStateEnabled(); defaultStateStore.delete(key); }
@Test(expectedExceptions = IllegalStateException.class) public void testDeleteStateStateDisabled() { context.deleteState("test-key"); }
@Override public String operation() { return "send"; }
@Test void operation() { assertThat(request.operation()).isEqualTo("send"); }
public boolean doesPluginSupportPasswordBasedAuthentication(String pluginId) { if (!pluginInfos.containsKey(pluginId)) { return false; } return pluginInfos.get(pluginId).getCapabilities().getSupportedAuthType() == SupportedAuthType.Password; }
@Test public void shouldBeAbleToAnswerIfPluginSupportsPasswordBasedAuthentication() throws Exception { assertTrue(store.doesPluginSupportPasswordBasedAuthentication("password.plugin-2")); assertFalse(store.doesPluginSupportPasswordBasedAuthentication("web.plugin-1")); }
public Collection<EvaluatedCondition> getEvaluatedConditions() { return evaluatedConditions; }
@Test public void getEvaluatedConditions_returns_empty_with_no_condition_added_to_builder() { assertThat(builder.getEvaluatedConditions()).isEmpty(); }
public static boolean needOpenTransaction(final SQLStatement sqlStatement) { if (sqlStatement instanceof SelectStatement && !((SelectStatement) sqlStatement).getFrom().isPresent()) { return false; } return sqlStatement instanceof DDLStatement || sqlStatement instanceof DMLStatement; }
@Test void assertNeedOpenTransactionForDDLOrDMLStatement() { assertTrue(AutoCommitUtils.needOpenTransaction(new MySQLCreateTableStatement(true))); assertTrue(AutoCommitUtils.needOpenTransaction(new MySQLInsertStatement())); }
public void submit(E item) throws ConcurrentConveyorException { submit(queue, item); }
@Test public void when_submit_then_poll() { // when conveyorSingleQueue.submit(item2); // then assertSame(item2, defaultQ.poll()); }
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void createNewWebmStickerSetAndAddSticker() { String setName = "test" + System.currentTimeMillis() + "_by_pengrad_test_bot"; String[] emojis = new String[]{"\uD83D\uDE00"}; InputSticker[] stickers = new InputSticker[]{new InputSticker(stickerFileVid, Sticker.Format.video, emojis)}; BaseResponse response = bot.execute( new CreateNewStickerSet(chatId, setName, "test1", stickers) .stickerType(Sticker.Type.regular) ); assertTrue(response.isOk()); }
@Override public RFuture<Boolean> tryLockAsync(long threadId) { RFuture<Long> longRFuture = tryAcquireAsync(-1, null, threadId); CompletionStage<Boolean> f = longRFuture.thenApply(res -> res == null); return new CompletableFutureWrapper<>(f); }
@Test public void testTryLockAsyncSucceed() throws InterruptedException, ExecutionException { RLock lock = redisson.getSpinLock("lock"); Boolean result = lock.tryLockAsync().get(); assertThat(result).isTrue(); lock.unlock(); }
@VisibleForTesting CompleteMultipartUploadResult multipartCopy( S3ResourceId sourcePath, S3ResourceId destinationPath, ObjectMetadata sourceObjectMetadata) throws AmazonClientException { InitiateMultipartUploadRequest initiateUploadRequest = new InitiateMultipartUploadRequest(destinationPath.getBucket(), destinationPath.getKey()) .withStorageClass(config.getS3StorageClass()) .withObjectMetadata(sourceObjectMetadata) .withSSECustomerKey(config.getSSECustomerKey()); InitiateMultipartUploadResult initiateUploadResult = amazonS3.get().initiateMultipartUpload(initiateUploadRequest); final String uploadId = initiateUploadResult.getUploadId(); List<PartETag> eTags = new ArrayList<>(); final long objectSize = sourceObjectMetadata.getContentLength(); // extra validation in case a caller calls directly S3FileSystem.multipartCopy // without using S3FileSystem.copy in the future if (objectSize == 0) { final CopyPartRequest copyPartRequest = new CopyPartRequest() .withSourceBucketName(sourcePath.getBucket()) .withSourceKey(sourcePath.getKey()) .withDestinationBucketName(destinationPath.getBucket()) .withDestinationKey(destinationPath.getKey()) .withUploadId(uploadId) .withPartNumber(1); copyPartRequest.setSourceSSECustomerKey(config.getSSECustomerKey()); copyPartRequest.setDestinationSSECustomerKey(config.getSSECustomerKey()); CopyPartResult copyPartResult = amazonS3.get().copyPart(copyPartRequest); eTags.add(copyPartResult.getPartETag()); } else { long bytePosition = 0; // Amazon parts are 1-indexed, not zero-indexed. for (int partNumber = 1; bytePosition < objectSize; partNumber++) { final CopyPartRequest copyPartRequest = new CopyPartRequest() .withSourceBucketName(sourcePath.getBucket()) .withSourceKey(sourcePath.getKey()) .withDestinationBucketName(destinationPath.getBucket()) .withDestinationKey(destinationPath.getKey()) .withUploadId(uploadId) .withPartNumber(partNumber) .withFirstByte(bytePosition) .withLastByte( Math.min(objectSize - 1, bytePosition + MAX_COPY_OBJECT_SIZE_BYTES - 1)); copyPartRequest.setSourceSSECustomerKey(config.getSSECustomerKey()); copyPartRequest.setDestinationSSECustomerKey(config.getSSECustomerKey()); CopyPartResult copyPartResult = amazonS3.get().copyPart(copyPartRequest); eTags.add(copyPartResult.getPartETag()); bytePosition += MAX_COPY_OBJECT_SIZE_BYTES; } } CompleteMultipartUploadRequest completeUploadRequest = new CompleteMultipartUploadRequest() .withBucketName(destinationPath.getBucket()) .withKey(destinationPath.getKey()) .withUploadId(uploadId) .withPartETags(eTags); return amazonS3.get().completeMultipartUpload(completeUploadRequest); }
@Test public void testMultipartCopy() { testMultipartCopy(s3Config("s3")); testMultipartCopy(s3Config("other")); testMultipartCopy(s3ConfigWithSSECustomerKey("s3")); testMultipartCopy(s3ConfigWithSSECustomerKey("other")); }
public Invoker<?> getInvoker() { return invoker; }
@Test void testListenUnExport() throws NoSuchFieldException, IllegalAccessException { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.addParameter(SCOPE_KEY, "local"); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter<?> exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl)); Invoker<DemoService> cluster = getClusterInvoker(url); invokers.add(cluster); exporter.unexport(); Assertions.assertTrue(cluster instanceof ScopeClusterInvoker); Field injvmInvoker = cluster.getClass().getDeclaredField("injvmInvoker"); injvmInvoker.setAccessible(true); Assertions.assertNull(injvmInvoker.get(cluster)); Field isExported = cluster.getClass().getDeclaredField("isExported"); isExported.setAccessible(true); Assertions.assertFalse(((AtomicBoolean) isExported.get(cluster)).get()); }
@Override public boolean isAutoTrackEventTypeIgnored(SensorsDataAPI.AutoTrackEventType eventType) { return true; }
@Test public void isAutoTrackEventTypeIgnored() { Assert.assertTrue(mSensorsAPI.isAutoTrackEventTypeIgnored(SensorsDataAPI.AutoTrackEventType.APP_CLICK)); }
public static <T extends Comparable<? super T>> T min(T[] numberArray) { return min(numberArray, null); }
@Test public void minTest() { int min = ArrayUtil.min(1, 2, 13, 4, 5); assertEquals(1, min); long minLong = ArrayUtil.min(1L, 2L, 13L, 4L, 5L); assertEquals(1, minLong); double minDouble = ArrayUtil.min(1D, 2.4D, 13.0D, 4.55D, 5D); assertEquals(1.0, minDouble, 0); }
@Override public ExactlyOnceSupport exactlyOnceSupport(Map<String, String> props) { AbstractConfig parsedConfig = new AbstractConfig(CONFIG_DEF, props); String filename = parsedConfig.getString(FILE_CONFIG); // We can provide exactly-once semantics if reading from a "real" file // (as long as the file is only appended to over the lifetime of the connector) // If we're reading from stdin, we can't provide exactly-once semantics // since we don't even track offsets return filename != null && !filename.isEmpty() ? ExactlyOnceSupport.SUPPORTED : ExactlyOnceSupport.UNSUPPORTED; }
@Test public void testExactlyOnceSupport() { sourceProperties.put(FileStreamSourceConnector.FILE_CONFIG, FILENAME); assertEquals(ExactlyOnceSupport.SUPPORTED, connector.exactlyOnceSupport(sourceProperties)); sourceProperties.put(FileStreamSourceConnector.FILE_CONFIG, " "); assertEquals(ExactlyOnceSupport.UNSUPPORTED, connector.exactlyOnceSupport(sourceProperties)); sourceProperties.remove(FileStreamSourceConnector.FILE_CONFIG); assertEquals(ExactlyOnceSupport.UNSUPPORTED, connector.exactlyOnceSupport(sourceProperties)); }
public static <T> Collection<T> newServiceInstances(final Class<T> service) { return SERVICES.containsKey(service) ? newServiceInstancesFromCache(service) : Collections.<T>emptyList(); }
@Test void newServiceInstances() { SpiTestInterface loadInstance = NacosServiceLoader.load(SpiTestInterface.class).iterator().next(); Collection<SpiTestInterface> actual = NacosServiceLoader.newServiceInstances(SpiTestInterface.class); assertEquals(1, actual.size()); assertEquals(SpiTestImpl.class, actual.iterator().next().getClass()); assertNotEquals(loadInstance, actual.iterator().next()); }
public static String removeCR( String in ) { return removeChar( in, '\r' ); }
@Test public void testRemoveCR() { assertEquals( "foo\n\tbar", Const.removeCR( "foo\r\n\tbar" ) ); assertEquals( "", Const.removeCR( "" ) ); assertEquals( "", Const.removeCR( null ) ); assertEquals( "", Const.removeCR( "\r" ) ); assertEquals( "\n\n", Const.removeCR( "\n\r\n" ) ); assertEquals( "This \nis a \ntest of \nthe \nemergency broadcast \nsystem\n", Const.removeCR( "This \r\nis \ra \ntest \rof \n\rthe \r\nemergency \rbroadcast \nsystem\r\n" ) ); }
public DrlxParseResult drlxParse(Class<?> patternType, String bindingId, String expression) { return drlxParse(patternType, bindingId, expression, false); }
@Test public void testMultiplyStringIntWithBindVariableCompareToBigDecimal() { SingleDrlxParseSuccess result = (SingleDrlxParseSuccess) parser.drlxParse(Person.class, "$p", "money == likes * 10"); // assuming likes contains number String assertThat(result.getExpr().toString()).isEqualTo(EvaluationUtil.class.getCanonicalName() + ".equals(" + EvaluationUtil.class.getCanonicalName() + ".toBigDecimal(_this.getMoney()), " + EvaluationUtil.class.getCanonicalName() + ".toBigDecimal(Double.valueOf(_this.getLikes()) * 10))"); }
@Override public Object getValue() { try { return mBeanServerConn.getAttribute(getObjectName(), attributeName); } catch (IOException | JMException e) { return null; } }
@Test public void returnsNullIfAttributeDoesNotExist() throws Exception { ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "DoesNotExist"); assertThat(gauge.getValue()).isNull(); }
@Override public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) { final QueryContext.Stacker contextStacker = buildContext.buildNodeContext(getId().toString()); final SchemaKStream<?> schemaKStream = getSource().buildStream(buildContext); if (!(schemaKStream instanceof SchemaKTable)) { throw new KsqlException("Failed in suppress node. Expected to find a Table, but " + "found a stream instead."); } return (((SchemaKTable<?>) schemaKStream) .suppress( refinementInfo, valueFormat.getFormatInfo(), contextStacker )); }
@Test @SuppressWarnings("unchecked") public void shouldSuppressOnSchemaKTable() { // Given: when(sourceNode.buildStream(any())).thenReturn(schemaKTable); when(sourceNode.getNodeOutputType()).thenReturn(DataSourceType.KTABLE); node = new SuppressNode(NODE_ID, sourceNode, refinementInfo); // When: node.buildStream(planBuildContext); // Then verify(schemaKTable).suppress(refinementInfo, valueFormat.getFormatInfo(), stacker); }
@Override public Reader getCharacterStream(final int columnIndex) throws SQLException { return mergedResult.getCharacterStream(columnIndex); }
@Test void assertGetCharacterStream() throws SQLException { Reader reader = mock(Reader.class); when(mergedResult.getCharacterStream(1)).thenReturn(reader); assertThat(new EncryptMergedResult(database, encryptRule, selectStatementContext, mergedResult).getCharacterStream(1), is(reader)); }
@Override public void publish(ScannerReportWriter writer) { AbstractProjectOrModule rootProject = moduleHierarchy.root(); ScannerReport.Metadata.Builder builder = ScannerReport.Metadata.newBuilder() .setAnalysisDate(projectInfo.getAnalysisDate().getTime()) // Here we want key without branch .setProjectKey(rootProject.key()) .setCrossProjectDuplicationActivated(cpdSettings.isCrossProjectDuplicationEnabled()) .setRootComponentRef(rootProject.scannerId()); projectInfo.getProjectVersion().ifPresent(builder::setProjectVersion); projectInfo.getBuildString().ifPresent(builder::setBuildString); if (branchConfiguration.branchName() != null) { addBranchInformation(builder); } String newCodeReferenceBranch = referenceBranchSupplier.getFromProperties(); if (newCodeReferenceBranch != null) { builder.setNewCodeReferenceBranch(newCodeReferenceBranch); } addScmInformation(builder); addNotAnalyzedFileCountsByLanguage(builder); for (QProfile qp : qProfiles.findAll()) { builder.putQprofilesPerLanguage(qp.getLanguage(), ScannerReport.Metadata.QProfile.newBuilder() .setKey(qp.getKey()) .setLanguage(qp.getLanguage()) .setName(qp.getName()) .setRulesUpdatedAt(qp.getRulesUpdatedAt().getTime()).build()); } for (Entry<String, ScannerPlugin> pluginEntry : pluginRepository.getPluginsByKey().entrySet()) { builder.putPluginsByKey(pluginEntry.getKey(), ScannerReport.Metadata.Plugin.newBuilder() .setKey(pluginEntry.getKey()) .setUpdatedAt(pluginEntry.getValue().getUpdatedAt()).build()); } addRelativePathFromScmRoot(builder); writer.writeMetadata(builder.build()); }
@Test @UseDataProvider("projectVersions") public void write_project_version(@Nullable String projectVersion, String expected) { when(projectInfo.getProjectVersion()).thenReturn(Optional.ofNullable(projectVersion)); underTest.publish(writer); ScannerReport.Metadata metadata = reader.readMetadata(); assertThat(metadata.getProjectVersion()).isEqualTo(expected); }
@Override public CompletableFuture<Acknowledge> disconnectTaskManager( final ResourceID resourceID, final Exception cause) { taskManagerHeartbeatManager.unmonitorTarget(resourceID); slotPoolService.releaseTaskManager(resourceID, cause); partitionTracker.stopTrackingPartitionsFor(resourceID); TaskManagerRegistration taskManagerRegistration = registeredTaskManagers.remove(resourceID); if (taskManagerRegistration != null) { log.info( "Disconnect TaskExecutor {} because: {}", resourceID.getStringWithMetadata(), cause.getMessage(), ExceptionUtils.returnExceptionIfUnexpected(cause.getCause())); ExceptionUtils.logExceptionIfExcepted(cause.getCause(), log); taskManagerRegistration .getTaskExecutorGateway() .disconnectJobManager(jobGraph.getJobID(), cause); } return CompletableFuture.completedFuture(Acknowledge.get()); }
@Test void testJobFailureWhenGracefulTaskExecutorTermination() throws Exception { runJobFailureWhenTaskExecutorTerminatesTest( heartbeatServices, (localTaskManagerLocation, jobMasterGateway) -> jobMasterGateway.disconnectTaskManager( localTaskManagerLocation.getResourceID(), new FlinkException("Test disconnectTaskManager exception."))); }
public static <K, V> Reshuffle<K, V> of() { return new Reshuffle<>(); }
@Test @Category(ValidatesRunner.class) public void testReshufflePreservesMetadata() { PCollection<KV<String, ValueInSingleWindow<String>>> input = pipeline .apply( Create.windowedValues( WindowedValue.of( "foo", BoundedWindow.TIMESTAMP_MIN_VALUE, GlobalWindow.INSTANCE, PaneInfo.NO_FIRING), WindowedValue.of( "foo", new Instant(0), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING), WindowedValue.of( "bar", new Instant(33), GlobalWindow.INSTANCE, PaneInfo.createPane(false, false, PaneInfo.Timing.LATE, 1, 1)), WindowedValue.of( "bar", GlobalWindow.INSTANCE.maxTimestamp(), GlobalWindow.INSTANCE, PaneInfo.NO_FIRING)) .withCoder(StringUtf8Coder.of()) .withWindowCoder(GlobalWindow.Coder.INSTANCE)) .apply(WithKeys.<String, String>of(v -> v).withKeyType(TypeDescriptors.strings())) .apply("ReifyOriginalMetadata", Reify.windowsInValue()); // The outer WindowedValue is the reified metadata post-reshuffle. The inner // WindowedValue is the pre-reshuffle metadata. PCollection<ValueInSingleWindow<ValueInSingleWindow<String>>> output = input .apply(Reshuffle.of()) .apply("ReifyReshuffledMetadata", Reify.windowsInValue()) .apply(Values.create()); PAssert.that(output) .satisfies( input1 -> { for (ValueInSingleWindow<ValueInSingleWindow<String>> elem : input1) { Instant originalTimestamp = elem.getValue().getTimestamp(); Instant afterReshuffleTimestamp = elem.getTimestamp(); assertThat( "Reshuffle did not preserve element timestamp for " + elem, afterReshuffleTimestamp, equalTo(originalTimestamp)); PaneInfo originalPaneInfo = elem.getValue().getPane(); PaneInfo afterReshufflePaneInfo = elem.getPane(); assertThat( "Reshuffle did not preserve pane info for " + elem, afterReshufflePaneInfo, equalTo(originalPaneInfo)); BoundedWindow originalWindow = elem.getValue().getWindow(); BoundedWindow afterReshuffleWindow = elem.getWindow(); assertThat( "Reshuffle did not preserve window for " + elem, afterReshuffleWindow, equalTo(originalWindow)); } return null; }); pipeline.run(); }
@Override public void updatePort(K8sPort port) { checkNotNull(port, ERR_NULL_PORT); checkArgument(!Strings.isNullOrEmpty(port.portId()), ERR_NULL_PORT_ID); checkArgument(!Strings.isNullOrEmpty(port.networkId()), ERR_NULL_PORT_NET_ID); k8sNetworkStore.updatePort(port); log.info(String.format(MSG_PORT, port.portId(), MSG_UPDATED)); }
@Test(expected = IllegalArgumentException.class) public void testUpdateUnregisteredPort() { target.updatePort(PORT); }
public void init(String keyId, String applicationKey, String exportService) throws BackblazeCredentialsException, IOException { // Fetch all the available buckets and use that to find which region the user is in ListBucketsResponse listBucketsResponse = null; String userRegion = null; // The Key ID starts with the region identifier number, so reorder the regions such that // the first region is most likely the user's region String regionId = keyId.substring(0, 3); BACKBLAZE_REGIONS.sort( (String region1, String region2) -> { if (region1.endsWith(regionId)) { return -1; } return 0; }); Throwable s3Exception = null; for (String region : BACKBLAZE_REGIONS) { try { s3Client = backblazeS3ClientFactory.createS3Client(keyId, applicationKey, region); listBucketsResponse = s3Client.listBuckets(); userRegion = region; break; } catch (S3Exception e) { s3Exception = e; if (s3Client != null) { s3Client.close(); } if (e.statusCode() == 403) { monitor.debug(() -> String.format("User is not in region %s", region)); } } } if (listBucketsResponse == null || userRegion == null) { throw new BackblazeCredentialsException( "User's credentials or permissions are not valid for any regions available", s3Exception); } bucketName = getOrCreateBucket(s3Client, listBucketsResponse, userRegion, exportService); }
@Test public void testInitBucketNameExists() throws BackblazeCredentialsException, IOException { createEmptyBucketList(); when(s3Client.createBucket(any(CreateBucketRequest.class))) .thenThrow(BucketAlreadyExistsException.builder().build()); BackblazeDataTransferClient client = createDefaultClient(); assertThrows(IOException.class, () -> { client.init(KEY_ID, APP_KEY, EXPORT_SERVICE); }); verify(monitor, atLeast(1)).info(any()); }
public long getPathHash() { return pathHash; }
@Test public void test() { RootPathLoadStatistic usageLow = new RootPathLoadStatistic(0L, "/home/disk1", 12345L, TStorageMedium.HDD, 4096L, 1024L, DiskState.ONLINE); RootPathLoadStatistic usageHigh = new RootPathLoadStatistic(0L, "/home/disk2", 67890L, TStorageMedium.HDD, 4096L, 2048L, DiskState.ONLINE); List<RootPathLoadStatistic> list = Lists.newArrayList(); list.add(usageLow); list.add(usageHigh); // low usage should be ahead Collections.sort(list); Assert.assertTrue(list.get(0).getPathHash() == usageLow.getPathHash()); }
static void activateHttpAndHttpsProxies(Settings settings, SettingsDecrypter decrypter) throws MojoExecutionException { List<Proxy> proxies = new ArrayList<>(2); for (String protocol : ImmutableList.of("http", "https")) { if (areProxyPropertiesSet(protocol)) { continue; } settings.getProxies().stream() .filter(Proxy::isActive) .filter(proxy -> protocol.equals(proxy.getProtocol())) .findFirst() .ifPresent(proxies::add); } if (proxies.isEmpty()) { return; } SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest().setProxies(proxies); SettingsDecryptionResult result = decrypter.decrypt(request); for (SettingsProblem problem : result.getProblems()) { if (problem.getSeverity() == SettingsProblem.Severity.ERROR || problem.getSeverity() == SettingsProblem.Severity.FATAL) { throw new MojoExecutionException( "Unable to decrypt proxy info from settings.xml: " + problem); } } result.getProxies().forEach(MavenSettingsProxyProvider::setProxyProperties); }
@Test public void testActivateHttpAndHttpsProxies_noActiveProxy() throws MojoExecutionException { MavenSettingsProxyProvider.activateHttpAndHttpsProxies( noActiveProxiesSettings, settingsDecrypter); Assert.assertNull(System.getProperty("http.proxyHost")); Assert.assertNull(System.getProperty("https.proxyHost")); }
@Override public String toString() { return data.toString(); }
@Test public void testToString() { for (short version : LEADER_AND_ISR.allVersions()) { LeaderAndIsrResponse response; if (version < 5) { List<LeaderAndIsrPartitionError> partitions = createPartitions("foo", asList(Errors.NONE, Errors.CLUSTER_AUTHORIZATION_FAILED)); response = new LeaderAndIsrResponse(new LeaderAndIsrResponseData() .setErrorCode(Errors.NONE.code()) .setPartitionErrors(partitions), version); String responseStr = response.toString(); assertTrue(responseStr.contains(LeaderAndIsrResponse.class.getSimpleName())); assertTrue(responseStr.contains(partitions.toString())); assertTrue(responseStr.contains("errorCode=" + Errors.NONE.code())); } else { Uuid id = Uuid.randomUuid(); LeaderAndIsrTopicErrorCollection topics = createTopic(id, asList(Errors.NONE, Errors.CLUSTER_AUTHORIZATION_FAILED)); response = new LeaderAndIsrResponse(new LeaderAndIsrResponseData() .setErrorCode(Errors.NONE.code()) .setTopics(topics), version); String responseStr = response.toString(); assertTrue(responseStr.contains(LeaderAndIsrResponse.class.getSimpleName())); assertTrue(responseStr.contains(topics.toString())); assertTrue(responseStr.contains(id.toString())); assertTrue(responseStr.contains("errorCode=" + Errors.NONE.code())); } } }
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testMultimapGet() { final String tag = "multimap"; StateTag<MultimapState<byte[], Integer>> addr = StateTags.multimap(tag, ByteArrayCoder.of(), VarIntCoder.of()); MultimapState<byte[], Integer> multimapState = underTest.state(NAMESPACE, addr); final byte[] key = "key".getBytes(StandardCharsets.UTF_8); SettableFuture<Iterable<Integer>> future = SettableFuture.create(); when(mockReader.multimapFetchSingleEntryFuture( encodeWithCoder(key, ByteArrayCoder.of()), key(NAMESPACE, tag), STATE_FAMILY, VarIntCoder.of())) .thenReturn(future); ReadableState<Iterable<Integer>> result = multimapState.get(dup(key)).readLater(); waitAndSet(future, Arrays.asList(1, 2, 3), 30); assertThat(result.read(), Matchers.containsInAnyOrder(1, 2, 3)); }
@Override public int rename(String oldPath, String newPath, int flags) { return AlluxioFuseUtils.call(LOG, () -> renameInternal(oldPath, newPath, flags), FuseConstants.FUSE_RENAME, "oldPath=%s,newPath=%s,", oldPath, newPath); }
@Test public void renameWithLengthLimit() throws Exception { String c256 = String.join("", Collections.nCopies(16, "0123456789ABCDEF")); AlluxioURI oldPath = BASE_EXPECTED_URI.join("/old"); AlluxioURI newPath = BASE_EXPECTED_URI.join("/" + c256); doNothing().when(mFileSystem).rename(oldPath, newPath); assertEquals(-ErrorCodes.ENAMETOOLONG(), mFuseFs.rename("/old", "/" + c256, AlluxioJniRenameUtils.NO_FLAGS)); }
@VisibleForTesting static DBCollection prepareCollection(final MongoConnection mongoConnection) { DBCollection coll = mongoConnection.getDatabase().getCollection(COLLECTION_NAME); coll.createIndex(DBSort.asc("type"), "unique_type", true); coll.setWriteConcern(WriteConcern.JOURNALED); return coll; }
@Test public void prepareCollectionCreatesCollectionIfItDoesNotExist() throws Exception { @SuppressWarnings("deprecation") final DB database = mongoConnection.getDatabase(); database.getCollection(COLLECTION_NAME).drop(); assertThat(database.collectionExists(COLLECTION_NAME)).isFalse(); DBCollection collection = ClusterConfigServiceImpl.prepareCollection(mongoConnection); assertThat(collection.getName()).isEqualTo(COLLECTION_NAME); assertThat(collection.getIndexInfo()).hasSize(2); assertThat(collection.getWriteConcern()).isEqualTo(WriteConcern.JOURNALED); }
public V2 v2() { return v2; }
@Test public void testZeroOthers() { QueryQueueOptions opts = new QueryQueueOptions(true, new QueryQueueOptions.V2(2, 0, 0, 0, 0, 0)); assertThat(opts.v2().getNumWorkers()).isOne(); assertThat(opts.v2().getNumRowsPerSlot()).isOne(); assertThat(opts.v2().getTotalSlots()).isEqualTo(2); assertThat(opts.v2().getTotalSmallSlots()).isOne(); assertThat(opts.v2().getMemBytesPerSlot()).isEqualTo(Long.MAX_VALUE); assertThat(opts.v2().getCpuCostsPerSlot()).isOne(); }
@Override public void invoke(NamingEvent event) { logInvoke(event); if (listener instanceof AbstractEventListener && ((AbstractEventListener) listener).getExecutor() != null) { ((AbstractEventListener) listener).getExecutor().execute(() -> listener.onEvent(event)); } else { listener.onEvent(event); } }
@Test public void testAbstractNamingChaneEventListener() { AbstractNamingChangeListener listener = spy(AbstractNamingChangeListener.class); NamingListenerInvoker listenerInvoker = new NamingListenerInvoker(listener); NamingChangeEvent event = new NamingChangeEvent("serviceName", Collections.emptyList(), new InstancesDiff()); listenerInvoker.invoke(event); verify(listener).onChange(event); }
public abstract Map<String, String> renderMap(Map<String, String> inline) throws IllegalVariableEvaluationException;
@Test void renderMap() throws IllegalVariableEvaluationException { RunContext runContext = runContextFactory.of(Map.of( "key", "default", "value", "default" )); Map<String, String> rendered = runContext.renderMap(Map.of("{{key}}", "{{value}}")); assertThat(rendered.get("default"), is("default")); rendered = runContext.renderMap(Map.of("{{key}}", "{{value}}"), Map.of( "key", "key", "value", "value" )); assertThat(rendered.get("key"), is("value")); }
@Override public CommitWorkStream commitWorkStream() { return windmillStreamFactory.createCommitWorkStream( dispatcherClient.getWindmillServiceStub(), throttleTimers.commitWorkThrottleTimer()); }
@Test // Tests stream retries on server errors before and after `close()` public void testStreamingCommitClosedStream() throws Exception { List<WorkItemCommitRequest> commitRequestList = new ArrayList<>(); List<CountDownLatch> latches = new ArrayList<>(); Map<Long, WorkItemCommitRequest> commitRequests = new ConcurrentHashMap<>(); AtomicBoolean shouldServerReturnError = new AtomicBoolean(true); AtomicBoolean isClientClosed = new AtomicBoolean(false); AtomicInteger errorsBeforeClose = new AtomicInteger(); AtomicInteger errorsAfterClose = new AtomicInteger(); for (int i = 0; i < 500; ++i) { // Build some requests of varying size with a few big ones. WorkItemCommitRequest request = makeCommitRequest(i, i * (i < 480 ? 8 : 128)); commitRequestList.add(request); commitRequests.put((long) i, request); latches.add(new CountDownLatch(1)); } Collections.shuffle(commitRequestList); // This server returns errors if shouldServerReturnError is true, else returns valid responses. serviceRegistry.addService( new CloudWindmillServiceV1Alpha1ImplBase() { @Override public StreamObserver<StreamingCommitWorkRequest> commitWorkStream( StreamObserver<StreamingCommitResponse> responseObserver) { StreamObserver<StreamingCommitWorkRequest> testCommitStreamObserver = getTestCommitStreamObserver(responseObserver, commitRequests); return new StreamObserver<StreamingCommitWorkRequest>() { @Override public void onNext(StreamingCommitWorkRequest request) { if (shouldServerReturnError.get()) { try { responseObserver.onError( new RuntimeException("shouldServerReturnError = true")); if (isClientClosed.get()) { errorsAfterClose.incrementAndGet(); } else { errorsBeforeClose.incrementAndGet(); } } catch (IllegalStateException e) { // The stream is already closed. } } else { testCommitStreamObserver.onNext(request); } } @Override public void onError(Throwable throwable) { testCommitStreamObserver.onError(throwable); } @Override public void onCompleted() { testCommitStreamObserver.onCompleted(); } }; } }); // Make the commit requests, waiting for each of them to be verified and acknowledged. CommitWorkStream stream = client.commitWorkStream(); try (CommitWorkStream.RequestBatcher batcher = stream.batcher()) { for (int i = 0; i < commitRequestList.size(); ) { final CountDownLatch latch = latches.get(i); if (batcher.commitWorkItem( "computation", commitRequestList.get(i), (CommitStatus status) -> { assertEquals(status, CommitStatus.OK); latch.countDown(); })) { i++; } else { batcher.flush(); } } } long deadline = System.currentTimeMillis() + 60_000; // 1 min while (true) { Thread.sleep(100); int tmpErrorsBeforeClose = errorsBeforeClose.get(); // wait for at least 1 error before close if (tmpErrorsBeforeClose > 0) { break; } if (System.currentTimeMillis() > deadline) { // Control should not reach here if the test is working as expected fail( String.format( "Expected errors not sent by server errorsBeforeClose: %s" + " \n Should not reach here if the test is working as expected.", tmpErrorsBeforeClose)); } } stream.halfClose(); isClientClosed.set(true); deadline = System.currentTimeMillis() + 60_000; // 1 min while (true) { Thread.sleep(100); int tmpErrorsAfterClose = errorsAfterClose.get(); // wait for at least 1 error after close if (tmpErrorsAfterClose > 0) { break; } if (System.currentTimeMillis() > deadline) { // Control should not reach here if the test is working as expected fail( String.format( "Expected errors not sent by server errorsAfterClose: %s" + " \n Should not reach here if the test is working as expected.", tmpErrorsAfterClose)); } } shouldServerReturnError.set(false); for (CountDownLatch latch : latches) { assertTrue(latch.await(1, TimeUnit.MINUTES)); } assertTrue(stream.awaitTermination(30, TimeUnit.SECONDS)); }
public static JsonObject serialize(RegisteredClient c) { if (c.getSource() != null) { // if we have the original object, just use that return c.getSource(); } else { JsonObject o = new JsonObject(); o.addProperty(CLIENT_ID, c.getClientId()); if (c.getClientSecret() != null) { o.addProperty(CLIENT_SECRET, c.getClientSecret()); if (c.getClientSecretExpiresAt() == null) { o.addProperty(CLIENT_SECRET_EXPIRES_AT, 0); // TODO: do we want to let secrets expire? } else { o.addProperty(CLIENT_SECRET_EXPIRES_AT, c.getClientSecretExpiresAt().getTime() / 1000L); } } if (c.getClientIdIssuedAt() != null) { o.addProperty(CLIENT_ID_ISSUED_AT, c.getClientIdIssuedAt().getTime() / 1000L); } else if (c.getCreatedAt() != null) { o.addProperty(CLIENT_ID_ISSUED_AT, c.getCreatedAt().getTime() / 1000L); } if (c.getRegistrationAccessToken() != null) { o.addProperty(REGISTRATION_ACCESS_TOKEN, c.getRegistrationAccessToken()); } if (c.getRegistrationClientUri() != null) { o.addProperty(REGISTRATION_CLIENT_URI, c.getRegistrationClientUri()); } // add in all other client properties // OAuth DynReg o.add(REDIRECT_URIS, getAsArray(c.getRedirectUris())); o.addProperty(CLIENT_NAME, c.getClientName()); o.addProperty(CLIENT_URI, c.getClientUri()); o.addProperty(LOGO_URI, c.getLogoUri()); o.add(CONTACTS, getAsArray(c.getContacts())); o.addProperty(TOS_URI, c.getTosUri()); o.addProperty(TOKEN_ENDPOINT_AUTH_METHOD, c.getTokenEndpointAuthMethod() != null ? c.getTokenEndpointAuthMethod().getValue() : null); o.addProperty(SCOPE, c.getScope() != null ? Joiner.on(SCOPE_SEPARATOR).join(c.getScope()) : null); o.add(GRANT_TYPES, getAsArray(c.getGrantTypes())); o.add(RESPONSE_TYPES, getAsArray(c.getResponseTypes())); o.addProperty(POLICY_URI, c.getPolicyUri()); o.addProperty(JWKS_URI, c.getJwksUri()); // get the JWKS sub-object if (c.getJwks() != null) { // We have to re-parse it into GSON because Nimbus uses a different parser JsonElement jwks = parser.parse(c.getJwks().toString()); o.add(JWKS, jwks); } else { o.add(JWKS, null); } // OIDC Registration o.addProperty(APPLICATION_TYPE, c.getApplicationType() != null ? c.getApplicationType().getValue() : null); o.addProperty(SECTOR_IDENTIFIER_URI, c.getSectorIdentifierUri()); o.addProperty(SUBJECT_TYPE, c.getSubjectType() != null ? c.getSubjectType().getValue() : null); o.addProperty(REQUEST_OBJECT_SIGNING_ALG, c.getRequestObjectSigningAlg() != null ? c.getRequestObjectSigningAlg().getName() : null); o.addProperty(USERINFO_SIGNED_RESPONSE_ALG, c.getUserInfoSignedResponseAlg() != null ? c.getUserInfoSignedResponseAlg().getName() : null); o.addProperty(USERINFO_ENCRYPTED_RESPONSE_ALG, c.getUserInfoEncryptedResponseAlg() != null ? c.getUserInfoEncryptedResponseAlg().getName() : null); o.addProperty(USERINFO_ENCRYPTED_RESPONSE_ENC, c.getUserInfoEncryptedResponseEnc() != null ? c.getUserInfoEncryptedResponseEnc().getName() : null); o.addProperty(ID_TOKEN_SIGNED_RESPONSE_ALG, c.getIdTokenSignedResponseAlg() != null ? c.getIdTokenSignedResponseAlg().getName() : null); o.addProperty(ID_TOKEN_ENCRYPTED_RESPONSE_ALG, c.getIdTokenEncryptedResponseAlg() != null ? c.getIdTokenEncryptedResponseAlg().getName() : null); o.addProperty(ID_TOKEN_ENCRYPTED_RESPONSE_ENC, c.getIdTokenEncryptedResponseEnc() != null ? c.getIdTokenEncryptedResponseEnc().getName() : null); o.addProperty(TOKEN_ENDPOINT_AUTH_SIGNING_ALG, c.getTokenEndpointAuthSigningAlg() != null ? c.getTokenEndpointAuthSigningAlg().getName() : null); o.addProperty(DEFAULT_MAX_AGE, c.getDefaultMaxAge()); o.addProperty(REQUIRE_AUTH_TIME, c.getRequireAuthTime()); o.add(DEFAULT_ACR_VALUES, getAsArray(c.getDefaultACRvalues())); o.addProperty(INITIATE_LOGIN_URI, c.getInitiateLoginUri()); o.add(POST_LOGOUT_REDIRECT_URIS, getAsArray(c.getPostLogoutRedirectUris())); o.add(REQUEST_URIS, getAsArray(c.getRequestUris())); o.add(CLAIMS_REDIRECT_URIS, getAsArray(c.getClaimsRedirectUris())); o.addProperty(CODE_CHALLENGE_METHOD, c.getCodeChallengeMethod() != null ? c.getCodeChallengeMethod().getName() : null); o.addProperty(SOFTWARE_ID, c.getSoftwareId()); o.addProperty(SOFTWARE_VERSION, c.getSoftwareVersion()); if (c.getSoftwareStatement() != null) { o.addProperty(SOFTWARE_STATEMENT, c.getSoftwareStatement().serialize()); } return o; } }
@Test public void testSerialize() { RegisteredClient c = new RegisteredClient(); c.setClientId("s6BhdRkqt3"); c.setClientSecret("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk"); c.setClientSecretExpiresAt(new Date(1577858400L * 1000L)); c.setRegistrationAccessToken("this.is.an.access.token.value.ffx83"); c.setRegistrationClientUri("https://server.example.com/connect/register?client_id=s6BhdRkqt3"); c.setApplicationType(ClientDetailsEntity.AppType.WEB); c.setRedirectUris(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2")); c.setClientName("My Example"); c.setResponseTypes(ImmutableSet.of("code", "token")); c.setGrantTypes(ImmutableSet.of("authorization_code", "implicit")); c.setLogoUri("https://client.example.org/logo.png"); c.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); c.setSectorIdentifierUri("https://other.example.net/file_of_redirect_uris.json"); c.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.SECRET_BASIC); c.setJwksUri("https://client.example.org/my_public_keys.jwks"); c.setUserInfoEncryptedResponseAlg(JWEAlgorithm.RSA1_5); c.setUserInfoEncryptedResponseEnc(EncryptionMethod.A128CBC_HS256); c.setContacts(ImmutableSet.of("[email protected]", "[email protected]")); c.setRequestUris(ImmutableSet.of("https://client.example.org/rf.txt#qpXaRLh_n93TTR9F252ValdatUQvQiJi5BDub2BeznA")); JsonObject j = ClientDetailsEntityJsonProcessor.serialize(c); assertEquals("s6BhdRkqt3", j.get("client_id").getAsString()); assertEquals("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk", j.get("client_secret").getAsString()); assertEquals(1577858400L, j.get("client_secret_expires_at").getAsNumber()); assertEquals("this.is.an.access.token.value.ffx83", j.get("registration_access_token").getAsString()); assertEquals("https://server.example.com/connect/register?client_id=s6BhdRkqt3", j.get("registration_client_uri").getAsString()); assertEquals(ClientDetailsEntity.AppType.WEB.getValue(), j.get("application_type").getAsString()); for (JsonElement e : j.get("redirect_uris").getAsJsonArray()) { assertTrue(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2").contains(e.getAsString())); } assertEquals("My Example", j.get("client_name").getAsString()); for (JsonElement e : j.get("response_types").getAsJsonArray()) { assertTrue(ImmutableSet.of("code", "token").contains(e.getAsString())); } for (JsonElement e : j.get("grant_types").getAsJsonArray()) { assertTrue(ImmutableSet.of("authorization_code", "implicit").contains(e.getAsString())); } assertEquals("https://client.example.org/logo.png", j.get("logo_uri").getAsString()); assertEquals(ClientDetailsEntity.SubjectType.PAIRWISE.getValue(), j.get("subject_type").getAsString()); assertEquals("https://other.example.net/file_of_redirect_uris.json", j.get("sector_identifier_uri").getAsString()); assertEquals(ClientDetailsEntity.AuthMethod.SECRET_BASIC.getValue(), j.get("token_endpoint_auth_method").getAsString()); assertEquals("https://client.example.org/my_public_keys.jwks", j.get("jwks_uri").getAsString()); assertEquals(JWEAlgorithm.RSA1_5.getName(), j.get("userinfo_encrypted_response_alg").getAsString()); assertEquals(EncryptionMethod.A128CBC_HS256.getName(), j.get("userinfo_encrypted_response_enc").getAsString()); for (JsonElement e : j.get("contacts").getAsJsonArray()) { assertTrue(ImmutableSet.of("[email protected]", "[email protected]").contains(e.getAsString())); } for (JsonElement e : j.get("request_uris").getAsJsonArray()) { assertTrue(ImmutableSet.of("https://client.example.org/rf.txt#qpXaRLh_n93TTR9F252ValdatUQvQiJi5BDub2BeznA").contains(e.getAsString())); } }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Struct other = (Struct) obj; if (schema != other.schema) return false; for (int i = 0; i < this.values.length; i++) { BoundField f = this.schema.get(i); boolean result; if (f.def.type.isArray()) { result = Arrays.equals((Object[]) this.get(f), (Object[]) other.get(f)); } else { Object thisField = this.get(f); Object otherField = other.get(f); result = Objects.equals(thisField, otherField); } if (!result) return false; } return true; }
@Test public void testEquals() { Struct struct1 = new Struct(FLAT_STRUCT_SCHEMA) .set("int8", (byte) 12) .set("int16", (short) 12) .set("int32", 12) .set("int64", (long) 12) .set("boolean", true) .set("float64", 0.5) .set("string", "foobar"); Struct struct2 = new Struct(FLAT_STRUCT_SCHEMA) .set("int8", (byte) 12) .set("int16", (short) 12) .set("int32", 12) .set("int64", (long) 12) .set("boolean", true) .set("float64", 0.5) .set("string", "foobar"); Struct struct3 = new Struct(FLAT_STRUCT_SCHEMA) .set("int8", (byte) 12) .set("int16", (short) 12) .set("int32", 12) .set("int64", (long) 12) .set("boolean", true) .set("float64", 0.5) .set("string", "mismatching string"); assertEquals(struct1, struct2); assertNotEquals(struct1, struct3); Object[] array = {(byte) 1, (byte) 2}; struct1 = new Struct(NESTED_SCHEMA) .set("array", array) .set("nested", new Struct(NESTED_CHILD_SCHEMA).set("int8", (byte) 12)); Object[] array2 = {(byte) 1, (byte) 2}; struct2 = new Struct(NESTED_SCHEMA) .set("array", array2) .set("nested", new Struct(NESTED_CHILD_SCHEMA).set("int8", (byte) 12)); Object[] array3 = {(byte) 1, (byte) 2, (byte) 3}; struct3 = new Struct(NESTED_SCHEMA) .set("array", array3) .set("nested", new Struct(NESTED_CHILD_SCHEMA).set("int8", (byte) 13)); assertEquals(struct1, struct2); assertNotEquals(struct1, struct3); }
@VisibleForTesting public List<ProjectionContext> planRemoteAssignments(Assignments assignments, VariableAllocator variableAllocator) { ImmutableList.Builder<List<ProjectionContext>> assignmentProjections = ImmutableList.builder(); for (Map.Entry<VariableReferenceExpression, RowExpression> entry : assignments.getMap().entrySet()) { List<ProjectionContext> rewritten = entry.getValue().accept(new Visitor(functionAndTypeManager, variableAllocator), null); if (rewritten.isEmpty()) { assignmentProjections.add(ImmutableList.of(new ProjectionContext(ImmutableMap.of(entry.getKey(), entry.getValue()), false))); } else { checkState(rewritten.get(rewritten.size() - 1).getProjections().size() == 1, "Expect at most 1 assignment from last projection in rewrite"); ProjectionContext last = rewritten.get(rewritten.size() - 1); ImmutableList.Builder<ProjectionContext> projectionContextBuilder = ImmutableList.builder(); projectionContextBuilder.addAll(rewritten.subList(0, rewritten.size() - 1)); projectionContextBuilder.add(new ProjectionContext(ImmutableMap.of(entry.getKey(), getOnlyElement(last.getProjections().values())), last.isRemote())); assignmentProjections.add(projectionContextBuilder.build()); } } List<ProjectionContext> mergedProjectionContexts = mergeProjectionContexts(assignmentProjections.build()); return dedupVariables(mergedProjectionContexts); }
@Test void testLocalOnly() { PlanBuilder planBuilder = new PlanBuilder(TEST_SESSION, new PlanNodeIdAllocator(), getMetadata()); planBuilder.variable("x", INTEGER); planBuilder.variable("y", INTEGER); PlanRemoteProjections rule = new PlanRemoteProjections(getFunctionAndTypeManager()); List<ProjectionContext> rewritten = rule.planRemoteAssignments(Assignments.builder() .put(planBuilder.variable("a"), planBuilder.rowExpression("abs(x) + abs(y)")) .put(planBuilder.variable("b", BOOLEAN), planBuilder.rowExpression("x is null and y is null")) .build(), new VariableAllocator(planBuilder.getTypes().allVariables())); assertEquals(rewritten.size(), 1); assertEquals(rewritten.get(0).getProjections().size(), 2); }
public void recycle(MemorySegment segment) { checkArgument(segment != null, "Buffer must be not null."); recycle(Collections.singletonList(segment)); }
@Test void testRecycle() throws Exception { BatchShuffleReadBufferPool bufferPool = createBufferPool(); List<MemorySegment> buffers = bufferPool.requestBuffers(); bufferPool.recycle(buffers); assertThat(bufferPool.getAvailableBuffers()).isEqualTo(bufferPool.getNumTotalBuffers()); }
public void createCatalog(CreateCatalogStmt stmt) throws DdlException { createCatalog(stmt.getCatalogType(), stmt.getCatalogName(), stmt.getComment(), stmt.getProperties()); }
@Test public void testCreateExceptionMsg() { CatalogMgr catalogMgr = GlobalStateMgr.getCurrentState().getCatalogMgr(); Map<String, String> config = new HashMap<>(); config.put("type", "jdbc"); try { catalogMgr.createCatalog("jdbc", "a", "", config); Assert.fail(); } catch (DdlException e) { Assert.assertTrue(e.getMessage().contains("Missing")); } config.put("type", "test_unsupported"); Assert.assertThrows(DdlException.class, () -> { catalogMgr.createCatalog("test_unsupported", "b", "", config); }); }
@Override public AttributedList<Path> search(final Path workdir, final Filter<Path> regex, final ListProgressListener listener) throws BackgroundException { final AttributedList<Path> list = new AttributedList<>(); // avoid searching the "special" folders if users search from the account root if(workdir.getParent().isRoot()) { final Predicate<MantaObject> fastSearchPredicate = o -> session.isWorldReadable(o) || session.isUserWritable(o); final List<Path> homeFolderPaths = findObjectsAsPaths(workdir, fastSearchPredicate); cleanResults(homeFolderPaths, regex); addPaths(list, workdir, listener, homeFolderPaths); /* // disable search of system directories until we can provide incremental results // slowSearchPredicate will prevent us from looking at ~~/public and ~~/stor twice final Predicate<MantaObject> slowSearchPredicate = fastSearchPredicate.negate(); final List<Path> systemFolderObjects = findObjectsAsPaths(workdir, slowSearchPredicate.and(regexPredicate)); cleanResults(systemFolderObjects, regex); addPaths(list, workdir, listener, systemFolderObjects); */ } else { final List<Path> foundPaths = findObjectsAsPaths(workdir, null); cleanResults(foundPaths, regex); addPaths(list, workdir, listener, foundPaths); } return list; }
@Test public void testSearchSameDirectory() throws Exception { Assume.assumeTrue(session.getClient().existsAndIsAccessible(testPathPrefix.getAbsolute())); final String newDirectoryName = new AlphanumericRandomStringService().random(); final Path newDirectory = new Path(testPathPrefix, newDirectoryName, TYPE_DIRECTORY); final String newFileName = new AlphanumericRandomStringService().random(); new MantaDirectoryFeature(session).mkdir(newDirectory, null); new MantaTouchFeature(session).touch(new Path(newDirectory, newFileName, TYPE_FILE), null); final MantaSearchFeature s = new MantaSearchFeature(session); final AttributedList<Path> search = s.search(newDirectory, new NullFilter<>(), new DisabledListProgressListener()); assertEquals(1, search.size()); assertEquals(newFileName, search.get(0).getName()); }
@Override public Set<K8sApiConfig> apiConfigs() { return configStore.apiConfigs(); }
@Test public void testGetAllNodes() { assertEquals(ERR_SIZE, 2, target.apiConfigs().size()); assertTrue(ERR_NOT_FOUND, target.apiConfigs().contains(apiConfig2)); assertTrue(ERR_NOT_FOUND, target.apiConfigs().contains(apiConfig3)); }
private void withdraw(ResolvedRoute route) { synchronized (this) { IpPrefix prefix = route.prefix(); MultiPointToSinglePointIntent intent = routeIntents.remove(prefix); if (intent == null) { log.trace("No intent in routeIntents to delete for prefix: {}", prefix); return; } intentSynchronizer.withdraw(intent); } }
@Test public void testRouteDelete() { // Add a route first testRouteAddToNoVlan(); // Construct the existing route entry ResolvedRoute route = createRoute(PREFIX1, IP3, MAC3); // Create existing intent MultiPointToSinglePointIntent removedIntent = createIntentToThreeSrcOneTwo(PREFIX1); // Set up expectation reset(intentSynchronizer); // Setup the expected intents intentSynchronizer.withdraw(eqExceptId(removedIntent)); replay(intentSynchronizer); // Send in the removed event routeListener.event(new RouteEvent(RouteEvent.Type.ROUTE_REMOVED, route)); verify(intentSynchronizer); }
@Override public FileMergingCheckpointStateOutputStream createCheckpointStateOutputStream( CheckpointedStateScope scope) throws IOException { return fileMergingSnapshotManager.createCheckpointStateOutputStream( subtaskKey, checkpointId, scope); }
@Test public void testWritingToClosedStream() { FileMergingSnapshotManager snapshotManager = createFileMergingSnapshotManager(); FsMergingCheckpointStorageLocation storageLocation = createFsMergingCheckpointStorageLocation(1, snapshotManager); try (FileMergingCheckpointStateOutputStream stream = storageLocation.createCheckpointStateOutputStream(EXCLUSIVE)) { stream.flushToFile(); stream.closeAndGetHandle(); stream.flushToFile(); fail("Expected IOException"); } catch (IOException e) { assertThat(e.getMessage()).isEqualTo("Cannot call flushToFile() to a closed stream."); } }
public void schedule(Node<K, V> node) { Node<K, V> sentinel = findBucket(node.getVariableTime()); link(sentinel, node); }
@Test(dataProvider = "schedule") public void schedule(long clock, long duration, int expired) { when(cache.evictEntry(captor.capture(), any(), anyLong())).thenReturn(true); timerWheel.nanos = clock; for (int timeout : new int[] { 25, 90, 240 }) { timerWheel.schedule(new Timer(clock + TimeUnit.SECONDS.toNanos(timeout))); } timerWheel.advance(cache, clock + duration); verify(cache, times(expired)).evictEntry(any(), any(), anyLong()); for (var node : captor.getAllValues()) { assertThat(node.getVariableTime()).isAtMost(clock + duration); } }
public Object runScript(String src) throws PropertyException { try { JexlScript script = JEXL.createScript(src); ObjectContext<PropertyManager> context = new ObjectContext<>(JEXL, this); return script.execute(context); } catch(JexlException je) { throw new PropertyException("script failed", je); } }
@Test public void testSerDerScript() { runSerDer(() -> { return (boolean) manager.runScript( "setProperty('framework', 'llap');" + "setProperty('ser.store', 'Parquet');" + "setProperty('ser.der.id', 42);" + "setProperty('ser.der.name', 'serder');" + "setProperty('ser.der.project', 'Metastore');" + "true;"); }); }
@Override protected Result[] run(String value) { final Map<String, Object> extractedJson; try { extractedJson = extractJson(value); } catch (IOException e) { throw new ExtractorException(e); } final List<Result> results = new ArrayList<>(extractedJson.size()); for (Map.Entry<String, Object> entry : extractedJson.entrySet()) { results.add(new Result(entry.getValue(), entry.getKey(), -1, -1)); } return results.toArray(new Result[results.size()]); }
@Test public void testRunWithScalarValues() throws Exception { final String value = "{\"text\": \"foobar\", \"number\": 1234.5678, \"bool\": true, \"null\": null}"; final Extractor.Result[] results = jsonExtractor.run(value); assertThat(results).contains( new Extractor.Result("foobar", "text", -1, -1), new Extractor.Result(1234.5678, "number", -1, -1), new Extractor.Result(true, "bool", -1, -1) ); // Null values should be ignored! assertThat(results).doesNotContain(new Extractor.Result(null, "null", -1, -1)); }