focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static Ip4Prefix valueOf(int address, int prefixLength) { return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength); }
@Test public void testToStringIPv4() { Ip4Prefix ipPrefix; ipPrefix = Ip4Prefix.valueOf("1.2.3.0/24"); assertThat(ipPrefix.toString(), is("1.2.3.0/24")); ipPrefix = Ip4Prefix.valueOf("1.2.3.4/24"); assertThat(ipPrefix.toString(), is("1.2.3.0/24")); ipPrefix = Ip4Prefix.valueOf("0.0.0.0/0"); assertThat(ipPrefix.toString(), is("0.0.0.0/0")); ipPrefix = Ip4Prefix.valueOf("255.255.255.255/32"); assertThat(ipPrefix.toString(), is("255.255.255.255/32")); }
@Override public TGetTablesInfoResponse getTablesInfo(TGetTablesInfoRequest request) throws TException { return InformationSchemaDataSource.generateTablesInfoResponse(request); }
@Test public void testGetTablesInfo() throws Exception { starRocksAssert.withDatabase("test_table").useDatabase("test_table") .withTable("CREATE TABLE `t1` (\n" + " `k1` date NULL COMMENT \"\",\n" + " `v1` int(11) NULL COMMENT \"\",\n" + " `v2` int(11) NULL COMMENT \"\"\n" + ") ENGINE=OLAP \n" + "DUPLICATE KEY(`k1`)\n" + "COMMENT \"OLAP\"\n" + "PROPERTIES (\n" + "\"replication_num\" = \"1\",\n" + "\"in_memory\" = \"false\",\n" + "\"enable_persistent_index\" = \"false\",\n" + "\"replicated_storage\" = \"true\",\n" + "\"compression\" = \"LZ4\"\n" + ")") .withTable("CREATE TABLE `t2` (\n" + " `k1` date NULL COMMENT \"\",\n" + " `v1` int(11) NULL COMMENT \"\",\n" + " `v2` int(11) NULL COMMENT \"\"\n" + ") ENGINE=OLAP \n" + "DUPLICATE KEY(`k1`)\n" + "COMMENT \"OLAP\"\n" + "PROPERTIES (\n" + "\"replication_num\" = \"1\",\n" + "\"in_memory\" = \"false\",\n" + "\"enable_persistent_index\" = \"false\",\n" + "\"replicated_storage\" = \"true\",\n" + "\"compression\" = \"LZ4\"\n" + ")"); ConnectContext ctx = starRocksAssert.getCtx(); String createUserSql = "create user test1"; DDLStmtExecutor.execute(UtFrameUtils.parseStmtWithNewParser(createUserSql, ctx), ctx); String grantSql = "GRANT SELECT ON TABLE test_table.t1 TO USER `test1`@`%`;"; DDLStmtExecutor.execute(UtFrameUtils.parseStmtWithNewParser(grantSql, ctx), ctx); FrontendServiceImpl impl = new FrontendServiceImpl(exeEnv); TGetTablesInfoRequest request = new TGetTablesInfoRequest(); TAuthInfo authInfo = new TAuthInfo(); TUserIdentity userIdentity = new TUserIdentity(); userIdentity.setUsername("test1"); userIdentity.setHost("%"); userIdentity.setIs_domain(false); authInfo.setCurrent_user_ident(userIdentity); authInfo.setPattern("test_table"); request.setAuth_info(authInfo); TGetTablesInfoResponse response = impl.getTablesInfo(request); List<TTableInfo> tablesInfos = response.getTables_infos(); Assert.assertEquals(1, tablesInfos.size()); Assert.assertEquals("t1", tablesInfos.get(0).getTable_name()); }
public Result runIndexOrPartitionScanQueryOnOwnedPartitions(Query query) { Result result = runIndexOrPartitionScanQueryOnOwnedPartitions(query, true); assert result != null; return result; }
@Test public void verifyIndexedQueryFailureWhileMigrating() { map.addIndex(IndexType.HASH, "this"); EqualPredicate predicate = new EqualPredicate("this", value); mapService.beforeMigration(new PartitionMigrationEvent(MigrationEndpoint.SOURCE, partitionId, 0, 1, UUID.randomUUID())); Query query = Query.of() .mapName(map.getName()) .predicate(predicate) .iterationType(IterationType.ENTRY) .partitionIdSet(SetUtil.allPartitionIds(instance.getPartitionService().getPartitions().size())) .build(); QueryResult result = (QueryResult) queryRunner.runIndexOrPartitionScanQueryOnOwnedPartitions(query); assertNull(result.getPartitionIds()); }
@Override public void upgrade() { if (clusterConfigService.get(MigrationCompleted.class) != null) { LOG.debug("Migration already completed."); return; } var result = collection.find(Filters.and( Filters.eq("config.type", "aggregation-v1"), Filters.type(SERIES_PATH_STRING, "array"), Filters.exists(SERIES_PATH_STRING + ".0") )); var bulkOperations = new ArrayList<WriteModel<? extends Document>>(); for (Document doc : result) { processDoc(doc, bulkOperations); } if (bulkOperations.size() > 0) { collection.bulkWrite(bulkOperations); } this.clusterConfigService.write(new MigrationCompleted()); }
@Test public void doesNotRunAgainIfMigrationHadCompletedBefore() { when(clusterConfigService.get(V20230629140000_RenameFieldTypeOfEventDefinitionSeries.MigrationCompleted.class)) .thenReturn(new V20230629140000_RenameFieldTypeOfEventDefinitionSeries.MigrationCompleted()); this.migration.upgrade(); verify(clusterConfigService, never()).write(any()); }
@Udf public <T extends Comparable<? super T>> List<T> arraySortDefault(@UdfParameter( description = "The array to sort") final List<T> input) { return arraySortWithDirection(input, "ASC"); }
@Test public void shouldSortBools() { final List<Boolean> input = Arrays.asList(true, false, false); final List<Boolean> output = udf.arraySortDefault(input); assertThat(output, contains(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE)); }
public static void notNull(Object obj, String message) { if (obj == null) { throw new IllegalArgumentException(message); } }
@Test void testNotNullWhenInputNotNull2() { notNull(new Object(), new IllegalStateException("null object")); }
@Override public boolean accept(final Path file) { if(list.find(new SimplePathPredicate(file)) != null) { return true; } for(Path f : list) { if(f.isChild(file)) { return true; } } if(log.isDebugEnabled()) { log.debug(String.format("Filter %s", file)); } return false; }
@Test public void testAcceptFileVersions() { final RecursiveSearchFilter f = new RecursiveSearchFilter(new AttributedList<>(Arrays.asList(new Path("/f", EnumSet.of(Path.Type.file))))); assertTrue(f.accept(new Path("/f", EnumSet.of(Path.Type.file), new PathAttributes().withVersionId("1")))); }
@Override public Map<K, V> loadAll(Collection<K> keys) { awaitSuccessfulInit(); Object[] keysArray = keys.toArray(); String sql = queries.loadAll(keys.size()); try (SqlResult queryResult = sqlService.execute(sql, keysArray)) { Iterator<SqlRow> it = queryResult.iterator(); Map<K, V> result = new HashMap<>(); while (it.hasNext()) { SqlRow sqlRow = it.next(); // If there is a single column as the value, return that column as the value if (queryResult.getRowMetadata().getColumnCount() == 2 && genericMapStoreProperties.singleColumnAsValue) { K id = sqlRow.getObject(genericMapStoreProperties.idColumn); result.put(id, sqlRow.getObject(1)); } else { K id = sqlRow.getObject(genericMapStoreProperties.idColumn); //noinspection unchecked V record = (V) toGenericRecord(sqlRow, genericMapStoreProperties); result.put(id, record); } } return result; } }
@Test public void givenRowAndIdColumn_whenLoadAll_thenReturnGenericRecord() { ObjectSpec spec = objectProvider.createObject(mapName, true); objectProvider.insertItems(spec, 1); Properties properties = new Properties(); properties.setProperty(DATA_CONNECTION_REF_PROPERTY, TEST_DATABASE_REF); properties.setProperty(ID_COLUMN_PROPERTY, "person-id"); mapLoader = createMapLoader(properties, hz); GenericRecord genericRecord = mapLoader.loadAll(newArrayList(0)).get(0); assertThat(genericRecord.getInt32("person-id")).isZero(); assertThat(genericRecord.getString("name")).isEqualTo("name-0"); }
@Override public InterpreterResult interpret(String st, InterpreterContext context) throws InterpreterException { LOGGER.debug("Interpret code: {}", st); this.z.setInterpreterContext(context); this.z.setGui(context.getGui()); this.z.setNoteGui(context.getNoteGui()); // set ClassLoader of current Thread to be the ClassLoader of Flink scala-shell, // otherwise codegen will fail to find classes defined in scala-shell ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getFlinkScalaShellLoader()); createPlannerAgain(); setParallelismIfNecessary(context); setSavepointPathIfNecessary(context); return innerIntp.interpret(st, context); } finally { Thread.currentThread().setContextClassLoader(originClassLoader); } }
@Test void testBatchWordCount() throws InterpreterException, IOException { InterpreterContext context = getInterpreterContext(); InterpreterResult result = interpreter.interpret( "val data = benv.fromElements(\"hello world\", \"hello flink\", \"hello hadoop\")", context); assertEquals(InterpreterResult.Code.SUCCESS, result.code()); context = getInterpreterContext(); result = interpreter.interpret( "data.flatMap(line => line.split(\"\\\\s\"))\n" + " .map(w => (w, 1))\n" + " .groupBy(0)\n" + " .sum(1)\n" + " .print()", context); assertEquals(InterpreterResult.Code.SUCCESS, result.code(), context.out.toString()); String[] expectedCounts = {"(hello,3)", "(world,1)", "(flink,1)", "(hadoop,1)"}; Arrays.sort(expectedCounts); String[] counts = context.out.toInterpreterResultMessage().get(0).getData().split("\n"); Arrays.sort(counts); assertArrayEquals(expectedCounts, counts); }
@Override protected void doProcess(Exchange exchange, MetricsEndpoint endpoint, MetricRegistry registry, String metricsName) throws Exception { Message in = exchange.getIn(); Histogram histogram = registry.histogram(metricsName); Long value = endpoint.getValue(); Long finalValue = getLongHeader(in, HEADER_HISTOGRAM_VALUE, value); if (finalValue != null) { histogram.update(finalValue); } else { LOG.warn("Cannot update histogram \"{}\" with null value", metricsName); } }
@Test public void testProcessValueNotSet() throws Exception { Object action = null; when(endpoint.getValue()).thenReturn(null); producer.doProcess(exchange, endpoint, registry, METRICS_NAME); inOrder.verify(exchange, times(1)).getIn(); inOrder.verify(registry, times(1)).histogram(METRICS_NAME); inOrder.verify(endpoint, times(1)).getValue(); inOrder.verify(in, times(1)).getHeader(HEADER_HISTOGRAM_VALUE, action, Long.class); inOrder.verifyNoMoreInteractions(); }
public static HbaseSinkConfig load(String yamlFile) throws IOException { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); return mapper.readValue(new File(yamlFile), HbaseSinkConfig.class); }
@Test public final void loadFromYamlFileTest() throws IOException { File yamlFile = getFile("sinkConfig.yaml"); String path = yamlFile.getAbsolutePath(); HbaseSinkConfig config = HbaseSinkConfig.load(path); assertNotNull(config); assertEquals("hbase-site.xml", config.getHbaseConfigResources()); assertEquals("localhost", config.getZookeeperQuorum()); assertEquals("2181", config.getZookeeperClientPort()); assertEquals("/hbase", config.getZookeeperZnodeParent()); assertEquals("pulsar_hbase", config.getTableName()); assertEquals("rowKey", config.getRowKeyName()); assertEquals("info", config.getFamilyName()); List<String> qualifierNames = new ArrayList<>(); qualifierNames.add("name"); qualifierNames.add("address"); qualifierNames.add("age"); assertEquals(qualifierNames, config.getQualifierNames()); }
public static Write write() { return new AutoValue_MongoDbIO_Write.Builder() .setMaxConnectionIdleTime(60000) .setBatchSize(1024L) .setSslEnabled(false) .setIgnoreSSLCertificate(false) .setSslInvalidHostNameAllowed(false) .setOrdered(true) .build(); }
@Test public void testWrite() { final String collectionName = "testWrite"; final int numElements = 1000; pipeline .apply(Create.of(createDocuments(numElements, false))) .apply( MongoDbIO.write() .withUri("mongodb://localhost:" + port) .withDatabase(DATABASE_NAME) .withCollection(collectionName)); pipeline.run(); assertEquals(numElements, countElements(collectionName)); }
private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = invocationHelper.newResponse(request); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.isEmpty()) { throw Log.REST.missingContent(); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { throw Log.REST.invalidContent(); } return invocationHelper.getCounterManager() .defineCounterAsync(counterName, configuration) .thenApply(created -> created ? responseBuilder.build() : responseBuilder.status(NOT_MODIFIED) .entity("Unable to create counter: " + counterName) .build()); }
@Test public void testWeakCounterOps() { String name = "weak-test"; createCounter(name, CounterConfiguration.builder(CounterType.WEAK).initialValue(5).build()); RestCounterClient counterClient = client.counter(name); CompletionStage<RestResponse> response = counterClient.increment(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 6); response = counterClient.increment(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 7); response = counterClient.decrement(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 6); response = counterClient.decrement(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 5); response = counterClient.add(10); assertThat(response).hasNoContent(); waitForCounterToReach(name, 15); response = counterClient.reset(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 5); }
public boolean isSecurityEnabled() { return securityAuthConfigs != null && !securityAuthConfigs.isEmpty(); }
@Test public void shouldNotSaySecurityEnabledIfSecurityHasNoAuthenticatorsDefined() { ServerConfig serverConfig = new ServerConfig(); assertFalse(serverConfig.isSecurityEnabled(), "Security should not be enabled by default"); }
public RingbufferStoreConfig setClassName(@Nonnull String className) { this.className = checkHasText(className, "Ringbuffer store class name must contain text"); this.storeImplementation = null; return this; }
@Test public void testEqualsAndHashCode() { assumeDifferentHashCodes(); EqualsVerifier.forClass(RingbufferStoreConfig.class) .suppress(Warning.NONFINAL_FIELDS) .withPrefabValues(RingbufferStoreConfigReadOnly.class, new RingbufferStoreConfigReadOnly(new RingbufferStoreConfig().setClassName("red")), new RingbufferStoreConfigReadOnly(new RingbufferStoreConfig().setClassName("black"))) .verify(); }
public Collection<? extends MqttProperty> listAll() { IntObjectHashMap<MqttProperty> props = this.props; if (props == null && subscriptionIds == null && userProperties == null) { return Collections.<MqttProperty>emptyList(); } if (subscriptionIds == null && userProperties == null) { return props.values(); } if (props == null && userProperties == null) { return subscriptionIds; } List<MqttProperty> propValues = new ArrayList<MqttProperty>(props != null ? props.size() : 1); if (props != null) { propValues.addAll(props.values()); } if (subscriptionIds != null) { propValues.addAll(subscriptionIds); } if (userProperties != null) { propValues.add(UserProperties.fromUserPropertyCollection(userProperties)); } return propValues; }
@Test public void testListAll() { MqttProperties props = createSampleProperties(); List<MqttProperties.MqttProperty> expectedProperties = new ArrayList<MqttProperties.MqttProperty>(); expectedProperties.add(new MqttProperties.IntegerProperty(PAYLOAD_FORMAT_INDICATOR.value(), 6)); expectedProperties.add(new MqttProperties.StringProperty(CONTENT_TYPE.value(), "text/plain")); expectedProperties.add(new MqttProperties.IntegerProperty(SUBSCRIPTION_IDENTIFIER.value(), 10)); expectedProperties.add(new MqttProperties.IntegerProperty(SUBSCRIPTION_IDENTIFIER.value(), 20)); MqttProperties.UserProperties expectedUserProperties = new MqttProperties.UserProperties(); expectedUserProperties.add(new MqttProperties.StringPair("isSecret", "true")); expectedUserProperties.add(new MqttProperties.StringPair("tag", "firstTag")); expectedUserProperties.add(new MqttProperties.StringPair("tag", "secondTag")); expectedProperties.add(expectedUserProperties); assertEquals(expectedProperties, props.listAll()); }
@Override public void run() throws InvalidInputException { String tableType = _input.getTableType(); if ((tableType.equalsIgnoreCase(REALTIME) || tableType.equalsIgnoreCase(HYBRID))) { _output.setAggregateMetrics(shouldAggregate(_input)); } }
@Test public void testRunWithGroupBy() throws Exception { Set<String> metrics = ImmutableSet.of("a", "b", "c"); InputManager input = createInput(metrics, "select d1, d2, sum(a), sum(b) from tableT group by d1, d2"); ConfigManager output = new ConfigManager(); AggregateMetricsRule rule = new AggregateMetricsRule(input, output); rule.run(); assertTrue(output.isAggregateMetrics()); }
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { for(Path f : files.keySet()) { try { new FilesApi(new BrickApiClient(session)).deleteFilesPath( StringUtils.removeStart(f.getAbsolute(), String.valueOf(Path.DELIMITER)), f.isDirectory()); } catch(ApiException e) { throw new BrickExceptionMappingService().map("Cannot delete {0}", e, f); } } }
@Test @Ignore public void testDeleteRecursively() throws Exception { final Path room = new BrickDirectoryFeature(session).mkdir(new Path( new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus()); final Path folder = new BrickDirectoryFeature(session).mkdir(new Path(room, new AlphanumericRandomStringService().random().toLowerCase(), EnumSet.of(Path.Type.directory)), new TransferStatus()); assertTrue(new BrickFindFeature(session).find(folder)); final Path file = new Path(folder, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new BrickTouchFeature(session).touch(file, new TransferStatus()); assertTrue(new BrickFindFeature(session).find(file)); new BrickDeleteFeature(session).delete(Collections.singletonList(folder), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(new BrickFindFeature(session).find(folder)); new BrickDeleteFeature(session).delete(Collections.singletonList(room), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(new BrickFindFeature(session).find(room)); }
@Override public void importData(JsonReader reader) throws IOException { logger.info("Reading configuration for 1.2"); // this *HAS* to start as an object reader.beginObject(); while (reader.hasNext()) { JsonToken tok = reader.peek(); switch (tok) { case NAME: String name = reader.nextName(); // find out which member it is if (name.equals(CLIENTS)) { readClients(reader); } else if (name.equals(GRANTS)) { readGrants(reader); } else if (name.equals(WHITELISTEDSITES)) { readWhitelistedSites(reader); } else if (name.equals(BLACKLISTEDSITES)) { readBlacklistedSites(reader); } else if (name.equals(AUTHENTICATIONHOLDERS)) { readAuthenticationHolders(reader); } else if (name.equals(ACCESSTOKENS)) { readAccessTokens(reader); } else if (name.equals(REFRESHTOKENS)) { readRefreshTokens(reader); } else if (name.equals(SYSTEMSCOPES)) { readSystemScopes(reader); } else { for (MITREidDataServiceExtension extension : extensions) { if (extension.supportsVersion(THIS_VERSION)) { extension.importExtensionData(name, reader); break; } } // unknown token, skip it reader.skipValue(); } break; case END_OBJECT: // the object ended, we're done here reader.endObject(); continue; default: logger.debug("Found unexpected entry"); reader.skipValue(); continue; } } fixObjectReferences(); for (MITREidDataServiceExtension extension : extensions) { if (extension.supportsVersion(THIS_VERSION)) { extension.fixExtensionObjectReferences(maps); break; } } maps.clearAll(); }
@Test public void testImportAccessTokens() throws IOException, ParseException { String expiration1 = "2014-09-10T22:49:44.090+00:00"; Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity(); token1.setId(1L); token1.setClient(mockedClient1); token1.setExpiration(expirationDate1); token1.setJwt(JWTParser.parse("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0")); token1.setAuthenticationHolder(mockedAuthHolder1); token1.setScope(ImmutableSet.of("id-token")); token1.setTokenType("Bearer"); String expiration2 = "2015-01-07T18:31:50.079+00:00"; Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class); when(mockRefreshToken2.getId()).thenReturn(1L); OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity(); token2.setId(2L); token2.setClient(mockedClient2); token2.setExpiration(expirationDate2); token2.setJwt(JWTParser.parse("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ")); token2.setAuthenticationHolder(mockedAuthHolder2); token2.setRefreshToken(mockRefreshToken2); token2.setScope(ImmutableSet.of("openid", "offline_access", "email", "profile")); token2.setTokenType("Bearer"); String configJson = "{" + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + "\"" + MITREidDataService.CLIENTS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [" + "{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+00:00\"," + "\"refreshTokenId\":null,\"idTokenId\":null,\"scope\":[\"id-token\"],\"type\":\"Bearer\"," + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0\"}," + "{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+00:00\"," + "\"refreshTokenId\":1,\"idTokenId\":1,\"scope\":[\"openid\",\"offline_access\",\"email\",\"profile\"],\"type\":\"Bearer\"," + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ\"}" + " ]" + "}"; logger.debug(configJson); JsonReader reader = new JsonReader(new StringReader(configJson)); final Map<Long, OAuth2AccessTokenEntity> fakeDb = new HashMap<>(); when(tokenRepository.saveAccessToken(isA(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer<OAuth2AccessTokenEntity>() { Long id = 324L; @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { OAuth2AccessTokenEntity _token = (OAuth2AccessTokenEntity) invocation.getArguments()[0]; if(_token.getId() == null) { _token.setId(id++); } fakeDb.put(_token.getId(), _token); return _token; } }); when(tokenRepository.getAccessTokenById(anyLong())).thenAnswer(new Answer<OAuth2AccessTokenEntity>() { @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { Long _id = (Long) invocation.getArguments()[0]; return fakeDb.get(_id); } }); when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer<ClientDetailsEntity>() { @Override public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable { String _clientId = (String) invocation.getArguments()[0]; ClientDetailsEntity _client = mock(ClientDetailsEntity.class); when(_client.getClientId()).thenReturn(_clientId); return _client; } }); when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer<AuthenticationHolderEntity>() { Long id = 133L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); when(_auth.getId()).thenReturn(id); id++; return _auth; } }); dataService.importData(reader); //2 times for token, 2 times to update client, 2 times to update authHolder, 1 times to update refresh token verify(tokenRepository, times(7)).saveAccessToken(capturedAccessTokens.capture()); List<OAuth2AccessTokenEntity> savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues(); Collections.sort(savedAccessTokens, new accessTokenIdComparator()); assertThat(savedAccessTokens.size(), is(2)); assertThat(savedAccessTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId())); assertThat(savedAccessTokens.get(0).getExpiration(), equalTo(token1.getExpiration())); assertThat(savedAccessTokens.get(0).getValue(), equalTo(token1.getValue())); assertThat(savedAccessTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId())); assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration())); assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue())); }
boolean isTaskManagerRegistered(ResourceID taskManagerId) { return registeredTaskManagers.contains(taskManagerId); }
@Test void testUnknownTaskManagerRegistration() throws Exception { try (DeclarativeSlotPoolService declarativeSlotPoolService = createDeclarativeSlotPoolService()) { final ResourceID unknownTaskManager = ResourceID.generate(); assertThat( declarativeSlotPoolService.isTaskManagerRegistered( unknownTaskManager.getResourceID())) .isFalse(); } }
public static boolean isTracerKey(String key) { return key.startsWith(PREFIX); }
@Test public void isTracerKey() { Assert.assertTrue(HttpTracerUtils.isTracerKey(RemotingConstants.RPC_TRACE_NAME + ".xx")); Assert.assertFalse(HttpTracerUtils.isTracerKey("rpc_trace_context111.xx")); }
@PostConstruct public void validateAndSetDefaults() { if (clusters != null) { validateClusterNames(); flattenClusterProperties(); setMetricsDefaults(); } }
@Test void ifOnlyOneClusterProvidedNameIsOptionalAndSetToDefault() { ClustersProperties properties = new ClustersProperties(); properties.getClusters().add(new ClustersProperties.Cluster()); properties.validateAndSetDefaults(); assertThat(properties.getClusters()) .element(0) .extracting("name") .isEqualTo("Default"); }
@Override public boolean add(ResourceConfig resourceConfig) { if (this.contains(resourceConfig) || isBlank(resourceConfig.getName())) { return false; } super.add(resourceConfig); return true; }
@Test public void shouldIgnoreCaseNamesOfResources() { ResourceConfigs resourceConfigs = new ResourceConfigs(); resourceConfigs.add(new ResourceConfig("Eoo")); resourceConfigs.add(new ResourceConfig("eoo")); assertThat(resourceConfigs.size(), is(1)); }
public static <K, E> Collector<E, ImmutableSetMultimap.Builder<K, E>, ImmutableSetMultimap<K, E>> unorderedIndex(Function<? super E, K> keyFunction) { return unorderedIndex(keyFunction, Function.identity()); }
@Test public void unorderedIndex_with_valueFunction_fails_if_key_function_returns_null() { assertThatThrownBy(() -> SINGLE_ELEMENT_LIST.stream().collect(unorderedIndex(s -> null, MyObj::getText))) .isInstanceOf(NullPointerException.class) .hasMessage("Key function can't return null"); }
public String compile(final String xls, final String template, int startRow, int startCol) { return compile( xls, template, InputType.XLS, startRow, startCol ); }
@Test public void testLoadSpecificWorksheet() { final String drl = converter.compile("/data/MultiSheetDST.drl.xls", "Another Sheet", "/templates/test_template1.drl", 11, 2); assertThat(drl).isNotNull(); }
@VisibleForTesting Date calcMostRecentDateForDeletion(@NonNull Date currentDate) { return minusHours(currentDate, numberOfHoursAfterPlayback); }
@Test public void testCalcMostRecentDateForDeletion() throws Exception { APCleanupAlgorithm algo = new APCleanupAlgorithm(24); Date curDateForTest = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse("2018-11-13T14:08:56-0800"); Date resExpected = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse("2018-11-12T14:08:56-0800"); Date resActual = algo.calcMostRecentDateForDeletion(curDateForTest); assertEquals("cutoff for retaining most recent 1 day", resExpected, resActual); }
@Override public Local find() { final NSFileManager manager = NSFileManager.defaultManager(); final NSURL group = manager .containerURLForSecurityApplicationGroupIdentifier(identifier); if(null == group) { log.warn("Missing com.apple.security.application-groups in sandbox entitlements"); } else { // You should organize the contents of this directory in the same way that any other Library folder is organized final String application = PreferencesFactory.get().getProperty("application.datafolder.name"); return new FinderLocal(String.format("%s/Library/Application Support", group.path()), application); } log.warn("Missing support for security application groups. Default to application support directory"); // Fallback for 10.7 and earlier return new ApplicationSupportDirectoryFinder().find(); }
@Test public void testFind() { assertNotNull(new SecurityApplicationGroupSupportDirectoryFinder().find()); assertEquals("~/Library/Group Containers/G69SCX94XU.duck/Library/Application Support/duck", new SecurityApplicationGroupSupportDirectoryFinder().find().getAbbreviatedPath()); }
boolean canFilterPlayer(String playerName) { boolean isMessageFromSelf = playerName.equals(client.getLocalPlayer().getName()); return !isMessageFromSelf && (config.filterFriends() || !client.isFriended(playerName, false)) && (config.filterFriendsChat() || !isFriendsChatMember(playerName)) && (config.filterClanChat() || !isClanChatMember(playerName)); }
@Test public void testMessageFromSelfIsNotFiltered() { when(localPlayer.getName()).thenReturn("Swampletics"); assertFalse(chatFilterPlugin.canFilterPlayer("Swampletics")); }
@Override public void validate(final String name, final Object value) { if (immutableProps.contains(name)) { throw new IllegalArgumentException(String.format("Cannot override property '%s'", name)); } final Consumer<Object> validator = HANDLERS.get(name); if (validator != null) { validator.accept(value); } }
@Test public void shouldThrowOnNoneOffsetReset() { // When: final IllegalArgumentException e = assertThrows( IllegalArgumentException.class, () -> validator.validate(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none") ); // Then: assertThat(e.getMessage(), containsString( "'none' is not valid for this property within KSQL" )); }
public String substring(final int beginIndex) { split(); final int beginChar = splitted.get(beginIndex); return input.substring(beginChar); }
@Test public void testSubstringGrapheme() { final UnicodeHelper lh = new UnicodeHelper("a", Method.GRAPHEME); assertEquals("a", lh.substring(0)); final UnicodeHelper lh2 = new UnicodeHelper(new String(Character.toChars(0x1f600)), Method.GRAPHEME); assertEquals(new String(Character.toChars(0x1f600)), lh2.substring(0)); final UnicodeHelper lh3 = new UnicodeHelper(UCSTR, Method.GRAPHEME); assertEquals(UCSTR, lh3.substring(0)); final UnicodeHelper lh4 = new UnicodeHelper("a" + UCSTR + "A", Method.GRAPHEME); assertEquals(UCSTR + "A", lh4.substring(1)); assertEquals("A", lh4.substring(2)); final UnicodeHelper lh5 = new UnicodeHelper("k\u035fh", Method.GRAPHEME); assertEquals("h", lh5.substring(1)); }
@Override public Registry getRegistry(URL url) { if (registryManager == null) { throw new IllegalStateException("Unable to fetch RegistryManager from ApplicationModel BeanFactory. " + "Please check if `setApplicationModel` has been override."); } Registry defaultNopRegistry = registryManager.getDefaultNopRegistryIfDestroyed(); if (null != defaultNopRegistry) { return defaultNopRegistry; } url = URLBuilder.from(url) .setPath(RegistryService.class.getName()) .addParameter(INTERFACE_KEY, RegistryService.class.getName()) .removeParameter(TIMESTAMP_KEY) .removeAttribute(EXPORT_KEY) .removeAttribute(REFER_KEY) .build(); String key = createRegistryCacheKey(url); Registry registry = null; boolean check = url.getParameter(CHECK_KEY, true) && url.getPort() != 0; // Lock the registry access process to ensure a single instance of the registry registryManager.getRegistryLock().lock(); try { // double check // fix https://github.com/apache/dubbo/issues/7265. defaultNopRegistry = registryManager.getDefaultNopRegistryIfDestroyed(); if (null != defaultNopRegistry) { return defaultNopRegistry; } registry = registryManager.getRegistry(key); if (registry != null) { return registry; } // create registry by spi/ioc registry = createRegistry(url); if (check && registry == null) { throw new IllegalStateException("Can not create registry " + url); } if (registry != null) { registryManager.putRegistry(key, registry); } } catch (Exception e) { if (check) { throw new RuntimeException("Can not create registry " + url, e); } else { // 1-11 Failed to obtain or create registry (service) object. LOGGER.warn(REGISTRY_FAILED_CREATE_INSTANCE, "", "", "Failed to obtain or create registry ", e); } } finally { // Release the lock registryManager.getRegistryLock().unlock(); } return registry; }
@Test void testRegistryFactoryGroupCache() { Registry registry1 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=aaa")); Registry registry2 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=bbb")); Assertions.assertNotSame(registry1, registry2); }
@VisibleForTesting static Set<Platform> getPlatformsSet(RawConfiguration rawConfiguration) throws InvalidPlatformException { Set<Platform> platforms = new LinkedHashSet<>(); for (PlatformConfiguration platformConfiguration : rawConfiguration.getPlatforms()) { Optional<String> architecture = platformConfiguration.getArchitectureName(); Optional<String> os = platformConfiguration.getOsName(); String platformToString = "architecture=" + architecture.orElse("<missing>") + ", os=" + os.orElse("<missing>"); if (!architecture.isPresent()) { throw new InvalidPlatformException( "platform configuration is missing an architecture value", platformToString); } if (!os.isPresent()) { throw new InvalidPlatformException( "platform configuration is missing an OS value", platformToString); } platforms.add(new Platform(architecture.get(), os.get())); } return platforms; }
@Test public void testGetPlatformsSet_osMissing() { TestPlatformConfiguration platform = new TestPlatformConfiguration("testArchitecture", null); Mockito.<List<?>>when(rawConfiguration.getPlatforms()).thenReturn(Arrays.asList(platform)); InvalidPlatformException exception = assertThrows( InvalidPlatformException.class, () -> PluginConfigurationProcessor.getPlatformsSet(rawConfiguration)); assertThat(exception) .hasMessageThat() .isEqualTo("platform configuration is missing an OS value"); assertThat(exception.getInvalidPlatform()) .isEqualTo("architecture=testArchitecture, os=<missing>"); }
@Override public void checkBeforeUpdate(final CreateEncryptRuleStatement sqlStatement) { if (!sqlStatement.isIfNotExists()) { checkDuplicateRuleNames(sqlStatement); } checkColumnNames(sqlStatement); checkAlgorithmTypes(sqlStatement); checkToBeCreatedEncryptors(sqlStatement); checkDataSources(); }
@Test void assertCheckSQLStatementWithConflictColumnNames() { EncryptRule rule = mock(EncryptRule.class); when(rule.getConfiguration()).thenReturn(getCurrentRuleConfiguration()); executor.setRule(rule); assertThrows(InvalidRuleConfigurationException.class, () -> executor.checkBeforeUpdate(createConflictColumnNameSQLStatement())); }
@Override public Bitmap clone() { return Bitmap.fromBytes(length, bitSet.toByteArray()); }
@Test public static void testClone() { Bitmap bitmapA = Bitmap.fromBytes(100 * 8, BYTE_STRING_A); Bitmap bitmapB = bitmapA.clone(); // all bits should match for (int i = 0; i < 100 * 8; i++) { assertEquals(bitmapA.getBit(i), bitmapB.getBit(i)); } // but the bitmaps should point to different bits bitmapA.flipBit(0); assertEquals(bitmapA.getBit(0), !bitmapB.getBit(0)); }
@VisibleForTesting void writeInjectedKtr( String targetFilPath ) throws KettleException { if ( shouldWriteToFilesystem() ) { writeInjectedKtrToFs( targetFilPath ); } else { writeInjectedKtrToRepo( targetFilPath ); } }
@Test public void writeInjectedKtrKeepsDataTest() throws Exception { String filepath = "filepath"; metaInject.writeInjectedKtr( filepath ); //Make sure realClone( false ) is called and no other, so that the resulting ktr keeps all the info verify( data.transMeta, times( 1 ) ).realClone( false ); verify( data.transMeta, times( 0 ) ).realClone( true ); verify( data.transMeta, times( 0 ) ).clone(); //Delete temporary file created by the test new File( filepath ).delete(); }
@Override public EncodedMessage transform(ActiveMQMessage message) throws Exception { if (message == null) { return null; } long messageFormat = 0; Header header = null; Properties properties = null; Map<Symbol, Object> daMap = null; Map<Symbol, Object> maMap = null; Map<String,Object> apMap = null; Map<Object, Object> footerMap = null; Section body = convertBody(message); if (message.isPersistent()) { if (header == null) { header = new Header(); } header.setDurable(true); } byte priority = message.getPriority(); if (priority != Message.DEFAULT_PRIORITY) { if (header == null) { header = new Header(); } header.setPriority(UnsignedByte.valueOf(priority)); } String type = message.getType(); if (type != null) { if (properties == null) { properties = new Properties(); } properties.setSubject(type); } MessageId messageId = message.getMessageId(); if (messageId != null) { if (properties == null) { properties = new Properties(); } properties.setMessageId(getOriginalMessageId(message)); } ActiveMQDestination destination = message.getDestination(); if (destination != null) { if (properties == null) { properties = new Properties(); } properties.setTo(destination.getQualifiedName()); if (maMap == null) { maMap = new HashMap<>(); } maMap.put(JMS_DEST_TYPE_MSG_ANNOTATION, destinationType(destination)); } ActiveMQDestination replyTo = message.getReplyTo(); if (replyTo != null) { if (properties == null) { properties = new Properties(); } properties.setReplyTo(replyTo.getQualifiedName()); if (maMap == null) { maMap = new HashMap<>(); } maMap.put(JMS_REPLY_TO_TYPE_MSG_ANNOTATION, destinationType(replyTo)); } String correlationId = message.getCorrelationId(); if (correlationId != null) { if (properties == null) { properties = new Properties(); } try { properties.setCorrelationId(AMQPMessageIdHelper.INSTANCE.toIdObject(correlationId)); } catch (AmqpProtocolException e) { properties.setCorrelationId(correlationId); } } long expiration = message.getExpiration(); if (expiration != 0) { long ttl = expiration - System.currentTimeMillis(); if (ttl < 0) { ttl = 1; } if (header == null) { header = new Header(); } header.setTtl(new UnsignedInteger((int) ttl)); if (properties == null) { properties = new Properties(); } properties.setAbsoluteExpiryTime(new Date(expiration)); } long timeStamp = message.getTimestamp(); if (timeStamp != 0) { if (properties == null) { properties = new Properties(); } properties.setCreationTime(new Date(timeStamp)); } // JMSX Message Properties int deliveryCount = message.getRedeliveryCounter(); if (deliveryCount > 0) { if (header == null) { header = new Header(); } header.setDeliveryCount(UnsignedInteger.valueOf(deliveryCount)); } String userId = message.getUserID(); if (userId != null) { if (properties == null) { properties = new Properties(); } properties.setUserId(new Binary(userId.getBytes(StandardCharsets.UTF_8))); } String groupId = message.getGroupID(); if (groupId != null) { if (properties == null) { properties = new Properties(); } properties.setGroupId(groupId); } int groupSequence = message.getGroupSequence(); if (groupSequence > 0) { if (properties == null) { properties = new Properties(); } properties.setGroupSequence(UnsignedInteger.valueOf(groupSequence)); } final Map<String, Object> entries; try { entries = message.getProperties(); } catch (IOException e) { throw JMSExceptionSupport.create(e); } for (Map.Entry<String, Object> entry : entries.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (key.startsWith(JMS_AMQP_PREFIX)) { if (key.startsWith(NATIVE, JMS_AMQP_PREFIX_LENGTH)) { // skip transformer appended properties continue; } else if (key.startsWith(ORIGINAL_ENCODING, JMS_AMQP_PREFIX_LENGTH)) { // skip transformer appended properties continue; } else if (key.startsWith(MESSAGE_FORMAT, JMS_AMQP_PREFIX_LENGTH)) { messageFormat = (long) TypeConversionSupport.convert(entry.getValue(), Long.class); continue; } else if (key.startsWith(HEADER, JMS_AMQP_PREFIX_LENGTH)) { if (header == null) { header = new Header(); } continue; } else if (key.startsWith(PROPERTIES, JMS_AMQP_PREFIX_LENGTH)) { if (properties == null) { properties = new Properties(); } continue; } else if (key.startsWith(MESSAGE_ANNOTATION_PREFIX, JMS_AMQP_PREFIX_LENGTH)) { if (maMap == null) { maMap = new HashMap<>(); } String name = key.substring(JMS_AMQP_MESSAGE_ANNOTATION_PREFIX.length()); maMap.put(Symbol.valueOf(name), value); continue; } else if (key.startsWith(FIRST_ACQUIRER, JMS_AMQP_PREFIX_LENGTH)) { if (header == null) { header = new Header(); } header.setFirstAcquirer((boolean) TypeConversionSupport.convert(value, Boolean.class)); continue; } else if (key.startsWith(CONTENT_TYPE, JMS_AMQP_PREFIX_LENGTH)) { if (properties == null) { properties = new Properties(); } properties.setContentType(Symbol.getSymbol((String) TypeConversionSupport.convert(value, String.class))); continue; } else if (key.startsWith(CONTENT_ENCODING, JMS_AMQP_PREFIX_LENGTH)) { if (properties == null) { properties = new Properties(); } properties.setContentEncoding(Symbol.getSymbol((String) TypeConversionSupport.convert(value, String.class))); continue; } else if (key.startsWith(REPLYTO_GROUP_ID, JMS_AMQP_PREFIX_LENGTH)) { if (properties == null) { properties = new Properties(); } properties.setReplyToGroupId((String) TypeConversionSupport.convert(value, String.class)); continue; } else if (key.startsWith(DELIVERY_ANNOTATION_PREFIX, JMS_AMQP_PREFIX_LENGTH)) { if (daMap == null) { daMap = new HashMap<>(); } String name = key.substring(JMS_AMQP_DELIVERY_ANNOTATION_PREFIX.length()); daMap.put(Symbol.valueOf(name), value); continue; } else if (key.startsWith(FOOTER_PREFIX, JMS_AMQP_PREFIX_LENGTH)) { if (footerMap == null) { footerMap = new HashMap<>(); } String name = key.substring(JMS_AMQP_FOOTER_PREFIX.length()); footerMap.put(Symbol.valueOf(name), value); continue; } } else if (key.startsWith(AMQ_SCHEDULED_MESSAGE_PREFIX )) { // strip off the scheduled message properties continue; } // The property didn't map into any other slot so we store it in the // Application Properties section of the message. if (apMap == null) { apMap = new HashMap<>(); } apMap.put(key, value); int messageType = message.getDataStructureType(); if (messageType == CommandTypes.ACTIVEMQ_MESSAGE) { // Type of command to recognize advisory message Object data = message.getDataStructure(); if(data != null) { apMap.put("ActiveMqDataStructureType", data.getClass().getSimpleName()); } } } final AmqpWritableBuffer buffer = new AmqpWritableBuffer(); encoder.setByteBuffer(buffer); if (header != null) { encoder.writeObject(header); } if (daMap != null) { encoder.writeObject(new DeliveryAnnotations(daMap)); } if (maMap != null) { encoder.writeObject(new MessageAnnotations(maMap)); } if (properties != null) { encoder.writeObject(properties); } if (apMap != null) { encoder.writeObject(new ApplicationProperties(apMap)); } if (body != null) { encoder.writeObject(body); } if (footerMap != null) { encoder.writeObject(new Footer(footerMap)); } return new EncodedMessage(messageFormat, buffer.getArray(), 0, buffer.getArrayLength()); }
@Test public void testConvertMapMessageToAmqpMessageWithByteArrayValueInBody() throws Exception { final byte[] byteArray = new byte[] { 1, 2, 3, 4, 5 }; ActiveMQMapMessage outbound = createMapMessage(); outbound.setBytes("bytes", byteArray); outbound.onSend(); outbound.storeContent(); JMSMappingOutboundTransformer transformer = new JMSMappingOutboundTransformer(); EncodedMessage encoded = transformer.transform(outbound); assertNotNull(encoded); Message amqp = encoded.decode(); assertNotNull(amqp.getBody()); assertTrue(amqp.getBody() instanceof AmqpValue); assertTrue(((AmqpValue) amqp.getBody()).getValue() instanceof Map); @SuppressWarnings("unchecked") Map<Object, Object> amqpMap = (Map<Object, Object>) ((AmqpValue) amqp.getBody()).getValue(); assertEquals(1, amqpMap.size()); Binary readByteArray = (Binary) amqpMap.get("bytes"); assertNotNull(readByteArray); }
@Override public ClientDetailsEntity saveNewClient(ClientDetailsEntity client) { if (client.getId() != null) { // if it's not null, it's already been saved, this is an error throw new IllegalArgumentException("Tried to save a new client with an existing ID: " + client.getId()); } if (client.getRegisteredRedirectUri() != null) { for (String uri : client.getRegisteredRedirectUri()) { if (blacklistedSiteService.isBlacklisted(uri)) { throw new IllegalArgumentException("Client URI is blacklisted: " + uri); } } } // assign a random clientid if it's empty // NOTE: don't assign a random client secret without asking, since public clients have no secret if (Strings.isNullOrEmpty(client.getClientId())) { client = generateClientId(client); } // make sure that clients with the "refresh_token" grant type have the "offline_access" scope, and vice versa ensureRefreshTokenConsistency(client); // make sure we don't have both a JWKS and a JWKS URI ensureKeyConsistency(client); // check consistency when using HEART mode checkHeartMode(client); // timestamp this to right now client.setCreatedAt(new Date()); // check the sector URI checkSectorIdentifierUri(client); ensureNoReservedScopes(client); ClientDetailsEntity c = clientRepository.saveClient(client); statsService.resetCache(); return c; }
@Test public void saveNewClient_yesOfflineAccess() { ClientDetailsEntity client = new ClientDetailsEntity(); Set<String> grantTypes = new HashSet<>(); grantTypes.add("refresh_token"); client.setGrantTypes(grantTypes); client = service.saveNewClient(client); assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(true))); }
@GetMapping("/api/v1/meetings/{uuid}/sharing") public MomoApiResponse<MeetingSharingResponse> findMeetingSharing(@PathVariable String uuid) { MeetingSharingResponse response = meetingService.findMeetingSharing(uuid); return new MomoApiResponse<>(response); }
@DisplayName("약속 공유 정보를 조회하면 200OK와 응답을 반환한다.") @Test void findMeetingSharing() { Meeting meeting = meetingRepository.save(MeetingFixture.DINNER.create()); RestAssured.given().log().all() .contentType(ContentType.JSON) .when().get("/api/v1/meetings/{uuid}/sharing", meeting.getUuid()) .then().log().all() .statusCode(HttpStatus.OK.value()); }
@CheckForNull public String getDecoratedSourceAsHtml(@Nullable String sourceLine, @Nullable String highlighting, @Nullable String symbols) { if (sourceLine == null) { return null; } DecorationDataHolder decorationDataHolder = new DecorationDataHolder(); if (StringUtils.isNotBlank(highlighting)) { decorationDataHolder.loadSyntaxHighlightingData(highlighting); } if (StringUtils.isNotBlank(symbols)) { decorationDataHolder.loadLineSymbolReferences(symbols); } HtmlTextDecorator textDecorator = new HtmlTextDecorator(); List<String> decoratedSource = textDecorator.decorateTextWithHtml(sourceLine, decorationDataHolder, 1, 1); if (decoratedSource == null) { return null; } else { if (decoratedSource.isEmpty()) { return ""; } else { return decoratedSource.get(0); } } }
@Test public void should_ignore_empty_rule() { String sourceLine = "@Deprecated"; String highlighting = "0,0,a;0,11,a"; String symbols = "1,11,1"; assertThat(sourceDecorator.getDecoratedSourceAsHtml(sourceLine, highlighting, symbols)).isEqualTo("<span class=\"a\">@<span class=\"sym-1 sym\">Deprecated</span></span>"); }
public void attempts() { try { requireJob(); } catch (Exception e) { renderText(e.getMessage()); return; } if (app.getJob() != null) { try { String taskType = $(TASK_TYPE); if (taskType.isEmpty()) { throw new RuntimeException("missing task-type."); } String attemptState = $(ATTEMPT_STATE); if (attemptState.isEmpty()) { throw new RuntimeException("missing attempt-state."); } setTitle(join(attemptState, " ", MRApps.taskType(taskType).toString(), " attempts in ", $(JOB_ID))); render(attemptsPage()); } catch (Exception e) { LOG.error("Failed to render attempts page with task type : " + $(TASK_TYPE) + " for job id : " + $(JOB_ID), e); badRequest(e.getMessage()); } } }
@Test public void testAttempts() { appController.getProperty().remove(AMParams.TASK_TYPE); when(job.checkAccess(any(UserGroupInformation.class), any(JobACL.class))) .thenReturn(false); appController.attempts(); verify(appController.response()).setContentType(MimeType.TEXT); assertEquals( "Access denied: User user does not have permission to view job job_01_01", appController.getData()); when(job.checkAccess(any(UserGroupInformation.class), any(JobACL.class))) .thenReturn(true); appController.getProperty().remove(AMParams.TASK_ID); appController.attempts(); assertEquals( "Access denied: User user does not have permission to view job job_01_01", appController.getData()); appController.getProperty().put(AMParams.TASK_ID, taskId); appController.attempts(); assertEquals("Bad request: missing task-type.", appController.getProperty() .get("title")); appController.getProperty().put(AMParams.TASK_TYPE, "m"); appController.attempts(); assertEquals("Bad request: missing attempt-state.", appController .getProperty().get("title")); appController.getProperty().put(AMParams.ATTEMPT_STATE, "State"); appController.attempts(); assertEquals(AttemptsPage.class, appController.getClazz()); appController.getProperty().remove(AMParams.ATTEMPT_STATE); }
public Value parse(String json) { return this.delegate.parse(json); }
@Test public void testExponentialFloat() throws Exception { final JsonParser parser = new JsonParser(); final Value msgpackValue = parser.parse("1.234512E4"); assertTrue(msgpackValue.getValueType().isNumberType()); assertTrue(msgpackValue.getValueType().isFloatType()); assertFalse(msgpackValue.getValueType().isIntegerType()); assertFalse(msgpackValue.getValueType().isStringType()); assertEquals(12345.12, msgpackValue.asFloatValue().toDouble(), 0.000000001); // Not sure this |toString| is to be tested... assertEquals("12345.12", msgpackValue.asFloatValue().toString()); }
public long getPositiveMillisOrDefault(HazelcastProperty property) { return getPositiveMillisOrDefault(property, Long.parseLong(property.getDefaultValue())); }
@Test public void getPositiveMillisOrDefaultWithManualDefault() { String name = ClusterProperty.PARTITION_TABLE_SEND_INTERVAL.getName(); config.setProperty(name, "-300"); HazelcastProperties properties = new HazelcastProperties(config); HazelcastProperty property = new HazelcastProperty(name, "20", TimeUnit.MILLISECONDS); long millis = properties.getPositiveMillisOrDefault(property, 50); assertEquals(50, millis); }
public final ResourceSkyline getResourceSkyline() { return resourceSkyline; }
@Test public final void testStringToUnixTimestamp() throws ParseException { final long submissionTime = logParserUtil.stringToUnixTimestamp("17/07/16 16:27:25"); Assert.assertEquals(jobMetaData.getResourceSkyline().getJobSubmissionTime(), submissionTime); }
@Override public Dataset<Row> apply(JavaSparkContext jsc, SparkSession sparkSession, Dataset<Row> rowDataset, TypedProperties properties) { String transformerSQL = getStringWithAltKeys(properties, SqlTransformerConfig.TRANSFORMER_SQL); try { // tmp table name doesn't like dashes String tmpTable = TMP_TABLE.concat(UUID.randomUUID().toString().replace("-", "_")); LOG.info("Registering tmp table: {}", tmpTable); rowDataset.createOrReplaceTempView(tmpTable); String sqlStr = transformerSQL.replaceAll(SRC_PATTERN, tmpTable); LOG.debug("SQL Query for transformation: {}", sqlStr); Dataset<Row> transformed = sparkSession.sql(sqlStr); sparkSession.catalog().dropTempView(tmpTable); return transformed; } catch (Exception e) { throw new HoodieTransformExecutionException("Failed to apply sql query based transformer", e); } }
@Test public void testSqlQuery() { SparkSession spark = SparkSession .builder() .config(getSparkConfForTest(TestSqlQueryBasedTransformer.class.getName())) .getOrCreate(); JavaSparkContext jsc = JavaSparkContext.fromSparkContext(spark.sparkContext()); // prepare test data String testData = "{\n" + " \"ts\": 1622126968000,\n" + " \"uuid\": \"c978e157-72ee-4819-8f04-8e46e1bb357a\",\n" + " \"rider\": \"rider-213\",\n" + " \"driver\": \"driver-213\",\n" + " \"begin_lat\": 0.4726905879569653,\n" + " \"begin_lon\": 0.46157858450465483,\n" + " \"end_lat\": 0.754803407008858,\n" + " \"end_lon\": 0.9671159942018241,\n" + " \"fare\": 34.158284716382845,\n" + " \"partitionpath\": \"americas/brazil/sao_paulo\"\n" + "}"; JavaRDD<String> testRdd = jsc.parallelize(Collections.singletonList(testData), 2); Dataset<Row> ds = spark.read().json(testRdd); // create a new column dt, whose value is transformed from ts, format is yyyyMMdd String transSql = "select\n" + "\tuuid,\n" + "\tbegin_lat,\n" + "\tbegin_lon,\n" + "\tdriver,\n" + "\tend_lat,\n" + "\tend_lon,\n" + "\tfare,\n" + "\tpartitionpath,\n" + "\trider,\n" + "\tts,\n" + "\tFROM_UNIXTIME(ts / 1000, 'yyyyMMdd') as dt\n" + "from\n" + "\t<SRC>"; TypedProperties props = new TypedProperties(); props.put("hoodie.streamer.transformer.sql", transSql); // transform SqlQueryBasedTransformer transformer = new SqlQueryBasedTransformer(); // test if the class throws illegal argument exception when sql-config is missing assertThrows(IllegalArgumentException.class, () -> transformer.apply(jsc, spark, ds, new TypedProperties())); Dataset<Row> result = transformer.apply(jsc, spark, ds, props); // check result assertEquals(11, result.columns().length); assertNotNull(result.col("dt")); assertEquals("20210527", result.first().get(10).toString()); spark.close(); }
@VisibleForTesting static String getDefaultBaseImage(ProjectProperties projectProperties) throws IncompatibleBaseImageJavaVersionException { if (projectProperties.isWarProject()) { return "jetty"; } int javaVersion = projectProperties.getMajorJavaVersion(); if (javaVersion <= 8) { return "eclipse-temurin:8-jre"; } else if (javaVersion <= 11) { return "eclipse-temurin:11-jre"; } else if (javaVersion <= 17) { return "eclipse-temurin:17-jre"; } else if (javaVersion <= 21) { return "eclipse-temurin:21-jre"; } throw new IncompatibleBaseImageJavaVersionException(21, javaVersion); }
@Test public void testGetDefaultBaseImage_warProject() throws IncompatibleBaseImageJavaVersionException { when(projectProperties.isWarProject()).thenReturn(true); assertThat(PluginConfigurationProcessor.getDefaultBaseImage(projectProperties)) .isEqualTo("jetty"); }
@Override public void writeInt(final int v) throws IOException { ensureAvailable(INT_SIZE_IN_BYTES); Bits.writeInt(buffer, pos, v, isBigEndian); pos += INT_SIZE_IN_BYTES; }
@Test public void testWriteIntForPositionV() throws Exception { int expected = 100; out.writeInt(1, expected); int actual = Bits.readIntB(out.buffer, 1); assertEquals(expected, actual); }
@Override public List<URL> lookup(URL url) { if (url == null) { throw new IllegalArgumentException("lookup url == null"); } try { checkDestroyed(); List<String> providers = new ArrayList<>(); for (String path : toCategoriesPath(url)) { List<String> children = zkClient.getChildren(path); if (children != null) { providers.addAll(children); } } return toUrlsWithoutEmpty(url, providers); } catch (Throwable e) { throw new RpcException( "Failed to lookup " + url + " from zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } }
@Test void testLookupIllegalUrl() { try { zookeeperRegistry.lookup(null); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage(), containsString("lookup url == null")); } }
public boolean matchesBeacon(Beacon beacon) { // All identifiers must match, or the corresponding region identifier must be null. for (int i = mIdentifiers.size(); --i >= 0; ) { final Identifier identifier = mIdentifiers.get(i); Identifier beaconIdentifier = null; if (i < beacon.mIdentifiers.size()) { beaconIdentifier = beacon.getIdentifier(i); } if ((beaconIdentifier == null && identifier != null) || (beaconIdentifier != null && identifier != null && !identifier.equals(beaconIdentifier))) { return false; } } if (mBluetoothAddress != null && !mBluetoothAddress.equalsIgnoreCase(beacon.mBluetoothAddress)) { return false; } return true; }
@Test public void testBeaconMatchesRegionWithDifferentIdentifier1() { Beacon beacon = new AltBeacon.Builder().setId1("1").setId2("2").setId3("3").setRssi(4) .setBeaconTypeCode(5).setTxPower(6).setBluetoothAddress("1:2:3:4:5:6").build(); Region region = new Region("myRegion", Identifier.parse("22222"), null, null); assertTrue("Beacon should not match region with first identifier different", !region.matchesBeacon(beacon)); }
@Override public Path calcPath(int from, int to) { setupFinishTime(); fromNode = from; endNode = findEndNode(from, to); if (endNode < 0 || isWeightLimitExceeded()) { Path path = createEmptyPath(); path.setFromNode(fromNode); path.setEndNode(endNode); return path; } Path path = new Path(graph); int node = endNode; while (true) { int edge = edgeIds[node]; if (!EdgeIterator.Edge.isValid(edge)) { break; } EdgeIteratorState edgeState = graph.getEdgeIteratorState(edge, node); path.addDistance(edgeState.getDistance()); // todo: we do not yet account for turn times here! path.addTime(weighting.calcEdgeMillis(edgeState, false)); path.addEdge(edge); node = parents[node]; } ArrayUtil.reverse(path.getEdges()); path.setFromNode(fromNode); path.setEndNode(endNode); path.setFound(true); path.setWeight(weights[endNode]); return path; }
@Test public void testIssue182() { BaseGraph graph = createGHStorage(); initGraph(graph); Path p = calcPath(graph, 0, 8); assertEquals(IntArrayList.from(0, 7, 8), p.calcNodes()); // expand SPT p = calcPath(graph, 0, 10); assertEquals(IntArrayList.from(0, 1, 2, 3, 4, 10), p.calcNodes()); }
@Override public String serializeRow(SeaTunnelRow row) { switch (row.getRowKind()) { case INSERT: case UPDATE_AFTER: return serializeUpsert(row); case UPDATE_BEFORE: case DELETE: return serializeDelete(row); default: throw new ElasticsearchConnectorException( CommonErrorCodeDeprecated.UNSUPPORTED_OPERATION, "Unsupported write row kind: " + row.getRowKind()); } }
@Test public void testSerializeUpsertWithoutKey() { String index = "st_index"; Map<String, Object> confMap = new HashMap<>(); confMap.put(SinkConfig.INDEX.key(), index); ReadonlyConfig pluginConf = ReadonlyConfig.fromMap(confMap); ElasticsearchClusterInfo clusterInfo = ElasticsearchClusterInfo.builder().clusterVersion("8.0.0").build(); IndexInfo indexInfo = new IndexInfo(index, pluginConf); SeaTunnelRowType schema = new SeaTunnelRowType( new String[] {"id", "name"}, new SeaTunnelDataType[] {STRING_TYPE, STRING_TYPE}); final ElasticsearchRowSerializer serializer = new ElasticsearchRowSerializer(clusterInfo, indexInfo, schema); String id = "0001"; String name = "jack"; SeaTunnelRow row = new SeaTunnelRow(new Object[] {id, name}); row.setRowKind(RowKind.UPDATE_AFTER); String expected = "{ \"index\" :{\"_index\":\"" + index + "\"} }\n" + "{\"name\":\"" + name + "\",\"id\":\"" + id + "\"}"; String upsertStr = serializer.serializeRow(row); Assertions.assertEquals(expected, upsertStr); }
@Override public byte[] toByteArray() { // write last chunk message id MessageIdData msgId = super.writeMessageIdData(null, -1, 0); // write first chunk message id msgId.setFirstChunkMessageId(); firstChunkMsgId.writeMessageIdData(msgId.getFirstChunkMessageId(), -1, 0); int size = msgId.getSerializedSize(); ByteBuf serialized = Unpooled.buffer(size, size); msgId.writeTo(serialized); return serialized.array(); }
@Test public void serializeAndDeserializeTest() throws IOException { ChunkMessageIdImpl chunkMessageId = new ChunkMessageIdImpl( new MessageIdImpl(0, 0, 0), new MessageIdImpl(1, 1, 1) ); byte[] serialized = chunkMessageId.toByteArray(); ChunkMessageIdImpl deserialized = (ChunkMessageIdImpl) MessageIdImpl.fromByteArray(serialized); assertEquals(deserialized, chunkMessageId); }
@Override void decode(ByteBufAllocator alloc, ByteBuf headerBlock, SpdyHeadersFrame frame) throws Exception { ObjectUtil.checkNotNull(headerBlock, "headerBlock"); ObjectUtil.checkNotNull(frame, "frame"); if (cumulation == null) { decodeHeaderBlock(headerBlock, frame); if (headerBlock.isReadable()) { cumulation = alloc.buffer(headerBlock.readableBytes()); cumulation.writeBytes(headerBlock); } } else { cumulation.writeBytes(headerBlock); decodeHeaderBlock(cumulation, frame); if (cumulation.isReadable()) { cumulation.discardReadBytes(); } else { releaseBuffer(); } } }
@Test public void testIllegalValueEndsWithNull() throws Exception { ByteBuf headerBlock = Unpooled.buffer(22); headerBlock.writeInt(1); headerBlock.writeInt(4); headerBlock.writeBytes(nameBytes); headerBlock.writeInt(6); headerBlock.writeBytes(valueBytes); headerBlock.writeByte(0); decoder.decode(ByteBufAllocator.DEFAULT, headerBlock, frame); assertFalse(headerBlock.isReadable()); assertTrue(frame.isInvalid()); assertEquals(0, frame.headers().names().size()); headerBlock.release(); }
public synchronized TopologyDescription describe() { return internalTopologyBuilder.describe(); }
@Test public void streamStreamLeftJoinTopologyWithCustomStoresNames() { final StreamsBuilder builder = new StreamsBuilder(); final KStream<Integer, String> stream1; final KStream<Integer, String> stream2; stream1 = builder.stream("input-topic1"); stream2 = builder.stream("input-topic2"); stream1.leftJoin( stream2, MockValueJoiner.TOSTRING_JOINER, JoinWindows.ofTimeDifferenceWithNoGrace(ofMillis(100)), StreamJoined.with(Serdes.Integer(), Serdes.String(), Serdes.String()) .withStoreName("custom-name")); final TopologyDescription describe = builder.build().describe(); assertEquals( "Topologies:\n" + " Sub-topology: 0\n" + " Source: KSTREAM-SOURCE-0000000000 (topics: [input-topic1])\n" + " --> KSTREAM-WINDOWED-0000000002\n" + " Source: KSTREAM-SOURCE-0000000001 (topics: [input-topic2])\n" + " --> KSTREAM-WINDOWED-0000000003\n" + " Processor: KSTREAM-WINDOWED-0000000002 (stores: [custom-name-this-join-store])\n" + " --> KSTREAM-JOINTHIS-0000000004\n" + " <-- KSTREAM-SOURCE-0000000000\n" + " Processor: KSTREAM-WINDOWED-0000000003 (stores: [custom-name-outer-other-join-store])\n" + " --> KSTREAM-OUTEROTHER-0000000005\n" + " <-- KSTREAM-SOURCE-0000000001\n" + " Processor: KSTREAM-JOINTHIS-0000000004 (stores: [custom-name-outer-other-join-store, custom-name-left-shared-join-store])\n" + " --> KSTREAM-MERGE-0000000006\n" + " <-- KSTREAM-WINDOWED-0000000002\n" + " Processor: KSTREAM-OUTEROTHER-0000000005 (stores: [custom-name-this-join-store, custom-name-left-shared-join-store])\n" + " --> KSTREAM-MERGE-0000000006\n" + " <-- KSTREAM-WINDOWED-0000000003\n" + " Processor: KSTREAM-MERGE-0000000006 (stores: [])\n" + " --> none\n" + " <-- KSTREAM-JOINTHIS-0000000004, KSTREAM-OUTEROTHER-0000000005\n\n", describe.toString()); }
@Override public MutableTreeRootHolder setRoots(Component root, Component reportRoot) { checkState(this.root == null, "root can not be set twice in holder"); this.root = requireNonNull(root, "root can not be null"); this.extendedTreeRoot = requireNonNull(reportRoot, "extended tree root can not be null"); return this; }
@Test public void setRoot_throws_ISE_when_called_twice() { underTest.setRoots(DUMB_PROJECT, DUMB_PROJECT); assertThatThrownBy(() -> underTest.setRoots(null, DUMB_PROJECT)) .isInstanceOf(IllegalStateException.class) .hasMessage("root can not be set twice in holder"); }
public void go(PrintStream out) { KieServices ks = KieServices.Factory.get(); KieRepository kr = ks.getRepository(); KieModule kModule = kr.addKieModule(ks.getResources().newFileSystemResource(getFile("default-kiesession"))); KieContainer kContainer = ks.newKieContainer(kModule.getReleaseId()); KieSession kSession = kContainer.newKieSession(); kSession.setGlobal("out", out); Object msg1 = createMessage(kContainer, "Dave", "Hello, HAL. Do you read me, HAL?"); kSession.insert(msg1); kSession.fireAllRules(); }
@Test public void testGo() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); new DefaultKieSessionFromFileExample().go(ps); ps.close(); String actual = baos.toString(); String expected = "" + "Dave: Hello, HAL. Do you read me, HAL?" + NL + "HAL: Dave. I read you." + NL; assertEquals(expected, actual); }
Set<String> getTargetImageAdditionalTags() { String property = getProperty(PropertyNames.TO_TAGS); List<String> tags = property != null ? ConfigurationPropertyValidator.parseListProperty(property) : to.tags; if (tags.stream().anyMatch(Strings::isNullOrEmpty)) { String source = property != null ? PropertyNames.TO_TAGS : "<to><tags>"; throw new IllegalArgumentException(source + " has empty tag"); } return new HashSet<>(tags); }
@Test public void testEmptyOrNullTags() { // https://github.com/GoogleContainerTools/jib/issues/1534 // Maven turns empty tags into null entries, and its possible to have empty tags in jib.to.tags sessionProperties.put("jib.to.tags", "a,,b"); Exception ex = assertThrows( IllegalArgumentException.class, () -> testPluginConfiguration.getTargetImageAdditionalTags()); assertThat(ex.getMessage()).isEqualTo("jib.to.tags has empty tag"); }
public void setCompostState(FarmingPatch fp, CompostState state) { log.debug("Storing compost state [{}] for patch [{}]", state, fp); if (state == null) { configManager.unsetRSProfileConfiguration(TimeTrackingConfig.CONFIG_GROUP, configKey(fp)); } else { configManager.setRSProfileConfiguration(TimeTrackingConfig.CONFIG_GROUP, configKey(fp), state); } }
@Test public void setCompostState_storesNonNullChangesToConfig() { compostTracker.setCompostState(farmingPatch, CompostState.COMPOST); verify(configManager).setRSProfileConfiguration("timetracking", "MOCK.compost", CompostState.COMPOST); }
@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 testFilterWithWhitespaceAroundKVNoException() { TokenizerConverter f = new TokenizerConverter(new HashMap<String, Object>()); @SuppressWarnings("unchecked") Map<String, String> result = (Map<String, String>) f.convert("k1 = "); assertEquals(0, result.size()); }
public static void checkArgument(boolean expression, Object errorMessage) { if (Objects.isNull(errorMessage)) { throw new IllegalArgumentException("errorMessage cannot be null."); } if (!expression) { throw new IllegalArgumentException(String.valueOf(errorMessage)); } }
@Test void testCheckArgument2Args1false() { assertThrows(IllegalArgumentException.class, () -> { Preconditions.checkArgument(false, ERRORMSG); }); }
public void validate(ExternalIssueReport report, Path reportPath) { if (report.rules != null && report.issues != null) { Set<String> ruleIds = validateRules(report.rules, reportPath); validateIssuesCctFormat(report.issues, ruleIds, reportPath); } else if (report.rules == null && report.issues != null) { String documentationLink = documentationLinkGenerator.getDocumentationLink(DOCUMENTATION_SUFFIX); LOGGER.warn("External issues were imported with a deprecated format which will be removed soon. " + "Please switch to the newest format to fully benefit from Clean Code: {}", documentationLink); validateIssuesDeprecatedFormat(report.issues, reportPath); } else { throw new IllegalStateException(String.format("Failed to parse report '%s': invalid report detected.", reportPath)); } }
@Test public void validate_whenDeprecatedReportMissingType_shouldThrowException() throws IOException { ExternalIssueReport report = read(DEPRECATED_REPORTS_LOCATION); report.issues[0].type = null; assertThatThrownBy(() -> validator.validate(report, reportPath)) .isInstanceOf(IllegalStateException.class) .hasMessage("Failed to parse report 'report-path': missing mandatory field 'type'."); assertWarningLog(); }
@Override public Object evaluate(final ProcessingDTO processingDTO) { Number input = (Number) getFromPossibleSources(name, processingDTO) .orElse(mapMissingTo); if (input == null) { throw new KiePMMLException("Failed to retrieve input number for " + name); } return evaluate(input); }
@Test void evaluateInputAndLimitLinearNorms() { double startOrig = 2.1; double startNorm = 2.6; double endOrig = 7.4; double endNorm = 6.9; KiePMMLLinearNorm startLinearNorm = new KiePMMLLinearNorm("start", Collections.emptyList(), startOrig, startNorm); KiePMMLLinearNorm endLinearNorm = new KiePMMLLinearNorm("end", Collections.emptyList(), endOrig, endNorm); KiePMMLLinearNorm[] limitLinearNorms = {startLinearNorm, endLinearNorm}; Number input = 3.5; Number retrieved = KiePMMLNormContinuous.evaluate(input, limitLinearNorms); assertThat(retrieved).isNotNull(); Number expected = startNorm + ((input.doubleValue() - startOrig) / (endOrig - startOrig)) * (endNorm - startNorm); assertThat(retrieved).isEqualTo(expected); }
public String toString(SqlFunctionProperties properties) { StringBuilder buffer = new StringBuilder(); if (isSingleValue()) { buffer.append('['); appendQuotedValue(buffer, low, properties); buffer.append(']'); } else { buffer.append((low.getBound() == Marker.Bound.EXACTLY) ? '[' : '('); if (low.isLowerUnbounded()) { buffer.append("<min>"); } else { appendQuotedValue(buffer, low, properties); } buffer.append(", "); if (high.isUpperUnbounded()) { buffer.append("<max>"); } else { appendQuotedValue(buffer, high, properties); } buffer.append((high.getBound() == Marker.Bound.EXACTLY) ? ']' : ')'); } return buffer.toString(); }
@Test public void testToString() { Range range = Range.all(VARCHAR); assertEquals(range.toString(PROPERTIES), "(<min>, <max>)"); range = Range.equal(VARCHAR, utf8Slice("some string")); assertEquals(range.toString(PROPERTIES), "[\"some string\"]"); range = Range.equal(VARCHAR, utf8Slice("here's a quote: \"")); assertEquals(range.toString(PROPERTIES), "[\"here's a quote: \\\"\"]"); range = Range.equal(VARCHAR, utf8Slice("")); assertEquals(range.toString(PROPERTIES), "[\"\"]"); range = Range.greaterThanOrEqual(VARCHAR, utf8Slice("string with \"quotes\" inside")).intersect(Range.lessThanOrEqual(VARCHAR, utf8Slice("this string's quote is here -> \""))); assertEquals(range.toString(PROPERTIES), "[\"string with \\\"quotes\\\" inside\", \"this string's quote is here -> \\\"\"]"); range = Range.greaterThan(VARCHAR, utf8Slice("string with \"quotes\" inside")).intersect(Range.lessThan(VARCHAR, utf8Slice("this string's quote is here -> \""))); assertEquals(range.toString(PROPERTIES), "(\"string with \\\"quotes\\\" inside\", \"this string's quote is here -> \\\"\")"); range = Range.equal(VARCHAR, utf8Slice("<min>")); assertEquals(range.toString(PROPERTIES), "[\"<min>\"]"); range = Range.equal(VARCHAR, utf8Slice("<max>")); assertEquals(range.toString(PROPERTIES), "[\"<max>\"]"); range = Range.equal(VARCHAR, utf8Slice("<min>, <max>")); assertEquals(range.toString(PROPERTIES), "[\"<min>, <max>\"]"); range = Range.greaterThanOrEqual(VARCHAR, utf8Slice("a")).intersect(Range.lessThanOrEqual(VARCHAR, utf8Slice("b"))); assertEquals(range.toString(PROPERTIES), "[\"a\", \"b\"]"); range = Range.equal(VARCHAR, utf8Slice("a, b")); assertEquals(range.toString(PROPERTIES), "[\"a, b\"]"); }
@Override public boolean supportsPluginSettingsNotification() { return false; }
@Test public void shouldNotSupportSettingsNotification() throws Exception { assertFalse(messageHandler.supportsPluginSettingsNotification()); }
@PostMapping("/token") @PermitAll @Operation(summary = "获得访问令牌", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【获取】调用") @Parameters({ @Parameter(name = "grant_type", required = true, description = "授权类型", example = "code"), @Parameter(name = "code", description = "授权范围", example = "userinfo.read"), @Parameter(name = "redirect_uri", description = "重定向 URI", example = "https://www.iocoder.cn"), @Parameter(name = "state", description = "状态", example = "1"), @Parameter(name = "username", example = "tudou"), @Parameter(name = "password", example = "cai"), // 多个使用空格分隔 @Parameter(name = "scope", example = "user_info"), @Parameter(name = "refresh_token", example = "123424233"), }) public CommonResult<OAuth2OpenAccessTokenRespVO> postAccessToken(HttpServletRequest request, @RequestParam("grant_type") String grantType, @RequestParam(value = "code", required = false) String code, // 授权码模式 @RequestParam(value = "redirect_uri", required = false) String redirectUri, // 授权码模式 @RequestParam(value = "state", required = false) String state, // 授权码模式 @RequestParam(value = "username", required = false) String username, // 密码模式 @RequestParam(value = "password", required = false) String password, // 密码模式 @RequestParam(value = "scope", required = false) String scope, // 密码模式 @RequestParam(value = "refresh_token", required = false) String refreshToken) { // 刷新模式 List<String> scopes = OAuth2Utils.buildScopes(scope); // 1.1 校验授权类型 OAuth2GrantTypeEnum grantTypeEnum = OAuth2GrantTypeEnum.getByGranType(grantType); if (grantTypeEnum == null) { throw exception0(BAD_REQUEST.getCode(), StrUtil.format("未知授权类型({})", grantType)); } if (grantTypeEnum == OAuth2GrantTypeEnum.IMPLICIT) { throw exception0(BAD_REQUEST.getCode(), "Token 接口不支持 implicit 授权模式"); } // 1.2 校验客户端 String[] clientIdAndSecret = obtainBasicAuthorization(request); OAuth2ClientDO client = oauth2ClientService.validOAuthClientFromCache(clientIdAndSecret[0], clientIdAndSecret[1], grantType, scopes, redirectUri); // 2. 根据授权模式,获取访问令牌 OAuth2AccessTokenDO accessTokenDO; switch (grantTypeEnum) { case AUTHORIZATION_CODE: accessTokenDO = oauth2GrantService.grantAuthorizationCodeForAccessToken(client.getClientId(), code, redirectUri, state); break; case PASSWORD: accessTokenDO = oauth2GrantService.grantPassword(username, password, client.getClientId(), scopes); break; case CLIENT_CREDENTIALS: accessTokenDO = oauth2GrantService.grantClientCredentials(client.getClientId(), scopes); break; case REFRESH_TOKEN: accessTokenDO = oauth2GrantService.grantRefreshToken(refreshToken, client.getClientId()); break; default: throw new IllegalArgumentException("未知授权类型:" + grantType); } Assert.notNull(accessTokenDO, "访问令牌不能为空"); // 防御性检查 return success(OAuth2OpenConvert.INSTANCE.convert(accessTokenDO)); }
@Test public void testPostAccessToken_refreshToken() { // 准备参数 String granType = OAuth2GrantTypeEnum.REFRESH_TOKEN.getGrantType(); String refreshToken = randomString(); String password = randomString(); HttpServletRequest request = mockRequest("test_client_id", "test_client_secret"); // mock 方法(client) OAuth2ClientDO client = randomPojo(OAuth2ClientDO.class).setClientId("test_client_id"); when(oauth2ClientService.validOAuthClientFromCache(eq("test_client_id"), eq("test_client_secret"), eq(granType), eq(Lists.newArrayList()), isNull())).thenReturn(client); // mock 方法(访问令牌) OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class) .setExpiresTime(LocalDateTimeUtil.offset(LocalDateTime.now(), 30000L, ChronoUnit.MILLIS)); when(oauth2GrantService.grantRefreshToken(eq(refreshToken), eq("test_client_id"))).thenReturn(accessTokenDO); // 调用 CommonResult<OAuth2OpenAccessTokenRespVO> result = oauth2OpenController.postAccessToken(request, granType, null, null, null, null, password, null, refreshToken); // 断言 assertEquals(0, result.getCode()); assertPojoEquals(accessTokenDO, result.getData()); assertTrue(ObjectUtils.equalsAny(result.getData().getExpiresIn(), 29L, 30L)); // 执行过程会过去几毫秒 }
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { this.trash(files, prompt, callback); for(Path f : files.keySet()) { fileid.cache(f, null); } }
@Test public void testDeleteRecursively() throws Exception { final EueResourceIdProvider fileid = new EueResourceIdProvider(session); final Path folder = new Path(new AlphanumericRandomStringService().random(), EnumSet.of(AbstractPath.Type.directory)); final Path file = new Path(folder, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new EueDirectoryFeature(session, fileid).mkdir(folder, new TransferStatus()); createFile(fileid, file, RandomUtils.nextBytes(511)); assertTrue(new EueFindFeature(session, fileid).find(file)); assertNotNull(fileid.getFileId(file)); new EueTrashFeature(session, fileid).delete(Collections.singletonList(folder), new DisabledLoginCallback(), new Delete.DisabledCallback()); file.attributes().setFileId(null); try { fileid.getFileId(file); fail(); } catch(NotfoundException e) { // } try { fileid.getFileId(folder); fail(); } catch(NotfoundException e) { // } }
@Udf public <T> List<T> distinct( @UdfParameter(description = "Array of values to distinct") final List<T> input) { if (input == null) { return null; } final Set<T> distinctVals = Sets.newLinkedHashSetWithExpectedSize(input.size()); distinctVals.addAll(input); return new ArrayList<>(distinctVals); }
@Test public void shouldDistinctIntArray() { final List<Integer> result = udf.distinct(Arrays.asList(1, 2, 3, 2, 1)); assertThat(result, contains(1, 2, 3)); }
@Transactional(readOnly = true) public AuthFindDto.FindUsernameRes findUsername(String phone) { User user = readGeneralSignUpUser(phone); return AuthFindDto.FindUsernameRes.of(user); }
@DisplayName("휴대폰 번호로 유저를 찾을 수 없을 때 AuthFinderException을 발생시킨다.") @Test void findUsernameIfUserNotFound() { // given String phone = "010-1234-5678"; given(userService.readUserByPhone(phone)).willReturn(Optional.empty()); // when - then UserErrorException exception = assertThrows(UserErrorException.class, () -> authFindService.findUsername(phone)); log.debug(exception.getExplainError()); }
public static Builder builder() { return new Builder(); }
@Test void testPrimaryKeyGeneratedColumn() { assertThatThrownBy( () -> TableSchema.builder() .field("f0", DataTypes.BIGINT().notNull(), "123") .primaryKey("pk", new String[] {"f0", "f2"}) .build()) .isInstanceOf(ValidationException.class) .hasMessage( "Could not create a PRIMARY KEY 'pk'. Column 'f0' is not a physical column."); }
@VisibleForTesting void cleanup(ConnectionPool pool) { if (pool.getNumConnections() > pool.getMinSize()) { // Check if the pool hasn't been active in a while or not 50% are used long timeSinceLastActive = Time.now() - pool.getLastActiveTime(); int total = pool.getNumConnections(); // Active is a transient status in many cases for a connection since // the handler thread uses the connection very quickly. Thus, the number // of connections with handlers using at the call time is constantly low. // Recently active is more lasting status, and it shows how many // connections have been used with a recent time period. (i.e. 30 seconds) int active = pool.getNumActiveConnectionsRecently(); float poolMinActiveRatio = pool.getMinActiveRatio(); if (timeSinceLastActive > connectionCleanupPeriodMs || active < poolMinActiveRatio * total) { // Be greedy here to close as many connections as possible in one shot // The number should at least be 1 int targetConnectionsCount = Math.max(1, (int)(poolMinActiveRatio * total) - active); List<ConnectionContext> connections = pool.removeConnections(targetConnectionsCount); for (ConnectionContext conn : connections) { conn.close(); } LOG.debug("Removed connection {} used {} seconds ago. " + "Pool has {}/{} connections", pool.getConnectionPoolId(), TimeUnit.MILLISECONDS.toSeconds(timeSinceLastActive), pool.getNumConnections(), pool.getMaxSize()); } } }
@Test public void testCleanup() throws Exception { Map<ConnectionPoolId, ConnectionPool> poolMap = connManager.getPools(); ConnectionPool pool1 = new ConnectionPool(conf, TEST_NN_ADDRESS, TEST_USER1, 0, 10, 0.5f, ClientProtocol.class, null); addConnectionsToPool(pool1, 9, 4); poolMap.put( new ConnectionPoolId(TEST_USER1, TEST_NN_ADDRESS, ClientProtocol.class), pool1); ConnectionPool pool2 = new ConnectionPool(conf, TEST_NN_ADDRESS, TEST_USER2, 0, 10, 0.5f, ClientProtocol.class, null); addConnectionsToPool(pool2, 10, 10); poolMap.put( new ConnectionPoolId(TEST_USER2, TEST_NN_ADDRESS, ClientProtocol.class), pool2); checkPoolConnections(TEST_USER1, 9, 4); checkPoolConnections(TEST_USER2, 10, 10); // Clean up first pool, one connection should be removed, and second pool // should remain the same. connManager.cleanup(pool1); checkPoolConnections(TEST_USER1, 8, 4); checkPoolConnections(TEST_USER2, 10, 10); // Clean up the first pool again, it should have no effect since it reached // the MIN_ACTIVE_RATIO. connManager.cleanup(pool1); checkPoolConnections(TEST_USER1, 8, 4); checkPoolConnections(TEST_USER2, 10, 10); // Make sure the number of connections doesn't go below minSize ConnectionPool pool3 = new ConnectionPool(conf, TEST_NN_ADDRESS, TEST_USER3, 2, 10, 0.5f, ClientProtocol.class, null); addConnectionsToPool(pool3, 8, 0); poolMap.put( new ConnectionPoolId(TEST_USER3, TEST_NN_ADDRESS, ClientProtocol.class), pool3); checkPoolConnections(TEST_USER3, 10, 0); for (int i = 0; i < 10; i++) { connManager.cleanup(pool3); } checkPoolConnections(TEST_USER3, 2, 0); // With active connections added to pool, make sure it honors the // MIN_ACTIVE_RATIO again addConnectionsToPool(pool3, 8, 2); checkPoolConnections(TEST_USER3, 10, 2); for (int i = 0; i < 10; i++) { connManager.cleanup(pool3); } checkPoolConnections(TEST_USER3, 4, 2); }
@Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { return inject(statement, new TopicProperties.Builder()); }
@Test public void shouldHaveCleanupPolicyCompactCtas() { // Given: givenStatement("CREATE TABLE x AS SELECT * FROM SOURCE;"); // When: final CreateAsSelect ctas = ((CreateAsSelect) injector.inject(statement, builder).getStatement()); // Then: final CreateSourceAsProperties props = ctas.getProperties(); assertThat(props.getCleanupPolicy(), is(Optional.of(TopicConfig.CLEANUP_POLICY_COMPACT))); }
@Override public void onClose(int code, String reason, boolean remote) { log.debug( "Closed WebSocket connection to {}, because of reason: '{}'." + "Connection closed remotely: {}", uri, reason, remote); listenerOpt.ifPresent(WebSocketListener::onClose); }
@Test public void testNotifyListenerOnClose() throws Exception { client.onClose(1, "reason", true); verify(listener).onClose(); }
void add(StorageType[] storageTypes, BlockStoragePolicy policy) { StorageTypeAllocation storageCombo = new StorageTypeAllocation(storageTypes, policy); Long count = storageComboCounts.get(storageCombo); if (count == null) { storageComboCounts.put(storageCombo, 1l); storageCombo.setActualStoragePolicy( getStoragePolicy(storageCombo.getStorageTypes())); } else { storageComboCounts.put(storageCombo, count.longValue()+1); } totalBlocks++; }
@Test public void testMultipleHots() { BlockStoragePolicySuite bsps = BlockStoragePolicySuite.createDefaultSuite(); StoragePolicySummary sts = new StoragePolicySummary(bsps.getAllPolicies()); BlockStoragePolicy hot = bsps.getPolicy("HOT"); sts.add(new StorageType[]{StorageType.DISK},hot); sts.add(new StorageType[]{StorageType.DISK,StorageType.DISK},hot); sts.add(new StorageType[]{StorageType.DISK, StorageType.DISK,StorageType.DISK},hot); sts.add(new StorageType[]{StorageType.DISK, StorageType.DISK,StorageType.DISK,StorageType.DISK},hot); Map<String, Long> actualOutput = convertToStringMap(sts); Assert.assertEquals(4,actualOutput.size()); Map<String, Long> expectedOutput = new HashMap<>(); expectedOutput.put("HOT|DISK:1(HOT)", 1l); expectedOutput.put("HOT|DISK:2(HOT)", 1l); expectedOutput.put("HOT|DISK:3(HOT)", 1l); expectedOutput.put("HOT|DISK:4(HOT)", 1l); Assert.assertEquals(expectedOutput,actualOutput); }
@Override public String getHeader(String name) { return stream.response().getHeader(name); }
@Test public void get_header() { underTest.getHeader("header"); verify(response).getHeader("header"); }
@Override protected Result[] run(String value) { final Map<String, Object> extractedJson; try { extractedJson = extractJson(value); } catch (IOException e) { throw new ExtractorException(e); } final List<Result> results = new ArrayList<>(extractedJson.size()); for (Map.Entry<String, Object> entry : extractedJson.entrySet()) { results.add(new Result(entry.getValue(), entry.getKey(), -1, -1)); } return results.toArray(new Result[results.size()]); }
@Test public void testRunWithFlattenedObject() throws Exception { final JsonExtractor jsonExtractor = new JsonExtractor(new MetricRegistry(), "json", "title", 0L, Extractor.CursorStrategy.COPY, "source", "target", ImmutableMap.<String, Object>of("flatten", true), "user", Collections.<Converter>emptyList(), Extractor.ConditionType.NONE, ""); final String value = "{" + "\"object\": {" + "\"text\": \"foobar\", " + "\"number\": 1234.5678, " + "\"bool\": true, " + "\"null\": null, " + "\"nested\": {\"text\": \"foobar\"}" + "}" + "}"; final Extractor.Result[] results = jsonExtractor.run(value); assertThat(results).contains( new Extractor.Result("text=foobar, number=1234.5678, bool=true, nested={text=foobar}", "object", -1, -1) ); }
public void pruneColumns(Configuration conf, Path inputFile, Path outputFile, List<String> cols) throws IOException { RewriteOptions options = new RewriteOptions.Builder(conf, inputFile, outputFile) .prune(cols) .build(); ParquetRewriter rewriter = new ParquetRewriter(options); rewriter.processBlocks(); rewriter.close(); }
@Test public void testNotExistsNestedColumn() throws Exception { // Create Parquet file String inputFile = createParquetFile("input"); String outputFile = createTempFile("output"); List<String> cols = Arrays.asList("Links.Not_exists"); columnPruner.pruneColumns(conf, new Path(inputFile), new Path(outputFile), cols); }
public GrantDTO create(GrantDTO grantDTO, @Nullable User currentUser) { return create(grantDTO, requireNonNull(currentUser, "currentUser cannot be null").getName()); }
@Test public void createWithGrantDTOAndUsernameString() { final GRN grantee = GRNTypes.USER.toGRN("jane"); final GRN target = GRNTypes.DASHBOARD.toGRN("54e3deadbeefdeadbeef0000"); final GrantDTO grant = dbService.create(GrantDTO.of(grantee, Capability.MANAGE, target), "admin"); assertThat(grant.id()).isNotBlank(); assertThat(grant.grantee()).isEqualTo(grantee); assertThat(grant.capability()).isEqualTo(Capability.MANAGE); assertThat(grant.target()).isEqualTo(target); assertThat(grant.createdBy()).isEqualTo("admin"); assertThat(grant.createdAt()).isBefore(ZonedDateTime.now(ZoneOffset.UTC)); assertThat(grant.updatedBy()).isEqualTo("admin"); assertThat(grant.updatedAt()).isBefore(ZonedDateTime.now(ZoneOffset.UTC)); }
@VisibleForTesting static boolean atMostOne(boolean... values) { boolean one = false; for (boolean value : values) { if (!one && value) { one = true; } else if (value) { return false; } } return true; }
@Test public void testAtMostOne() { assertTrue(atMostOne(true)); assertTrue(atMostOne(false)); assertFalse(atMostOne(true, true)); assertTrue(atMostOne(true, false)); assertTrue(atMostOne(false, true)); assertTrue(atMostOne(false, false)); assertFalse(atMostOne(true, true, true)); assertFalse(atMostOne(true, true, false)); assertFalse(atMostOne(true, false, true)); assertTrue(atMostOne(true, false, false)); assertFalse(atMostOne(false, true, true)); assertTrue(atMostOne(false, true, false)); assertTrue(atMostOne(false, false, true)); assertTrue(atMostOne(false, false, false)); }
@Override public void start() { DatabaseCharsetChecker.State state = DatabaseCharsetChecker.State.STARTUP; if (upgradeStatus.isUpgraded()) { state = DatabaseCharsetChecker.State.UPGRADE; } else if (upgradeStatus.isFreshInstall()) { state = DatabaseCharsetChecker.State.FRESH_INSTALL; } charsetChecker.check(state); }
@Test public void test_fresh_install() { when(upgradeStatus.isFreshInstall()).thenReturn(true); underTest.start(); verify(charsetChecker).check(DatabaseCharsetChecker.State.FRESH_INSTALL); }
@Override public long freeze() { finalizeSnapshotWithFooter(); appendBatches(accumulator.drain()); snapshot.freeze(); accumulator.close(); return snapshot.sizeInBytes(); }
@Test void testBuilderKRaftVersion0() { OffsetAndEpoch snapshotId = new OffsetAndEpoch(100, 10); int maxBatchSize = 1024; AtomicReference<ByteBuffer> buffer = new AtomicReference<>(null); RecordsSnapshotWriter.Builder builder = new RecordsSnapshotWriter.Builder() .setKraftVersion(KRaftVersion.KRAFT_VERSION_0) .setVoterSet(Optional.empty()) .setTime(new MockTime()) .setMaxBatchSize(maxBatchSize) .setRawSnapshotWriter( new MockRawSnapshotWriter(snapshotId, buffer::set) ); try (RecordsSnapshotWriter<String> snapshot = builder.build(STRING_SERDE)) { snapshot.freeze(); } try (RecordsSnapshotReader<String> reader = RecordsSnapshotReader.of( new MockRawSnapshotReader(snapshotId, buffer.get()), STRING_SERDE, BufferSupplier.NO_CACHING, maxBatchSize, true ) ) { // Consume the control record batch Batch<String> batch = reader.next(); assertEquals(1, batch.controlRecords().size()); // Check snapshot header control record assertEquals(ControlRecordType.SNAPSHOT_HEADER, batch.controlRecords().get(0).type()); assertEquals(new SnapshotHeaderRecord(), batch.controlRecords().get(0).message()); // Consume the reader until we find a control record do { batch = reader.next(); } while (batch.controlRecords().isEmpty()); // Check snapshot footer control record assertEquals(1, batch.controlRecords().size()); assertEquals(ControlRecordType.SNAPSHOT_FOOTER, batch.controlRecords().get(0).type()); assertEquals(new SnapshotFooterRecord(), batch.controlRecords().get(0).message()); // Snapshot footer must be last record assertFalse(reader.hasNext()); } }
public FEELFnResult<List<Object>> invoke(@ParameterName("list") Object[] lists) { if ( lists == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "lists", "cannot be null")); } final Set<Object> resultSet = new LinkedHashSet<>(); for ( final Object list : lists ) { if ( list instanceof Collection ) { resultSet.addAll((Collection) list); } else { resultSet.add(list); } } // spec requires us to return a new list return FEELFnResult.ofResult( new ArrayList<>(resultSet) ); }
@Test void invokeListAndSingleObject() { FunctionTestUtil.assertResultList(unionFunction.invoke(new Object[]{Arrays.asList(10, 4, 5), 1}), Arrays.asList(10, 4, 5, 1)); }
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) { return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context); }
@Test public void testShowDbPriv() throws AnalysisException, DdlException { ShowDbStmt stmt = new ShowDbStmt(null); ctx.setGlobalStateMgr(AccessTestUtil.fetchBlockCatalog()); ctx.setCurrentUserIdentity(UserIdentity.ROOT); ShowResultSet resultSet = ShowExecutor.execute(stmt, ctx); }
public static InternalLogger getInstance(Class<?> clazz) { return getInstance(clazz.getName()); }
@Test public void testDebugWithException() { final InternalLogger logger = InternalLoggerFactory.getInstance("mock"); logger.debug("a", e); verify(mockLogger).debug("a", e); }
public void init(final InternalProcessorContext<KOut, VOut> context) { if (!closed) throw new IllegalStateException("The processor is not closed"); try { threadId = Thread.currentThread().getName(); internalProcessorContext = context; droppedRecordsSensor = TaskMetrics.droppedRecordsSensor(threadId, internalProcessorContext.taskId().toString(), internalProcessorContext.metrics()); if (processor != null) { processor.init(context); } if (fixedKeyProcessor != null) { @SuppressWarnings("unchecked") final FixedKeyProcessorContext<KIn, VOut> fixedKeyProcessorContext = (FixedKeyProcessorContext<KIn, VOut>) context; fixedKeyProcessor.init(fixedKeyProcessorContext); } } catch (final Exception e) { throw new StreamsException(String.format("failed to initialize processor %s", name), e); } // revived tasks could re-initialize the topology, // in which case we should reset the flag closed = false; }
@Test public void shouldThrowStreamsExceptionIfExceptionCaughtDuringInit() { final ProcessorNode<Object, Object, Object, Object> node = new ProcessorNode<>(NAME, new ExceptionalProcessor(), Collections.emptySet()); assertThrows(StreamsException.class, () -> node.init(null)); }
public List<Shard> listShardsFollowingClosedShard( final String streamName, final String exclusiveStartShardId) throws TransientKinesisException { ShardFilter shardFilter = ShardFilter.builder() .type(ShardFilterType.AFTER_SHARD_ID) .shardId(exclusiveStartShardId) .build(); return wrapExceptions( () -> ShardListingUtils.listShards(kinesis.get(), streamName, shardFilter)); }
@Test public void shouldListAllShardsForExclusiveStartShardId() throws Exception { Shard shard1 = Shard.builder().shardId(SHARD_1).build(); Shard shard2 = Shard.builder().shardId(SHARD_2).build(); Shard shard3 = Shard.builder().shardId(SHARD_3).build(); String exclusiveStartShardId = "exclusiveStartShardId"; when(kinesis.listShards( ListShardsRequest.builder() .streamName(STREAM) .maxResults(1_000) .shardFilter( ShardFilter.builder() .type(ShardFilterType.AFTER_SHARD_ID) .shardId(exclusiveStartShardId) .build()) .build())) .thenReturn( ListShardsResponse.builder().shards(shard1, shard2, shard3).nextToken(null).build()); List<Shard> shards = underTest.listShardsFollowingClosedShard(STREAM, exclusiveStartShardId); assertThat(shards).containsOnly(shard1, shard2, shard3); }
public void commitVersions() { this.jobVersioners.forEach(JobVersioner::commitVersion); }
@Test void testJobListVersionerOnCommitVersionIsIncreased() { // GIVEN Job job1 = aScheduledJob().withVersion(5).build(); Job job2 = aScheduledJob().withVersion(5).build(); // WHEN JobListVersioner jobListVersioner = new JobListVersioner(asList(job1, job2)); jobListVersioner.commitVersions(); // THEN assertThat(job1).hasVersion(6); assertThat(job2).hasVersion(6); }
public static Write write() { return new AutoValue_RedisIO_Write.Builder() .setConnectionConfiguration(RedisConnectionConfiguration.create()) .setMethod(Write.Method.APPEND) .build(); }
@Test public void testWriteWithMethodPFAdd() { String key = "testWriteWithMethodPFAdd"; List<String> values = Arrays.asList("0", "1", "2", "3", "2", "4", "0", "5"); List<KV<String, String>> data = buildConstantKeyList(key, values); PCollection<KV<String, String>> write = p.apply(Create.of(data)); write.apply(RedisIO.write().withEndpoint(REDIS_HOST, port).withMethod(Method.PFADD)); p.run(); long count = client.pfcount(key); assertEquals(6, count); assertEquals(NO_EXPIRATION, Long.valueOf(client.ttl(key))); }
@Override public void archiveCompletedReservations(long tick) { // Since we are looking for old reservations, read lock is optimal LOG.debug("Running archival at time: {}", tick); List<InMemoryReservationAllocation> expiredReservations = new ArrayList<InMemoryReservationAllocation>(); readLock.lock(); // archive reservations and delete the ones which are beyond // the reservation policy "window" try { long archivalTime = tick - policy.getValidWindow(); ReservationInterval searchInterval = new ReservationInterval(archivalTime, archivalTime); SortedMap<ReservationInterval, Set<InMemoryReservationAllocation>> reservations = currentReservations.headMap(searchInterval, true); if (!reservations.isEmpty()) { for (Set<InMemoryReservationAllocation> reservationEntries : reservations .values()) { for (InMemoryReservationAllocation reservation : reservationEntries) { if (reservation.getEndTime() <= archivalTime) { expiredReservations.add(reservation); } } } } } finally { readLock.unlock(); } if (expiredReservations.isEmpty()) { return; } // Need write lock only if there are any reservations to be deleted writeLock.lock(); try { for (InMemoryReservationAllocation expiredReservation : expiredReservations) { removeReservation(expiredReservation); } } finally { writeLock.unlock(); } }
@Test public void testArchiveCompletedReservations() { SharingPolicy sharingPolicy = mock(SharingPolicy.class); Plan plan = new InMemoryPlan(queueMetrics, sharingPolicy, agent, totalCapacity, 1L, resCalc, minAlloc, maxAlloc, planName, replanner, true, context); ReservationId reservationID1 = ReservationSystemTestUtil.getNewReservationId(); // First add a reservation int[] alloc1 = { 10, 10, 10, 10, 10, 10 }; int start = 100; ReservationAllocation rAllocation = createReservationAllocation(reservationID1, start, alloc1); Assert.assertNull(plan.getReservationById(reservationID1)); try { plan.addReservation(rAllocation, false); } catch (PlanningException e) { Assert.fail(e.getMessage()); } doAssertions(plan, rAllocation); checkAllocation(plan, alloc1, start, 0); // Now add another one ReservationId reservationID2 = ReservationSystemTestUtil.getNewReservationId(); int[] alloc2 = { 0, 5, 10, 5, 0 }; rAllocation = createReservationAllocation(reservationID2, start, alloc2, true); Assert.assertNull(plan.getReservationById(reservationID2)); try { plan.addReservation(rAllocation, false); } catch (PlanningException e) { Assert.fail(e.getMessage()); } Assert.assertNotNull(plan.getReservationById(reservationID2)); RLESparseResourceAllocation userCons = plan.getConsumptionForUserOverTime(user, start, start + alloc2.length); for (int i = 0; i < alloc2.length; i++) { assertEquals( Resource.newInstance(1024 * (alloc1[i] + alloc2[i] + i), alloc1[i] + alloc2[i] + i), plan.getTotalCommittedResources(start + i)); assertEquals( Resource.newInstance(1024 * (alloc1[i] + alloc2[i] + i), alloc1[i] + alloc2[i] + i), userCons.getCapacityAtTime(start + i)); } // Now archive completed reservations when(clock.getTime()).thenReturn(106L); when(sharingPolicy.getValidWindow()).thenReturn(1L); try { // will only remove 2nd reservation as only that has fallen out of the // archival window plan.archiveCompletedReservations(clock.getTime()); } catch (PlanningException e) { Assert.fail(e.getMessage()); } Assert.assertNotNull(plan.getReservationById(reservationID1)); Assert.assertNull(plan.getReservationById(reservationID2)); checkAllocation(plan, alloc1, start, 0); when(clock.getTime()).thenReturn(107L); try { // will remove 1st reservation also as it has fallen out of the archival // window plan.archiveCompletedReservations(clock.getTime()); } catch (PlanningException e) { Assert.fail(e.getMessage()); } userCons = plan.getConsumptionForUserOverTime(user, start, start + alloc1.length); Assert.assertNull(plan.getReservationById(reservationID1)); for (int i = 0; i < alloc1.length; i++) { assertEquals(Resource.newInstance(0, 0), plan.getTotalCommittedResources(start + i)); assertEquals(Resource.newInstance(0, 0), userCons.getCapacityAtTime(start + i)); } }
@Beta public static Application fromBuilder(Builder builder) throws Exception { return builder.build(); }
@Test void application_generation_metric() throws Exception { try (ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container() .component(ComponentWithMetrics.class))))) { var component = (ComponentWithMetrics)app.getComponentById(ComponentWithMetrics.class.getName()); assertNotNull(component); var metrics = (SimpleMetricConsumer)component.metrics().newInstance(); // not actually a new instance assertNotNull(metrics); int maxWaitMs = 10000; Bucket snapshot = null; while (maxWaitMs-- > 0 && ( snapshot = metrics.receiver().getSnapshot() ) == null) { Thread.sleep(1); } assertNotNull(snapshot); assertEquals(1, snapshot.getValuesForMetric("application_generation").size()); assertEquals(0, snapshot.getValuesForMetric("application_generation").iterator().next().getValue().getLast()); } }
public static CustomWeighting.Parameters createWeightingParameters(CustomModel customModel, EncodedValueLookup lookup) { String key = customModel.toString(); Class<?> clazz = customModel.isInternal() ? INTERNAL_CACHE.get(key) : null; if (CACHE_SIZE > 0 && clazz == null) clazz = CACHE.get(key); if (clazz == null) { clazz = createClazz(customModel, lookup); if (customModel.isInternal()) { INTERNAL_CACHE.put(key, clazz); if (INTERNAL_CACHE.size() > 100) { CACHE.putAll(INTERNAL_CACHE); INTERNAL_CACHE.clear(); LoggerFactory.getLogger(CustomModelParser.class).warn("Internal cache must stay small but was " + INTERNAL_CACHE.size() + ". Cleared it. Misuse of CustomModel::internal?"); } } else if (CACHE_SIZE > 0) { CACHE.put(key, clazz); } } try { // The class does not need to be thread-safe as we create an instance per request CustomWeightingHelper prio = (CustomWeightingHelper) clazz.getDeclaredConstructor().newInstance(); prio.init(customModel, lookup, CustomModel.getAreasAsMap(customModel.getAreas())); return new CustomWeighting.Parameters( prio::getSpeed, prio::calcMaxSpeed, prio::getPriority, prio::calcMaxPriority, customModel.getDistanceInfluence() == null ? 0 : customModel.getDistanceInfluence(), customModel.getHeadingPenalty() == null ? Parameters.Routing.DEFAULT_HEADING_PENALTY : customModel.getHeadingPenalty()); } catch (ReflectiveOperationException ex) { throw new IllegalArgumentException("Cannot compile expression " + ex.getMessage(), ex); } }
@Test void testPriority() { EdgeIteratorState primary = graph.edge(0, 1).setDistance(10). set(roadClassEnc, PRIMARY).set(avgSpeedEnc, 80).set(accessEnc, true, true); EdgeIteratorState secondary = graph.edge(1, 2).setDistance(10). set(roadClassEnc, SECONDARY).set(avgSpeedEnc, 70).set(accessEnc, true, true); EdgeIteratorState tertiary = graph.edge(1, 2).setDistance(10). set(roadClassEnc, TERTIARY).set(avgSpeedEnc, 70).set(accessEnc, true, true); CustomModel customModel = new CustomModel(); customModel.addToPriority(If("road_class == PRIMARY", MULTIPLY, "0.5")); customModel.addToPriority(ElseIf("road_class == SECONDARY", MULTIPLY, "0.7")); customModel.addToPriority(Else(MULTIPLY, "0.9")); customModel.addToPriority(If("road_environment != FERRY", MULTIPLY, "0.8")); customModel.addToSpeed(If("true", LIMIT, "100")); CustomWeighting.EdgeToDoubleMapping priorityMapping = CustomModelParser.createWeightingParameters(customModel, encodingManager).getEdgeToPriorityMapping(); assertEquals(0.5 * 0.8, priorityMapping.get(primary, false), 0.01); assertEquals(0.7 * 0.8, priorityMapping.get(secondary, false), 0.01); assertEquals(0.9 * 0.8, priorityMapping.get(tertiary, false), 0.01); // force integer value customModel = new CustomModel(); customModel.addToPriority(If("road_class == PRIMARY", MULTIPLY, "1")); customModel.addToPriority(If("road_class == SECONDARY", MULTIPLY, "0.9")); customModel.addToSpeed(If("true", LIMIT, "100")); priorityMapping = CustomModelParser.createWeightingParameters(customModel, encodingManager).getEdgeToPriorityMapping(); assertEquals(1, priorityMapping.get(primary, false), 0.01); assertEquals(0.9, priorityMapping.get(secondary, false), 0.01); }
@Override public Checksum compute(final InputStream in, final TransferStatus status) throws BackgroundException { return new Checksum(HashAlgorithm.md5, this.digest("MD5", this.normalize(in, status), status)); }
@Test public void testCompute() throws Exception { assertEquals("a43c1b0aa53a0c908810c06ab1ff3967", new MD5ChecksumCompute().compute(IOUtils.toInputStream("input", Charset.defaultCharset()), new TransferStatus()).hash); }
public void validate(ProjectReactor reactor) { List<String> validationMessages = new ArrayList<>(); for (ProjectDefinition moduleDef : reactor.getProjects()) { validateModule(moduleDef, validationMessages); } if (isBranchFeatureAvailable()) { branchParamsValidator.validate(validationMessages); } else { validateBranchParamsWhenPluginAbsent(validationMessages); validatePullRequestParamsWhenPluginAbsent(validationMessages); } if (!validationMessages.isEmpty()) { throw MessageException.of("Validation of project failed:\n o " + String.join("\n o ", validationMessages)); } }
@Test void fail_when_backslash_in_key() { ProjectReactor reactor = createProjectReactor("foo\\bar"); assertThatThrownBy(() -> underTest.validate(reactor)) .isInstanceOf(MessageException.class) .hasMessageContaining("\"foo\\bar\" is not a valid project key. Allowed characters are alphanumeric, " + "'-', '_', '.' and ':', with at least one non-digit."); }
@Override public void commitJob(JobContext jobContext) throws IOException { Configuration conf = jobContext.getConfiguration(); syncFolder = conf.getBoolean(DistCpConstants.CONF_LABEL_SYNC_FOLDERS, false); overwrite = conf.getBoolean(DistCpConstants.CONF_LABEL_OVERWRITE, false); updateRoot = conf.getBoolean(CONF_LABEL_UPDATE_ROOT, false); targetPathExists = conf.getBoolean( DistCpConstants.CONF_LABEL_TARGET_PATH_EXISTS, true); ignoreFailures = conf.getBoolean( DistCpOptionSwitch.IGNORE_FAILURES.getConfigLabel(), false); if (blocksPerChunk > 0) { concatFileChunks(conf); } super.commitJob(jobContext); cleanupTempFiles(jobContext); try { if (conf.getBoolean(DistCpConstants.CONF_LABEL_DELETE_MISSING, false)) { deleteMissing(conf); } else if (conf.getBoolean(DistCpConstants.CONF_LABEL_ATOMIC_COPY, false)) { commitData(conf); } else if (conf.get(CONF_LABEL_TRACK_MISSING) != null) { // save missing information to a directory trackMissing(conf); } // for HDFS-14621, should preserve status after -delete String attributes = conf.get(DistCpConstants.CONF_LABEL_PRESERVE_STATUS); final boolean preserveRawXattrs = conf.getBoolean( DistCpConstants.CONF_LABEL_PRESERVE_RAWXATTRS, false); if ((attributes != null && !attributes.isEmpty()) || preserveRawXattrs) { preserveFileAttributesForDirectories(conf); } taskAttemptContext.setStatus("Commit Successful"); } finally { cleanup(conf); } }
@Test public void testNoCommitAction() throws IOException { TaskAttemptContext taskAttemptContext = getTaskAttemptContext(config); JobContext jobContext = new JobContextImpl( taskAttemptContext.getConfiguration(), taskAttemptContext.getTaskAttemptID().getJobID()); OutputCommitter committer = new CopyCommitter(null, taskAttemptContext); committer.commitJob(jobContext); Assert.assertEquals("Commit Successful", taskAttemptContext.getStatus()); //Test for idempotent commit committer.commitJob(jobContext); Assert.assertEquals("Commit Successful", taskAttemptContext.getStatus()); }
public static List<AclEntry> filterAclEntriesByAclSpec( List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); EnumMap<AclEntryScope, AclEntry> providedMask = Maps.newEnumMap(AclEntryScope.class); EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class); EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class); for (AclEntry existingEntry: existingAcl) { if (aclSpec.containsKey(existingEntry)) { scopeDirty.add(existingEntry.getScope()); if (existingEntry.getType() == MASK) { maskDirty.add(existingEntry.getScope()); } } else { if (existingEntry.getType() == MASK) { providedMask.put(existingEntry.getScope(), existingEntry); } else { aclBuilder.add(existingEntry); } } } copyDefaultsIfNeeded(aclBuilder); calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty); return buildAndValidateAcl(aclBuilder); }
@Test public void testFilterAclEntriesByAclSpecAutomaticDefaultOther() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, OTHER, READ)) .add(aclEntry(DEFAULT, USER, READ_WRITE)) .add(aclEntry(DEFAULT, GROUP, READ_WRITE)) .add(aclEntry(DEFAULT, OTHER, NONE)) .build(); List<AclEntry> aclSpec = Lists.newArrayList( aclEntry(DEFAULT, OTHER)); List<AclEntry> expected = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, OTHER, READ)) .add(aclEntry(DEFAULT, USER, READ_WRITE)) .add(aclEntry(DEFAULT, GROUP, READ_WRITE)) .add(aclEntry(DEFAULT, OTHER, READ)) .build(); assertEquals(expected, filterAclEntriesByAclSpec(existing, aclSpec)); }
@Override public DescriptiveUrlBag toUrl(final Path file) { final DescriptiveUrlBag list = new DescriptiveUrlBag(); if(new HostPreferences(session.getHost()).getBoolean("s3.bucket.virtualhost.disable")) { list.addAll(new DefaultUrlProvider(session.getHost()).toUrl(file)); } else { list.add(this.toUrl(file, session.getHost().getProtocol().getScheme(), session.getHost().getPort())); list.add(this.toUrl(file, Scheme.http, 80)); if(StringUtils.isNotBlank(session.getHost().getWebURL())) { // Only include when custom domain is configured list.addAll(new HostWebUrlProvider(session.getHost()).toUrl(file)); } } if(file.isFile()) { if(!session.getHost().getCredentials().isAnonymousLogin()) { // X-Amz-Expires must be less than a week (in seconds); that is, the given X-Amz-Expires must be less // than 604800 seconds // In one hour list.add(this.toSignedUrl(file, (int) TimeUnit.HOURS.toSeconds(1))); // Default signed URL expiring in 24 hours. list.add(this.toSignedUrl(file, (int) TimeUnit.SECONDS.toSeconds( new HostPreferences(session.getHost()).getInteger("s3.url.expire.seconds")))); // 1 Week list.add(this.toSignedUrl(file, (int) TimeUnit.DAYS.toSeconds(7))); switch(session.getSignatureVersion()) { case AWS2: // 1 Month list.add(this.toSignedUrl(file, (int) TimeUnit.DAYS.toSeconds(30))); // 1 Year list.add(this.toSignedUrl(file, (int) TimeUnit.DAYS.toSeconds(365))); break; case AWS4HMACSHA256: break; } } } // AWS services require specifying an Amazon S3 bucket using S3://bucket list.add(new DescriptiveUrl(URI.create(String.format("s3://%s%s", containerService.getContainer(file).getName(), file.isRoot() ? Path.DELIMITER : containerService.isContainer(file) ? Path.DELIMITER : String.format("/%s", URIEncoder.encode(containerService.getKey(file))))), DescriptiveUrl.Type.provider, MessageFormat.format(LocaleFactory.localizedString("{0} URL"), "S3"))); // Filter by matching container name final Optional<Set<Distribution>> filtered = distributions.entrySet().stream().filter(entry -> new SimplePathPredicate(containerService.getContainer(file)).test(entry.getKey())) .map(Map.Entry::getValue).findFirst(); if(filtered.isPresent()) { // Add CloudFront distributions for(Distribution distribution : filtered.get()) { list.addAll(new DistributionUrlProvider(distribution).toUrl(file)); } } return list; }
@Test public void testProviderUriWithKey() { final Iterator<DescriptiveUrl> provider = new S3UrlProvider(session, Collections.emptyMap()).toUrl(new Path("/test-eu-west-1-cyberduck/key", EnumSet.of(Path.Type.file))).filter(DescriptiveUrl.Type.provider).iterator(); assertEquals("s3://test-eu-west-1-cyberduck/key", provider.next().getUrl()); }
public ServiceBusConfiguration getConfiguration() { return configuration; }
@Test void testCreateEndpointWithConfig() throws Exception { final String uri = "azure-servicebus://testTopicOrQueue"; final String remaining = "testTopicOrQueue"; final Map<String, Object> params = new HashMap<>(); params.put("serviceBusType", ServiceBusType.topic); params.put("prefetchCount", 10); params.put("connectionString", "testString"); params.put("binary", "true"); final ServiceBusEndpoint endpoint = (ServiceBusEndpoint) context.getComponent("azure-servicebus", ServiceBusComponent.class) .createEndpoint(uri, remaining, params); assertEquals(ServiceBusType.topic, endpoint.getConfiguration().getServiceBusType()); assertEquals("testTopicOrQueue", endpoint.getConfiguration().getTopicOrQueueName()); assertEquals(10, endpoint.getConfiguration().getPrefetchCount()); assertEquals("testString", endpoint.getConfiguration().getConnectionString()); assertEquals(true, endpoint.getConfiguration().isBinary()); }
public PackageRepository findPackageRepositoryHaving(String packageId) { for (PackageRepository packageRepository : this) { for (PackageDefinition packageDefinition : packageRepository.getPackages()) { if (packageDefinition.getId().equals(packageId)) { return packageRepository; } } } return null; }
@Test void shouldReturnNullWhenRepositoryForGivenPackageNotFound() throws Exception { PackageRepositories packageRepositories = new PackageRepositories(); assertThat(packageRepositories.findPackageRepositoryHaving("invalid")).isNull(); }
@Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException { boolean forceRedirect = config .getBoolean(SONAR_FORCE_REDIRECT_DEFAULT_ADMIN_CREDENTIALS) .orElse(true); if (forceRedirect && userSession.hasSession() && userSession.isLoggedIn() && userSession.isSystemAdministrator() && !"admin".equals(userSession.getLogin()) && defaultAdminCredentialsVerifier.hasDefaultCredentialUser()) { redirectTo(response, request.getContextPath() + CHANGE_ADMIN_PASSWORD_PATH); } chain.doFilter(request, response); }
@Test public void do_not_redirect_if_config_says_so() throws Exception { when(config.getBoolean("sonar.forceRedirectOnDefaultAdminCredentials")).thenReturn(Optional.of(false)); underTest.doFilter(request, response, chain); verify(response, never()).sendRedirect(any()); }
@Override public Thread newThread(Runnable r) { Thread t = newThread(FastThreadLocalRunnable.wrap(r), prefix + nextId.incrementAndGet()); try { if (t.isDaemon() != daemon) { t.setDaemon(daemon); } if (t.getPriority() != priority) { t.setPriority(priority); } } catch (Exception ignored) { // Doesn't matter even if failed to set. } return t; }
@Test @Timeout(value = 2000, unit = TimeUnit.MILLISECONDS) public void testCurrentThreadGroupIsUsed() throws InterruptedException { final AtomicReference<DefaultThreadFactory> factory = new AtomicReference<DefaultThreadFactory>(); final AtomicReference<ThreadGroup> firstCaptured = new AtomicReference<ThreadGroup>(); final ThreadGroup group = new ThreadGroup("first"); final Thread first = new Thread(group, new Runnable() { @Override public void run() { final Thread current = Thread.currentThread(); firstCaptured.set(current.getThreadGroup()); factory.set(new DefaultThreadFactory("sticky", false)); } }); first.start(); first.join(); assertEquals(group, firstCaptured.get()); ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup(); Thread second = factory.get().newThread(new Runnable() { @Override public void run() { // NOOP. } }); second.join(); assertEquals(currentThreadGroup, currentThreadGroup); }
public static long hash(Slice decimal) { return hash(getRawLong(decimal, 0), getRawLong(decimal, 1)); }
@Test public void testHash() { assertEquals(hash(unscaledDecimal(0)), hash(negate(unscaledDecimal(0)))); assertNotEquals(hash(unscaledDecimal(0)), hash(unscaledDecimal(1))); }
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchingFunctionException(arguments); } // if none were found (candidate isn't present) try again with implicit casting candidate = findMatchingCandidate(arguments, true); if (candidate.isPresent()) { return candidate.get(); } throw createNoMatchingFunctionException(arguments); }
@Test public void shouldFindVarargsOne() { // Given: givenFunctions( function(EXPECTED, 0, STRING_VARARGS) ); // When: final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of(SqlArgument.of(SqlTypes.STRING))); // Then: assertThat(fun.name(), equalTo(EXPECTED)); }