focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Mono<ReserveUsernameHashResponse> reserveUsernameHash(final ReserveUsernameHashRequest request) { final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice(); if (request.getUsernameHashesCount() == 0) { throw Status.INVALID_ARGUMENT .withDescription("List of username hashes must not be empty") .asRuntimeException(); } if (request.getUsernameHashesCount() > AccountController.MAXIMUM_USERNAME_HASHES_LIST_LENGTH) { throw Status.INVALID_ARGUMENT .withDescription(String.format("List of username hashes may have at most %d elements, but actually had %d", AccountController.MAXIMUM_USERNAME_HASHES_LIST_LENGTH, request.getUsernameHashesCount())) .asRuntimeException(); } final List<byte[]> usernameHashes = new ArrayList<>(request.getUsernameHashesCount()); for (final ByteString usernameHash : request.getUsernameHashesList()) { if (usernameHash.size() != AccountController.USERNAME_HASH_LENGTH) { throw Status.INVALID_ARGUMENT .withDescription(String.format("Username hash length must be %d bytes, but was actually %d", AccountController.USERNAME_HASH_LENGTH, usernameHash.size())) .asRuntimeException(); } usernameHashes.add(usernameHash.toByteArray()); } return rateLimiters.getUsernameReserveLimiter().validateReactive(authenticatedDevice.accountIdentifier()) .then(Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))) .map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException)) .flatMap(account -> Mono.fromFuture(() -> accountsManager.reserveUsernameHash(account, usernameHashes))) .map(reservation -> ReserveUsernameHashResponse.newBuilder() .setUsernameHash(ByteString.copyFrom(reservation.reservedUsernameHash())) .build()) .onErrorReturn(UsernameHashNotAvailableException.class, ReserveUsernameHashResponse.newBuilder() .setError(ReserveUsernameHashError.newBuilder() .setErrorType(ReserveUsernameHashErrorType.RESERVE_USERNAME_HASH_ERROR_TYPE_NO_HASHES_AVAILABLE) .build()) .build()); }
@Test void reserveUsernameHashRateLimited() { final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH); final Duration retryAfter = Duration.ofMinutes(3); when(rateLimiter.validateReactive(any(UUID.class))) .thenReturn(Mono.error(new RateLimitExceededException(retryAfter))); //noinspection ResultOfMethodCallIgnored GrpcTestUtils.assertRateLimitExceeded(retryAfter, () -> authenticatedServiceStub().reserveUsernameHash(ReserveUsernameHashRequest.newBuilder() .addUsernameHashes(ByteString.copyFrom(usernameHash)) .build()), accountsManager); }
@Override public String getName() { return "Dart Package Analyzer"; }
@Test public void testDartPubspecYamlAnalyzer() throws AnalysisException { final Engine engine = new Engine(getSettings()); final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, "dart.yaml/pubspec.yaml")); dartAnalyzer.analyze(result, engine); assertThat(engine.getDependencies().length, equalTo(7)); Dependency dependency1 = engine.getDependencies()[0]; Dependency dependency2 = engine.getDependencies()[1]; Dependency dependency3 = engine.getDependencies()[2]; Dependency dependency4 = engine.getDependencies()[3]; Dependency dependency5 = engine.getDependencies()[4]; Dependency dependency6 = engine.getDependencies()[5]; Dependency dependency7 = engine.getDependencies()[6]; assertThat(dependency1.getName(), equalTo("auto_size_text")); assertThat(dependency1.getVersion(), equalTo("3.0.0")); for (Identifier identifier : dependency1.getSoftwareIdentifiers()) { if (identifier instanceof GenericIdentifier) { assertThat(identifier.getValue(), equalTo("cpe:2.3:a:*:auto_size_text:3.0.0:*:*:*:*:*:*:*")); } if (identifier instanceof PurlIdentifier) { assertThat(identifier.getValue(), equalTo("pkg:pub/auto_size_text@3.0.0")); } } assertThat(dependency2.getName(), equalTo("carousel_slider")); assertThat(dependency2.getVersion(), equalTo("")); for (Identifier identifier : dependency2.getSoftwareIdentifiers()) { if (identifier instanceof GenericIdentifier) { assertThat(identifier.getValue(), equalTo("cpe:2.3:a:*:carousel_slider:*:*:*:*:*:*:*:*")); } if (identifier instanceof PurlIdentifier) { assertThat(identifier.getValue(), equalTo("pkg:pub/carousel_slider")); } } assertThat(dependency3.getName(), equalTo("collection")); assertThat(dependency3.getVersion(), equalTo("1.16.0")); assertThat(dependency4.getName(), equalTo("corsac_jwt")); assertThat(dependency4.getVersion(), equalTo("1.0.0-nullsafety.1")); assertThat(dependency5.getName(), equalTo("build_runner")); assertThat(dependency5.getVersion(), equalTo("2.1.11")); assertThat(dependency6.getName(), equalTo("flutter_test")); assertThat(dependency6.getVersion(), equalTo("")); for (Identifier identifier : dependency6.getSoftwareIdentifiers()) { if (identifier instanceof GenericIdentifier) { assertThat(identifier.getValue(), equalTo("cpe:2.3:a:*:flutter_test:*:*:*:*:*:*:*:*")); } if (identifier instanceof PurlIdentifier) { assertThat(identifier.getValue(), equalTo("pkg:pub/flutter_test")); } } assertThat(dependency7.getName(), equalTo("dart_software_development_kit")); assertThat(dependency7.getVersion(), equalTo("2.17.0")); }
public Set<? extends AuthenticationRequest> getRequest(final Host bookmark, final LoginCallback prompt) throws LoginCanceledException { final StringBuilder url = new StringBuilder(); url.append(bookmark.getProtocol().getScheme().toString()).append("://"); url.append(bookmark.getHostname()); if(!(bookmark.getProtocol().getScheme().getPort() == bookmark.getPort())) { url.append(":").append(bookmark.getPort()); } final String context = PathNormalizer.normalize(bookmark.getProtocol().getContext()); // Custom authentication context url.append(context); if(bookmark.getProtocol().getDefaultHostname().endsWith("identity.api.rackspacecloud.com") || bookmark.getHostname().endsWith("identity.api.rackspacecloud.com")) { return Collections.singleton(new Authentication20RAXUsernameKeyRequest( URI.create(url.toString()), bookmark.getCredentials().getUsername(), bookmark.getCredentials().getPassword(), null) ); } final LoginOptions options = new LoginOptions(bookmark.getProtocol()).password(false).anonymous(false).publickey(false); if(context.contains("1.0")) { return Collections.singleton(new Authentication10UsernameKeyRequest(URI.create(url.toString()), bookmark.getCredentials().getUsername(), bookmark.getCredentials().getPassword())); } else if(context.contains("1.1")) { return Collections.singleton(new Authentication11UsernameKeyRequest(URI.create(url.toString()), bookmark.getCredentials().getUsername(), bookmark.getCredentials().getPassword())); } else if(context.contains("2.0")) { // Prompt for tenant final String user; final String tenant; if(StringUtils.contains(bookmark.getCredentials().getUsername(), ':')) { final String[] parts = StringUtils.splitPreserveAllTokens(bookmark.getCredentials().getUsername(), ':'); tenant = parts[0]; user = parts[1]; } else { user = bookmark.getCredentials().getUsername(); tenant = prompt.prompt(bookmark, bookmark.getCredentials().getUsername(), LocaleFactory.localizedString("Provide additional login credentials", "Credentials"), LocaleFactory.localizedString("Tenant Name", "Mosso"), options .usernamePlaceholder(LocaleFactory.localizedString("Tenant Name", "Mosso"))).getUsername(); // Save tenant in username bookmark.getCredentials().setUsername(String.format("%s:%s", tenant, bookmark.getCredentials().getUsername())); } final Set<AuthenticationRequest> requests = new LinkedHashSet<>(); requests.add(new Authentication20UsernamePasswordRequest( URI.create(url.toString()), user, bookmark.getCredentials().getPassword(), tenant) ); requests.add(new Authentication20UsernamePasswordTenantIdRequest( URI.create(url.toString()), user, bookmark.getCredentials().getPassword(), tenant) ); requests.add(new Authentication20AccessKeySecretKeyRequest( URI.create(url.toString()), user, bookmark.getCredentials().getPassword(), tenant)); return requests; } else if(context.contains("3")) { // Prompt for project final String user; final String project; final String domain; if(StringUtils.contains(bookmark.getCredentials().getUsername(), ':')) { final String[] parts = StringUtils.splitPreserveAllTokens(bookmark.getCredentials().getUsername(), ':'); if(parts.length == 3) { project = parts[0]; domain = parts[1]; user = parts[2]; } else { project = parts[0]; user = parts[1]; domain = prompt.prompt(bookmark, bookmark.getCredentials().getUsername(), LocaleFactory.localizedString("Provide additional login credentials", "Credentials"), LocaleFactory.localizedString("Project Domain Name", "Mosso"), options .usernamePlaceholder(LocaleFactory.localizedString("Project Domain Name", "Mosso"))).getUsername(); // Save project name and domain in username bookmark.getCredentials().setUsername(String.format("%s:%s:%s", project, domain, bookmark.getCredentials().getUsername())); } } else { user = bookmark.getCredentials().getUsername(); final Credentials projectName = prompt.prompt(bookmark, bookmark.getCredentials().getUsername(), LocaleFactory.localizedString("Provide additional login credentials", "Credentials"), LocaleFactory.localizedString("Project Name", "Mosso"), options .usernamePlaceholder(LocaleFactory.localizedString("Project Name", "Mosso"))); if(StringUtils.contains(bookmark.getCredentials().getUsername(), ':')) { final String[] parts = StringUtils.splitPreserveAllTokens(projectName.getUsername(), ':'); project = parts[0]; domain = parts[1]; } else { project = projectName.getUsername(); domain = prompt.prompt(bookmark, bookmark.getCredentials().getUsername(), LocaleFactory.localizedString("Provide additional login credentials", "Credentials"), LocaleFactory.localizedString("Project Domain Name", "Mosso"), options .usernamePlaceholder(LocaleFactory.localizedString("Project Domain Name", "Mosso"))).getUsername(); } // Save project name and domain in username bookmark.getCredentials().setUsername(String.format("%s:%s:%s", project, domain, bookmark.getCredentials().getUsername())); } final Set<AuthenticationRequest> requests = new LinkedHashSet<>(); requests.add(new Authentication3UsernamePasswordProjectRequest( URI.create(url.toString()), user, bookmark.getCredentials().getPassword(), project, domain) ); return requests; } else { log.warn(String.format("Unknown context version in %s. Default to v1 authentication.", context)); // Default to 1.0 return Collections.singleton(new Authentication10UsernameKeyRequest(URI.create(url.toString()), bookmark.getCredentials().getUsername(), bookmark.getCredentials().getPassword())); } }
@Test public void testEmptyTenant() throws Exception { final SwiftAuthenticationService s = new SwiftAuthenticationService(); final SwiftProtocol protocol = new SwiftProtocol() { @Override public String getContext() { return "/v2.0/tokens"; } }; final Host host = new Host(protocol, "auth.lts2.evault.com", new Credentials( "u", "p" )); s.getRequest(host, new DisabledLoginCallback() { @Override public Credentials prompt(final Host bookmark, String username, String title, String reason, LoginOptions options) { return new Credentials(""); } }); assertEquals(":u", host.getCredentials().getUsername()); s.getRequest(host, new DisabledLoginCallback() { @Override public Credentials prompt(final Host bookmark, String username, String title, String reason, LoginOptions options) { fail(); return null; } }); }
public Result parse(final String string) throws DateNotParsableException { return this.parse(string, new Date()); }
@Test public void testParseMondayLastWeek() throws Exception { DateTime reference = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss").withZoneUTC().parseDateTime("12.06.2021 09:45:23"); NaturalDateParser.Result result = naturalDateParser.parse("monday last week", reference.toDate()); DateTime lastMondayStart = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss").withZoneUTC().parseDateTime("31.05.2021 00:00:00"); DateTime lastMondayEnd = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss").withZoneUTC().parseDateTime("01.06.2021 00:00:00"); assertThat(result.getFrom()).as("should be equal to").isEqualTo(lastMondayStart); assertThat(result.getTo()).as("should be equal to").isEqualTo(lastMondayEnd); }
@Override String getInterfaceName(Invoker invoker, String prefix) { return DubboUtils.getInterfaceName(invoker, prefix); }
@Test public void testInterfaceLevelFollowControlAsync() throws InterruptedException { Invoker invoker = DubboTestUtil.getDefaultMockInvoker(); Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne(); when(invocation.getAttachment(ASYNC_KEY)).thenReturn(Boolean.TRUE.toString()); initFlowRule(DubboUtils.getInterfaceName(invoker)); Result result1 = invokeDubboRpc(false, invoker, invocation); assertEquals("normal", result1.getValue()); // should fallback because the qps > 1 Result result2 = invokeDubboRpc(false, invoker, invocation); assertEquals("fallback", result2.getValue()); // sleeping 1000 ms to reset qps Thread.sleep(1000); Result result3 = invokeDubboRpc(false, invoker, invocation); assertEquals("normal", result3.getValue()); verifyInvocationStructureForCallFinish(invoker, invocation); }
@Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof Features)) { return false; } final Features that = (Features) other; return Objects.equals(this.features, that.features); }
@Test public void testEquals() { SupportedVersionRange v1 = new SupportedVersionRange((short) 1, (short) 2); Map<String, SupportedVersionRange> allFeatures = mkMap(mkEntry("feature_1", v1)); Features<SupportedVersionRange> features = Features.supportedFeatures(allFeatures); Features<SupportedVersionRange> featuresClone = Features.supportedFeatures(allFeatures); assertEquals(features, featuresClone); SupportedVersionRange v2 = new SupportedVersionRange((short) 1, (short) 3); Map<String, SupportedVersionRange> allFeaturesDifferent = mkMap(mkEntry("feature_1", v2)); Features<SupportedVersionRange> featuresDifferent = Features.supportedFeatures(allFeaturesDifferent); assertNotEquals(features, featuresDifferent); assertNotEquals(null, features); }
@InvokeOnHeader(Web3jConstants.SHH_GET_FILTER_CHANGES) void shhGetFilterChanges(Message message) throws IOException { BigInteger filterId = message.getHeader(Web3jConstants.FILTER_ID, configuration::getFilterId, BigInteger.class); Request<?, ShhMessages> request = web3j.shhGetFilterChanges(filterId); setRequestId(message, request); ShhMessages response = request.send(); boolean hasError = checkForError(message, response); if (!hasError) { message.setBody(response.getMessages()); } }
@Test public void shhGetFilterChangesTest() throws Exception { ShhMessages response = Mockito.mock(ShhMessages.class); Mockito.when(mockWeb3j.shhGetFilterChanges(any())).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getMessages()).thenReturn(Collections.EMPTY_LIST); Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.SHH_GET_FILTER_CHANGES); template.send(exchange); List body = exchange.getIn().getBody(List.class); assertTrue(body.isEmpty()); }
public static DateTimeFormatter createDateTimeFormatter(String format, Mode mode) { DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder(); boolean formatContainsHourOfAMPM = false; for (Token token : tokenize(format)) { switch (token.getType()) { case DateFormat.TEXT: builder.appendLiteral(token.getText()); break; case DateFormat.DD: builder.appendValue(DAY_OF_MONTH, mode.getMinTwoPositionFieldWidth(), 2, NOT_NEGATIVE); break; case DateFormat.HH24: builder.appendValue(HOUR_OF_DAY, mode.getMinTwoPositionFieldWidth(), 2, NOT_NEGATIVE); break; case DateFormat.HH: builder.appendValue(HOUR_OF_AMPM, mode.getMinTwoPositionFieldWidth(), 2, NOT_NEGATIVE); formatContainsHourOfAMPM = true; break; case DateFormat.MI: builder.appendValue(MINUTE_OF_HOUR, mode.getMinTwoPositionFieldWidth(), 2, NOT_NEGATIVE); break; case DateFormat.MM: builder.appendValue(MONTH_OF_YEAR, mode.getMinTwoPositionFieldWidth(), 2, NOT_NEGATIVE); break; case DateFormat.SS: builder.appendValue(SECOND_OF_MINUTE, mode.getMinTwoPositionFieldWidth(), 2, NOT_NEGATIVE); break; case DateFormat.YY: builder.appendValueReduced(YEAR, 2, 2, 2000); break; case DateFormat.YYYY: builder.appendValue(YEAR, 4); break; case DateFormat.UNRECOGNIZED: default: throw new PrestoException( StandardErrorCode.INVALID_FUNCTION_ARGUMENT, String.format("Failed to tokenize string [%s] at offset [%d]", token.getText(), token.getCharPositionInLine())); } } try { // Append default values(0) for time fields(HH24, HH, MI, SS) because JSR-310 does not accept bare Date value as DateTime if (formatContainsHourOfAMPM) { // At the moment format does not allow to include AM/PM token, thus it was never possible to specify PM hours using 'HH' token in format // Keep existing behaviour by defaulting to 0(AM) for AMPM_OF_DAY if format string contains 'HH' builder.parseDefaulting(HOUR_OF_AMPM, 0) .parseDefaulting(AMPM_OF_DAY, 0); } else { builder.parseDefaulting(HOUR_OF_DAY, 0); } return builder.parseDefaulting(MINUTE_OF_HOUR, 0) .parseDefaulting(SECOND_OF_MINUTE, 0) .toFormatter(); } catch (UnsupportedOperationException e) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, e); } }
@Test(expectedExceptions = PrestoException.class) public void testParserInvalidTokenCreate1() { DateFormatParser.createDateTimeFormatter("ala", PARSER); }
@Override public String getReplacement(String variable) { try { return decrypt(variable); } catch (Exception e) { logger.warning("Unable to decrypt variable " + variable, e); } return null; }
@Test public void testWrongVariables() throws Exception { assumeDefaultAlgorithmsSupported(); AbstractPbeReplacer replacer = createAndInitReplacer("test", new Properties()); assertNull(replacer.getReplacement(null)); assertNull(replacer.getReplacement("WronglyFormatted")); assertNull(replacer.getReplacement("aSalt:1:EncryptedValue")); // following incorrect value was generated using replacer.encrypt("test", 777).replace(":777:", ":1:"); assertNull("Null value expected as javax.crypto.BadPaddingException should be thrown in the AbstractPbeReplacer", replacer.getReplacement("IVJXCMo0XBE=:1:NnZjBhX7sB/IT0sTFZ2eIA==")); }
@VisibleForTesting List<String> getFuseInfo() { return mFuseInfo; }
@Test public void UnderFileSystemHdfs() { try (FuseUpdateChecker checker = getUpdateCheckerWithUfs("hdfs://namenode:port/testFolder")) { Assert.assertTrue(containsTargetInfo(checker.getFuseInfo(), "hdfs")); } }
@Override public byte[] serialize(final String topic, final List<?> data) { if (data == null) { return null; } try { final StringWriter stringWriter = new StringWriter(); final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat); csvPrinter.printRecord(() -> new FieldIterator(data, schema)); final String result = stringWriter.toString(); return result.substring(0, result.length() - 2).getBytes(StandardCharsets.UTF_8); } catch (final Exception e) { throw new SerializationException("Error serializing CSV message", e); } }
@Test public void shouldSerializeRowCorrectly() { // Given: final List<?> values = Arrays.asList(1511897796092L, 1L, "item_1", 10.0, new Time(100), new Date(864000000L), new Timestamp(100), ByteBuffer.wrap(new byte[] {123}), new BigDecimal("10")); // When: final byte[] bytes = serializer.serialize("t1", values); // Then: final String delimitedString = new String(bytes, StandardCharsets.UTF_8); assertThat(delimitedString, equalTo("1511897796092,1,item_1,10.0,100,10,100,ew==,10")); }
public static <E> List<E> executePaginatedRequest(String request, OAuth20Service scribe, OAuth2AccessToken accessToken, Function<String, List<E>> function) { List<E> result = new ArrayList<>(); readPage(result, scribe, accessToken, addPerPageQueryParameter(request, DEFAULT_PAGE_SIZE), function); return result; }
@Test public void execute_paginated_request() { mockWebServer.enqueue(new MockResponse() .setHeader("Link", "<" + serverUrl + "/test?per_page=100&page=2>; rel=\"next\", <" + serverUrl + "/test?per_page=100&page=2>; rel=\"last\"") .setBody("A")); mockWebServer.enqueue(new MockResponse() .setHeader("Link", "<" + serverUrl + "/test?per_page=100&page=1>; rel=\"prev\", <" + serverUrl + "/test?per_page=100&page=1>; rel=\"first\"") .setBody("B")); List<String> response = executePaginatedRequest(serverUrl + "/test", oAuth20Service, auth2AccessToken, Arrays::asList); assertThat(response).contains("A", "B"); }
@Override public MutablePathKeys getPathKeys() { return _pathKeys; }
@Test public void testPathKeysImpl() throws RestLiSyntaxException { final ResourceContextImpl context = new ResourceContextImpl(); MutablePathKeys mutablePathKeys = context.getPathKeys(); mutablePathKeys.append("aKey", "aValue") .append("bKey", "bValue") .append("cKey", "cValue"); Assert.assertEquals(mutablePathKeys.getKeyMap().size(), 3); }
public EventJournalConfig setTimeToLiveSeconds(int timeToLiveSeconds) { this.timeToLiveSeconds = checkNotNegative(timeToLiveSeconds, "timeToLiveSeconds can't be smaller than 0"); return this; }
@Test(expected = UnsupportedOperationException.class) public void testReadOnlyClass_setTTL_throwsException() { getReadOnlyConfig().setTimeToLiveSeconds(20); }
CacheConfig<K, V> asCacheConfig() { return this.copy(new CacheConfig<>(), false); }
@Test public void serializationSucceeds_cacheExpiryFactory() { CacheConfig<String, Person> cacheConfig = newDefaultCacheConfig("test"); cacheConfig.setExpiryPolicyFactory(new PersonExpiryPolicyFactory()); PreJoinCacheConfig preJoinCacheConfig = new PreJoinCacheConfig(cacheConfig); Data data = serializationService.toData(preJoinCacheConfig); PreJoinCacheConfig deserialized = serializationService.toObject(data); assertEquals(preJoinCacheConfig, deserialized); assertEquals(cacheConfig, deserialized.asCacheConfig()); assertNull(deserialized.getCacheWriterFactory()); assertTrue("Invalid Factory Class", deserialized.getExpiryPolicyFactory() instanceof PersonExpiryPolicyFactory); }
public static Field toBeamField(org.apache.avro.Schema.Field field) { TypeWithNullability nullableType = new TypeWithNullability(field.schema()); FieldType beamFieldType = toFieldType(nullableType); return Field.of(field.name(), beamFieldType); }
@Test public void testNullableArrayFieldToBeamArrayField() { org.apache.avro.Schema.Field avroField = new org.apache.avro.Schema.Field( "arrayField", ReflectData.makeNullable( org.apache.avro.Schema.createArray(org.apache.avro.Schema.create(Type.INT))), "", (Object) null); Field expectedBeamField = Field.nullable("arrayField", FieldType.array(FieldType.INT32)); Field beamField = AvroUtils.toBeamField(avroField); assertEquals(expectedBeamField, beamField); }
@Override public int run(String[] args) throws Exception { try { webServiceClient = WebServiceClient.getWebServiceClient().createClient(); return runCommand(args); } finally { if (yarnClient != null) { yarnClient.close(); } if (webServiceClient != null) { webServiceClient.destroy(); } } }
@Test(timeout = 5000l) public void testFailResultCodes() throws Exception { conf.setClass("fs.file.impl", LocalFileSystem.class, FileSystem.class); LogCLIHelpers cliHelper = new LogCLIHelpers(); cliHelper.setConf(conf); YarnClient mockYarnClient = createMockYarnClient( YarnApplicationState.FINISHED, UserGroupInformation.getCurrentUser().getShortUserName()); LogsCLI dumper = new LogsCLIForTest(mockYarnClient); dumper.setConf(conf); // verify dumping a non-existent application's logs returns a failure code int exitCode = dumper.run( new String[] { "-applicationId", "application_0_0" } ); assertTrue("Should return an error code", exitCode != 0); // verify dumping a non-existent container log is a failure code exitCode = cliHelper.dumpAContainersLogs("application_0_0", "container_0_0", "nonexistentnode:1234", "nobody"); assertTrue("Should return an error code", exitCode != 0); }
public static Entry entry(String name) throws BlockException { return Env.sph.entry(name, EntryType.OUT, 1, OBJECTS0); }
@Test public void testStringEntryCountType() throws BlockException { Entry e = SphU.entry("resourceName", EntryType.IN, 2); assertSame(e.resourceWrapper.getEntryType(), EntryType.IN); e.exit(2); }
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { String returnCommand = null; String subCommand = safeReadLine(reader); if (subCommand.equals(MEMORY_DEL_SUB_COMMAND_NAME)) { returnCommand = deleteObject(reader); } else { returnCommand = Protocol.getOutputErrorCommand("Unknown Memory SubCommand Name: " + subCommand); } logger.finest("Returning command: " + returnCommand); writer.write(returnCommand); writer.flush(); }
@Test public void testDelete() { String inputCommand = "d\n" + target + "\ne\n"; try { assertTrue(gateway.getBindings().containsKey(target)); command.execute("m", new BufferedReader(new StringReader(inputCommand)), writer); assertEquals("!yv\n", sWriter.toString()); assertFalse(gateway.getBindings().containsKey(target)); command.execute("m", new BufferedReader(new StringReader(inputCommand)), writer); assertEquals("!yv\n!yv\n", sWriter.toString()); } catch (Exception e) { e.printStackTrace(); fail(); } }
public void execute(ProjectReactor reactor) { executeProjectBuilders(projectBuilders, reactor, "Execute project builders"); }
@Test public void testProjectBuilderFailsWithoutToString() { ProjectBuilder[] projectBuilders = {new MyProjectBuilder()}; assertThatThrownBy(() -> new ProjectBuildersExecutor(mock(GlobalConfiguration.class), projectBuilders).execute(reactor)) .isInstanceOf(MessageException.class) .hasMessage("Failed to execute project builder: org.sonar.scanner.scan.ProjectBuildersExecutorTest$MyProjectBuilder"); }
public Map<String, Gauge<Long>> gauges() { Map<String, Gauge<Long>> gauges = new HashMap<>(); final TrafficCounter tc = trafficCounter(); gauges.put(READ_BYTES_1_SEC, new Gauge<Long>() { @Override public Long getValue() { return tc.lastReadBytes(); } }); gauges.put(WRITTEN_BYTES_1_SEC, new Gauge<Long>() { @Override public Long getValue() { return tc.lastWrittenBytes(); } }); gauges.put(READ_BYTES_TOTAL, new Gauge<Long>() { @Override public Long getValue() { return tc.cumulativeReadBytes(); } }); gauges.put(WRITTEN_BYTES_TOTAL, new Gauge<Long>() { @Override public Long getValue() { return tc.cumulativeWrittenBytes(); } }); return gauges; }
@Test @Ignore("Flaky test") public void counterReturnsReadBytes() throws InterruptedException { final ByteBuf byteBuf = Unpooled.copiedBuffer("Test", StandardCharsets.US_ASCII); channel.writeInbound(byteBuf); Thread.sleep(1000L); channel.writeInbound(byteBuf); channel.finish(); final Map<String, Gauge<Long>> gauges = throughputCounter.gauges(); assertThat(gauges.get(ThroughputCounter.READ_BYTES_1_SEC).getValue()).isEqualTo(4L); assertThat(gauges.get(ThroughputCounter.WRITTEN_BYTES_1_SEC).getValue()).isEqualTo(0L); assertThat(gauges.get(ThroughputCounter.READ_BYTES_TOTAL).getValue()).isEqualTo(8L); assertThat(gauges.get(ThroughputCounter.WRITTEN_BYTES_TOTAL).getValue()).isEqualTo(0L); }
@Override public void registerQuery(ManagedQueryExecution queryExecution) { QueryId queryId = queryExecution.getBasicQueryInfo().getQueryId(); queries.computeIfAbsent(queryId, unused -> { AtomicLong sequenceId = new AtomicLong(); PeriodicTaskExecutor taskExecutor = new PeriodicTaskExecutor( queryHeartbeatInterval.toMillis(), executor, () -> sendQueryHeartbeat(queryExecution, sequenceId.incrementAndGet())); taskExecutor.start(); return taskExecutor; }); queryExecution.addStateChangeListener(newState -> { if (newState.isDone()) { queries.computeIfPresent(queryId, (unused, queryHeartbeatSender) -> { queryHeartbeatSender.forceRun(); queryHeartbeatSender.stop(); return null; }); } }); }
@Test(timeOut = 6_000) public void testQueryHeartbeat() throws Exception { MockManagedQueryExecution queryExecution = new MockManagedQueryExecution(1); sender.registerQuery(queryExecution); Thread.sleep(SLEEP_DURATION); int queryHeartbeats = resourceManagerClient.getQueryHeartbeats(); assertTrue(queryHeartbeats > TARGET_HEARTBEATS * 0.5 && queryHeartbeats <= TARGET_HEARTBEATS * 1.5, format("Expect number of heartbeats to fall within target range (%s), +/- 50%%. Was: %s", TARGET_HEARTBEATS, queryHeartbeats)); // Completing the query stops the heartbeats queryExecution.complete(); queryHeartbeats = resourceManagerClient.getQueryHeartbeats(); Thread.sleep(SLEEP_DURATION); assertTrue(resourceManagerClient.getQueryHeartbeats() <= (queryHeartbeats + 1)); }
public static void changeLocalFilePermission(String filePath, String perms) { try { Files.setPosixFilePermissions(Paths.get(filePath), PosixFilePermissions.fromString(perms)); } catch (UnsupportedOperationException e) { throw new UnimplementedRuntimeException(e, ErrorType.External); } catch (ClassCastException e) { throw new InvalidArgumentRuntimeException(e); } catch (SecurityException e) { throw new PermissionDeniedRuntimeException(e); } catch (IOException e) { throw new UnknownRuntimeException(e); } }
@Test public void changeNonExistentFile() { File ghostFile = new File(mTestFolder.getRoot(), "ghost.txt"); Assert.assertThrows(UnknownRuntimeException.class, () -> FileUtils.changeLocalFilePermission(ghostFile.getAbsolutePath(), "rwxrwxrwx")); }
@Override public void close() { close(Duration.ofMillis(Long.MAX_VALUE)); }
@Test public void testSerializerClose() { Map<String, Object> configs = new HashMap<>(); configs.put(ProducerConfig.CLIENT_ID_CONFIG, "testConstructorClose"); configs.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9999"); configs.put(ProducerConfig.METRIC_REPORTER_CLASSES_CONFIG, MockMetricsReporter.class.getName()); configs.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, CommonClientConfigs.DEFAULT_SECURITY_PROTOCOL); final int oldInitCount = MockSerializer.INIT_COUNT.get(); final int oldCloseCount = MockSerializer.CLOSE_COUNT.get(); KafkaProducer<byte[], byte[]> producer = new KafkaProducer<>( configs, new MockSerializer(), new MockSerializer()); assertEquals(oldInitCount + 2, MockSerializer.INIT_COUNT.get()); assertEquals(oldCloseCount, MockSerializer.CLOSE_COUNT.get()); producer.close(); assertEquals(oldInitCount + 2, MockSerializer.INIT_COUNT.get()); assertEquals(oldCloseCount + 2, MockSerializer.CLOSE_COUNT.get()); }
@Operation(summary = "confirm pincode", tags = { SwaggerConfig.ACTIVATE_WEBSITE, SwaggerConfig.REQUEST_ACCOUNT_AND_APP, SwaggerConfig.ACTIVATE_SMS, SwaggerConfig.ACTIVATE_LETTER, SwaggerConfig.ACTIVATE_RDA, SwaggerConfig.ACTIVATE_WITH_APP, SwaggerConfig.RS_ACTIVATE_WITH_APP}, operationId = "pincode", parameters = {@Parameter(ref = "API-V"), @Parameter(ref = "OS-T"), @Parameter(ref = "APP-V"), @Parameter(ref = "OS-V"), @Parameter(ref = "REL-T")}) @PostMapping(value = "pincode", produces = "application/json") @ResponseBody public AppResponse setPincode(@Valid @RequestBody ActivateAppRequest request) throws FlowNotDefinedException, NoSuchAlgorithmException, FlowStateNotDefinedException, IOException, SharedServiceClientException { return service.processAction(ActivationFlowFactory.TYPE, Action.SET_PINCODE, request); }
@Test void validateIfCorrectProcessesAreCalledSetPincode() throws FlowNotDefinedException, NoSuchAlgorithmException, IOException, FlowStateNotDefinedException, SharedServiceClientException { ActivateAppRequest request = new ActivateAppRequest(); activationController.setPincode(request); verify(flowService, times(1)).processAction(anyString(), any(Action.class), any(ActivateAppRequest.class)); }
public boolean shouldDropFrame(final InetSocketAddress address, final UnsafeBuffer buffer, final int length) { return false; }
@Test void shouldDropForIndependentStreams() { final FixedLossGenerator fixedLossGenerator = new FixedLossGenerator(0, 50, 1408); assertTrue(fixedLossGenerator.shouldDropFrame(null, null, 123, 456, 0, 0, 1408)); assertTrue(fixedLossGenerator.shouldDropFrame(null, null, 123, 456, 0, 1408, 1408)); assertFalse(fixedLossGenerator.shouldDropFrame(null, null, 123, 456, 0, 2 * 1408, 1408)); assertTrue(fixedLossGenerator.shouldDropFrame(null, null, 123, 457, 0, 0, 1408)); assertTrue(fixedLossGenerator.shouldDropFrame(null, null, 123, 457, 0, 1408, 1408)); assertFalse(fixedLossGenerator.shouldDropFrame(null, null, 123, 457, 0, 2 * 1408, 1408)); assertTrue(fixedLossGenerator.shouldDropFrame(null, null, 124, 456, 0, 0, 1408)); assertTrue(fixedLossGenerator.shouldDropFrame(null, null, 124, 456, 0, 1408, 1408)); assertFalse(fixedLossGenerator.shouldDropFrame(null, null, 124, 456, 0, 2 * 1408, 1408)); assertTrue(fixedLossGenerator.shouldDropFrame(null, null, 124, 457, 0, 0, 1408)); assertTrue(fixedLossGenerator.shouldDropFrame(null, null, 124, 457, 0, 1408, 1408)); assertFalse(fixedLossGenerator.shouldDropFrame(null, null, 124, 457, 0, 2 * 1408, 1408)); }
@Override public String getName() { return _name; }
@Test public void testStringReplaceTransformFunction() { ExpressionContext expression = RequestContextUtils.getExpression(String.format("replace(%s, 'A', 'B')", STRING_ALPHANUM_SV_COLUMN)); TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap); assertTrue(transformFunction instanceof ScalarTransformFunctionWrapper); assertEquals(transformFunction.getName(), "replace"); String[] expectedValues = new String[NUM_ROWS]; for (int i = 0; i < NUM_ROWS; i++) { expectedValues[i] = StringUtils.replace(_stringAlphaNumericSVValues[i], "A", "B"); } testTransformFunction(transformFunction, expectedValues); }
@VisibleForTesting protected void copyFromHost(MapHost host) throws IOException { // reset retryStartTime for a new host retryStartTime = 0; // Get completed maps on 'host' List<TaskAttemptID> maps = scheduler.getMapsForHost(host); // Sanity check to catch hosts with only 'OBSOLETE' maps, // especially at the tail of large jobs if (maps.size() == 0) { return; } if (LOG.isDebugEnabled()) { LOG.debug("Fetcher " + id + " going to fetch from " + host + " for: " + maps); } // List of maps to be fetched yet Set<TaskAttemptID> remaining = new HashSet<TaskAttemptID>(maps); // Construct the url and connect URL url = getMapOutputURL(host, maps); DataInputStream input = null; try { input = openShuffleUrl(host, remaining, url); if (input == null) { return; } // Loop through available map-outputs and fetch them // On any error, faildTasks is not null and we exit // after putting back the remaining maps to the // yet_to_be_fetched list and marking the failed tasks. TaskAttemptID[] failedTasks = null; while (!remaining.isEmpty() && failedTasks == null) { try { failedTasks = copyMapOutput(host, input, remaining, fetchRetryEnabled); } catch (IOException e) { IOUtils.cleanupWithLogger(LOG, input); // // Setup connection again if disconnected by NM connection.disconnect(); // Get map output from remaining tasks only. url = getMapOutputURL(host, remaining); input = openShuffleUrl(host, remaining, url); if (input == null) { return; } } } if(failedTasks != null && failedTasks.length > 0) { LOG.warn("copyMapOutput failed for tasks "+Arrays.toString(failedTasks)); scheduler.hostFailed(host.getHostName()); for(TaskAttemptID left: failedTasks) { scheduler.copyFailed(left, host, true, false); } } // Sanity check if (failedTasks == null && !remaining.isEmpty()) { throw new IOException("server didn't return all expected map outputs: " + remaining.size() + " left."); } input.close(); input = null; } finally { if (input != null) { IOUtils.cleanupWithLogger(LOG, input); input = null; } for (TaskAttemptID left : remaining) { scheduler.putBackKnownMapOutput(host, left); } } }
@SuppressWarnings("unchecked") @Test(timeout=10000) public void testCopyFromHostWithRetryUnreserve() throws Exception { InMemoryMapOutput<Text, Text> immo = mock(InMemoryMapOutput.class); Fetcher<Text,Text> underTest = new FakeFetcher<Text,Text>(jobWithRetry, id, ss, mm, r, metrics, except, key, connection); String replyHash = SecureShuffleUtils.generateHash(encHash.getBytes(), key); when(connection.getResponseCode()).thenReturn(200); when(connection.getHeaderField(SecureShuffleUtils.HTTP_HEADER_REPLY_URL_HASH)) .thenReturn(replyHash); ShuffleHeader header = new ShuffleHeader(map1ID.toString(), 10, 10, 1); ByteArrayOutputStream bout = new ByteArrayOutputStream(); header.write(new DataOutputStream(bout)); ByteArrayInputStream in = new ByteArrayInputStream(bout.toByteArray()); when(connection.getInputStream()).thenReturn(in); when(connection.getHeaderField(ShuffleHeader.HTTP_HEADER_NAME)) .thenReturn(ShuffleHeader.DEFAULT_HTTP_HEADER_NAME); when(connection.getHeaderField(ShuffleHeader.HTTP_HEADER_VERSION)) .thenReturn(ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION); // Verify that unreserve occurs if an exception happens after shuffle // buffer is reserved. when(mm.reserve(any(TaskAttemptID.class), anyLong(), anyInt())) .thenReturn(immo); doThrow(new IOException("forced error")).when(immo).shuffle( any(MapHost.class), any(InputStream.class), anyLong(), anyLong(), any(ShuffleClientMetrics.class), any(Reporter.class)); underTest.copyFromHost(host); verify(immo).abort(); }
@Override public void configure(final Map<String, ?> configs, final boolean isKey) { this.isKey = isKey; delegate.configure(configs, isKey); }
@Test public void shouldConfigureDelegate() { // Given: final Map<String, ?> configs = ImmutableMap.of("some", "thing"); // When: deserializer.configure(configs, true); // Then: verify(delegate).configure(configs, true); }
static JavaType constructType(Type type) { try { return constructTypeInner(type); } catch (Exception e) { throw new InvalidDataTableTypeException(type, e); } }
@Test void should_provide_canonical_representation_of_list_of_object() { JavaType javaType = TypeFactory.constructType(LIST_OF_OBJECT); assertThat(javaType.getTypeName(), is(LIST_OF_OBJECT.getTypeName())); }
@Override public RecordStore getExistingRecordStore(int partitionId, String mapName) { return getPartitionContainer(partitionId).getExistingRecordStore(mapName); }
@Test(expected = AssertionError.class) @RequireAssertEnabled public void testGetExistingRecordStore_withGenericPartitionId() { mapServiceContext.getExistingRecordStore(GENERIC_PARTITION_ID, "anyMap"); }
public static DataType appendRowFields(DataType dataType, List<DataTypes.Field> fields) { Preconditions.checkArgument(dataType.getLogicalType().is(ROW), "Row data type expected."); if (fields.size() == 0) { return dataType; } DataType newRow = Stream.concat(DataType.getFields(dataType).stream(), fields.stream()) .collect(Collectors.collectingAndThen(Collectors.toList(), DataTypes::ROW)); if (!dataType.getLogicalType().isNullable()) { newRow = newRow.notNull(); } return newRow; }
@Test void testAppendRowFields() { assertThat( DataTypeUtils.appendRowFields( ROW( FIELD("a0", BOOLEAN()), FIELD("a1", DOUBLE()), FIELD("a2", INT())), Arrays.asList(FIELD("a3", BIGINT()), FIELD("a4", TIMESTAMP(3))))) .isEqualTo( ROW( FIELD("a0", BOOLEAN()), FIELD("a1", DOUBLE()), FIELD("a2", INT()), FIELD("a3", BIGINT()), FIELD("a4", TIMESTAMP(3)))); assertThat( DataTypeUtils.appendRowFields( ROW(), Arrays.asList(FIELD("a", BOOLEAN()), FIELD("b", INT())))) .isEqualTo(ROW(FIELD("a", BOOLEAN()), FIELD("b", INT()))); }
@Override public void onIssue(Component component, DefaultIssue issue) { if (issue.authorLogin() != null) { return; } loadScmChangesets(component); Optional<String> scmAuthor = guessScmAuthor(issue, component); if (scmAuthor.isPresent()) { if (scmAuthor.get().length() <= IssueDto.AUTHOR_MAX_SIZE) { issueUpdater.setNewAuthor(issue, scmAuthor.get(), changeContext); } else { LOGGER.debug("SCM account '{}' is too long to be stored as issue author", scmAuthor.get()); } } if (issue.assignee() == null) { UserIdDto userId = scmAuthor.map(scmAccountToUser::getNullable).orElse(defaultAssignee.loadDefaultAssigneeUserId()); issueUpdater.setNewAssignee(issue, userId, changeContext); } }
@Test void assign_to_default_assignee_if_no_author() { DefaultIssue issue = newIssueOnLines(); when(defaultAssignee.loadDefaultAssigneeUserId()).thenReturn(new UserIdDto("u123", "john")); underTest.onIssue(FILE, issue); assertThat(issue.assignee()).isEqualTo("u123"); assertThat(issue.assigneeLogin()).isEqualTo("john"); }
public static Collection<File> getFileResourcesFromDirectory(File directory, Pattern pattern) { if (directory == null || directory.listFiles() == null) { return Collections.emptySet(); } return Arrays.stream(Objects.requireNonNull(directory.listFiles())) .flatMap( elem -> { if (elem.isDirectory()) { return getFileResourcesFromDirectory(elem, pattern).stream(); } else { try { if (pattern.matcher(elem.getCanonicalPath()).matches()) { return Stream.of(elem); } } catch (final IOException e) { throw new RuntimeException("Failed to retrieve resources from directory " + directory.getAbsolutePath() + " with pattern " + pattern.pattern(), e); } } return Stream.empty(); }) .collect(Collectors.toSet()); }
@Test public void getResourcesFromDirectoryNotExisting() { File directory = new File("." + File.separator + "target" + File.separator + "test-classes"); Pattern pattern = Pattern.compile(".*arg"); final Collection<File> retrieved = getFileResourcesFromDirectory(directory, pattern); commonVerifyCollectionWithoutExpectedFile(retrieved); }
@Override public int drainTo(Collection<? super V> c) { return get(drainToAsync(c)); }
@Test public void testDrainToSingle() { RBlockingQueue<Integer> queue = getQueue(); Assertions.assertTrue(queue.add(1)); Assertions.assertEquals(1, queue.size()); Set<Integer> batch = new HashSet<Integer>(); int count = queue.drainTo(batch); Assertions.assertEquals(1, count); Assertions.assertEquals(1, batch.size()); Assertions.assertTrue(queue.isEmpty()); }
@Override public int getOutdegree(int vertex) { return graph[vertex].size(); }
@Test public void testGetOutdegree() { System.out.println("getOutdegree"); assertEquals(0, g1.getOutdegree(1)); assertEquals(1, g2.getOutdegree(1)); g2.addEdge(1, 1); assertEquals(2, g2.getOutdegree(1)); assertEquals(2, g3.getOutdegree(1)); assertEquals(2, g3.getOutdegree(2)); assertEquals(2, g3.getOutdegree(3)); assertEquals(1, g4.getOutdegree(4)); assertEquals(0, g5.getOutdegree(1)); assertEquals(1, g6.getOutdegree(1)); g6.addEdge(1, 1); assertEquals(2, g6.getOutdegree(1)); assertEquals(2, g7.getOutdegree(1)); assertEquals(2, g7.getOutdegree(2)); assertEquals(2, g7.getOutdegree(3)); assertEquals(2, g8.getOutdegree(4)); }
@VisibleForTesting static Optional<String> performUpdateCheck( Path configDir, String currentVersion, String versionUrl, String toolName, Consumer<LogEvent> log) { Path lastUpdateCheck = configDir.resolve(LAST_UPDATE_CHECK_FILENAME); try { // Check time of last update check if (Files.exists(lastUpdateCheck)) { try { String fileContents = new String(Files.readAllBytes(lastUpdateCheck), StandardCharsets.UTF_8); Instant modifiedTime = Instant.parse(fileContents); if (modifiedTime.plus(Duration.ofDays(1)).isAfter(Instant.now())) { return Optional.empty(); } } catch (DateTimeParseException | IOException ex) { // If reading update time failed, file might be corrupt, so delete it log.accept(LogEvent.debug("Failed to read lastUpdateCheck; " + ex.getMessage())); Files.delete(lastUpdateCheck); } } // Check for update FailoverHttpClient httpClient = new FailoverHttpClient(true, false, ignored -> {}); try { Response response = httpClient.get( new URL(versionUrl), Request.builder() .setHttpTimeout(3000) .setUserAgent("jib " + currentVersion + " " + toolName) .build()); VersionJsonTemplate version = JsonTemplateMapper.readJson(response.getBody(), VersionJsonTemplate.class); Path lastUpdateCheckTemp = Files.createTempFile(configDir, LAST_UPDATE_CHECK_FILENAME, null); lastUpdateCheckTemp.toFile().deleteOnExit(); Files.write(lastUpdateCheckTemp, Instant.now().toString().getBytes(StandardCharsets.UTF_8)); Files.move(lastUpdateCheckTemp, lastUpdateCheck, StandardCopyOption.REPLACE_EXISTING); if (currentVersion.equals(version.latest)) { return Optional.empty(); } return Optional.of(version.latest); } finally { httpClient.shutDown(); } } catch (IOException ex) { log.accept(LogEvent.debug("Update check failed; " + ex.getMessage())); } return Optional.empty(); }
@Test public void testPerformUpdateCheck_newVersionFound() throws IOException, InterruptedException { Instant before = Instant.now(); Thread.sleep(100); setupLastUpdateCheck(); Optional<String> message = UpdateChecker.performUpdateCheck( configDir, "1.0.2", testWebServer.getEndpoint(), "tool-name", ignored -> {}); assertThat(testWebServer.getInputRead()).contains("User-Agent: jib 1.0.2 tool-name"); assertThat(message).hasValue("2.0.0"); String modifiedTime = new String( Files.readAllBytes(configDir.resolve("lastUpdateCheck")), StandardCharsets.UTF_8); assertThat(Instant.parse(modifiedTime)).isGreaterThan(before); }
public static Path getConfigHome() { return getConfigHome(System.getProperties(), System.getenv()); }
@Test public void testGetConfigHome_hasXdgConfigHome() { Properties fakeProperties = new Properties(); fakeProperties.setProperty("user.home", fakeConfigHome); Map<String, String> fakeEnvironment = ImmutableMap.of("XDG_CONFIG_HOME", fakeConfigHome); fakeProperties.setProperty("os.name", "linux"); Assert.assertEquals( Paths.get(fakeConfigHome).resolve("google-cloud-tools-java").resolve("jib"), XdgDirectories.getConfigHome(fakeProperties, fakeEnvironment)); fakeProperties.setProperty("os.name", "windows"); Assert.assertEquals( Paths.get(fakeConfigHome).resolve("Google").resolve("Jib").resolve("Config"), XdgDirectories.getConfigHome(fakeProperties, fakeEnvironment)); fakeProperties.setProperty("os.name", "mac"); Assert.assertEquals( Paths.get(fakeConfigHome).resolve("Google").resolve("Jib"), XdgDirectories.getConfigHome(fakeProperties, fakeEnvironment)); }
public void deregister(CacheEntryListenerConfiguration<K, V> configuration) { requireNonNull(configuration); dispatchQueues.keySet().removeIf(registration -> configuration.equals(registration.getConfiguration())); }
@Test public void deregister() { var dispatcher = new EventDispatcher<Integer, Integer>(Runnable::run); var configuration = new MutableCacheEntryListenerConfiguration<>( () -> createdListener, null, false, false); dispatcher.register(configuration); dispatcher.deregister(configuration); assertThat(dispatcher.dispatchQueues).isEmpty(); }
public Path getLocalPathToRead(String pathStr, Configuration conf) throws IOException { AllocatorPerContext context = obtainContext(contextCfgItemName); return context.getLocalPathToRead(pathStr, conf); }
@Test (timeout = 30000) public void testGetLocalPathToRead() throws IOException { assumeNotWindows(); String dir = buildBufferDir(ROOT, 0); try { conf.set(CONTEXT, dir); assertTrue(localFs.mkdirs(new Path(dir))); File f1 = dirAllocator.createTmpFileForWrite(FILENAME, SMALL_FILE_SIZE, conf); Path p1 = dirAllocator.getLocalPathToRead(f1.getName(), conf); assertEquals(f1.getName(), p1.getName()); assertEquals("file", p1.getFileSystem(conf).getUri().getScheme()); } finally { Shell.execCommand(Shell.getSetPermissionCommand("u+w", false, BUFFER_DIR_ROOT)); rmBufferDirs(); } }
@Override public Iterator<T> iterator() { return new LinkedSetIterator(); }
@Test public void testOneElementBasic() { LOG.info("Test one element basic"); set.add(list.get(0)); // set should be non-empty assertEquals(1, set.size()); assertFalse(set.isEmpty()); // iterator should have next Iterator<Integer> iter = set.iterator(); assertTrue(iter.hasNext()); // iterator should not have next assertEquals(list.get(0), iter.next()); assertFalse(iter.hasNext()); LOG.info("Test one element basic - DONE"); }
public static Class<?> getLiteral(String className, String literal) { LiteralAnalyzer analyzer = ANALYZERS.get( className ); Class result = null; if ( analyzer != null ) { analyzer.validate( literal ); result = analyzer.getLiteral(); } return result; }
@Test public void testShortAndByte() { assertThat( getLiteral( short.class.getCanonicalName(), "0xFE" ) ).isNotNull(); // some examples of ints assertThat( getLiteral( byte.class.getCanonicalName(), "0" ) ).isNotNull(); assertThat( getLiteral( byte.class.getCanonicalName(), "2" ) ).isNotNull(); assertThat( getLiteral( byte.class.getCanonicalName(), "127" ) ).isNotNull(); assertThat( getLiteral( byte.class.getCanonicalName(), "-128" ) ).isNotNull(); assertThat( getLiteral( short.class.getCanonicalName(), "1996" ) ).isNotNull(); assertThat( getLiteral( short.class.getCanonicalName(), "-1996" ) ).isNotNull(); }
@SuppressWarnings("unchecked") public <V> V run(String callableName, RetryOperation<V> operation) { int attempt = 1; while (true) { try { return operation.run(); } catch (Exception e) { if (!exceptionClass.isInstance(e)) { throwIfUnchecked(e); throw new RuntimeException(e); } E qe = (E) e; exceptionCallback.accept(qe); if (attempt >= maxAttempts || !retryPredicate.test(qe)) { throw qe; } attempt++; int delayMillis = (int) min(minBackoffDelay.toMillis() * pow(scaleFactor, attempt - 1), maxBackoffDelay.toMillis()); int jitterMillis = ThreadLocalRandom.current().nextInt(max(1, (int) (delayMillis * 0.1))); log.info( "Failed on executing %s with attempt %d. Retry after %sms. Cause: %s", callableName, attempt - 1, delayMillis, qe.getMessage()); try { MILLISECONDS.sleep(delayMillis + jitterMillis); } catch (InterruptedException ie) { currentThread().interrupt(); throw new RuntimeException(ie); } } } }
@Test(timeOut = 5000) public void testBackoffTimeCapped() { RetryDriver retryDriver = new RetryDriver<>( new RetryConfig() .setMaxAttempts(5) .setMinBackoffDelay(new Duration(10, MILLISECONDS)) .setMaxBackoffDelay(new Duration(100, MILLISECONDS)) .setScaleFactor(1000), QueryException::isRetryable, QueryException.class, verificationContext::addException); retryDriver.run("test", new MockOperation(5, RETRYABLE_EXCEPTION)); }
public void setSimpleLoadBalancerState(SimpleLoadBalancerState state) { _watcherManager.updateWatcher(state, this::doRegisterLoadBalancerState); doRegisterLoadBalancerState(state, null); state.register(new SimpleLoadBalancerStateListener() { @Override public void onStrategyAdded(String serviceName, String scheme, LoadBalancerStrategy strategy) { _watcherManager.updateWatcher(serviceName, scheme, strategy, (item, mode) -> doRegisterLoadBalancerStrategy(serviceName, scheme, item, mode)); doRegisterLoadBalancerStrategy(serviceName, scheme, strategy, null); } @Override public void onStrategyRemoved(String serviceName, String scheme, LoadBalancerStrategy strategy) { _watcherManager.removeWatcherForLoadBalancerStrategy(serviceName, scheme); _jmxManager.unregister(getLoadBalancerStrategyJmxName(serviceName, scheme, null)); } @Override public void onClientAdded(String clusterName, TrackerClient client) { // We currently think we can make this no-op as the info provided is not helpful // _jmxManager.checkReg(new DegraderControl((DegraderImpl) client.getDegrader(DefaultPartitionAccessor.DEFAULT_PARTITION_ID)), // _prefix + "-" + clusterName + "-" + client.getUri().toString().replace("://", "-") + "-TrackerClient-Degrader"); } @Override public void onClientRemoved(String clusterName, TrackerClient client) { // We currently think we can make this no-op as the info provided is not helpful // _jmxManager.unregister(_prefix + "-" + clusterName + "-" + client.getUri().toString().replace("://", "-") + "-TrackerClient-Degrader"); } @Override public void onClusterInfoUpdate(ClusterInfoItem clusterInfoItem) { if (clusterInfoItem != null && clusterInfoItem.getClusterPropertiesItem() != null && clusterInfoItem.getClusterPropertiesItem().getProperty() != null) { String clusterName = clusterInfoItem.getClusterPropertiesItem().getProperty().getClusterName(); _watcherManager.updateWatcher(clusterName, clusterInfoItem, (item, mode) -> doRegisterClusterInfo(clusterName, item, mode)); doRegisterClusterInfo(clusterName, clusterInfoItem, null); } } @Override public void onClusterInfoRemoval(ClusterInfoItem clusterInfoItem) { if (clusterInfoItem != null && clusterInfoItem.getClusterPropertiesItem() != null && clusterInfoItem.getClusterPropertiesItem().getProperty() != null) { String clusterName = clusterInfoItem.getClusterPropertiesItem().getProperty().getClusterName(); _watcherManager.removeWatcherForClusterInfoItem(clusterName); _jmxManager.unregister(getClusterInfoJmxName(clusterName, null)); } } @Override public void onServicePropertiesUpdate(LoadBalancerStateItem<ServiceProperties> serviceProperties) { if (serviceProperties != null && serviceProperties.getProperty() != null) { String serviceName = serviceProperties.getProperty().getServiceName(); _watcherManager.updateWatcher(serviceName, serviceProperties, (item, mode) -> doRegisterServiceProperties(serviceName, item, mode)); doRegisterServiceProperties(serviceName, serviceProperties, null); } } @Override public void onServicePropertiesRemoval(LoadBalancerStateItem<ServiceProperties> serviceProperties) { if (serviceProperties != null && serviceProperties.getProperty() != null) { String serviceName = serviceProperties.getProperty().getServiceName(); _watcherManager.removeWatcherForServiceProperties(serviceName); _jmxManager.unregister(getServicePropertiesJmxName(serviceName, null)); } } private void doRegisterLoadBalancerStrategy(String serviceName, String scheme, LoadBalancerStrategy strategy, @Nullable DualReadModeProvider.DualReadMode mode) { String jmxName = getLoadBalancerStrategyJmxName(serviceName, scheme, mode); _jmxManager.registerLoadBalancerStrategy(jmxName, strategy); } private void doRegisterClusterInfo(String clusterName, ClusterInfoItem clusterInfoItem, @Nullable DualReadModeProvider.DualReadMode mode) { String jmxName = getClusterInfoJmxName(clusterName, mode); _jmxManager.registerClusterInfo(jmxName, clusterInfoItem); } private void doRegisterServiceProperties(String serviceName, LoadBalancerStateItem<ServiceProperties> serviceProperties, @Nullable DualReadModeProvider.DualReadMode mode) { _jmxManager.registerServiceProperties(getServicePropertiesJmxName(serviceName, mode), serviceProperties); } private String getClusterInfoJmxName(String clusterName, @Nullable DualReadModeProvider.DualReadMode mode) { return String.format("%s%s-ClusterInfo", getClusterPrefixForLBPropertyJmxNames(clusterName, mode), clusterName); } private String getServicePropertiesJmxName(String serviceName, @Nullable DualReadModeProvider.DualReadMode mode) { return String.format("%s%s-ServiceProperties", getServicePrefixForLBPropertyJmxNames(serviceName, mode), serviceName); } private String getLoadBalancerStrategyJmxName(String serviceName, String scheme, @Nullable DualReadModeProvider.DualReadMode mode) { return String.format("%s%s-%s-LoadBalancerStrategy", getServicePrefixForLBPropertyJmxNames(serviceName, mode), serviceName, scheme); } }); }
@Test(dataProvider = "nonDualReadD2ClientJmxManagers") public void testSetSimpleLBStateListenerUpdateServiceProperties(String prefix, D2ClientJmxManager.DiscoverySourceType sourceType, Boolean isDualReadLB) { D2ClientJmxManagerFixture fixture = new D2ClientJmxManagerFixture(); D2ClientJmxManager d2ClientJmxManager = fixture.getD2ClientJmxManager(prefix, sourceType, isDualReadLB); d2ClientJmxManager.setSimpleLoadBalancerState(fixture._simpleLoadBalancerState); fixture._simpleLoadBalancerStateListenerCaptor.getValue().onServicePropertiesUpdate(null); Mockito.verify(fixture._jmxManager, never()).registerServiceProperties(any(), any()); fixture._simpleLoadBalancerStateListenerCaptor.getValue().onServicePropertiesUpdate(NO_PROPERTY_LB_STATE_ITEM); Mockito.verify(fixture._jmxManager, never()).registerServiceProperties(any(), any()); fixture._simpleLoadBalancerStateListenerCaptor.getValue().onServicePropertiesUpdate( SERVICE_PROPERTIES_LOAD_BALANCER_STATE_ITEM); Assert.assertEquals( fixture._registerObjectNameCaptor.getValue(), "S_Foo-ServiceProperties" ); Assert.assertEquals( fixture._servicePropertiesArgumentCaptor.getValue(), SERVICE_PROPERTIES_LOAD_BALANCER_STATE_ITEM ); }
@UdafFactory(description = "collect values of a field into a single Array") public static <T> TableUdaf<T, List<T>, List<T>> createCollectListT() { return new Collect<>(); }
@Test public void shouldRespectSizeLimitString() { final TableUdaf<Integer, List<Integer>, List<Integer>> udaf = CollectListUdaf.createCollectListT(); ((Configurable) udaf).configure(ImmutableMap.of(CollectListUdaf.LIMIT_CONFIG, "10")); List<Integer> runningList = udaf.initialize(); for (int i = 1; i < 25; i++) { runningList = udaf.aggregate(i, runningList); } assertThat(runningList, hasSize(10)); assertThat(runningList, hasItem(1)); assertThat(runningList, hasItem(10)); assertThat(runningList, not(hasItem(11))); }
public static MessageDigest digest(String algorithm) { final Matcher matcher = WITH_PATTERN.matcher(algorithm); final String digestAlgorithm = matcher.matches() ? matcher.group(1) : algorithm; try { return MessageDigest.getInstance(digestAlgorithm); } catch (NoSuchAlgorithmException e) { throw new CryptoException("Invalid algorithm", e); } }
@Test public void digestUsingAlgorithmIdentifier() { assertEquals("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS", Hex.toHexString( DigestUtils.digest(new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.3.14.3.2.26"))).digest(new byte[0]) )); }
@Override public int getColumnCount() { return 1; }
@Test void assertGetColumnCount() throws SQLException { assertThat(actualMetaData.getColumnCount(), is(1)); }
public GenericRow createRow(final KeyValue<List<?>, GenericRow> row) { if (row.value() != null) { throw new IllegalArgumentException("Not a tombstone: " + row); } final List<?> key = row.key(); if (key.size() < keyIndexes.size()) { throw new IllegalArgumentException("Not enough key columns. " + "expected at least" + keyIndexes.size() + ", got: " + key); } final GenericRow values = new GenericRow(numColumns); for (int columnIdx = 0; columnIdx < numColumns; columnIdx++) { final Integer keyIdx = keyIndexes.get(columnIdx); if (keyIdx == null) { values.append(null); } else { values.append(key.get(keyIdx)); } } return values; }
@Test public void shouldHandleKeyColumnNotInProjection() { // Given: givenSchema(LogicalSchema.builder() .keyColumn(ColumnName.of("K1"), SqlTypes.INTEGER) .keyColumn(ColumnName.of("K2"), SqlTypes.INTEGER) .valueColumn(ColumnName.of("V0"), SqlTypes.INTEGER) .valueColumn(ColumnName.of("V1"), SqlTypes.INTEGER) .valueColumn(ColumnName.of("V2"), SqlTypes.INTEGER) .build()); final KeyValue<List<?>, GenericRow> kv = KeyValue.keyValue( ImmutableList.of(4), null ); // When: final GenericRow result = factory.createRow(kv); // Then: assertThat(result, is(genericRow(null, null, null))); }
@AfterStartUp(order = AfterStartUp.BEFORE_TRANSPORT_SERVICE) public void init() { List<LwM2MModelConfig> models = modelStore.getAll(); log.debug("Fetched model configs: {}", models); currentModelConfigs = models.stream() .collect(Collectors.toConcurrentMap(LwM2MModelConfig::getEndpoint, m -> m, (existing, replacement) -> existing)); }
@Test void testInitWithEmptyModels() { willReturn(Collections.emptyList()).given(modelStore).getAll(); service.init(); assertThat(service.currentModelConfigs).isEmpty(); }
@Override public void onBeginFailure(GlobalTransaction tx, Throwable cause) { LOGGER.warn("Failed to begin transaction. ", cause); }
@Test void onBeginFailure() { RootContext.bind(DEFAULT_XID); GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate(); FailureHandler failureHandler = new DefaultFailureHandlerImpl(); failureHandler.onBeginFailure(tx, new MyRuntimeException("").getCause()); }
@SuppressWarnings("unchecked") public static <T> Promise<T> value(final T value) { if (value == null) { if (VOID == null) { return new ResolvedValue<T>(value); } else { return (Promise<T>) VOID; } } return new ResolvedValue<T>(value); }
@Test public void testValue() { final String value = "value"; final Promise<String> promise = Promises.value(value); assertTrue(promise.isDone()); assertFalse(promise.isFailed()); assertEquals(value, promise.get()); }
@Override public DarkClusterConfigMap getDarkClusterConfigMap(String clusterName) throws ServiceUnavailableException { FutureCallback<DarkClusterConfigMap> darkClusterConfigMapFutureCallback = new FutureCallback<>(); getDarkClusterConfigMap(clusterName, darkClusterConfigMapFutureCallback); try { return darkClusterConfigMapFutureCallback.get(_timeout, _unit); } catch (ExecutionException | TimeoutException | IllegalStateException | InterruptedException e) { if (e instanceof TimeoutException || e.getCause() instanceof TimeoutException) { DarkClusterConfigMap darkClusterConfigMap = getDarkClusterConfigMapFromCache(clusterName); if (darkClusterConfigMap != null) { _log.info("Got dark cluster config map for {} timed out, used cached value instead.", clusterName); return darkClusterConfigMap; } } die("ClusterInfo", "PEGA_1018, unable to retrieve dark cluster info for cluster: " + clusterName + ", exception" + ": " + e); return new DarkClusterConfigMap(); } }
@Test public void testClusterInfoProviderGetDarkClusters() throws InterruptedException, ExecutionException, ServiceUnavailableException { int numHttp = 3; int numHttps = 4; int partitionIdForAdd = 0; MockStore<ServiceProperties> serviceRegistry = new MockStore<>(); MockStore<ClusterProperties> clusterRegistry = new MockStore<>(); MockStore<UriProperties> uriRegistry = new MockStore<>(); SimpleLoadBalancer loadBalancer = setupLoadBalancer(serviceRegistry, clusterRegistry, uriRegistry); DarkClusterConfig darkClusterConfig = new DarkClusterConfig() .setMultiplier(1.0f) .setDispatcherOutboundTargetRate(1) .setDispatcherMaxRequestsToBuffer(1) .setDispatcherBufferedRequestExpiryInSeconds(1); DarkClusterConfigMap darkClusterConfigMap = new DarkClusterConfigMap(); darkClusterConfigMap.put(DARK_CLUSTER1_NAME, darkClusterConfig); clusterRegistry.put(CLUSTER1_NAME, new ClusterProperties(CLUSTER1_NAME, Collections.emptyList(), Collections.emptyMap(), Collections.emptySet(), NullPartitionProperties.getInstance(), Collections.emptyList(), DarkClustersConverter.toProperties(darkClusterConfigMap), false)); populateUriRegistry(numHttp, numHttps, partitionIdForAdd, uriRegistry); loadBalancer.getDarkClusterConfigMap(CLUSTER1_NAME, new Callback<DarkClusterConfigMap>() { @Override public void onError(Throwable e) { Assert.fail("getDarkClusterConfigMap threw exception", e); } @Override public void onSuccess(DarkClusterConfigMap returnedDarkClusterConfigMap) { Assert.assertEquals(returnedDarkClusterConfigMap, darkClusterConfigMap, "dark cluster configs should be equal"); Assert.assertEquals(returnedDarkClusterConfigMap.get(DARK_CLUSTER1_NAME).getMultiplier(), 1.0f, "multiplier should match"); } }); }
@Override public Integer getCategoryLevel(Long id) { if (Objects.equals(id, PARENT_ID_NULL)) { return 0; } int level = 1; // for 的原因,是因为避免脏数据,导致可能的死循环。一般不会超过 100 层哈 for (int i = 0; i < Byte.MAX_VALUE; i++) { // 如果没有父节点,break 结束 ProductCategoryDO category = productCategoryMapper.selectById(id); if (category == null || Objects.equals(category.getParentId(), PARENT_ID_NULL)) { break; } // 继续递归父节点 level++; id = category.getParentId(); } return level; }
@Test public void testGetCategoryLevel() { // mock 数据 ProductCategoryDO category1 = randomPojo(ProductCategoryDO.class, o -> o.setParentId(PARENT_ID_NULL)); productCategoryMapper.insert(category1); ProductCategoryDO category2 = randomPojo(ProductCategoryDO.class, o -> o.setParentId(category1.getId())); productCategoryMapper.insert(category2); ProductCategoryDO category3 = randomPojo(ProductCategoryDO.class, o -> o.setParentId(category2.getId())); productCategoryMapper.insert(category3); // 调用,并断言 assertEquals(productCategoryService.getCategoryLevel(category1.getId()), 1); assertEquals(productCategoryService.getCategoryLevel(category2.getId()), 2); assertEquals(productCategoryService.getCategoryLevel(category3.getId()), 3); }
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void copyMessage() { MessageIdResponse response = bot.execute(new CopyMessage(chatId, chatId, forwardMessageId) .messageThreadId(0) .caption("new **caption**") .parseMode(ParseMode.MarkdownV2) .captionEntities(new MessageEntity(MessageEntity.Type.bold, 0, 1)) .allowSendingWithoutReply(false) .replyToMessageId(1) .disableNotification(true) ); assertTrue(response.messageId() > 0); }
@Override public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) { if (readError == null) { try { processHighlightings(lineBuilder); } catch (RangeOffsetConverterException e) { readError = new ReadError(HIGHLIGHTING, lineBuilder.getLine()); LOG.debug(format("Inconsistency detected in Highlighting data. Highlighting will be ignored for file '%s'", file.getKey()), e); } } return Optional.ofNullable(readError); }
@Test public void display_file_key_in_debug_when_range_offset_converter_throw_RangeOffsetConverterException() { TextRange textRange1 = newTextRange(LINE_1, LINE_1); doThrow(RangeOffsetConverterException.class).when(rangeOffsetConverter).offsetToString(textRange1, LINE_1, DEFAULT_LINE_LENGTH); HighlightingLineReader highlightingLineReader = newReader(of(textRange1, ANNOTATION)); assertThat(highlightingLineReader.read(line1)) .contains(new LineReader.ReadError(HIGHLIGHTING, 1)); assertThat(logTester.logs(DEBUG)).containsOnly("Inconsistency detected in Highlighting data. Highlighting will be ignored for file 'FILE_KEY'"); }
@Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("key="); stringBuilder.append(this.key); stringBuilder.append(", value="); stringBuilder.append(this.value); return stringBuilder.toString(); }
@Test public void toStringTest() { Tag tag = new Tag(KEY, VALUE); Assert.assertEquals(TAG_TO_STRING, tag.toString()); }
public int getFederationSubClustersFailedRetrieved() { return numGetFederationSubClustersFailedRetrieved.value(); }
@Test public void testGetFederationSubClustersFailedRetrieved() { long totalBadBefore = metrics.getFederationSubClustersFailedRetrieved(); badSubCluster.getFederationSubClustersFailedRetrieved(); Assert.assertEquals(totalBadBefore + 1, metrics.getFederationSubClustersFailedRetrieved()); }
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload, final ConnectionSession connectionSession) { switch (commandPacketType) { case COM_QUIT: return new MySQLComQuitPacket(); case COM_INIT_DB: return new MySQLComInitDbPacket(payload); case COM_FIELD_LIST: return new MySQLComFieldListPacket(payload); case COM_QUERY: return new MySQLComQueryPacket(payload); case COM_STMT_PREPARE: return new MySQLComStmtPreparePacket(payload); case COM_STMT_EXECUTE: MySQLServerPreparedStatement serverPreparedStatement = connectionSession.getServerPreparedStatementRegistry().getPreparedStatement(payload.getByteBuf().getIntLE(payload.getByteBuf().readerIndex())); return new MySQLComStmtExecutePacket(payload, serverPreparedStatement.getSqlStatementContext().getSqlStatement().getParameterCount()); case COM_STMT_SEND_LONG_DATA: return new MySQLComStmtSendLongDataPacket(payload); case COM_STMT_RESET: return new MySQLComStmtResetPacket(payload); case COM_STMT_CLOSE: return new MySQLComStmtClosePacket(payload); case COM_SET_OPTION: return new MySQLComSetOptionPacket(payload); case COM_PING: return new MySQLComPingPacket(); case COM_RESET_CONNECTION: return new MySQLComResetConnectionPacket(); default: return new MySQLUnsupportedCommandPacket(commandPacketType); } }
@Test void assertNewInstanceWithComConnectOutPacket() { assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_CONNECT_OUT, payload, connectionSession), instanceOf(MySQLUnsupportedCommandPacket.class)); }
public static void mergeParams( Map<String, ParamDefinition> params, Map<String, ParamDefinition> paramsToMerge, MergeContext context) { if (paramsToMerge == null) { return; } Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream()) .forEach( name -> { ParamDefinition paramToMerge = paramsToMerge.get(name); if (paramToMerge == null) { return; } if (paramToMerge.getType() == ParamType.MAP && paramToMerge.isLiteral()) { Map<String, ParamDefinition> baseMap = mapValueOrEmpty(params, name); Map<String, ParamDefinition> toMergeMap = mapValueOrEmpty(paramsToMerge, name); mergeParams( baseMap, toMergeMap, MergeContext.copyWithParentMode( context, params.getOrDefault(name, paramToMerge).getMode())); params.put( name, buildMergedParamDefinition( name, paramToMerge, params.get(name), context, baseMap)); } else if (paramToMerge.getType() == ParamType.STRING_MAP && paramToMerge.isLiteral()) { Map<String, String> baseMap = stringMapValueOrEmpty(params, name); Map<String, String> toMergeMap = stringMapValueOrEmpty(paramsToMerge, name); baseMap.putAll(toMergeMap); params.put( name, buildMergedParamDefinition( name, paramToMerge, params.get(name), context, baseMap)); } else { params.put( name, buildMergedParamDefinition( name, paramToMerge, params.get(name), context, paramToMerge.getValue())); } }); }
@Test public void testMergeNoOverwrite() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap( "{'tomerge1': {'type': 'STRING','value': 'hello', 'source': 'SYSTEM', 'validator': '@notEmpty'}}"); Map<String, ParamDefinition> paramsToMerge = parseParamDefMap( "{'tomerge2': {'type': 'STRING', 'value': 'goodbye', 'validator': 'param != null'}}"); ParamsMergeHelper.mergeParams(allParams, paramsToMerge, definitionContext); assertEquals(2, allParams.size()); assertEquals("hello", allParams.get("tomerge1").asStringParamDef().getValue()); assertEquals("goodbye", allParams.get("tomerge2").asStringParamDef().getValue()); assertEquals(ParamSource.SYSTEM, allParams.get("tomerge1").asStringParamDef().getSource()); assertEquals(ParamSource.DEFINITION, allParams.get("tomerge2").asStringParamDef().getSource()); assertEquals( "@notEmpty", allParams.get("tomerge1").asStringParamDef().getValidator().getRule()); assertEquals( "param != null", allParams.get("tomerge2").asStringParamDef().getValidator().getRule()); }
@Override public Object apply(Object input) { return PropertyOrFieldSupport.EXTRACTION.getValueOf(propertyOrFieldName, input); }
@Test void should_extract_single_value_from_map_by_key() { // GIVEN Map<String, Employee> map = mapOf(entry("key", YODA)); ByNameSingleExtractor underTest = new ByNameSingleExtractor("key"); // WHEN Object result = underTest.apply(map); // THEN then(result).isEqualTo(YODA); }
public static UpdateRequirement fromJson(String json) { return JsonUtil.parse(json, UpdateRequirementParser::fromJson); }
@Test public void testAssertLastAssignedFieldIdFromJson() { String requirementType = UpdateRequirementParser.ASSERT_LAST_ASSIGNED_FIELD_ID; int lastAssignedFieldId = 12; String json = String.format( "{\"type\":\"%s\",\"last-assigned-field-id\":%d}", requirementType, lastAssignedFieldId); UpdateRequirement expected = new UpdateRequirement.AssertLastAssignedFieldId(lastAssignedFieldId); assertEquals(requirementType, expected, UpdateRequirementParser.fromJson(json)); }
public static boolean isUnclosedQuote(final String line) { // CHECKSTYLE_RULES.ON: CyclomaticComplexity int quoteStart = -1; for (int i = 0; i < line.length(); ++i) { if (quoteStart < 0 && isQuoteChar(line, i)) { quoteStart = i; } else if (quoteStart >= 0 && isTwoQuoteStart(line, i) && !isEscaped(line, i)) { // Together, two quotes are effectively an escaped quote and don't act as a quote character. // Skip the next quote char, since it's coupled with the first. i++; } else if (quoteStart >= 0 && isQuoteChar(line, i) && !isEscaped(line, i)) { quoteStart = -1; } } final int commentInd = line.indexOf(COMMENT); if (commentInd < 0) { return quoteStart >= 0; } else if (quoteStart < 0) { return false; } else { return commentInd > quoteStart; } }
@Test public void shouldNotFindUnclosedQuote_manyQuote() { // Given: final String line = "some line 'this is in a quote'''''"; // Then: assertThat(UnclosedQuoteChecker.isUnclosedQuote(line), is(false)); }
int checkBackupPathForRepair() throws IOException { if (cfg.backupPath == null) { SecureRandom random = new SecureRandom(); long randomLong = random.nextLong(); cfg.backupPath = "/tmp/" + BACKUP_DIR_PREFIX + randomLong; } StoragePath backupPath = new StoragePath(cfg.backupPath); if (metaClient.getStorage().exists(backupPath) && metaClient.getStorage().listDirectEntries(backupPath).size() > 0) { LOG.error(String.format("Cannot use backup path %s: it is not empty", cfg.backupPath)); return -1; } return checkBackupPathAgainstBasePath(); }
@Test public void testCheckBackupPathForRepair() throws IOException { for (Arguments arguments: configPathParamsWithFS().collect(Collectors.toList())) { Object[] args = arguments.get(); String backupPath = (String) args[0]; String basePath = (String) args[1]; int expectedResult = (Integer) args[2]; HoodieRepairTool.Config config = new HoodieRepairTool.Config(); config.backupPath = backupPath; config.basePath = basePath; HoodieRepairTool tool = new HoodieRepairTool(jsc, config); assertEquals(expectedResult, tool.checkBackupPathForRepair()); if (backupPath == null) { // Backup path should be created if not provided assertNotNull(config.backupPath); } } }
@Override public void process(Exchange exchange) throws Exception { Object payload = exchange.getMessage().getBody(); if (payload == null) { return; } ProtobufSchema answer = computeIfAbsent(exchange); if (answer != null) { exchange.setProperty(SchemaHelper.CONTENT_SCHEMA, answer); exchange.setProperty(SchemaHelper.CONTENT_SCHEMA_TYPE, SchemaType.PROTOBUF.type()); exchange.setProperty(SchemaHelper.CONTENT_CLASS, SchemaHelper.resolveContentClass(exchange, this.contentClass)); } }
@Test void shouldReadSchemaFromSchema() throws Exception { Exchange exchange = new DefaultExchange(camelContext); exchange.setProperty(SchemaHelper.CONTENT_CLASS, Person.class.getName()); String schemaString = new String(this.getClass().getResourceAsStream("Person.proto").readAllBytes()); exchange.setProperty(SchemaHelper.SCHEMA, schemaString); exchange.getMessage().setBody(person); ProtobufSchemaResolver schemaResolver = new ProtobufSchemaResolver(); schemaResolver.process(exchange); Assertions.assertNotNull(exchange.getProperty(SchemaHelper.CONTENT_SCHEMA)); Assertions.assertEquals(ProtobufSchema.class, exchange.getProperty(SchemaHelper.CONTENT_SCHEMA).getClass()); Assertions.assertEquals(SchemaType.PROTOBUF.type(), exchange.getProperty(SchemaHelper.CONTENT_SCHEMA_TYPE)); Assertions.assertEquals(Person.class.getName(), exchange.getProperty(SchemaHelper.CONTENT_CLASS)); }
@Subscribe public synchronized void completeToReportLocalProcesses(final ReportLocalProcessesCompletedEvent event) { ProcessOperationLockRegistry.getInstance().notify(event.getTaskId()); }
@Test void assertCompleteToReportLocalProcesses() { String taskId = "foo_id"; long startMillis = System.currentTimeMillis(); Executors.newFixedThreadPool(1).submit(() -> { Awaitility.await().pollDelay(50L, TimeUnit.MILLISECONDS).until(() -> true); subscriber.completeToReportLocalProcesses(new ReportLocalProcessesCompletedEvent(taskId)); }); waitUntilReleaseReady(taskId); long currentMillis = System.currentTimeMillis(); assertThat(currentMillis, greaterThanOrEqualTo(startMillis + 50L)); assertThat(currentMillis, lessThanOrEqualTo(startMillis + 5000L)); }
@Override public Optional<Object> getNativeSchema() { return Optional.of(getProtobufNativeSchema()); }
@Test public void testGetNativeSchema() { ProtobufNativeSchema<org.apache.pulsar.client.schema.proto.Test.TestMessage> protobufSchema = ProtobufNativeSchema.of(org.apache.pulsar.client.schema.proto.Test.TestMessage.class); Descriptors.Descriptor nativeSchema = (Descriptors.Descriptor) protobufSchema.getNativeSchema().get(); assertNotNull(nativeSchema); }
@Override @NotNull public List<PartitionStatistics> select(@NotNull Collection<PartitionStatistics> statistics, @NotNull Set<Long> excludeTables) { double minScore = Config.lake_compaction_score_selector_min_score; long now = System.currentTimeMillis(); return statistics.stream() .filter(p -> p.getCompactionScore() != null) .filter(p -> !excludeTables.contains(p.getPartition().getTableId())) // When manual compaction is triggered, we just skip min score and time check .filter(p -> (p.getPriority() != PartitionStatistics.CompactionPriority.DEFAULT || (p.getNextCompactionTime() <= now && p.getCompactionScore().getMax() >= minScore))) .collect(Collectors.toList()); }
@Test public void testPriority() { List<PartitionStatistics> statisticsList = new ArrayList<>(); PartitionStatistics statistics = new PartitionStatistics(new PartitionIdentifier(1, 2, 3)); statistics.setCompactionScore(Quantiles.compute(Collections.singleton(0.0))); statistics.setPriority(PartitionStatistics.CompactionPriority.MANUAL_COMPACT); statisticsList.add(statistics); statistics = new PartitionStatistics(new PartitionIdentifier(1, 2, 4)); statistics.setCompactionScore(Quantiles.compute(Collections.singleton(0.99))); statistics.setPriority(PartitionStatistics.CompactionPriority.MANUAL_COMPACT); statisticsList.add(statistics); statistics = new PartitionStatistics(new PartitionIdentifier(1, 2, 5)); statistics.setCompactionScore(Quantiles.compute(Collections.singleton(1.0))); statisticsList.add(statistics); statistics = new PartitionStatistics(new PartitionIdentifier(1, 2, 6)); statistics.setCompactionScore(Quantiles.compute(Collections.singleton(1.1))); statisticsList.add(statistics); List<PartitionStatistics> targetList = selector.select(statisticsList, new HashSet<Long>()); Assert.assertEquals(4, targetList.size()); Assert.assertEquals(3, targetList.get(0).getPartition().getPartitionId()); Assert.assertEquals(4, targetList.get(1).getPartition().getPartitionId()); Assert.assertEquals(5, targetList.get(2).getPartition().getPartitionId()); Assert.assertEquals(6, targetList.get(3).getPartition().getPartitionId()); }
public String getSchemaName(final String logicTableName) { return mapping.get(new CaseInsensitiveIdentifier(logicTableName)); }
@Test void assertConstructFromMap() { assertThat(new TableAndSchemaNameMapper(Collections.singletonMap("t_order", "public")).getSchemaName("t_order"), is("public")); }
@Override public Map<K, V> getCachedMap() { return localCacheView.getCachedMap(); }
@Test public void testGetStoringCacheMissGetAll() { RLocalCachedMap<String, Integer> map = redisson.getLocalCachedMap(LocalCachedMapOptions.<String, Integer>name("test").storeCacheMiss(true).loader(new MapLoader<String, Integer>() { @Override public Integer load(String key) { return null; } @Override public Iterable<String> loadAllKeys() { return new ArrayList<>(); } })); Map<String, Integer> cache = map.getCachedMap(); Map<String, Integer> s1 = map.getAll(new HashSet<>(Arrays.asList("1", "2", "3"))); assertThat(s1).isEmpty(); Awaitility.await().atMost(Durations.ONE_SECOND) .untilAsserted(() -> assertThat(cache.size()).isEqualTo(3)); Map<String, Integer> s2 = map.getAll(new HashSet<>(Arrays.asList("1", "2", "3"))); assertThat(s2).isEmpty(); Awaitility.await().atMost(Durations.ONE_SECOND) .untilAsserted(() -> assertThat(cache.size()).isEqualTo(3)); }
@Override // add synchronized to avoid process 2 or more stmts at same time public synchronized ShowResultSet process(List<AlterClause> alterClauses, Database dummyDb, OlapTable dummyTbl) throws UserException { Preconditions.checkArgument(alterClauses.size() == 1); AlterClause alterClause = alterClauses.get(0); alterClause.accept(SystemHandler.Visitor.getInstance(), null); return null; }
@Test public void testDecommissionBackends() throws UserException { List<String> hostAndPorts = Lists.newArrayList("host1:123"); DecommissionBackendClause decommissionBackendClause = new DecommissionBackendClause(hostAndPorts); Analyzer.analyze(new AlterSystemStmt(decommissionBackendClause), new ConnectContext()); Backend backend4 = new Backend(100, "host4", 123); backend4.setAlive(true); GlobalStateMgr.getCurrentState().getNodeMgr().getClusterInfo().addBackend(backend4); DiskInfo diskInfo = new DiskInfo("/data"); diskInfo.setAvailableCapacityB(900); diskInfo.setDataUsedCapacityB(100); diskInfo.setTotalCapacityB(1000); Map<String, DiskInfo> diskInfoMap = Maps.newHashMap(); diskInfoMap.put("/data", diskInfo); for (Backend backend : GlobalStateMgr.getCurrentState().getNodeMgr().getClusterInfo().getBackends()) { backend.setDisks(ImmutableMap.copyOf(diskInfoMap)); } systemHandler.process(Lists.newArrayList(decommissionBackendClause), null, null); }
@Override public void setConfigAttributes(Object attributes) { clear(); if (attributes == null) { return; } Map attributeMap = (Map) attributes; String materialType = (String) attributeMap.get(AbstractMaterialConfig.MATERIAL_TYPE); if (SvnMaterialConfig.TYPE.equals(materialType)) { addMaterialConfig(getSvnMaterial(), (Map) attributeMap.get(SvnMaterialConfig.TYPE)); } else if (HgMaterialConfig.TYPE.equals(materialType)) { addMaterialConfig(getHgMaterial(), (Map) attributeMap.get(HgMaterialConfig.TYPE)); } else if (GitMaterialConfig.TYPE.equals(materialType)) { addMaterialConfig(getGitMaterial(), (Map) attributeMap.get(GitMaterialConfig.TYPE)); } else if (P4MaterialConfig.TYPE.equals(materialType)) { addMaterialConfig(getP4Material(), (Map) attributeMap.get(P4MaterialConfig.TYPE)); } else if (DependencyMaterialConfig.TYPE.equals(materialType)) { addMaterialConfig(getDependencyMaterial(), (Map) attributeMap.get(DependencyMaterialConfig.TYPE)); } else if (TfsMaterialConfig.TYPE.equals(materialType)) { addMaterialConfig(getTfsMaterial(), (Map) attributeMap.get(TfsMaterialConfig.TYPE)); } else if (PackageMaterialConfig.TYPE.equals(materialType)) { addMaterialConfig(getPackageMaterial(), (Map) attributeMap.get(PackageMaterialConfig.TYPE)); } else if (PluggableSCMMaterialConfig.TYPE.equals(materialType)) { addMaterialConfig(getSCMMaterial(), (Map) attributeMap.get(PluggableSCMMaterialConfig.TYPE)); } }
@Test public void shouldSetP4ConfigAttributesForMaterial() { MaterialConfigs materialConfigs = new MaterialConfigs(); Map<String, String> hashMap = new HashMap<>(); hashMap.put(P4MaterialConfig.SERVER_AND_PORT, "localhost:1666"); hashMap.put(P4MaterialConfig.USERNAME, "username"); hashMap.put(P4MaterialConfig.PASSWORD, "password"); hashMap.put(P4MaterialConfig.VIEW, "foo"); Map<String, Object> attributeMap = new HashMap<>(); attributeMap.put(AbstractMaterialConfig.MATERIAL_TYPE, P4MaterialConfig.TYPE); attributeMap.put(P4MaterialConfig.TYPE, hashMap); materialConfigs.setConfigAttributes(attributeMap); assertThat(materialConfigs).hasSize(1); P4MaterialConfig expected = p4("localhost:1666", "foo", "username"); expected.setPassword("password"); assertThat(materialConfigs.first()).isEqualTo(expected); }
@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 testFilterWithoutKVPairs() { TokenizerConverter f = new TokenizerConverter(new HashMap<String, Object>()); @SuppressWarnings("unchecked") Map<String, String> result = (Map<String, String>) f.convert("trolololololol"); assertEquals(0, result.size()); }
@Override public Optional<String> getValue(Object arg, String type) { String methodName = getMethodNameByFieldName(getKey(type)); return Optional.ofNullable(ReflectUtils.invokeWithNoneParameterAndReturnString(arg, methodName)); }
@Test public void testValue() { TypeStrategy strategy = new ObjectTypeStrategy(); Entity entity = new Entity(); entity.setTest("bar"); // Normal Assert.assertEquals("bar", strategy.getValue(entity, ".test").orElse(null)); // Test null Assert.assertNotEquals("bar", strategy.getValue(new Entity(), ".test").orElse(null)); // The test couldn't find methods Assert.assertNull(strategy.getValue(new Entity(), ".foo").orElse(null)); Assert.assertNull(strategy.getValue(new Entity(), ".Foo").orElse(null)); Assert.assertNull(strategy.getValue(new Entity(), ".$oo").orElse(null)); // The test is not equal entity.setTest("foo"); Assert.assertNotEquals("bar", strategy.getValue(entity, ".test").orElse(null)); }
public void addMethod(MethodDescriptor methodDescriptor) { methods.put(methodDescriptor.getMethodName(), Collections.singletonList(methodDescriptor)); }
@Test void addMethod() { ReflectionServiceDescriptor service2 = new ReflectionServiceDescriptor(DemoService.class); MethodDescriptor method = Mockito.mock(MethodDescriptor.class); when(method.getMethodName()).thenReturn("sayHello2"); service2.addMethod(method); Assertions.assertEquals(1, service2.getMethods("sayHello2").size()); }
public static Type arrayOf(Type elementType) { return TypeFactory.arrayOf(elementType); }
@Test public void createPrimitiveArrayType() { assertThat(Types.arrayOf(int.class)).isEqualTo(int[].class); }
public static <K, V> GroupingTable<K, V, List<V>> buffering( GroupingKeyCreator<? super K> groupingKeyCreator, PairInfo pairInfo, SizeEstimator<? super K> keySizer, SizeEstimator<? super V> valueSizer) { return new BufferingGroupingTable<>( DEFAULT_MAX_GROUPING_TABLE_BYTES, groupingKeyCreator, pairInfo, keySizer, valueSizer); }
@Test public void testBufferingGroupingTable() throws Exception { GroupingTableBase<String, String, List<String>> table = (GroupingTableBase<String, String, List<String>>) GroupingTables.buffering( new IdentityGroupingKeyCreator(), new KvPairInfo(), new StringPowerSizeEstimator(), new StringPowerSizeEstimator()); table.setMaxSize(1000); TestOutputReceiver receiver = new TestOutputReceiver( KvCoder.of(StringUtf8Coder.of(), IterableCoder.of(StringUtf8Coder.of())), NameContextsForTests.nameContextForTest()); table.put("A", "a", receiver); table.put("B", "b1", receiver); table.put("B", "b2", receiver); table.put("C", "c", receiver); assertThat(receiver.outputElems, empty()); table.put("C", "cccc", receiver); assertThat(receiver.outputElems, hasItem((Object) KV.of("C", Arrays.asList("c", "cccc")))); table.put("DDDD", "d", receiver); assertThat(receiver.outputElems, hasItem((Object) KV.of("DDDD", Arrays.asList("d")))); table.flush(receiver); assertThat( receiver.outputElems, IsIterableContainingInAnyOrder.<Object>containsInAnyOrder( KV.of("A", Arrays.asList("a")), KV.of("B", Arrays.asList("b1", "b2")), KV.of("C", Arrays.asList("c", "cccc")), KV.of("DDDD", Arrays.asList("d")))); }
@ScalarOperator(CAST) @SqlType(StandardTypes.SMALLINT) public static long castToSmallint(@SqlType(StandardTypes.REAL) long value) { try { return Shorts.checkedCast(DoubleMath.roundToInt(intBitsToFloat((int) value), HALF_UP)); } catch (ArithmeticException | IllegalArgumentException e) { throw new PrestoException(INVALID_CAST_ARGUMENT, format("Unable to cast %s to smallint", intBitsToFloat((int) value)), e); } }
@Test public void testCastToSmallint() { assertFunction("CAST(REAL'754.2008' AS SMALLINT)", SMALLINT, (short) 754); assertFunction("CAST(REAL'-754.1985' AS SMALLINT)", SMALLINT, (short) -754); assertFunction("CAST(REAL'9.99' AS SMALLINT)", SMALLINT, (short) 10); assertFunction("CAST(REAL'-0.0' AS SMALLINT)", SMALLINT, (short) 0); assertInvalidFunction("CAST(cast(nan() AS REAL) as SMALLINT)", INVALID_CAST_ARGUMENT, "Unable to cast NaN to smallint"); assertInvalidFunction("CAST(cast(infinity() AS REAL) as SMALLINT)", INVALID_CAST_ARGUMENT, "Unable to cast Infinity to smallint"); assertInvalidFunction("CAST(cast(-infinity() AS REAL) as SMALLINT)", INVALID_CAST_ARGUMENT, "Unable to cast -Infinity to smallint"); assertInvalidFunction("CAST(REAL '" + (Short.MAX_VALUE + 0.6) + "' as SMALLINT)", INVALID_CAST_ARGUMENT, "Unable to cast 32767.6 to smallint"); }
@Override public LeaderElection createLeaderElection(String componentId) { synchronized (lock) { Preconditions.checkState( !leadershipOperationExecutor.isShutdown(), "The service was already closed and cannot be reused."); Preconditions.checkState( !leaderContenderRegistry.containsKey(componentId), "There shouldn't be any contender registered under the passed component '%s'.", componentId); return new DefaultLeaderElection(this, componentId); } }
@Test void testErrorOnComponentIdReuse() throws Exception { new Context() { { runTestWithSynchronousEventHandling( () -> assertThatThrownBy( () -> leaderElectionService.createLeaderElection( contenderContext0.componentId)) .isInstanceOf(IllegalStateException.class)); } }; }
@Override public PMML_MODEL getPMMLModelType() { return PMML_MODEL_TYPE; }
@Test void getPMMLModelType() { assertThat(PROVIDER.getPMMLModelType()).isEqualTo(PMML_MODEL.SCORECARD_MODEL); }
public void set(String name, String value) { set(name, value, null); }
@Test public void testSettingValueNull() throws Exception { Configuration config = new Configuration(); try { config.set("testClassName", null); fail("Should throw an IllegalArgumentException exception "); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); assertEquals(e.getMessage(), "The value of property testClassName must not be null"); } }
@Override public void commitTransaction(GlobalTransaction tx) throws TransactionalExecutor.ExecutionException { try { triggerBeforeCommit(tx); tx.commit(); triggerAfterCommit(tx); } catch (TransactionException txe) { // 4.1 Failed to commit throw new TransactionalExecutor.ExecutionException(tx, txe, TransactionalExecutor.Code.CommitFailure); } }
@Test public void testCommitTransaction() { MockGlobalTransaction mockGlobalTransaction = new MockGlobalTransaction(); Assertions.assertDoesNotThrow(() -> sagaTransactionalTemplate.commitTransaction(mockGlobalTransaction)); }
public static WorkerIdentity fromProto(alluxio.grpc.WorkerIdentity proto) throws ProtoParsingException { return Parsers.fromProto(proto); }
@Test public void legacyMissingFields() { alluxio.grpc.WorkerIdentity missingId = alluxio.grpc.WorkerIdentity.newBuilder() .setVersion(1) .build(); assertThrows(MissingRequiredFieldsParsingException.class, () -> WorkerIdentity.ParserV1.INSTANCE.fromProto(missingId)); alluxio.grpc.WorkerIdentity missingVersion = alluxio.grpc.WorkerIdentity.newBuilder() .setIdentifier(ByteString.copyFrom("id", Charset.defaultCharset())) .build(); assertThrows(MissingRequiredFieldsParsingException.class, () -> WorkerIdentity.ParserV0.INSTANCE.fromProto(missingVersion)); }
public static void downloadFromHttpUrl(String destPkgUrl, File targetFile) throws IOException { final URL url = new URL(destPkgUrl); final URLConnection connection = url.openConnection(); if (StringUtils.isNotEmpty(url.getUserInfo())) { final AuthenticationDataBasic authBasic = new AuthenticationDataBasic(url.getUserInfo()); for (Map.Entry<String, String> header : authBasic.getHttpHeaders()) { connection.setRequestProperty(header.getKey(), header.getValue()); } } try (InputStream in = connection.getInputStream()) { log.info("Downloading function package from {} to {} ...", destPkgUrl, targetFile.getAbsoluteFile()); Files.copy(in, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } log.info("Downloading function package from {} to {} completed!", destPkgUrl, targetFile.getAbsoluteFile()); }
@Test public void testDownloadFileWithBasicAuth() throws Exception { @Cleanup("stop") WireMockServer server = new WireMockServer(0); server.start(); configureFor(server.port()); stubFor(get(urlPathEqualTo("/")) .withBasicAuth("foo", "bar") .willReturn(aResponse().withBody("Hello world!").withStatus(200))); final String jarHttpUrl = "http://foo:bar@localhost:" + server.port() + "/"; final File file = Files.newTemporaryFile(); file.deleteOnExit(); assertThat(file.length()).isZero(); FunctionCommon.downloadFromHttpUrl(jarHttpUrl, file); assertThat(file.length()).isGreaterThan(0); }
@Override public boolean test(Creature t) { return t.getMovement().equals(movement); }
@Test void testMovement() { final var swimmingCreature = mock(Creature.class); when(swimmingCreature.getMovement()).thenReturn(Movement.SWIMMING); final var flyingCreature = mock(Creature.class); when(flyingCreature.getMovement()).thenReturn(Movement.FLYING); final var swimmingSelector = new MovementSelector(Movement.SWIMMING); assertTrue(swimmingSelector.test(swimmingCreature)); assertFalse(swimmingSelector.test(flyingCreature)); }
public abstract void verify(String value);
@Test public void testEnumAttribute() { EnumAttribute enumAttribute = new EnumAttribute("enum.key", true, newHashSet("enum-1", "enum-2", "enum-3"), "enum-1"); Assert.assertThrows(RuntimeException.class, () -> enumAttribute.verify("")); Assert.assertThrows(RuntimeException.class, () -> enumAttribute.verify("x")); Assert.assertThrows(RuntimeException.class, () -> enumAttribute.verify("enum-4")); enumAttribute.verify("enum-1"); enumAttribute.verify("enum-2"); enumAttribute.verify("enum-3"); }
public static String fromTimeUUID(UUID src) { if (src.version() != 1) { throw new IllegalArgumentException("Only Time-Based UUID (Version 1) is supported!"); } String str = src.toString(); // 58e0a7d7-eebc-11d8-9669-0800200c9a66 => 1d8eebc58e0a7d796690800200c9a66. Note that [11d8] -> [1d8] return str.substring(15, 18) + str.substring(9, 13) + str.substring(0, 8) + str.substring(19, 23) + str.substring(24); }
@Test public void basicUuidComperisonTest() { Random r = new Random(System.currentTimeMillis()); for (int i = 0; i < 100000; i++) { long ts = System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 365 * 10; long before = (long) (Math.random() * ts); long after = (long) (Math.random() * ts); if (before > after) { long tmp = after; after = before; before = tmp; } String beforeStr = UUIDConverter.fromTimeUUID(Uuids.startOf(before)); String afterStr = UUIDConverter.fromTimeUUID(Uuids.startOf(after)); if (afterStr.compareTo(beforeStr) < 0) { System.out.println("Before: " + before + " | " + beforeStr); System.out.println("After: " + after + " | " + afterStr); } Assertions.assertTrue(afterStr.compareTo(beforeStr) >= 0); } }
@Override public V remove(K key) { return map.remove(key); }
@Test public void testRemove() { map.put(23, "value-23"); assertTrue(map.containsKey(23)); assertEquals("value-23", adapter.remove(23)); assertFalse(map.containsKey(23)); }
public static Checksum newInstance(final String className) { Objects.requireNonNull(className, "className is required!"); if (Crc32.class.getName().equals(className)) { return crc32(); } else if (Crc32c.class.getName().equals(className)) { return crc32c(); } else { try { final Class<?> klass = Class.forName(className); final Object instance = klass.getDeclaredConstructor().newInstance(); return (Checksum)instance; } catch (final ReflectiveOperationException ex) { throw new IllegalArgumentException("failed to create Checksum instance for class: " + className, ex); } } }
@Test void newInstanceThrowsIllegalArgumentExceptionIfInstanceCannotBeCreated() { final IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, () -> Checksums.newInstance(TimeUnit.class.getName())); assertEquals(NoSuchMethodException.class, exception.getCause().getClass()); }
public FullyFinishedOperatorState(OperatorID operatorID, int parallelism, int maxParallelism) { super(operatorID, parallelism, maxParallelism); }
@Test void testFullyFinishedOperatorState() { OperatorState operatorState = new FullyFinishedOperatorState(new OperatorID(), 5, 256); assertThat(operatorState.isFullyFinished()).isTrue(); assertThat(operatorState.getSubtaskStates()).isEmpty(); assertThat(operatorState.getStates()).isEmpty(); assertThat(operatorState.getNumberCollectedStates()).isZero(); assertThatThrownBy(() -> operatorState.putState(0, OperatorSubtaskState.builder().build())) .as("Should not be able to put new subtask states for a fully finished state") .isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy( () -> operatorState.setCoordinatorState( new ByteStreamStateHandle("test", new byte[] {1, 2, 3, 4}))) .as("Should not be able to put new subtask states for a fully finished state") .isInstanceOf(UnsupportedOperationException.class); }
@Override @Transactional(rollbackFor = Exception.class) public void updateSpu(ProductSpuSaveReqVO updateReqVO) { // 校验 SPU 是否存在 validateSpuExists(updateReqVO.getId()); // 校验分类、品牌 validateCategory(updateReqVO.getCategoryId()); brandService.validateProductBrand(updateReqVO.getBrandId()); // 校验SKU List<ProductSkuSaveReqVO> skuSaveReqList = updateReqVO.getSkus(); productSkuService.validateSkuList(skuSaveReqList, updateReqVO.getSpecType()); // 更新 SPU ProductSpuDO updateObj = BeanUtils.toBean(updateReqVO, ProductSpuDO.class); initSpuFromSkus(updateObj, skuSaveReqList); productSpuMapper.updateById(updateObj); // 批量更新 SKU productSkuService.updateSkuList(updateObj.getId(), updateReqVO.getSkus()); }
@Test public void testValidateSpuExists_exception() { ProductSpuSaveReqVO reqVO = randomPojo(ProductSpuSaveReqVO.class); // 调用 Assertions.assertThrows(ServiceException.class, () -> productSpuService.updateSpu(reqVO)); }
static Properties argumentsToProperties(String[] args) { Properties props = new Properties(); for (String arg : args) { if (!arg.startsWith("-D") || !arg.contains("=")) { throw new IllegalArgumentException(String.format( "Command-line argument must start with -D, for example -Dsonar.jdbc.username=sonar. Got: %s", arg)); } String key = StringUtils.substringBefore(arg, "=").substring(2); String value = StringUtils.substringAfter(arg, "="); props.setProperty(key, value); } return props; }
@Test public void argumentsToProperties_throws_IAE_if_argument_does_not_start_with_minusD() { Properties p = CommandLineParser.argumentsToProperties(new String[] {"-Dsonar.foo=bar", "-Dsonar.whitespace=foo bar"}); assertThat(p).hasSize(2); assertThat(p.getProperty("sonar.foo")).isEqualTo("bar"); assertThat(p.getProperty("sonar.whitespace")).isEqualTo("foo bar"); assertThatThrownBy(() -> CommandLineParser.argumentsToProperties(new String[] {"-Dsonar.foo=bar", "sonar.bad=true"})) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Command-line argument must start with -D, for example -Dsonar.jdbc.username=sonar. Got: sonar.bad=true"); }
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .nullable(column.isNullable()) .comment(column.getComment()) .defaultValue(column.getDefaultValue()); switch (column.getDataType().getSqlType()) { case BOOLEAN: builder.columnType(String.format("%s(%s)", ORACLE_NUMBER, 1)); builder.dataType(ORACLE_NUMBER); builder.length(1L); break; case TINYINT: case SMALLINT: case INT: case BIGINT: builder.columnType(ORACLE_INTEGER); builder.dataType(ORACLE_INTEGER); break; case FLOAT: builder.columnType(ORACLE_BINARY_FLOAT); builder.dataType(ORACLE_BINARY_FLOAT); break; case DOUBLE: builder.columnType(ORACLE_BINARY_DOUBLE); builder.dataType(ORACLE_BINARY_DOUBLE); break; case DECIMAL: DecimalType decimalType = (DecimalType) column.getDataType(); long precision = decimalType.getPrecision(); int scale = decimalType.getScale(); if (precision <= 0) { precision = DEFAULT_PRECISION; scale = DEFAULT_SCALE; log.warn( "The decimal column {} type decimal({},{}) is out of range, " + "which is precision less than 0, " + "it will be converted to decimal({},{})", column.getName(), decimalType.getPrecision(), decimalType.getScale(), precision, scale); } else if (precision > MAX_PRECISION) { scale = (int) Math.max(0, scale - (precision - MAX_PRECISION)); precision = MAX_PRECISION; log.warn( "The decimal column {} type decimal({},{}) is out of range, " + "which exceeds the maximum precision of {}, " + "it will be converted to decimal({},{})", column.getName(), decimalType.getPrecision(), decimalType.getScale(), MAX_PRECISION, precision, scale); } if (scale < 0) { scale = 0; log.warn( "The decimal column {} type decimal({},{}) is out of range, " + "which is scale less than 0, " + "it will be converted to decimal({},{})", column.getName(), decimalType.getPrecision(), decimalType.getScale(), precision, scale); } else if (scale > MAX_SCALE) { scale = MAX_SCALE; log.warn( "The decimal column {} type decimal({},{}) is out of range, " + "which exceeds the maximum scale of {}, " + "it will be converted to decimal({},{})", column.getName(), decimalType.getPrecision(), decimalType.getScale(), MAX_SCALE, precision, scale); } builder.columnType(String.format("%s(%s,%s)", ORACLE_NUMBER, precision, scale)); builder.dataType(ORACLE_NUMBER); builder.precision(precision); builder.scale(scale); break; case BYTES: if (column.getColumnLength() == null || column.getColumnLength() <= 0) { builder.columnType(ORACLE_BLOB); builder.dataType(ORACLE_BLOB); } else if (column.getColumnLength() <= MAX_RAW_LENGTH) { builder.columnType( String.format("%s(%s)", ORACLE_RAW, column.getColumnLength())); builder.dataType(ORACLE_RAW); } else { builder.columnType(ORACLE_BLOB); builder.dataType(ORACLE_BLOB); } break; case STRING: if (column.getColumnLength() == null || column.getColumnLength() <= 0) { builder.columnType( String.format("%s(%s)", ORACLE_VARCHAR2, MAX_VARCHAR_LENGTH)); builder.dataType(ORACLE_VARCHAR2); } else if (column.getColumnLength() <= MAX_VARCHAR_LENGTH) { builder.columnType( String.format("%s(%s)", ORACLE_VARCHAR2, column.getColumnLength())); builder.dataType(ORACLE_VARCHAR2); } else { builder.columnType(ORACLE_CLOB); builder.dataType(ORACLE_CLOB); } break; case DATE: builder.columnType(ORACLE_DATE); builder.dataType(ORACLE_DATE); break; case TIMESTAMP: if (column.getScale() == null || column.getScale() <= 0) { builder.columnType(ORACLE_TIMESTAMP_WITH_LOCAL_TIME_ZONE); } else { int timestampScale = column.getScale(); if (column.getScale() > MAX_TIMESTAMP_SCALE) { timestampScale = MAX_TIMESTAMP_SCALE; log.warn( "The timestamp column {} type timestamp({}) is out of range, " + "which exceeds the maximum scale of {}, " + "it will be converted to timestamp({})", column.getName(), column.getScale(), MAX_TIMESTAMP_SCALE, timestampScale); } builder.columnType( String.format("TIMESTAMP(%s) WITH LOCAL TIME ZONE", timestampScale)); builder.scale(timestampScale); } builder.dataType(ORACLE_TIMESTAMP_WITH_LOCAL_TIME_ZONE); break; default: throw CommonError.convertToConnectorTypeError( DatabaseIdentifier.ORACLE, column.getDataType().getSqlType().name(), column.getName()); } return builder.build(); }
@Test public void testReconvertString() { Column column = PhysicalColumn.builder() .name("test") .dataType(BasicType.STRING_TYPE) .columnLength(null) .build(); BasicTypeDefine typeDefine = OracleTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Assertions.assertEquals("VARCHAR2(4000)", typeDefine.getColumnType()); Assertions.assertEquals(OracleTypeConverter.ORACLE_VARCHAR2, typeDefine.getDataType()); column = PhysicalColumn.builder() .name("test") .dataType(BasicType.STRING_TYPE) .columnLength(2000L) .build(); typeDefine = OracleTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Assertions.assertEquals( String.format( "%s(%s)", OracleTypeConverter.ORACLE_VARCHAR2, column.getColumnLength()), typeDefine.getColumnType()); Assertions.assertEquals(OracleTypeConverter.ORACLE_VARCHAR2, typeDefine.getDataType()); column = PhysicalColumn.builder() .name("test") .dataType(BasicType.STRING_TYPE) .columnLength(4000L) .build(); typeDefine = OracleTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Assertions.assertEquals( String.format( "%s(%s)", OracleTypeConverter.ORACLE_VARCHAR2, column.getColumnLength()), typeDefine.getColumnType()); Assertions.assertEquals(OracleTypeConverter.ORACLE_VARCHAR2, typeDefine.getDataType()); column = PhysicalColumn.builder() .name("test") .dataType(BasicType.STRING_TYPE) .columnLength(40001L) .build(); typeDefine = OracleTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Assertions.assertEquals(OracleTypeConverter.ORACLE_CLOB, typeDefine.getColumnType()); Assertions.assertEquals(OracleTypeConverter.ORACLE_CLOB, typeDefine.getDataType()); }
@Override public Router router(String routerId) { checkArgument(!Strings.isNullOrEmpty(routerId), ERR_NULL_ROUTER_ID); return osRouterStore.router(routerId); }
@Test public void testGetRouterById() { createBasicRouters(); assertTrue("Router did not exist", target.router(ROUTER_ID) != null); assertTrue("Router did not exist", target.router(UNKNOWN_ID) == null); }
public double getDouble(String key, double _default) { Object object = map.get(key); return object instanceof Number ? ((Number) object).doubleValue() : _default; }
@Test public void numericPropertyCanBeRetrievedAsDouble() { PMap subject = new PMap("foo=123.45|bar=56.78"); assertEquals(123.45, subject.getDouble("foo", 0), 1e-4); }
public static Future<Void> unregisterNodes( Reconciliation reconciliation, Vertx vertx, AdminClientProvider adminClientProvider, PemTrustSet pemTrustSet, PemAuthIdentity pemAuthIdentity, List<Integer> nodeIdsToUnregister ) { try { String bootstrapHostname = KafkaResources.bootstrapServiceName(reconciliation.name()) + "." + reconciliation.namespace() + ".svc:" + KafkaCluster.REPLICATION_PORT; Admin adminClient = adminClientProvider.createAdminClient(bootstrapHostname, pemTrustSet, pemAuthIdentity); List<Future<Void>> futures = new ArrayList<>(); for (Integer nodeId : nodeIdsToUnregister) { futures.add(unregisterNode(reconciliation, vertx, adminClient, nodeId)); } return Future.all(futures) .eventually(() -> { adminClient.close(); return Future.succeededFuture(); }) .map((Void) null); } catch (KafkaException e) { LOGGER.warnCr(reconciliation, "Failed to unregister nodes", e); return Future.failedFuture(e); } }
@Test void testUnknownNodeUnregistration(VertxTestContext context) { Admin mockAdmin = ResourceUtils.adminClient(); ArgumentCaptor<Integer> unregisteredNodeIdCaptor = ArgumentCaptor.forClass(Integer.class); when(mockAdmin.unregisterBroker(unregisteredNodeIdCaptor.capture())).thenAnswer(i -> { if (i.getArgument(0, Integer.class) == 1919) { KafkaFutureImpl<Void> unregistrationFuture = new KafkaFutureImpl<>(); unregistrationFuture.completeExceptionally(new BrokerIdNotRegisteredException("Unknown node")); UnregisterBrokerResult ubr = mock(UnregisterBrokerResult.class); when(ubr.all()).thenReturn(unregistrationFuture); return ubr; } else { UnregisterBrokerResult ubr = mock(UnregisterBrokerResult.class); when(ubr.all()).thenReturn(KafkaFuture.completedFuture(null)); return ubr; } }); AdminClientProvider mockProvider = ResourceUtils.adminClientProvider(mockAdmin); Checkpoint async = context.checkpoint(); KafkaNodeUnregistration.unregisterNodes(Reconciliation.DUMMY_RECONCILIATION, vertx, mockProvider, null, null, List.of(1874, 1919)) .onComplete(context.succeeding(v -> context.verify(() -> { assertThat(unregisteredNodeIdCaptor.getAllValues().size(), is(2)); assertThat(unregisteredNodeIdCaptor.getAllValues(), hasItems(1874, 1919)); async.flag(); }))); }
void format(NamespaceInfo nsInfo, boolean force) throws IOException { Preconditions.checkState(nsInfo.getNamespaceID() != 0, "can't format with uninitialized namespace info: %s", nsInfo); LOG.info("Formatting journal id : " + journalId + " with namespace info: " + nsInfo + " and force: " + force); storage.format(nsInfo, force); this.cache = createCache(); refreshCachedData(); }
@Test public void testFormatNonEmptyStorageDirectoriesWhenforceOptionIsTrue() throws Exception { try { // Format again here and to format the non-empty directories in // journal node. journal.format(FAKE_NSINFO, true); } catch (IOException ioe) { fail("Format should be success with force option."); } }
public void maybeDeleteGroup(String groupId, List<CoordinatorRecord> records) { Group group = groups.get(groupId); if (group != null && group.isEmpty()) { createGroupTombstoneRecords(groupId, records); } }
@Test public void testClassicGroupMaybeDelete() { GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .build(); ClassicGroup group = context.createClassicGroup("group-id"); List<CoordinatorRecord> expectedRecords = Collections.singletonList(GroupCoordinatorRecordHelpers.newGroupMetadataTombstoneRecord("group-id")); List<CoordinatorRecord> records = new ArrayList<>(); context.groupMetadataManager.maybeDeleteGroup("group-id", records); assertEquals(expectedRecords, records); records = new ArrayList<>(); group.transitionTo(PREPARING_REBALANCE); context.groupMetadataManager.maybeDeleteGroup("group-id", records); assertEquals(Collections.emptyList(), records); records = new ArrayList<>(); context.groupMetadataManager.maybeDeleteGroup("invalid-group-id", records); assertEquals(Collections.emptyList(), records); }
@Override protected void encode(ChannelHandlerContext ctx, FileRegion msg, final ByteBuf out) throws Exception { WritableByteChannel writableByteChannel = new WritableByteChannel() { @Override public int write(ByteBuffer src) { int prev = out.writerIndex(); out.writeBytes(src); return out.writerIndex() - prev; } @Override public boolean isOpen() { return true; } @Override public void close() throws IOException { } }; long toTransfer = msg.count(); while (true) { long transferred = msg.transferred(); if (toTransfer - transferred <= 0) { break; } msg.transferTo(writableByteChannel, transferred); } }
@Test public void testEncode() throws IOException { FileRegionEncoder fileRegionEncoder = new FileRegionEncoder(); EmbeddedChannel channel = new EmbeddedChannel(fileRegionEncoder); File file = File.createTempFile(UUID.randomUUID().toString(), ".data"); file.deleteOnExit(); Random random = new Random(System.currentTimeMillis()); int dataLength = 1 << 10; byte[] data = new byte[dataLength]; random.nextBytes(data); write(file, data); FileRegion fileRegion = new DefaultFileRegion(file, 0, dataLength); Assert.assertEquals(0, fileRegion.transfered()); Assert.assertEquals(dataLength, fileRegion.count()); Assert.assertTrue(channel.writeOutbound(fileRegion)); ByteBuf out = (ByteBuf) channel.readOutbound(); byte[] arr = new byte[out.readableBytes()]; out.getBytes(0, arr); Assert.assertArrayEquals("Data should be identical", data, arr); }
public static IpPrefix valueOf(int address, int prefixLength) { return new IpPrefix(IpAddress.valueOf(address), prefixLength); }
@Test public void testEqualityIPv6() { new EqualsTester() .addEqualityGroup( IpPrefix.valueOf("1111:2222:3333:4444::/120"), IpPrefix.valueOf("1111:2222:3333:4444::1/120"), IpPrefix.valueOf("1111:2222:3333:4444::/120")) .addEqualityGroup( IpPrefix.valueOf("1111:2222:3333:4444::/64"), IpPrefix.valueOf("1111:2222:3333:4444::/64")) .addEqualityGroup( IpPrefix.valueOf("1111:2222:3333:4444::/128"), IpPrefix.valueOf("1111:2222:3333:4444::/128")) .addEqualityGroup( IpPrefix.valueOf("1111:2222:3333:4445::/64"), IpPrefix.valueOf("1111:2222:3333:4445::/64")) .addEqualityGroup( IpPrefix.valueOf("::/0"), IpPrefix.valueOf("::/0")) .addEqualityGroup( IpPrefix.valueOf("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128"), IpPrefix.valueOf("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128")) .testEquals(); }
@Override public ParSeqBasedCompletionStage<Void> thenRunAsync(Runnable action, Executor executor) { return nextStageByComposingTask(_task.flatMap("thenRunAsync", t -> Task.blocking(() -> { action.run(); return null; }, executor))); }
@Test public void testThenRunAsync() throws Exception { CompletionStage<String> completionStage = createTestStage(TESTVALUE1); CountDownLatch waitLatch = new CountDownLatch(1); completionStage.thenRunAsync(() -> { assertEquals(THREAD_NAME_VALUE, Thread.currentThread().getName()); waitLatch.countDown(); }, _mockExecutor); finish(completionStage); waitLatch.await(1000, TimeUnit.MILLISECONDS); }