focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
boolean needsMigration() { File mappingFile = UserIdMapper.getConfigFile(usersDirectory); if (mappingFile.exists() && mappingFile.isFile()) { LOGGER.finest("User mapping file already exists. No migration needed."); return false; } File[] userDirectories = listUserDirectories(); return userDirectories != null && userDirectories.length > 0; }
@Test public void migrateUsersXml() throws IOException { File usersDirectory = createTestDirectory(getClass(), name); IdStrategy idStrategy = IdStrategy.CASE_INSENSITIVE; UserIdMigrator migrator = new UserIdMigrator(usersDirectory, idStrategy); TestUserIdMapper mapper = new TestUserIdMapper(usersDirectory, idStrategy); mapper.init(); assertThat(migrator.needsMigration(), is(false)); mapper = new TestUserIdMapper(usersDirectory, idStrategy); mapper.init(); assertThat(mapper.getConvertedUserIds().size(), is(1)); assertThat(mapper.isMapped("users.xml"), is(true)); }
@Override public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer) { return aggregate(initializer, Materialized.with(null, null)); }
@Test public void slidingWindowAggregateOverlappingWindowsTest() { final KTable<Windowed<String>, String> customers = groupedStream.cogroup(MockAggregator.TOSTRING_ADDER) .windowedBy(SlidingWindows.withTimeDifferenceAndGrace(ofMillis(WINDOW_SIZE_MS), ofMillis(2000L))).aggregate( MockInitializer.STRING_INIT, Materialized.with(Serdes.String(), Serdes.String())); customers.toStream().to(OUTPUT); try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) { final TestInputTopic<String, String> testInputTopic = driver.createInputTopic( TOPIC, new StringSerializer(), new StringSerializer()); final TestOutputTopic<Windowed<String>, String> testOutputTopic = driver.createOutputTopic( OUTPUT, new TimeWindowedDeserializer<>(new StringDeserializer(), WINDOW_SIZE_MS), new StringDeserializer()); testInputTopic.pipeInput("k1", "A", 500); testInputTopic.pipeInput("k2", "A", 500); testInputTopic.pipeInput("k1", "B", 750); testInputTopic.pipeInput("k2", "B", 750); testInputTopic.pipeInput("k2", "A", 1000L); testInputTopic.pipeInput("k1", "A", 1000L); // left window k1@500 assertOutputKeyValueTimestamp(testOutputTopic, "k1", "0+A", 500); // left window k2@500 assertOutputKeyValueTimestamp(testOutputTopic, "k2", "0+A", 500); // right window k1@500 assertOutputKeyValueTimestamp(testOutputTopic, "k1", "0+B", 750); // left window k1@750 assertOutputKeyValueTimestamp(testOutputTopic, "k1", "0+A+B", 750); // right window k2@500 assertOutputKeyValueTimestamp(testOutputTopic, "k2", "0+B", 750); // left window k2@750 assertOutputKeyValueTimestamp(testOutputTopic, "k2", "0+A+B", 750); // right window k2@500 update assertOutputKeyValueTimestamp(testOutputTopic, "k2", "0+B+A", 1000); // right window k2@750 assertOutputKeyValueTimestamp(testOutputTopic, "k2", "0+A", 1000); // left window k2@1000 assertOutputKeyValueTimestamp(testOutputTopic, "k2", "0+A+B+A", 1000); // right window k1@500 update assertOutputKeyValueTimestamp(testOutputTopic, "k1", "0+B+A", 1000); // right window k1@750 assertOutputKeyValueTimestamp(testOutputTopic, "k1", "0+A", 1000); // left window k1@1000 assertOutputKeyValueTimestamp(testOutputTopic, "k1", "0+A+B+A", 1000); } }
@Override public StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { final java.nio.file.Path p = session.toPath(file); final Set<OpenOption> options = new HashSet<>(); options.add(StandardOpenOption.WRITE); if(status.isAppend()) { if(!status.isExists()) { options.add(StandardOpenOption.CREATE); } } else { if(status.isExists()) { if(file.isSymbolicLink()) { Files.delete(p); options.add(StandardOpenOption.CREATE); } else { options.add(StandardOpenOption.TRUNCATE_EXISTING); } } else { options.add(StandardOpenOption.CREATE_NEW); } } final FileChannel channel = FileChannel.open(session.toPath(file), options.stream().toArray(OpenOption[]::new)); channel.position(status.getOffset()); return new VoidStatusOutputStream(Channels.newOutputStream(channel)); } catch(IOException e) { throw new LocalExceptionMappingService().map("Upload {0} failed", e, file); } }
@Test public void testWriteTildeFilename() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCallback()); session.login(new DisabledLoginCallback(), new DisabledCancelCallback()); final LocalWriteFeature feature = new LocalWriteFeature(session); final Path workdir = new LocalHomeFinderFeature().find(); final Path test = new Path(workdir, String.format("~$%s", new AsciiRandomStringService().random()), EnumSet.of(Path.Type.file)); final byte[] content = RandomUtils.nextBytes(2048); final TransferStatus status = new TransferStatus().withLength(content.length); final OutputStream out = feature.write(test, status, new DisabledConnectionCallback()); new StreamCopier(status, status).withOffset(status.getOffset()).withLimit(status.getLength()).transfer(new ByteArrayInputStream(content), out); out.flush(); out.close(); final ByteArrayOutputStream b = new ByteArrayOutputStream(content.length); IOUtils.copy(new LocalReadFeature(session).read(test, new TransferStatus().withLength(content.length), new DisabledConnectionCallback()), b); assertArrayEquals(content, b.toByteArray()); assertTrue(new DefaultFindFeature(session).find(test)); assertEquals(content.length, new DefaultAttributesFinderFeature(session).find(test).getSize()); new LocalDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
@Override public KubevirtPort port(MacAddress mac) { checkArgument(mac != null, ERR_NULL_PORT_MAC); return kubevirtPortStore.port(mac); }
@Test public void testGetPortById() { createBasicPorts(); assertNotNull("Port did not match", target.port(MacAddress.valueOf(PORT_MAC))); }
@Override public SingleRuleConfiguration buildToBeCreatedRuleConfiguration(final LoadSingleTableStatement sqlStatement) { SingleRuleConfiguration result = new SingleRuleConfiguration(); if (null != rule) { result.getTables().addAll(rule.getConfiguration().getTables()); } result.getTables().addAll(getRequiredTables(sqlStatement)); return result; }
@Test void assertUpdate() { Collection<String> currentTables = new LinkedList<>(Collections.singletonList("ds_0.foo")); SingleRuleConfiguration currentConfig = new SingleRuleConfiguration(currentTables, null); LoadSingleTableStatement sqlStatement = new LoadSingleTableStatement(Collections.singletonList(new SingleTableSegment("ds_0", null, "bar"))); SingleRule rule = mock(SingleRule.class); when(rule.getConfiguration()).thenReturn(currentConfig); executor.setRule(rule); SingleRuleConfiguration toBeCreatedConfig = executor.buildToBeCreatedRuleConfiguration(sqlStatement); Iterator<String> iterator = toBeCreatedConfig.getTables().iterator(); assertThat(iterator.next(), is("ds_0.foo")); assertThat(iterator.next(), is("ds_0.bar")); }
public static Class getJavaType(int sqlType) { switch (sqlType) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: return String.class; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: return byte[].class; case Types.BIT: return Boolean.class; case Types.TINYINT: case Types.SMALLINT: return Short.class; case Types.INTEGER: return Integer.class; case Types.BIGINT: return Long.class; case Types.REAL: return Float.class; case Types.DOUBLE: case Types.FLOAT: return Double.class; case Types.DATE: return Date.class; case Types.TIME: return Time.class; case Types.TIMESTAMP: return Timestamp.class; default: throw new RuntimeException("We do not support tables with SqlType: " + getSqlTypeName(sqlType)); } }
@Test public void testBasic() { assertEquals(String.class, Util.getJavaType(Types.CHAR)); assertEquals(String.class, Util.getJavaType(Types.VARCHAR)); assertEquals(String.class, Util.getJavaType(Types.LONGVARCHAR)); assertEquals(byte[].class, Util.getJavaType(Types.BINARY)); assertEquals(byte[].class, Util.getJavaType(Types.VARBINARY)); assertEquals(byte[].class, Util.getJavaType(Types.LONGVARBINARY)); assertEquals(Boolean.class, Util.getJavaType(Types.BIT)); assertEquals(Short.class, Util.getJavaType(Types.TINYINT)); assertEquals(Short.class, Util.getJavaType(Types.SMALLINT)); assertEquals(Integer.class, Util.getJavaType(Types.INTEGER)); assertEquals(Long.class, Util.getJavaType(Types.BIGINT)); assertEquals(Float.class, Util.getJavaType(Types.REAL)); assertEquals(Double.class, Util.getJavaType(Types.DOUBLE)); assertEquals(Double.class, Util.getJavaType(Types.FLOAT)); assertEquals(Date.class, Util.getJavaType(Types.DATE)); assertEquals(Time.class, Util.getJavaType(Types.TIME)); assertEquals(Timestamp.class, Util.getJavaType(Types.TIMESTAMP)); }
@NonNull static String getImageUrl(List<FastDocumentFile> files, Uri folderUri) { // look for special file names for (String iconLocation : PREFERRED_FEED_IMAGE_FILENAMES) { for (FastDocumentFile file : files) { if (iconLocation.equals(file.getName())) { return file.getUri().toString(); } } } // use the first image in the folder if existing for (FastDocumentFile file : files) { String mime = file.getType(); if (mime != null && (mime.startsWith("image/jpeg") || mime.startsWith("image/png"))) { return file.getUri().toString(); } } // use default icon as fallback return Feed.PREFIX_GENERATIVE_COVER + folderUri; }
@Test public void testGetImageUrl_OtherImageFilenameUnsupportedMimeType() { List<FastDocumentFile> folder = Arrays.asList(mockDocumentFile("audio.mp3", "audio/mp3"), mockDocumentFile("my-image.svg", "image/svg+xml")); String imageUrl = LocalFeedUpdater.getImageUrl(folder, Uri.EMPTY); assertThat(imageUrl, startsWith(Feed.PREFIX_GENERATIVE_COVER)); }
@Override public Object evaluate(final Map<String, Object> requestData, final PMMLRuntimeContext pmmlContext) { throw new KiePMMLException("KiePMMLMiningModel is not meant to be used for actual evaluation"); }
@Test void evaluate() { assertThatExceptionOfType(KiePMMLException.class).isThrownBy(() -> { KIE_PMML_MINING_MODEL.evaluate(Collections.EMPTY_MAP, new PMMLRuntimeContextTest()); }); }
public static List<SubscriptionItem> readFrom( final InputStream in, @Nullable final ImportExportEventListener eventListener) throws InvalidSourceException { if (in == null) { throw new InvalidSourceException("input is null"); } final List<SubscriptionItem> channels = new ArrayList<>(); try { final JsonObject parentObject = JsonParser.object().from(in); if (!parentObject.has(JSON_SUBSCRIPTIONS_ARRAY_KEY)) { throw new InvalidSourceException("Channels array is null"); } final JsonArray channelsArray = parentObject.getArray(JSON_SUBSCRIPTIONS_ARRAY_KEY); if (eventListener != null) { eventListener.onSizeReceived(channelsArray.size()); } for (final Object o : channelsArray) { if (o instanceof JsonObject) { final JsonObject itemObject = (JsonObject) o; final int serviceId = itemObject.getInt(JSON_SERVICE_ID_KEY, 0); final String url = itemObject.getString(JSON_URL_KEY); final String name = itemObject.getString(JSON_NAME_KEY); if (url != null && name != null && !url.isEmpty() && !name.isEmpty()) { channels.add(new SubscriptionItem(serviceId, url, name)); if (eventListener != null) { eventListener.onItemCompleted(name); } } } } } catch (final Throwable e) { throw new InvalidSourceException("Couldn't parse json", e); } return channels; }
@Test public void testEmptySource() throws Exception { final String emptySource = "{\"app_version\":\"0.11.6\",\"app_version_int\": 47,\"subscriptions\":[]}"; final List<SubscriptionItem> items = ImportExportJsonHelper.readFrom( new ByteArrayInputStream(emptySource.getBytes(StandardCharsets.UTF_8)), null); assertTrue(items.isEmpty()); }
@Override public void process(boolean validate, boolean documentsOnly) { if (!validate) return; String searchName = schema.getName(); Map<String, DataType> seenFields = new HashMap<>(); verifySearchAndDocFields(searchName, seenFields); verifySummaryFields(searchName, seenFields); }
@Test void throws_exception_if_type_of_document_field_does_not_match_summary_field() { Throwable exception = assertThrows(IllegalArgumentException.class, () -> { Schema schema = createSearchWithDocument(DOCUMENT_NAME); schema.setImportedFields(createSingleImportedField(IMPORTED_FIELD_NAME, DataType.INT)); schema.addSummary(createDocumentSummary(IMPORTED_FIELD_NAME, DataType.STRING, schema)); ValidateFieldTypes validator = new ValidateFieldTypes(schema, null, null, null); validator.process(true, false); }); assertTrue(exception.getMessage().contains("For schema '" + DOCUMENT_NAME + "', field '" + IMPORTED_FIELD_NAME + "': Incompatible types. " + "Expected int for summary field '" + IMPORTED_FIELD_NAME + "', got string.")); }
@Bean public ShenyuPlugin wafPlugin() { return new WafPlugin(); }
@Test public void testWafPlugin() { new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(WafPluginConfiguration.class)) .withBean(WafPluginConfigurationTest.class) .withPropertyValues("debug=true") .run(context -> { ShenyuPlugin plugin = context.getBean("wafPlugin", ShenyuPlugin.class); assertNotNull(plugin); assertThat(plugin.named()).isEqualTo(PluginEnum.WAF.getName()); }); }
static <K, V> StateSerdes<K, V> prepareStoreSerde(final StateStoreContext context, final String storeName, final String changelogTopic, final Serde<K> keySerde, final Serde<V> valueSerde, final PrepareFunc<V> prepareValueSerdeFunc) { return new StateSerdes<>( changelogTopic, prepareSerde(WrappingNullableUtils::prepareKeySerde, storeName, keySerde, new SerdeGetter(context), true, context.taskId()), prepareSerde(prepareValueSerdeFunc, storeName, valueSerde, new SerdeGetter(context), false, context.taskId()) ); }
@Test public void shouldPrepareStoreSerdeForProcessorContext() { final Serde<String> keySerde = new Serdes.StringSerde(); final Serde<String> valueSerde = new Serdes.StringSerde(); final MockInternalNewProcessorContext<String, String> context = new MockInternalNewProcessorContext<>(); utilsMock.when(() -> WrappingNullableUtils.prepareKeySerde(any(), any())).thenReturn(keySerde); utilsMock.when(() -> WrappingNullableUtils.prepareValueSerde(any(), any())).thenReturn(valueSerde); final StateSerdes<String, String> result = StoreSerdeInitializer.prepareStoreSerde( (ProcessorContext) context, "myStore", "topic", keySerde, valueSerde, WrappingNullableUtils::prepareValueSerde); assertThat(result.keySerde(), equalTo(keySerde)); assertThat(result.valueSerde(), equalTo(valueSerde)); assertThat(result.topic(), equalTo("topic")); }
public void initialize(Configuration config) throws YarnException { setConf(config); this.plugin.initPlugin(config); // Try to diagnose FPGA LOG.info("Trying to diagnose FPGA information ..."); if (!diagnose()) { LOG.warn("Failed to pass FPGA devices diagnose"); } }
@Test public void testExecutablePathWhenFileIsEmpty() throws YarnException { conf.set(YarnConfiguration.NM_FPGA_PATH_TO_EXEC, ""); fpgaDiscoverer.initialize(conf); assertEquals("configuration with empty string value, should use aocl", "aocl", openclPlugin.getPathToExecutable()); }
public static Configuration loadConfiguration( String workingDirectory, Configuration dynamicParameters, Map<String, String> env) { final Configuration configuration = GlobalConfiguration.loadConfiguration(workingDirectory, dynamicParameters); final String keytabPrincipal = env.get(YarnConfigKeys.KEYTAB_PRINCIPAL); final String hostname = env.get(ApplicationConstants.Environment.NM_HOST.key()); Preconditions.checkState( hostname != null, "ApplicationMaster hostname variable %s not set", ApplicationConstants.Environment.NM_HOST.key()); configuration.set(JobManagerOptions.ADDRESS, hostname); configuration.set(RestOptions.ADDRESS, hostname); configuration.set(RestOptions.BIND_ADDRESS, hostname); // if a web monitor shall be started, set the port to random binding if (configuration.get(WebOptions.PORT, 0) >= 0) { configuration.set(WebOptions.PORT, 0); } if (!configuration.contains(RestOptions.BIND_PORT)) { // set the REST port to 0 to select it randomly configuration.set(RestOptions.BIND_PORT, "0"); } // if the user has set the deprecated YARN-specific config keys, we add the // corresponding generic config keys instead. that way, later code needs not // deal with deprecated config keys BootstrapTools.substituteDeprecatedConfigPrefix( configuration, ConfigConstants.YARN_APPLICATION_MASTER_ENV_PREFIX, ResourceManagerOptions.CONTAINERIZED_MASTER_ENV_PREFIX); BootstrapTools.substituteDeprecatedConfigPrefix( configuration, ConfigConstants.YARN_TASK_MANAGER_ENV_PREFIX, ResourceManagerOptions.CONTAINERIZED_TASK_MANAGER_ENV_PREFIX); final String keytabPath = Utils.resolveKeytabPath( workingDirectory, env.get(YarnConfigKeys.LOCAL_KEYTAB_PATH)); if (keytabPath != null && keytabPrincipal != null) { configuration.set(SecurityOptions.KERBEROS_LOGIN_KEYTAB, keytabPath); configuration.set(SecurityOptions.KERBEROS_LOGIN_PRINCIPAL, keytabPrincipal); } final String localDirs = env.get(ApplicationConstants.Environment.LOCAL_DIRS.key()); BootstrapTools.updateTmpDirectoriesInConfiguration(configuration, localDirs); return configuration; }
@Test void testRestPortAndBindingPortSpecified() throws IOException { final Configuration initialConfiguration = new Configuration(); final int port = 1337; final String bindingPortRange = "1337-7331"; initialConfiguration.set(RestOptions.PORT, port); initialConfiguration.set(RestOptions.BIND_PORT, bindingPortRange); final Configuration configuration = loadConfiguration(initialConfiguration); // bind port should have precedence over the rest port assertThat(configuration.get(RestOptions.BIND_PORT)).isEqualTo(bindingPortRange); }
@Override public Iterable<RedisClusterNode> clusterGetNodes() { return read(null, StringCodec.INSTANCE, CLUSTER_NODES); }
@Test public void testClusterGetNodes() { Iterable<RedisClusterNode> nodes = connection.clusterGetNodes(); assertThat(nodes).hasSize(6); for (RedisClusterNode redisClusterNode : nodes) { assertThat(redisClusterNode.getLinkState()).isNotNull(); assertThat(redisClusterNode.getFlags()).isNotEmpty(); assertThat(redisClusterNode.getHost()).isNotNull(); assertThat(redisClusterNode.getPort()).isNotNull(); assertThat(redisClusterNode.getId()).isNotNull(); assertThat(redisClusterNode.getType()).isNotNull(); if (redisClusterNode.getType() == NodeType.MASTER) { assertThat(redisClusterNode.getSlotRange().getSlots()).isNotEmpty(); } else { assertThat(redisClusterNode.getMasterId()).isNotNull(); } } }
public char readWPChar() throws IOException { int c = in.read(); if (c == -1) { throw new EOFException(); } return (char) c; }
@Test public void testReadChar() throws Exception { try (WPInputStream wpInputStream = emptyWPStream()) { wpInputStream.readWPChar(); fail("should have thrown EOF"); } catch (EOFException e) { //swallow } }
public static int optimalNumOfBits(long inputEntries, double fpp) { int numBits = (int) (-inputEntries * Math.log(fpp) / (Math.log(2) * Math.log(2))); return numBits; }
@Test void testBloomNumBits() { assertThat(BloomFilter.optimalNumOfBits(0, 0)).isZero(); assertThat(BloomFilter.optimalNumOfBits(0, 0)).isZero(); assertThat(BloomFilter.optimalNumOfBits(0, 1)).isZero(); assertThat(BloomFilter.optimalNumOfBits(1, 1)).isZero(); assertThat(BloomFilter.optimalNumOfBits(1, 0.03)).isEqualTo(7); assertThat(BloomFilter.optimalNumOfBits(10, 0.03)).isEqualTo(72); assertThat(BloomFilter.optimalNumOfBits(100, 0.03)).isEqualTo(729); assertThat(BloomFilter.optimalNumOfBits(1000, 0.03)).isEqualTo(7298); assertThat(BloomFilter.optimalNumOfBits(10000, 0.03)).isEqualTo(72984); assertThat(BloomFilter.optimalNumOfBits(100000, 0.03)).isEqualTo(729844); assertThat(BloomFilter.optimalNumOfBits(1000000, 0.03)).isEqualTo(7298440); assertThat(BloomFilter.optimalNumOfBits(1000000, 0.05)).isEqualTo(6235224); }
public static String toDotString(Pipeline pipeline) { final PipelineDotRenderer visitor = new PipelineDotRenderer(); visitor.begin(); pipeline.traverseTopologically(visitor); visitor.end(); return visitor.dotBuilder.toString(); }
@Test public void testEmptyPipeline() { assertEquals( "digraph {" + " rankdir=LR" + " subgraph cluster_0 {" + " label = \"\"" + " }" + "}", PipelineDotRenderer.toDotString(p).replaceAll(System.lineSeparator(), "")); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } if(file.getType().contains(Path.Type.upload)) { // Pending large file upload final Write.Append append = new B2LargeUploadService(session, fileid, new B2WriteFeature(session, fileid)).append(file, new TransferStatus()); if(append.append) { return new PathAttributes().withSize(append.offset); } return PathAttributes.EMPTY; } if(containerService.isContainer(file)) { try { final B2BucketResponse info = session.getClient().listBucket(file.getName()); if(null == info) { throw new NotfoundException(file.getAbsolute()); } return this.toAttributes(info); } catch(B2ApiException e) { throw new B2ExceptionMappingService(fileid).map("Failure to read attributes of {0}", e, file); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map(e); } } else { final String id = fileid.getVersionId(file); if(null == id) { return PathAttributes.EMPTY; } B2FileResponse response; try { response = this.findFileInfo(file, id); } catch(NotfoundException e) { // Try with reset cache after failure finding node id response = this.findFileInfo(file, fileid.getVersionId(file)); } final PathAttributes attr = this.toAttributes(response); if(attr.isDuplicate()) { // Throw failure if latest version has hide marker set and lookup was without explicit version if(StringUtils.isBlank(file.attributes().getVersionId())) { if(log.isDebugEnabled()) { log.debug(String.format("Latest version of %s is duplicate", file)); } throw new NotfoundException(file.getAbsolute()); } } return attr; } }
@Test public void testFind() throws Exception { final B2VersionIdProvider fileid = new B2VersionIdProvider(session); final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(bucket, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final long timestamp = System.currentTimeMillis(); new B2TouchFeature(session, fileid).touch(test, new TransferStatus().withModified(timestamp)); final B2AttributesFinderFeature f = new B2AttributesFinderFeature(session, fileid); final PathAttributes attributes = f.find(test); assertEquals(0L, attributes.getSize()); assertEquals(timestamp, attributes.getModificationDate()); assertNotNull(attributes.getVersionId()); assertNull(attributes.getFileId()); assertNotEquals(Checksum.NONE, attributes.getChecksum()); new B2DeleteFeature(session, fileid).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
@Override public String toString() { return "ConfigChangedEvent{" + "key='" + key + '\'' + ", group='" + group + '\'' + ", content='" + content + '\'' + ", changeType=" + changeType + "} " + super.toString(); }
@Test void testToString() { ConfigChangedEvent event = new ConfigChangedEvent(KEY, GROUP, CONTENT); assertNotNull(event.toString()); }
@Override public void afterRequest(long consumeTimeMs) { baseStats(consumeTimeMs); }
@Test public void afterRequest() { final InstanceStats stats = new InstanceStats(); long consumerMs = 100L; stats.beforeRequest(); stats.afterRequest(consumerMs); Assert.assertEquals(stats.getActiveRequests(), 0); }
static String getAbbreviation(Exception ex, Integer statusCode, String storageErrorMessage) { String result = null; for (RetryReasonCategory retryReasonCategory : rankedReasonCategories) { final String abbreviation = retryReasonCategory.captureAndGetAbbreviation(ex, statusCode, storageErrorMessage); if (abbreviation != null) { result = abbreviation; } } return result; }
@Test public void testUnknownSocketException() { Assertions.assertThat(RetryReason.getAbbreviation(new SocketException(), null, null)).isEqualTo( SOCKET_EXCEPTION_ABBREVIATION ); }
@Override public V get() throws InterruptedException, ExecutionException { try { return resolve(future.get()); } catch (HazelcastSerializationException e) { throw new ExecutionException(e); } }
@Test(expected = ExecutionException.class) public void test_get_Exception() throws Exception { Throwable error = new Throwable(); Future<Object> future = new DelegatingCompletableFuture<>(serializationService, completedExceptionally(error)); future.get(); }
public TreeMap<AggregationFunctionColumnPair, AggregationSpec> getAggregationSpecs() { return _aggregationSpecs; }
@Test public void testUniqueAggregationSpecs() { TreeMap<AggregationFunctionColumnPair, AggregationSpec> expected = new TreeMap<>(); expected.put(AggregationFunctionColumnPair.fromColumnName("count__*"), AggregationSpec.DEFAULT); expected.put(AggregationFunctionColumnPair.fromColumnName("sum__dimX"), AggregationSpec.DEFAULT); Configuration metadataProperties = createMetadata(List.of("dimX"), expected); StarTreeV2Metadata starTreeV2Metadata = new StarTreeV2Metadata(metadataProperties); TreeMap<AggregationFunctionColumnPair, AggregationSpec> actual = starTreeV2Metadata.getAggregationSpecs(); assertEquals(expected, actual); }
@Override public String toString() { if (null != table && null != column) { return String.format("database.table.column: '%s'.'%s'.'%s'", database, table, column); } if (null != table) { return String.format("database.table: '%s'.'%s'", database, table); } return String.format("database: '%s'", database); }
@Test void assertToStringForDatabaseIdentifier() { assertThat(new SQLExceptionIdentifier("foo_db").toString(), is("database: 'foo_db'")); }
public static PDImageXObject createFromFileByExtension(File file, PDDocument doc) throws IOException { String name = file.getName(); int dot = name.lastIndexOf('.'); if (dot == -1) { throw new IllegalArgumentException("Image type not supported: " + name); } String ext = name.substring(dot + 1).toLowerCase(); if ("jpg".equals(ext) || "jpeg".equals(ext)) { try (FileInputStream fis = new FileInputStream(file)) { return JPEGFactory.createFromStream(doc, fis); } } if ("tif".equals(ext) || "tiff".equals(ext)) { try { return CCITTFactory.createFromFile(doc, file); } catch (IOException ex) { LOG.debug("Reading as TIFF failed, setting fileType to PNG", ex); // Plan B: try reading with ImageIO // common exception: // First image in tiff is not CCITT T4 or T6 compressed ext = "png"; } } if ("gif".equals(ext) || "bmp".equals(ext) || "png".equals(ext)) { BufferedImage bim = ImageIO.read(file); return LosslessFactory.createFromImage(doc, bim); } throw new IllegalArgumentException("Image type not supported: " + name); }
@Test void testCreateFromFileByExtension() throws IOException, URISyntaxException { testCompareCreatedFileByExtensionWithCreatedByCCITTFactory("ccittg4.tif"); testCompareCreatedFileByExtensionWithCreatedByJPEGFactory("jpeg.jpg"); testCompareCreatedFileByExtensionWithCreatedByJPEGFactory("jpegcmyk.jpg"); testCompareCreatedFileByExtensionWithCreatedByLosslessFactory("gif.gif"); testCompareCreatedFileByExtensionWithCreatedByLosslessFactory("gif-1bit-transparent.gif"); testCompareCreatedFileByExtensionWithCreatedByLosslessFactory("png_indexed_8bit_alpha.png"); testCompareCreatedFileByExtensionWithCreatedByLosslessFactory("png.png"); testCompareCreatedFileByExtensionWithCreatedByLosslessFactory("lzw.tif"); }
public static Configuration loadConfiguration( String workingDirectory, Configuration dynamicParameters, Map<String, String> env) { final Configuration configuration = GlobalConfiguration.loadConfiguration(workingDirectory, dynamicParameters); final String keytabPrincipal = env.get(YarnConfigKeys.KEYTAB_PRINCIPAL); final String hostname = env.get(ApplicationConstants.Environment.NM_HOST.key()); Preconditions.checkState( hostname != null, "ApplicationMaster hostname variable %s not set", ApplicationConstants.Environment.NM_HOST.key()); configuration.set(JobManagerOptions.ADDRESS, hostname); configuration.set(RestOptions.ADDRESS, hostname); configuration.set(RestOptions.BIND_ADDRESS, hostname); // if a web monitor shall be started, set the port to random binding if (configuration.get(WebOptions.PORT, 0) >= 0) { configuration.set(WebOptions.PORT, 0); } if (!configuration.contains(RestOptions.BIND_PORT)) { // set the REST port to 0 to select it randomly configuration.set(RestOptions.BIND_PORT, "0"); } // if the user has set the deprecated YARN-specific config keys, we add the // corresponding generic config keys instead. that way, later code needs not // deal with deprecated config keys BootstrapTools.substituteDeprecatedConfigPrefix( configuration, ConfigConstants.YARN_APPLICATION_MASTER_ENV_PREFIX, ResourceManagerOptions.CONTAINERIZED_MASTER_ENV_PREFIX); BootstrapTools.substituteDeprecatedConfigPrefix( configuration, ConfigConstants.YARN_TASK_MANAGER_ENV_PREFIX, ResourceManagerOptions.CONTAINERIZED_TASK_MANAGER_ENV_PREFIX); final String keytabPath = Utils.resolveKeytabPath( workingDirectory, env.get(YarnConfigKeys.LOCAL_KEYTAB_PATH)); if (keytabPath != null && keytabPrincipal != null) { configuration.set(SecurityOptions.KERBEROS_LOGIN_KEYTAB, keytabPath); configuration.set(SecurityOptions.KERBEROS_LOGIN_PRINCIPAL, keytabPrincipal); } final String localDirs = env.get(ApplicationConstants.Environment.LOCAL_DIRS.key()); BootstrapTools.updateTmpDirectoriesInConfiguration(configuration, localDirs); return configuration; }
@Test void testRestPortSpecified() throws IOException { final Configuration initialConfiguration = new Configuration(); final int port = 1337; initialConfiguration.set(RestOptions.PORT, port); final Configuration configuration = loadConfiguration(initialConfiguration); // if the bind port is not specified it should fall back to the rest port assertThat(configuration.get(RestOptions.BIND_PORT)).isEqualTo(String.valueOf(port)); }
static Reference<File> createBlobStorageDirectory( Configuration configuration, @Nullable Reference<File> fallbackStorageDirectory) throws IOException { final String basePath = configuration.get(BlobServerOptions.STORAGE_DIRECTORY); File baseDir = null; if (StringUtils.isNullOrWhitespaceOnly(basePath)) { if (fallbackStorageDirectory != null) { baseDir = fallbackStorageDirectory.deref(); if (baseDir.mkdirs() || baseDir.exists()) { return fallbackStorageDirectory; } } } else { baseDir = new File(basePath); File storageDir; // NOTE: although we will be using UUIDs, there may be collisions int maxAttempts = 10; for (int attempt = 0; attempt < maxAttempts; attempt++) { storageDir = new File(baseDir, String.format("blobStore-%s", UUID.randomUUID())); // Create the storage dir if it doesn't exist. Only return it when the operation was // successful. if (storageDir.mkdirs()) { return Reference.owned(storageDir); } } } if (baseDir != null) { throw new IOException( "Could not create storage directory for BLOB store in '" + baseDir + "'."); } else { throw new IOException( String.format( "Could not create storage directory for BLOB store because no storage directory has " + "been specified under %s and no fallback storage directory provided.", BlobServerOptions.STORAGE_DIRECTORY.key())); } }
@Test void testBlobUtilsFailIfNoStorageDirectoryIsSpecified() { assertThatThrownBy(() -> BlobUtils.createBlobStorageDirectory(new Configuration(), null)) .isInstanceOf(IOException.class); }
@Override public E computeIfAbsent(String key, Function<? super String, ? extends E> mappingFunction) { try { return cacheStore.invoke(key, new AtomicComputeProcessor<>(), mappingFunction); } catch (EntryProcessorException e) { throw new RuntimeException(e.getCause()); } }
@Test public void computeIfAbsent_cacheHit_mappingFunctionNotInvoked() { doReturn(1).when(mutableEntryMock).getValue(); Function<String, Integer> mappingFunctionMock = Mockito.mock(Function.class); entryProcessorMock = new CacheRegistryStore.AtomicComputeProcessor<>(); entryProcessorArgMock = mappingFunctionMock; classUnderTest.computeIfAbsent(CACHE_KEY, mappingFunctionMock); verify(mappingFunctionMock, never()).apply(CACHE_KEY); verify(mutableEntryMock, never()).setValue(any()); }
@OnClose public void onClose(final Session session) { clearSession(session); LOG.warn("websocket close on client[{}]", getClientIp(session)); }
@Test public void testOnClose() { websocketCollector.onOpen(session); assertEquals(1L, getSessionSetSize()); doNothing().when(loggerSpy).warn(anyString(), anyString()); websocketCollector.onClose(session); assertEquals(0L, getSessionSetSize()); assertNull(getSession()); }
@VisibleForTesting static boolean checkHttpsStrictAndNotProvided( HttpServletResponse resp, URI link, YarnConfiguration conf) throws IOException { String httpsPolicy = conf.get( YarnConfiguration.RM_APPLICATION_HTTPS_POLICY, YarnConfiguration.DEFAULT_RM_APPLICATION_HTTPS_POLICY); boolean required = httpsPolicy.equals("STRICT"); boolean provided = link.getScheme().equals("https"); if (required && !provided) { resp.setContentType(MimeType.HTML); Page p = new Page(resp.getWriter()); p.html(). h1("HTTPS must be used"). h3(). __(YarnConfiguration.RM_APPLICATION_HTTPS_POLICY, "is set to STRICT, which means that the tracking URL ", "must be an HTTPS URL, but it is not."). __("The tracking URL is: ", link). __(). __(); return true; } return false; }
@Test @Timeout(5000) void testCheckHttpsStrictAndNotProvided() throws Exception { HttpServletResponse resp = mock(HttpServletResponse.class); StringWriter sw = new StringWriter(); when(resp.getWriter()).thenReturn(new PrintWriter(sw)); YarnConfiguration conf = new YarnConfiguration(); final URI httpLink = new URI("http://foo.com"); final URI httpsLink = new URI("https://foo.com"); // NONE policy conf.set(YarnConfiguration.RM_APPLICATION_HTTPS_POLICY, "NONE"); assertFalse(WebAppProxyServlet.checkHttpsStrictAndNotProvided( resp, httpsLink, conf)); assertEquals("", sw.toString()); Mockito.verify(resp, Mockito.times(0)).setContentType(Mockito.any()); assertFalse(WebAppProxyServlet.checkHttpsStrictAndNotProvided( resp, httpLink, conf)); assertEquals("", sw.toString()); Mockito.verify(resp, Mockito.times(0)).setContentType(Mockito.any()); // LENIENT policy conf.set(YarnConfiguration.RM_APPLICATION_HTTPS_POLICY, "LENIENT"); assertFalse(WebAppProxyServlet.checkHttpsStrictAndNotProvided( resp, httpsLink, conf)); assertEquals("", sw.toString()); Mockito.verify(resp, Mockito.times(0)).setContentType(Mockito.any()); assertFalse(WebAppProxyServlet.checkHttpsStrictAndNotProvided( resp, httpLink, conf)); assertEquals("", sw.toString()); Mockito.verify(resp, Mockito.times(0)).setContentType(Mockito.any()); // STRICT policy conf.set(YarnConfiguration.RM_APPLICATION_HTTPS_POLICY, "STRICT"); assertFalse(WebAppProxyServlet.checkHttpsStrictAndNotProvided( resp, httpsLink, conf)); assertEquals("", sw.toString()); Mockito.verify(resp, Mockito.times(0)).setContentType(Mockito.any()); assertTrue(WebAppProxyServlet.checkHttpsStrictAndNotProvided( resp, httpLink, conf)); String s = sw.toString(); assertTrue(s.contains("HTTPS must be used"), "Was expecting an HTML page explaining that an HTTPS tracking" + " url must be used but found " + s); Mockito.verify(resp, Mockito.times(1)).setContentType(MimeType.HTML); }
@Override public String getName() { return this.jsonParser.getName(); }
@Test public void testGetName() { assertEquals("customParser", parserWrap.getName()); }
@Override public Local create(final Path file) { return this.create(new UUIDRandomStringService().random(), file); }
@Test public void testTemporaryPathCustomPrefix() { final Path file = new Path("/f1/f2/t.txt", EnumSet.of(Path.Type.file)); file.attributes().setDuplicate(true); file.attributes().setVersionId("1"); final Local local = new DefaultTemporaryFileService().create("u", file); assertTrue(local.getParent().exists()); assertEquals("t.txt", file.getName()); assertEquals("t.txt", local.getName()); }
public boolean liveness() { if (!Health.Status.GREEN.equals(dbConnectionNodeCheck.check().getStatus())) { return false; } if (!Health.Status.GREEN.equals(webServerStatusNodeCheck.check().getStatus())) { return false; } if (!Health.Status.GREEN.equals(ceStatusNodeCheck.check().getStatus())) { return false; } if (esStatusNodeCheck != null && Health.Status.RED.equals(esStatusNodeCheck.check().getStatus())) { return false; } return true; }
@Test public void fail_when_ce_check_fail() { when(dbConnectionNodeCheck.check()).thenReturn(Health.GREEN); when(webServerStatusNodeCheck.check()).thenReturn(Health.GREEN); when(ceStatusNodeCheck.check()).thenReturn(RED); Assertions.assertThat(underTest.liveness()).isFalse(); }
static Map<String, ValueExtractor> instantiateExtractors(List<AttributeConfig> attributeConfigs, ClassLoader classLoader) { Map<String, ValueExtractor> extractors = createHashMap(attributeConfigs.size()); for (AttributeConfig config : attributeConfigs) { if (extractors.containsKey(config.getName())) { throw new IllegalArgumentException("Could not add " + config + ". Extractor for this attribute name already added."); } extractors.put(config.getName(), instantiateExtractor(config, classLoader)); } return extractors; }
@Test public void instantiate_extractors() { // GIVEN AttributeConfig iqExtractor = new AttributeConfig("iq", "com.hazelcast.query.impl.getters.ExtractorHelperTest$IqExtractor"); AttributeConfig nameExtractor = new AttributeConfig("name", "com.hazelcast.query.impl.getters.ExtractorHelperTest$NameExtractor"); // WHEN Map<String, ValueExtractor> extractors = instantiateExtractors(asList(iqExtractor, nameExtractor)); // THEN assertThat(extractors.get("iq")).isInstanceOf(IqExtractor.class); assertThat(extractors.get("name")).isInstanceOf(NameExtractor.class); }
@Override public <T> @Nullable Schema schemaFor(TypeDescriptor<T> typeDescriptor) { checkForDynamicType(typeDescriptor); return ProtoSchemaTranslator.getSchema((Class<Message>) typeDescriptor.getRawType()); }
@Test public void testOuterOneOfSchema() { Schema schema = new ProtoMessageSchema().schemaFor(TypeDescriptor.of(OuterOneOf.class)); assertEquals(OUTER_ONEOF_SCHEMA, schema); }
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) { while (in.readableBytes() >= 1 + MySQLBinlogEventHeader.MYSQL_BINLOG_EVENT_HEADER_LENGTH) { in.markReaderIndex(); MySQLPacketPayload payload = new MySQLPacketPayload(in, ctx.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY).get()); checkPayload(payload); MySQLBinlogEventHeader binlogEventHeader = new MySQLBinlogEventHeader(payload, binlogContext.getChecksumLength()); if (!checkEventIntegrity(in, binlogEventHeader)) { return; } Optional<MySQLBaseBinlogEvent> binlogEvent = decodeEvent(binlogEventHeader, payload); if (!binlogEvent.isPresent()) { skipChecksum(binlogEventHeader.getEventType(), in); return; } if (binlogEvent.get() instanceof PlaceholderBinlogEvent) { out.add(binlogEvent.get()); skipChecksum(binlogEventHeader.getEventType(), in); return; } if (decodeWithTX) { processEventWithTX(binlogEvent.get(), out); } else { processEventIgnoreTX(binlogEvent.get(), out); } skipChecksum(binlogEventHeader.getEventType(), in); } }
@Test void assertBinlogEventHeaderIncomplete() { ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(); byte[] completeData = StringUtil.decodeHexDump("002a80a862200100000038000000c569000000007400000000000100020004ff0801000000000000000100000007535543434553531c9580c5"); byteBuf.writeBytes(completeData); byteBuf.writeBytes(StringUtil.decodeHexDump("006acb656410010000001f000000fa29000000001643000000000000b13f8340")); // write incomplete event data byteBuf.writeBytes(StringUtil.decodeHexDump("3400")); List<Object> decodedEvents = new LinkedList<>(); binlogContext.getTableMap().put(116L, tableMapEventPacket); when(tableMapEventPacket.getColumnDefs()).thenReturn(columnDefs); binlogEventPacketDecoder.decode(channelHandlerContext, byteBuf, decodedEvents); assertThat(decodedEvents.size(), is(1)); }
public T add(String str) { requireNonNull(str, JVM_OPTION_NOT_NULL_ERROR_MESSAGE); String value = str.trim(); if (isInvalidOption(value)) { throw new IllegalArgumentException("a JVM option can't be empty and must start with '-'"); } checkMandatoryOptionOverwrite(value); options.add(value); return castThis(); }
@Test public void add_throws_MessageException_if_option_starts_with_prefix_of_mandatory_option_but_has_different_value() { String[] optionOverrides = { randomPrefix, randomPrefix + randomAlphanumeric(1), randomPrefix + randomAlphanumeric(2), randomPrefix + randomAlphanumeric(3), randomPrefix + randomAlphanumeric(4), randomPrefix + randomValue.substring(1), randomPrefix + randomValue.substring(2), randomPrefix + randomValue.substring(3) }; JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue)); for (String optionOverride : optionOverrides) { try { underTest.add(optionOverride); fail("an MessageException should have been thrown"); } catch (MessageException e) { assertThat(e.getMessage()).isEqualTo("a JVM option can't overwrite mandatory JVM options. " + optionOverride + " overwrites " + randomPrefix + randomValue); } } }
public void validateMatcher() throws ValidationException { validate(Validator.lengthValidator(255), getMatcher()); }
@Test void shouldInvalidateMatcherMoreThan255Of() throws Exception { user = new User("UserName", new String[]{onlyChars(200), onlyChars(55)}, "user@mail.com", true); try { user.validateMatcher(); fail("validator should capture the matcher"); } catch (ValidationException ignored) { } }
@Override public <T> AsyncResult<T> startProcess(Callable<T> task) { return startProcess(task, null); }
@Test void testNullTaskWithCallback() { assertTimeout(ofMillis(3000), () -> { // Instantiate a new executor and start a new 'null' task ... final var executor = new ThreadAsyncExecutor(); final var asyncResult = executor.startProcess(null, callback); assertNotNull(asyncResult, "The AsyncResult should not be 'null', even though the task was 'null'."); asyncResult.await(); // Prevent timing issues, and wait until the result is available assertTrue(asyncResult.isCompleted()); verify(callback, times(0)).onComplete(any()); verify(callback, times(1)).onError(exceptionCaptor.capture()); final var exception = exceptionCaptor.getValue(); assertNotNull(exception); assertEquals(NullPointerException.class, exception.getClass()); try { asyncResult.getValue(); fail("Expected ExecutionException with NPE as cause"); } catch (final ExecutionException e) { assertNotNull(e.getMessage()); assertNotNull(e.getCause()); assertEquals(NullPointerException.class, e.getCause().getClass()); } }); }
public synchronized void createTable(String tableId, Iterable<String> columnFamilies) throws BigtableResourceManagerException { createTable(tableId, columnFamilies, Duration.ofHours(1)); }
@Test public void testCreateTableShouldNotCreateTableWhenTableAlreadyExists() { when(bigtableResourceManagerClientFactory.bigtableTableAdminClient().exists(anyString())) .thenReturn(true); assertThrows( BigtableResourceManagerException.class, () -> testManager.createTable(TABLE_ID, ImmutableList.of("cf1"))); }
public Value hexToByteDecode() throws KettleValueException { setType( VALUE_TYPE_STRING ); if ( isNull() ) { return this; } setValue( getString() ); String hexString = getString(); int len = hexString.length(); char[] chArray = new char[( len + 1 ) / 2]; boolean evenByte = true; int nextByte = 0; // we assume a leading 0 if the length is not even. if ( ( len % 2 ) == 1 ) { evenByte = false; } int nibble; int i, j; for ( i = 0, j = 0; i < len; i++ ) { char c = hexString.charAt( i ); if ( ( c >= '0' ) && ( c <= '9' ) ) { nibble = c - '0'; } else if ( ( c >= 'A' ) && ( c <= 'F' ) ) { nibble = c - 'A' + 0x0A; } else if ( ( c >= 'a' ) && ( c <= 'f' ) ) { nibble = c - 'a' + 0x0A; } else { throw new KettleValueException( "invalid hex digit '" + c + "'." ); } if ( evenByte ) { nextByte = ( nibble << 4 ); } else { nextByte += nibble; chArray[j] = (char) nextByte; j++; } evenByte = !evenByte; } setValue( new String( chArray ) ); return this; }
@Test public void testHexToByteDecode() throws KettleValueException { Value vs1 = new Value( "Name1", Value.VALUE_TYPE_INTEGER ); vs1.setValue( "6120622063" ); vs1.hexToByteDecode(); assertEquals( "a b c", vs1.getString() ); vs1.setValue( "4161426243643039207A5A2E3F2F" ); vs1.hexToByteDecode(); assertEquals( "AaBbCd09 zZ.?/", vs1.getString() ); vs1.setValue( "4161426243643039207a5a2e3f2f" ); vs1.hexToByteDecode(); assertEquals( "AaBbCd09 zZ.?/", vs1.getString() ); // leading 0 if odd. vs1.setValue( "F6120622063" ); vs1.hexToByteDecode(); assertEquals( "\u000fa b c", vs1.getString() ); try { vs1.setValue( "g" ); vs1.hexToByteDecode(); fail( "Expected KettleValueException" ); } catch ( KettleValueException ex ) { } }
public synchronized <K, V> KStream<K, V> stream(final String topic) { return stream(Collections.singleton(topic)); }
@Test public void shouldThrowExceptionWhenNoTopicPresent() { builder.stream(Collections.emptyList()); assertThrows(TopologyException.class, builder::build); }
@Override public boolean acquirePermit(String nsId) { if (contains(nsId)) { return super.acquirePermit(nsId); } return super.acquirePermit(DEFAULT_NS); }
@Test public void testAllocationWithZeroProportion() { Configuration conf = createConf(40); conf.setDouble(DFS_ROUTER_FAIR_HANDLER_PROPORTION_KEY_PREFIX + "ns1", 0); RouterRpcFairnessPolicyController routerRpcFairnessPolicyController = FederationUtil.newFairnessPolicyController(conf); // ns1 should have 1 permit allocated assertTrue(routerRpcFairnessPolicyController.acquirePermit("ns1")); assertFalse(routerRpcFairnessPolicyController.acquirePermit("ns1")); }
@Override public Status check() { if (applicationContext == null && applicationModel != null) { SpringExtensionInjector springExtensionInjector = SpringExtensionInjector.get(applicationModel); applicationContext = springExtensionInjector.getContext(); } if (applicationContext == null) { return new Status(Status.Level.UNKNOWN); } Status.Level level; if (applicationContext instanceof Lifecycle) { if (((Lifecycle) applicationContext).isRunning()) { level = Status.Level.OK; } else { level = Status.Level.ERROR; } } else { level = Status.Level.UNKNOWN; } StringBuilder buf = new StringBuilder(); try { Class<?> cls = applicationContext.getClass(); Method method = null; while (cls != null && method == null) { try { method = cls.getDeclaredMethod("getConfigLocations", new Class<?>[0]); } catch (NoSuchMethodException t) { cls = cls.getSuperclass(); } } if (method != null) { if (!method.isAccessible()) { method.setAccessible(true); } String[] configs = (String[]) method.invoke(applicationContext, new Object[0]); if (configs != null && configs.length > 0) { for (String config : configs) { if (buf.length() > 0) { buf.append(','); } buf.append(config); } } } } catch (Throwable t) { if (t.getCause() instanceof UnsupportedOperationException) { logger.debug(t.getMessage(), t); } else { logger.warn(CONFIG_WARN_STATUS_CHECKER, "", "", t.getMessage(), t); } } return new Status(level, buf.toString()); }
@Test void testGenericWebApplicationContext() { GenericWebApplicationContext context = mock(GenericWebApplicationContext.class); given(context.isRunning()).willReturn(true); SpringStatusChecker checker = new SpringStatusChecker(context); Status status = checker.check(); Assertions.assertEquals(Status.Level.OK, status.getLevel()); }
public static String secondToTime(int seconds) { if (seconds < 0) { throw new IllegalArgumentException("Seconds must be a positive number!"); } int hour = seconds / 3600; int other = seconds % 3600; int minute = other / 60; int second = other % 60; final StringBuilder sb = new StringBuilder(); if (hour < 10) { sb.append("0"); } sb.append(hour); sb.append(":"); if (minute < 10) { sb.append("0"); } sb.append(minute); sb.append(":"); if (second < 10) { sb.append("0"); } sb.append(second); return sb.toString(); }
@Test public void secondToTimeTest() { String time = DateUtil.secondToTime(3600); assertEquals("01:00:00", time); time = DateUtil.secondToTime(3800); assertEquals("01:03:20", time); time = DateUtil.secondToTime(0); assertEquals("00:00:00", time); time = DateUtil.secondToTime(30); assertEquals("00:00:30", time); }
@Override @CanIgnoreReturnValue public Key register(Watchable watchable, Iterable<? extends WatchEvent.Kind<?>> eventTypes) throws IOException { JimfsPath path = checkWatchable(watchable); Key key = super.register(path, eventTypes); Snapshot snapshot = takeSnapshot(path); synchronized (this) { snapshots.put(key, snapshot); if (pollingFuture == null) { startPolling(); } } return key; }
@Test public void testRegister_fileDoesNotExist() throws IOException { try { watcher.register(fs.getPath("/a/b/c"), ImmutableList.of(ENTRY_CREATE)); fail(); } catch (NoSuchFileException expected) { } }
public static WindowedValueCoderComponents getWindowedValueCoderComponents(Coder coder) { checkArgument(WINDOWED_VALUE_CODER_URN.equals(coder.getSpec().getUrn())); return new AutoValue_ModelCoders_WindowedValueCoderComponents( coder.getComponentCoderIds(0), coder.getComponentCoderIds(1)); }
@Test public void windowedValueCoderComponentsWrongUrn() { thrown.expect(IllegalArgumentException.class); ModelCoders.getWindowedValueCoderComponents( Coder.newBuilder() .setSpec(FunctionSpec.newBuilder().setUrn(ModelCoders.LENGTH_PREFIX_CODER_URN)) .build()); }
static JarFileWithEntryClass findOnlyEntryClass(Iterable<File> jarFiles) throws IOException { List<JarFileWithEntryClass> jarsWithEntryClasses = new ArrayList<>(); for (File jarFile : jarFiles) { findEntryClass(jarFile) .ifPresent( entryClass -> jarsWithEntryClasses.add( new JarFileWithEntryClass(jarFile, entryClass))); } int size = jarsWithEntryClasses.size(); if (size == 0) { throw new NoSuchElementException("No JAR with manifest attribute for entry class"); } if (size == 1) { return jarsWithEntryClasses.get(0); } // else: size > 1 throw new IllegalArgumentException( "Multiple JARs with manifest attribute for entry class: " + jarsWithEntryClasses); }
@Test void testFindOnlyEntryClassSingleJarWithNoManifest() { assertThatThrownBy( () -> { File jarWithNoManifest = createJarFileWithManifest(ImmutableMap.of()); JarManifestParser.findOnlyEntryClass( ImmutableList.of(jarWithNoManifest)); }) .isInstanceOf(NoSuchElementException.class); }
@GetMapping("/search") @Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.READ) public List<String> searchRoles(@RequestParam String role) { return roleService.findRolesLikeRoleName(role); }
@Test void testSearchRoles() { List<String> test = new ArrayList<>(); when(roleService.findRolesLikeRoleName(anyString())).thenReturn(test); List<String> list = roleController.searchRoles("test"); assertEquals(test, list); }
@Override void toHtml() throws IOException { writeHtmlHeader(); htmlCoreReport.toHtml(); writeHtmlFooter(); }
@SuppressWarnings("deprecation") @Test public void testCache() throws IOException { final String cacheName = "test 1"; final CacheManager cacheManager = CacheManager.getInstance(); cacheManager.addCache(cacheName); // test empty cache name in the cache keys link: // cacheManager.addCache("") does nothing, but cacheManager.addCache(new Cache("", ...)) works cacheManager.addCache(new Cache("", 1000, true, false, 10000, 10000, false, 10000)); final String cacheName2 = "test 2"; try { final Cache cache = cacheManager.getCache(cacheName); cache.put(new Element(1, Math.random())); cache.get(1); cache.get(0); cacheManager.addCache(cacheName2); final Cache cache2 = cacheManager.getCache(cacheName2); cache2.getCacheConfiguration().setOverflowToDisk(false); cache2.getCacheConfiguration().setEternal(true); cache2.getCacheConfiguration().setMaxElementsInMemory(0); // JavaInformations doit être réinstancié pour récupérer les caches final List<JavaInformations> javaInformationsList2 = Collections .singletonList(new JavaInformations(null, true)); final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList2, Period.TOUT, writer); htmlReport.toHtml(null, null); assertNotEmptyAndClear(writer); setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, "false"); htmlReport.toHtml(null, null); assertNotEmptyAndClear(writer); } finally { setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, null); cacheManager.removeCache(cacheName); cacheManager.removeCache(cacheName2); } }
abstract GenericUrl genericUrl();
@Test public void genericURLTest() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException { String baseURL = "http://example.com"; HttpEventPublisher.Builder builder = HttpEventPublisher.newBuilder() .withUrl(baseURL) .withToken("test-token") .withDisableCertificateValidation(false) .withEnableGzipHttpCompression(true); assertEquals( new GenericUrl(Joiner.on('/').join(baseURL, "services/collector/event")), builder.genericUrl()); }
@Override public int run(InputStream stdin, PrintStream out, PrintStream err, List<String> args) throws Exception { if (args.size() < 2) { printInfo(err); return 1; } int index = 0; String input = args.get(index); String option = "all"; if ("-o".equals(input)) { option = args.get(1); index += 2; } if (!OPTIONS.contains(option) || (args.size() - index < 1)) { printInfo(err); return 1; } input = args.get(index++); if (!REPORT.equals(option)) { if (args.size() - index < 1) { printInfo(err); return 1; } } if (ALL.equals(option)) { return recoverAll(input, args.get(index), out, err); } else if (PRIOR.equals(option)) { return recoverPrior(input, args.get(index), out, err); } else if (AFTER.equals(option)) { return recoverAfter(input, args.get(index), out, err); } else if (REPORT.equals(option)) { return reportOnly(input, out, err); } else { return 1; } }
@Test void repairAfterCorruptRecord() throws Exception { String output = run(new DataFileRepairTool(), "-o", "after", corruptRecordFile.getPath(), repairedFile.getPath()); assertTrue(output.contains("Number of blocks: 3 Number of corrupt blocks: 1"), output); assertTrue(output.contains("Number of records: 8 Number of corrupt records: 2"), output); checkFileContains(repairedFile, "guava", "hazelnut"); }
public static ResourceModel processResource(final Class<?> resourceClass) { return processResource(resourceClass, null); }
@Test(description = "verifies return types of action resource methods", dataProvider = "actionReturnTypeData") public void actionResourceMethodReturnTypes(final Class<?> resourceClass, final Class<?> expectedActionReturnType) { final ResourceModel model = RestLiAnnotationReader.processResource(resourceClass); Assert.assertNotNull(model); for (final ResourceMethodDescriptor methodDescriptor : model.getResourceMethodDescriptors()) { final Class<?> expectedReturnType = methodDescriptor.getActionReturnType(); Assert.assertEquals(expectedReturnType, expectedActionReturnType); } }
public String toDataURI() { return "data:" + contentType + ";base64," + data; }
@Test void convertsToDataUri() { String encodedString = Base64.getEncoder().encodeToString("asdf".getBytes(StandardCharsets.UTF_8)); String dataURI = new Image("image/png", encodedString, "sha-256").toDataURI(); assertThat(dataURI, is("data:image/png;base64," + encodedString)); }
Duration getLockAtLeastFor(AnnotationData annotation) { return getValue( annotation.getLockAtLeastFor(), annotation.getLockAtLeastForString(), this.defaultLockAtLeastFor, "lockAtLeastForString"); }
@Test public void shouldGetPositiveGracePeriodFromAnnotation() throws NoSuchMethodException { noopResolver(); SpringLockConfigurationExtractor.AnnotationData annotation = getAnnotation("annotatedMethodWithPositiveGracePeriod"); TemporalAmount gracePeriod = extractor.getLockAtLeastFor(annotation); assertThat(gracePeriod).isEqualTo(Duration.of(10, MILLIS)); }
@Override protected void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier) { zkClient.delete(getNodePath(metadataIdentifier)); }
@Test void testDoRemoveMetadata() throws ExecutionException, InterruptedException { String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService"; String version = "1.0.0"; String group = null; String application = "etc-metadata-report-consumer-test"; String revision = "90980"; String protocol = "xxx"; URL url = generateURL(interfaceName, version, group, application); ServiceMetadataIdentifier serviceMetadataIdentifier = new ServiceMetadataIdentifier(interfaceName, version, group, "provider", revision, protocol); zookeeperMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url); String fileContent = zookeeperMetadataReport.zkClient.getContent( zookeeperMetadataReport.getNodePath(serviceMetadataIdentifier)); Assertions.assertNotNull(fileContent); zookeeperMetadataReport.doRemoveMetadata(serviceMetadataIdentifier); fileContent = zookeeperMetadataReport.zkClient.getContent( zookeeperMetadataReport.getNodePath(serviceMetadataIdentifier)); Assertions.assertNull(fileContent); }
@Override public String getConfigAndSignListener(String dataId, String group, long timeoutMs, Listener listener) throws NacosException { group = StringUtils.isBlank(group) ? Constants.DEFAULT_GROUP : group.trim(); ConfigResponse configResponse = worker.getAgent() .queryConfig(dataId, group, worker.getAgent().getTenant(), timeoutMs, false); String content = configResponse.getContent(); String encryptedDataKey = configResponse.getEncryptedDataKey(); worker.addTenantListenersWithContent(dataId, group, content, encryptedDataKey, Collections.singletonList(listener)); // get a decryptContent, fix https://github.com/alibaba/nacos/issues/7039 ConfigResponse cr = new ConfigResponse(); cr.setDataId(dataId); cr.setGroup(group); cr.setContent(content); cr.setEncryptedDataKey(encryptedDataKey); configFilterChainManager.doFilter(null, cr); return cr.getContent(); }
@Test void testGetConfigAndSignListener() throws NacosException { final String dataId = "1"; final String group = "2"; final String tenant = ""; final String content = "123"; final int timeout = 3000; final Listener listener = new Listener() { @Override public Executor getExecutor() { return null; } @Override public void receiveConfigInfo(String configInfo) { } }; final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(new Properties()); Mockito.when(mockWoker.getAgent()).thenReturn(new ConfigTransportClient(properties, new ServerListManager()) { @Override public void startInternal() throws NacosException { // NOOP } @Override public String getName() { return "TestConfigTransportClient"; } @Override public void notifyListenConfig() { // NOOP } @Override public void executeConfigListen() { // NOOP } @Override public void removeCache(String dataId, String group) { // NOOP } @Override public ConfigResponse queryConfig(String dataId, String group, String tenant, long readTimeous, boolean notify) throws NacosException { ConfigResponse configResponse = new ConfigResponse(); configResponse.setContent(content); configResponse.setDataId(dataId); configResponse.setGroup(group); configResponse.setTenant(tenant); return configResponse; } @Override public boolean publishConfig(String dataId, String group, String tenant, String appName, String tag, String betaIps, String content, String encryptedDataKey, String casMd5, String type) throws NacosException { return false; } @Override public boolean removeConfig(String dataId, String group, String tenant, String tag) throws NacosException { return false; } }); final String config = nacosConfigService.getConfigAndSignListener(dataId, group, timeout, listener); assertEquals(content, config); Mockito.verify(mockWoker, Mockito.times(1)).addTenantListenersWithContent(dataId, group, content, null, Arrays.asList(listener)); }
@Override public long localCount() { return count(InputImpl.class, new BasicDBObject(MessageInput.FIELD_GLOBAL, false)); }
@Test @MongoDBFixtures("InputServiceImplTest.json") public void localCountReturnsNumberOfLocalInputs() { assertThat(inputService.localCount()).isEqualTo(2); }
public IssueQuery create(SearchRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone()); Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules()); Collection<String> ruleUuids = ruleDtos.stream().map(RuleDto::getUuid).collect(Collectors.toSet()); Collection<String> issueKeys = collectIssueKeys(dbSession, request); if (request.getRules() != null && request.getRules().stream().collect(Collectors.toSet()).size() != ruleDtos.size()) { ruleUuids.add("non-existing-uuid"); } IssueQuery.Builder builder = IssueQuery.builder() .issueKeys(issueKeys) .severities(request.getSeverities()) .cleanCodeAttributesCategories(request.getCleanCodeAttributesCategories()) .impactSoftwareQualities(request.getImpactSoftwareQualities()) .impactSeverities(request.getImpactSeverities()) .statuses(request.getStatuses()) .resolutions(request.getResolutions()) .issueStatuses(request.getIssueStatuses()) .resolved(request.getResolved()) .prioritizedRule(request.getPrioritizedRule()) .rules(ruleDtos) .ruleUuids(ruleUuids) .assigneeUuids(request.getAssigneeUuids()) .authors(request.getAuthors()) .scopes(request.getScopes()) .languages(request.getLanguages()) .tags(request.getTags()) .types(request.getTypes()) .pciDss32(request.getPciDss32()) .pciDss40(request.getPciDss40()) .owaspAsvs40(request.getOwaspAsvs40()) .owaspAsvsLevel(request.getOwaspAsvsLevel()) .owaspTop10(request.getOwaspTop10()) .owaspTop10For2021(request.getOwaspTop10For2021()) .stigAsdR5V3(request.getStigAsdV5R3()) .casa(request.getCasa()) .sansTop25(request.getSansTop25()) .cwe(request.getCwe()) .sonarsourceSecurity(request.getSonarsourceSecurity()) .assigned(request.getAssigned()) .createdAt(parseStartingDateOrDateTime(request.getCreatedAt(), timeZone)) .createdBefore(parseEndingDateOrDateTime(request.getCreatedBefore(), timeZone)) .facetMode(request.getFacetMode()) .timeZone(timeZone) .codeVariants(request.getCodeVariants()); List<ComponentDto> allComponents = new ArrayList<>(); boolean effectiveOnComponentOnly = mergeDeprecatedComponentParameters(dbSession, request, allComponents); addComponentParameters(builder, dbSession, effectiveOnComponentOnly, allComponents, request); setCreatedAfterFromRequest(dbSession, builder, request, allComponents, timeZone); String sort = request.getSort(); if (!isNullOrEmpty(sort)) { builder.sort(sort); builder.asc(request.getAsc()); } return builder.build(); } }
@Test public void in_new_code_period_start_date_is_exclusive() { long newCodePeriodStart = addDays(new Date(), -14).getTime(); ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(project)); SnapshotDto analysis = db.components().insertSnapshot(project, s -> s.setPeriodDate(newCodePeriodStart)); SearchRequest request = new SearchRequest() .setComponentUuids(Collections.singletonList(file.uuid())) .setOnComponentOnly(true) .setInNewCodePeriod(true); IssueQuery query = underTest.create(request); assertThat(query.componentUuids()).containsOnly(file.uuid()); assertThat(query.createdAfter().date()).isEqualTo(new Date(newCodePeriodStart)); assertThat(query.createdAfter().inclusive()).isFalse(); assertThat(query.newCodeOnReference()).isNull(); }
static String headerLine(CSVFormat csvFormat) { return String.join(String.valueOf(csvFormat.getDelimiter()), csvFormat.getHeader()); }
@Test public void givenTrim_removesSpaces() { CSVFormat csvFormat = csvFormat().withTrim(true); PCollection<String> input = pipeline.apply( Create.of( headerLine(csvFormat), " a ,1,1.1", "b, 2 ,2.2", "c,3, 3.3 ")); CsvIOStringToCsvRecord underTest = new CsvIOStringToCsvRecord(csvFormat); CsvIOParseResult<List<String>> result = input.apply(underTest); PAssert.that(result.getOutput()) .containsInAnyOrder( Arrays.asList( Arrays.asList("a", "1", "1.1"), Arrays.asList("b", "2", "2.2"), Arrays.asList("c", "3", "3.3"))); PAssert.that(result.getErrors()).empty(); pipeline.run(); }
@SuppressWarnings("unchecked") RestartRequest recordToRestartRequest(ConsumerRecord<String, byte[]> record, SchemaAndValue value) { String connectorName = record.key().substring(RESTART_PREFIX.length()); if (!(value.value() instanceof Map)) { log.error("Ignoring restart request because the value is not a Map but is {}", className(value.value())); return null; } Map<String, Object> valueAsMap = (Map<String, Object>) value.value(); Object failed = valueAsMap.get(ONLY_FAILED_FIELD_NAME); boolean onlyFailed; if (!(failed instanceof Boolean)) { log.warn("Invalid data for restart request '{}' field should be a Boolean but is {}, defaulting to {}", ONLY_FAILED_FIELD_NAME, className(failed), ONLY_FAILED_DEFAULT); onlyFailed = ONLY_FAILED_DEFAULT; } else { onlyFailed = (Boolean) failed; } Object withTasks = valueAsMap.get(INCLUDE_TASKS_FIELD_NAME); boolean includeTasks; if (!(withTasks instanceof Boolean)) { log.warn("Invalid data for restart request '{}' field should be a Boolean but is {}, defaulting to {}", INCLUDE_TASKS_FIELD_NAME, className(withTasks), INCLUDE_TASKS_DEFAULT); includeTasks = INCLUDE_TASKS_DEFAULT; } else { includeTasks = (Boolean) withTasks; } return new RestartRequest(connectorName, onlyFailed, includeTasks); }
@Test public void testRecordToRestartRequestOnlyFailedInconsistent() { ConsumerRecord<String, byte[]> record = new ConsumerRecord<>(TOPIC, 0, 0, 0L, TimestampType.CREATE_TIME, 0, 0, RESTART_CONNECTOR_KEYS.get(0), CONFIGS_SERIALIZED.get(0), new RecordHeaders(), Optional.empty()); Struct struct = ONLY_FAILED_MISSING_STRUCT; SchemaAndValue schemaAndValue = new SchemaAndValue(struct.schema(), structToMap(struct)); RestartRequest restartRequest = configStorage.recordToRestartRequest(record, schemaAndValue); assertEquals(CONNECTOR_1_NAME, restartRequest.connectorName()); assertEquals(struct.getBoolean(INCLUDE_TASKS_FIELD_NAME), restartRequest.includeTasks()); assertFalse(restartRequest.onlyFailed()); }
public static JibContainerBuilder toJibContainerBuilder( ArtifactProcessor processor, CommonCliOptions commonCliOptions, CommonContainerConfigCliOptions commonContainerConfigCliOptions, ConsoleLogger logger) throws IOException, InvalidImageReferenceException { String baseImage = commonContainerConfigCliOptions.getFrom().orElse("jetty"); JibContainerBuilder containerBuilder = ContainerBuilders.create(baseImage, Collections.emptySet(), commonCliOptions, logger); List<String> programArguments = commonContainerConfigCliOptions.getProgramArguments(); if (!commonContainerConfigCliOptions.getProgramArguments().isEmpty()) { containerBuilder.setProgramArguments(programArguments); } containerBuilder .setEntrypoint(computeEntrypoint(commonContainerConfigCliOptions)) .setFileEntriesLayers(processor.createLayers()) .setExposedPorts(commonContainerConfigCliOptions.getExposedPorts()) .setVolumes(commonContainerConfigCliOptions.getVolumes()) .setEnvironment(commonContainerConfigCliOptions.getEnvironment()) .setLabels(commonContainerConfigCliOptions.getLabels()); commonContainerConfigCliOptions.getUser().ifPresent(containerBuilder::setUser); commonContainerConfigCliOptions.getFormat().ifPresent(containerBuilder::setFormat); commonContainerConfigCliOptions.getCreationTime().ifPresent(containerBuilder::setCreationTime); return containerBuilder; }
@Test public void testToJibContainerBuilder_optionalParameters() throws IOException, InvalidImageReferenceException { when(mockCommonContainerConfigCliOptions.getFrom()).thenReturn(Optional.of("base-image")); when(mockCommonContainerConfigCliOptions.getExposedPorts()) .thenReturn(ImmutableSet.of(Port.udp(123))); when(mockCommonContainerConfigCliOptions.getVolumes()) .thenReturn( ImmutableSet.of(AbsoluteUnixPath.get("/volume1"), AbsoluteUnixPath.get("/volume2"))); when(mockCommonContainerConfigCliOptions.getEnvironment()) .thenReturn(ImmutableMap.of("key1", "value1")); when(mockCommonContainerConfigCliOptions.getLabels()) .thenReturn(ImmutableMap.of("label", "mylabel")); when(mockCommonContainerConfigCliOptions.getUser()).thenReturn(Optional.of("customUser")); when(mockCommonContainerConfigCliOptions.getFormat()).thenReturn(Optional.of(ImageFormat.OCI)); when(mockCommonContainerConfigCliOptions.getProgramArguments()) .thenReturn(ImmutableList.of("arg1")); when(mockCommonContainerConfigCliOptions.getEntrypoint()) .thenReturn(ImmutableList.of("custom", "entrypoint")); when(mockCommonContainerConfigCliOptions.getCreationTime()) .thenReturn(Optional.of(Instant.ofEpochSecond(5))); JibContainerBuilder containerBuilder = WarFiles.toJibContainerBuilder( mockStandardWarExplodedProcessor, mockCommonCliOptions, mockCommonContainerConfigCliOptions, mockLogger); ContainerBuildPlan buildPlan = containerBuilder.toContainerBuildPlan(); assertThat(buildPlan.getBaseImage()).isEqualTo("base-image"); assertThat(buildPlan.getExposedPorts()).isEqualTo(ImmutableSet.of(Port.udp(123))); assertThat(buildPlan.getVolumes()) .isEqualTo( ImmutableSet.of(AbsoluteUnixPath.get("/volume1"), AbsoluteUnixPath.get("/volume2"))); assertThat(buildPlan.getEnvironment()).isEqualTo(ImmutableMap.of("key1", "value1")); assertThat(buildPlan.getLabels()).isEqualTo(ImmutableMap.of("label", "mylabel")); assertThat(buildPlan.getUser()).isEqualTo("customUser"); assertThat(buildPlan.getFormat()).isEqualTo(ImageFormat.OCI); assertThat(buildPlan.getCmd()).isEqualTo(ImmutableList.of("arg1")); assertThat(buildPlan.getEntrypoint()).isEqualTo(ImmutableList.of("custom", "entrypoint")); assertThat(buildPlan.getCreationTime()).isEqualTo(Instant.ofEpochSecond(5)); }
public static <T extends Comparable<? super T>> Combine.Globally<T, T> globally() { return Combine.globally(Min.<T>naturalOrder()); }
@Test public void testDisplayData() { Top.Reversed<Integer> comparer = new Top.Reversed<>(); Combine.Globally<Integer, Integer> min = Min.globally(comparer); assertThat(DisplayData.from(min), hasDisplayItem("comparer", comparer.getClass())); }
@Override public Product updateProductById(String productId, ProductUpdateRequest productUpdateRequest) { checkProductNameUniqueness(productUpdateRequest.getName()); final ProductEntity productEntityToBeUpdate = productRepository .findById(productId) .orElseThrow(() -> new ProductNotFoundException("With given productID = " + productId)); productUpdateRequestToProductEntityMapper.mapForUpdating(productEntityToBeUpdate, productUpdateRequest); ProductEntity updatedProductEntity = productRepository.save(productEntityToBeUpdate); return productEntityToProductMapper.map(updatedProductEntity); }
@Test void givenProductUpdateRequest_whenProductUpdated_thenReturnProduct() { // Given String productId = "1"; String newProductName = "New Product Name"; ProductUpdateRequest productUpdateRequest = ProductUpdateRequest.builder() .name(newProductName) .amount(BigDecimal.valueOf(5)) .unitPrice(BigDecimal.valueOf(12)) .build(); ProductEntity existingProductEntity = ProductEntity.builder() .id(productId) .name(productUpdateRequest.getName()) .unitPrice(productUpdateRequest.getUnitPrice()) .amount(productUpdateRequest.getAmount()) .build(); productUpdateRequestToProductEntityMapper.mapForUpdating(existingProductEntity,productUpdateRequest); Product expected = productEntityToProductMapper.map(existingProductEntity); // When when(productRepository.findById(productId)).thenReturn(Optional.of(existingProductEntity)); when(productRepository.existsProductEntityByName(newProductName)).thenReturn(false); when(productRepository.save(any(ProductEntity.class))).thenReturn(existingProductEntity); // Then Product updatedProduct = productUpdateService.updateProductById(productId, productUpdateRequest); // Then assertNotNull(updatedProduct); assertEquals(expected.getId(), updatedProduct.getId()); assertEquals(expected.getName(), updatedProduct.getName()); assertEquals(expected.getAmount(), updatedProduct.getAmount()); assertEquals(expected.getUnitPrice(), updatedProduct.getUnitPrice()); // Verify verify(productRepository, times(1)).findById(productId); verify(productRepository, times(1)).existsProductEntityByName(newProductName); verify(productRepository, times(1)).save(any(ProductEntity.class)); }
private void readUnknownFrame(ChannelHandlerContext ctx, ByteBuf payload, Http2FrameListener listener) throws Http2Exception { listener.onUnknownFrame(ctx, frameType, streamId, flags, payload); }
@Test public void readUnknownFrame() throws Http2Exception { ByteBuf input = Unpooled.buffer(); ByteBuf payload = Unpooled.buffer(); try { payload.writeByte(1); writeFrameHeader(input, payload.readableBytes(), (byte) 0xff, new Http2Flags(), 0); input.writeBytes(payload); frameReader.readFrame(ctx, input, listener); verify(listener).onUnknownFrame( ctx, (byte) 0xff, 0, new Http2Flags(), payload.slice(0, 1)); } finally { payload.release(); input.release(); } }
public static GetAllResourceProfilesResponse mergeClusterResourceProfilesResponse( Collection<GetAllResourceProfilesResponse> responses) { GetAllResourceProfilesResponse profilesResponse = Records.newRecord(GetAllResourceProfilesResponse.class); Map<String, Resource> profilesMap = new HashMap<>(); for (GetAllResourceProfilesResponse response : responses) { if (response != null && response.getResourceProfiles() != null) { for (Map.Entry<String, Resource> entry : response.getResourceProfiles().entrySet()) { String key = entry.getKey(); Resource r1 = profilesMap.getOrDefault(key, null); Resource r2 = entry.getValue(); Resource rAdd = r1 == null ? r2 : Resources.add(r1, r2); profilesMap.put(key, rAdd); } } } profilesResponse.setResourceProfiles(profilesMap); return profilesResponse; }
@Test public void testMergeResourceProfiles() { // normal response1 Map<String, Resource> profiles = new HashMap<>(); Resource resource1 = Resource.newInstance(1024, 1); GetAllResourceProfilesResponse response1 = GetAllResourceProfilesResponse.newInstance(); profiles.put("maximum", resource1); response1.setResourceProfiles(profiles); // normal response2 profiles = new HashMap<>(); Resource resource2 = Resource.newInstance(2048, 2); GetAllResourceProfilesResponse response2 = GetAllResourceProfilesResponse.newInstance(); profiles.put("maximum", resource2); response2.setResourceProfiles(profiles); // empty response GetAllResourceProfilesResponse response3 = GetAllResourceProfilesResponse.newInstance(); // null response GetAllResourceProfilesResponse response4 = null; List<GetAllResourceProfilesResponse> responses = new ArrayList<>(); responses.add(response1); responses.add(response2); responses.add(response3); responses.add(response4); GetAllResourceProfilesResponse response = RouterYarnClientUtils.mergeClusterResourceProfilesResponse(responses); Resource resource = response.getResourceProfiles().get("maximum"); Assert.assertEquals(3, resource.getVirtualCores()); Assert.assertEquals(3072, resource.getMemorySize()); }
static byte[] deriveMac(byte[] seed, int offset, int length) { final MessageDigest md = DigestUtils.digest("SHA1"); md.update(seed, offset, length); md.update(new byte[] {0, 0, 0, 2}); return Arrays.copyOfRange(md.digest(), 0, 16); }
@Test public void shouldDeriveMacKey() { assertEquals( "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS", ByteArrayUtils.prettyHex(TDEASecureMessaging.deriveMac( Hex.decode("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"),0, 16) ) ); }
public static List<AclEntry> replaceAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); // Replacement is done separately for each scope: access and default. EnumMap<AclEntryScope, AclEntry> providedMask = Maps.newEnumMap(AclEntryScope.class); EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class); EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class); for (AclEntry aclSpecEntry: aclSpec) { scopeDirty.add(aclSpecEntry.getScope()); if (aclSpecEntry.getType() == MASK) { providedMask.put(aclSpecEntry.getScope(), aclSpecEntry); maskDirty.add(aclSpecEntry.getScope()); } else { aclBuilder.add(aclSpecEntry); } } // Copy existing entries if the scope was not replaced. for (AclEntry existingEntry: existingAcl) { if (!scopeDirty.contains(existingEntry.getScope())) { 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 testReplaceAclEntries() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, USER, "bruce", ALL)) .add(aclEntry(ACCESS, GROUP, READ_EXECUTE)) .add(aclEntry(ACCESS, MASK, ALL)) .add(aclEntry(ACCESS, OTHER, NONE)) .build(); List<AclEntry> aclSpec = Lists.newArrayList( aclEntry(ACCESS, USER, ALL), aclEntry(ACCESS, USER, "bruce", READ_WRITE), aclEntry(ACCESS, GROUP, READ_EXECUTE), aclEntry(ACCESS, GROUP, "sales", ALL), aclEntry(ACCESS, MASK, ALL), aclEntry(ACCESS, OTHER, NONE), aclEntry(DEFAULT, USER, ALL), aclEntry(DEFAULT, USER, "bruce", READ_WRITE), aclEntry(DEFAULT, GROUP, READ_EXECUTE), aclEntry(DEFAULT, GROUP, "sales", ALL), aclEntry(DEFAULT, MASK, ALL), aclEntry(DEFAULT, OTHER, NONE)); List<AclEntry> expected = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, USER, "bruce", READ_WRITE)) .add(aclEntry(ACCESS, GROUP, READ_EXECUTE)) .add(aclEntry(ACCESS, GROUP, "sales", ALL)) .add(aclEntry(ACCESS, MASK, ALL)) .add(aclEntry(ACCESS, OTHER, NONE)) .add(aclEntry(DEFAULT, USER, ALL)) .add(aclEntry(DEFAULT, USER, "bruce", READ_WRITE)) .add(aclEntry(DEFAULT, GROUP, READ_EXECUTE)) .add(aclEntry(DEFAULT, GROUP, "sales", ALL)) .add(aclEntry(DEFAULT, MASK, ALL)) .add(aclEntry(DEFAULT, OTHER, NONE)) .build(); assertEquals(expected, replaceAclEntries(existing, aclSpec)); }
@Override public Mono<GetExpiringProfileKeyCredentialResponse> getExpiringProfileKeyCredential( final GetExpiringProfileKeyCredentialAnonymousRequest request) { final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier()); if (targetIdentifier.identityType() != IdentityType.ACI) { throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asRuntimeException(); } if (request.getRequest().getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) { throw Status.INVALID_ARGUMENT.withDescription("Expected expiring profile key credential type").asRuntimeException(); } return getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray()) .flatMap(account -> ProfileGrpcHelper.getExpiringProfileKeyCredentialResponse(account.getUuid(), request.getRequest().getVersion(), request.getRequest().getCredentialRequest().toByteArray(), profilesManager, zkProfileOperations)); }
@Test void getExpiringProfileKeyCredentialProfileNotFound() { final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH); final UUID targetUuid = UUID.randomUUID(); when(account.getUuid()).thenReturn(targetUuid); when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey)); when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(targetUuid))).thenReturn( CompletableFuture.completedFuture(Optional.of(account))); when(profilesManager.getAsync(targetUuid, "someVersion")).thenReturn(CompletableFuture.completedFuture(Optional.empty())); final GetExpiringProfileKeyCredentialAnonymousRequest request = GetExpiringProfileKeyCredentialAnonymousRequest.newBuilder() .setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey)) .setRequest(GetExpiringProfileKeyCredentialRequest.newBuilder() .setAccountIdentifier(ServiceIdentifier.newBuilder() .setIdentityType(IdentityType.IDENTITY_TYPE_ACI) .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid))) .build()) .setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8))) .setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) .setVersion("someVersion") .build()) .build(); assertStatusException(Status.NOT_FOUND, () -> unauthenticatedServiceStub().getExpiringProfileKeyCredential(request)); }
@Override @NonNull public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) { String sessionId = createSession(lockConfiguration); return tryLock(sessionId, lockConfiguration); }
@Test void doesNotLockIfLockIsAlreadyObtained() { mockLock(eq("naruto-leader"), false); Optional<SimpleLock> lock = lockProvider.lock(lockConfig("naruto", SMALL_MIN_TTL, SMALL_MIN_TTL.dividedBy(2))); assertThat(lock).isEmpty(); }
private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; // Indexing is still blocking - can be removed when https://issues.redhat.com/browse/ISPN-11731 is complete if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); }
@Test public void testIntegerKeysXmlToTextValues() { Integer key = 123; String keyContentType = "application/x-java-object;type=java.lang.Integer"; String valueContentType = "application/xml; charset=UTF-8"; String value = "<root>test</root>"; putInCache("default", key, keyContentType, value, valueContentType); RestResponse response = get("default", key, keyContentType, "text/plain"); ResponseAssertion.assertThat(response).hasReturnedText(value); }
@Override public Map<String, Histogram> getConnectorHistogramStatistics(Table table, List<String> columns) { Preconditions.checkState(table != null); List<ConnectorTableColumnKey> cacheKeys = new ArrayList<>(); for (String columnName : columns) { cacheKeys.add(new ConnectorTableColumnKey(table.getUUID(), columnName)); } try { CompletableFuture<Map<ConnectorTableColumnKey, Optional<Histogram>>> result = connectorHistogramCache.getAll(cacheKeys); if (result.isDone()) { Map<ConnectorTableColumnKey, Optional<Histogram>> realResult = result.get(); Map<String, Histogram> histogramStats = Maps.newHashMap(); for (String columnName : columns) { Optional<Histogram> histogramStatistics = realResult.getOrDefault(new ConnectorTableColumnKey(table.getUUID(), columnName), Optional.empty()); histogramStatistics.ifPresent(histogram -> histogramStats.put(columnName, histogram)); } return histogramStats; } else { return Maps.newHashMap(); } } catch (Exception e) { LOG.warn("Failed to execute getConnectorHistogramStatistics", e); return Maps.newHashMap(); } }
@Test public void testGetConnectorHistogramStatistics(@Mocked AsyncLoadingCache<ConnectorTableColumnKey, Optional<Histogram>> histogramCache) { Table table = connectContext.getGlobalStateMgr().getMetadataMgr().getTable("hive0", "partitioned_db", "t1"); ConnectorTableColumnKey key = new ConnectorTableColumnKey("hive0.partitioned_db.t1.1234", "c1"); new Expectations() { { histogramCache.getAll((Iterable<? extends ConnectorTableColumnKey>) any); result = CompletableFuture.completedFuture(ImmutableMap.of(key, Optional.empty())); minTimes = 0; } }; CachedStatisticStorage cachedStatisticStorage = new CachedStatisticStorage(); Map<String, Histogram> histogramMap = cachedStatisticStorage.getConnectorHistogramStatistics(table, ImmutableList.of("c1")); Assert.assertEquals(0, histogramMap.size()); }
public void validateUniverseDomain() throws IOException { if (!(httpRequestInitializer instanceof HttpCredentialsAdapter)) { return; } Credentials credentials = ((HttpCredentialsAdapter) httpRequestInitializer).getCredentials(); // No need for a null check as HttpCredentialsAdapter cannot be initialized with null // Credentials String expectedUniverseDomain = credentials.getUniverseDomain(); if (!expectedUniverseDomain.equals(getUniverseDomain())) { throw new IllegalStateException( String.format( "The configured universe domain (%s) does not match the universe domain found" + " in the credentials (%s). If you haven't configured the universe domain" + " explicitly, `googleapis.com` is the default.", getUniverseDomain(), expectedUniverseDomain)); } }
@Test public void validateUniverseDomain_notUsingHttpCredentialsAdapter_defaultUniverseDomain() throws IOException { String rootUrl = "https://test.googleapis.com/"; String applicationName = "Test Application"; String servicePath = "test/"; AbstractGoogleClient client = new MockGoogleClient.Builder( TRANSPORT, rootUrl, servicePath, JSON_OBJECT_PARSER, new TestHttpRequestInitializer()) .setApplicationName(applicationName) .build(); // Nothing throws client.validateUniverseDomain(); }
@Override public String getMethod() { return PATH; }
@Test public void testBanChatMemberWithEmptyChatId() { BanChatMember banChatMember = BanChatMember .builder() .chatId("") .userId(12345L) .untilDate(1000) .revokeMessages(true) .build(); assertEquals("banChatMember", banChatMember.getMethod()); Throwable thrown = assertThrows(TelegramApiValidationException.class, banChatMember::validate); assertEquals("ChatId can't be empty", thrown.getMessage()); }
@Override public int compareTo(DateTimeStamp dateTimeStamp) { return comparator.compare(this,dateTimeStamp); }
@Test void testCompareEqualsTimeStampWithoutDateTime() { DateTimeStamp object1 = new DateTimeStamp(123); DateTimeStamp object2 = new DateTimeStamp(123); assertEquals(0, object2.compareTo(object1)); }
public int tryClaim(final int msgTypeId, final int length) { checkTypeId(msgTypeId); checkMsgLength(length); final AtomicBuffer buffer = this.buffer; final int recordLength = length + HEADER_LENGTH; final int recordIndex = claimCapacity(buffer, recordLength); if (INSUFFICIENT_CAPACITY == recordIndex) { return recordIndex; } buffer.putIntOrdered(lengthOffset(recordIndex), -recordLength); MemoryAccess.releaseFence(); buffer.putInt(typeOffset(recordIndex), msgTypeId); return encodedMsgOffset(recordIndex); }
@Test void tryClaimShouldThrowIllegalArgumentExceptionIfLengthIsNegative() { assertThrows(IllegalArgumentException.class, () -> ringBuffer.tryClaim(MSG_TYPE_ID, -6)); }
public static long getNumSector(String requestSize, String sectorSize) { Double memSize = Double.parseDouble(requestSize); Double sectorBytes = Double.parseDouble(sectorSize); Double nSectors = memSize / sectorBytes; Double memSizeKB = memSize / 1024; Double memSizeGB = memSize / (1024 * 1024 * 1024); Double memSize100GB = memSizeGB / 100; // allocation bitmap file: one bit per sector Double allocBitmapSize = nSectors / 8; // extend overflow file: 4MB, plus 4MB per 100GB Double extOverflowFileSize = memSize100GB * 1024 * 1024 * 4; // journal file: 8MB, plus 8MB per 100GB Double journalFileSize = memSize100GB * 1024 * 1024 * 8; // catalog file: 10bytes per KB Double catalogFileSize = memSizeKB * 10; // hot files: 5bytes per KB Double hotFileSize = memSizeKB * 5; // quota users file and quota groups file Double quotaUsersFileSize = (memSizeGB * 256 + 1) * 64; Double quotaGroupsFileSize = (memSizeGB * 32 + 1) * 64; Double metadataSize = allocBitmapSize + extOverflowFileSize + journalFileSize + catalogFileSize + hotFileSize + quotaUsersFileSize + quotaGroupsFileSize; Double allocSize = memSize + metadataSize; Double numSectors = allocSize / sectorBytes; System.out.println(numSectors.longValue() + 1); // round up return numSectors.longValue() + 1; }
@Test public void getSectorTest100GB() { String testRequestSize = "107374182400"; // 100GB String testSectorSize = "512"; long result = HFSUtils.getNumSector(testRequestSize, testSectorSize); assertEquals(212866577L, result); // 100GB/512B = 209715200 }
@Override public MaskRuleConfiguration buildToBeDroppedRuleConfiguration(final DropMaskRuleStatement sqlStatement) { Collection<MaskTableRuleConfiguration> toBeDroppedTables = new LinkedList<>(); for (String each : sqlStatement.getTables()) { toBeDroppedTables.add(new MaskTableRuleConfiguration(each, Collections.emptyList())); dropRule(each); } Map<String, AlgorithmConfiguration> toBeDroppedAlgorithms = new LinkedHashMap<>(); findUnusedAlgorithms(rule.getConfiguration()).forEach(each -> toBeDroppedAlgorithms.put(each, rule.getConfiguration().getMaskAlgorithms().get(each))); return new MaskRuleConfiguration(toBeDroppedTables, toBeDroppedAlgorithms); }
@Test void assertUpdateCurrentRuleConfiguration() { MaskRuleConfiguration ruleConfig = createCurrentRuleConfiguration(); MaskRule rule = mock(MaskRule.class); when(rule.getConfiguration()).thenReturn(ruleConfig); executor.setRule(rule); MaskRuleConfiguration toBeDroppedRuleConfig = executor.buildToBeDroppedRuleConfiguration(createSQLStatement(false, "t_mask")); assertThat(toBeDroppedRuleConfig.getTables().size(), is(1)); assertTrue(toBeDroppedRuleConfig.getMaskAlgorithms().isEmpty()); }
@Operation( summary = "Monitor the given search keys in the key transparency log", description = """ Enforced unauthenticated endpoint. Return proofs proving that the log tree has been constructed correctly in later entries for each of the given search keys . """ ) @ApiResponse(responseCode = "200", description = "All search keys exist in the log", useReturnTypeSchema = true) @ApiResponse(responseCode = "404", description = "At least one search key lookup did not find the key") @ApiResponse(responseCode = "413", description = "Ratelimited") @ApiResponse(responseCode = "422", description = "Invalid request format") @POST @Path("/monitor") @RateLimitedByIp(RateLimiters.For.KEY_TRANSPARENCY_MONITOR_PER_IP) @Produces(MediaType.APPLICATION_JSON) public KeyTransparencyMonitorResponse monitor( @ReadOnly @Auth final Optional<AuthenticatedDevice> authenticatedAccount, @NotNull @Valid final KeyTransparencyMonitorRequest request) { // Disallow clients from making authenticated requests to this endpoint requireNotAuthenticated(authenticatedAccount); try { final List<MonitorKey> monitorKeys = new ArrayList<>(List.of( createMonitorKey(getFullSearchKeyByteString(ACI_PREFIX, request.aci().toCompactByteArray()), request.aciPositions()) )); request.usernameHash().ifPresent(usernameHash -> monitorKeys.add(createMonitorKey(getFullSearchKeyByteString(USERNAME_PREFIX, usernameHash), request.usernameHashPositions().get())) ); request.e164().ifPresent(e164 -> monitorKeys.add( createMonitorKey(getFullSearchKeyByteString(E164_PREFIX, e164.getBytes(StandardCharsets.UTF_8)), request.e164Positions().get())) ); return new KeyTransparencyMonitorResponse(keyTransparencyServiceClient.monitor( monitorKeys, request.lastNonDistinguishedTreeHeadSize(), request.lastDistinguishedTreeHeadSize(), KEY_TRANSPARENCY_RPC_TIMEOUT).join()); } catch (final CancellationException exception) { LOGGER.error("Unexpected cancellation from key transparency service", exception); throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, exception); } catch (final CompletionException exception) { handleKeyTransparencyServiceError(exception); } // This is unreachable return null; }
@Test void monitorSuccess() { when(keyTransparencyServiceClient.monitor(any(), any(), any(), any())) .thenReturn(CompletableFuture.completedFuture(TestRandomUtil.nextBytes(16))); final Invocation.Builder request = resources.getJerseyTest() .target("/v1/key-transparency/monitor") .request(); try (Response response = request.post(Entity.json( createMonitorRequestJson( ACI, List.of(3L), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(3L), Optional.of(4L))))) { assertEquals(200, response.getStatus()); final KeyTransparencyMonitorResponse keyTransparencyMonitorResponse = response.readEntity( KeyTransparencyMonitorResponse.class); assertNotNull(keyTransparencyMonitorResponse.monitorResponse()); verify(keyTransparencyServiceClient, times(1)).monitor( any(), eq(Optional.of(3L)), eq(Optional.of(4L)), eq(KeyTransparencyController.KEY_TRANSPARENCY_RPC_TIMEOUT)); } }
@Override public void run() { // top-level command, do nothing }
@Test public void test_suspendJob_byJobId() { // Given Job job = newJob(); // When run("suspend", job.getIdString()); // Then assertThat(job).eventuallyHasStatus(JobStatus.SUSPENDED); }
@Override public boolean commit() { // TODO: add retry attempts String name = Thread.currentThread().getName(); try { for (ReplicationStateSync stateSync : replicationStateSyncList) { Thread.currentThread().setName(stateSync.getClusterId()); LOG.info("starting sync for state " + stateSync); stateSync.sync(); LOG.info("synced state " + stateSync); } } catch (Exception e) { Thread.currentThread().setName(name); LOG.error(String.format("Error while trying to commit replication state %s", e.getMessage()), e); return false; } finally { Thread.currentThread().setName(name); } LOG.info("done syncing to all tables, verifying the timestamps..."); ReplicationStateSync base = replicationStateSyncList.get(0); boolean success = true; LOG.info("expecting all timestamps to be similar to: " + base); for (int idx = 1; idx < replicationStateSyncList.size(); ++idx) { ReplicationStateSync other = replicationStateSyncList.get(idx); if (!base.replicationStateIsInSync(other)) { LOG.error("the timestamp of other : " + other + " is not matching with base: " + base); success = false; } } return success; }
@Test public void testBasicGlobalCommit() throws Exception { String commitTime = "100"; localCluster.createCOWTable(commitTime, 5, DB_NAME, TBL_NAME); // simulate drs remoteCluster.createCOWTable(commitTime, 5, DB_NAME, TBL_NAME); HiveSyncGlobalCommitParams params = getGlobalCommitConfig(commitTime); HiveSyncGlobalCommitTool tool = new HiveSyncGlobalCommitTool(params); assertTrue(tool.commit()); compareEqualLastReplicatedTimeStamp(params); }
@Override public void close() { try { recoveryManagerService.stop(); // CHECKSTYLE:OFF } catch (final Exception ex) { // CHECKSTYLE:ON throw new CloseTransactionManagerFailedException(ex); } recoveryManagerService.destroy(); cleanPropertiesFactory(); cleanBeanInstances(); cleanAtomicActionRecovery(); cleanXARecoveryModule(); cleanStoreManager(); }
@Test void assertClose() throws Exception { transactionManagerProvider.close(); verify(recoveryManagerService).stop(); verify(recoveryManagerService).destroy(); }
private static void metricsConfig(XmlGenerator gen, Config config) { MetricsConfig metricsConfig = config.getMetricsConfig(); gen.open("metrics", "enabled", metricsConfig.isEnabled()) .open("management-center", "enabled", metricsConfig.getManagementCenterConfig().isEnabled()) .node("retention-seconds", metricsConfig.getManagementCenterConfig().getRetentionSeconds()) .close() .open("jmx", "enabled", metricsConfig.getJmxConfig().isEnabled()) .close() .node("collection-frequency-seconds", metricsConfig.getCollectionFrequencySeconds()) .close(); }
@Test public void testMetricsConfig() { Config config = new Config(); config.getMetricsConfig() .setEnabled(false) .setCollectionFrequencySeconds(10); config.getMetricsConfig().getManagementCenterConfig() .setEnabled(false) .setRetentionSeconds(11); config.getMetricsConfig().getJmxConfig() .setEnabled(false); MetricsConfig generatedConfig = getNewConfigViaXMLGenerator(config).getMetricsConfig(); assertTrue(generatedConfig + " should be compatible with " + config.getMetricsConfig(), new MetricsConfigChecker().check(config.getMetricsConfig(), generatedConfig)); }
public static byte[] floatToBytesBE(float f, byte[] bytes, int off) { return intToBytesBE(Float.floatToIntBits(f), bytes, off); }
@Test public void testFloatToBytesBE() { assertArrayEquals(FLOAT_PI_BE , ByteUtils.floatToBytesBE((float) Math.PI, new byte[4], 0)); }
public void transitionTo(ClassicGroupState groupState) { assertValidTransition(groupState); previousState = state; state = groupState; currentStateTimestamp = Optional.of(time.milliseconds()); metrics.onClassicGroupStateTransition(previousState, state); }
@Test public void testPreparingRebalanceToEmptyTransition() { group.transitionTo(PREPARING_REBALANCE); group.transitionTo(EMPTY); assertState(group, EMPTY); }
@Override public void deliverOperatorEventToCoordinator( ExecutionAttemptID taskExecution, OperatorID operator, OperatorEvent evt) throws FlinkException { final StateWithExecutionGraph stateWithExecutionGraph = state.as(StateWithExecutionGraph.class) .orElseThrow( () -> new TaskNotRunningException( "Task is not known or in state running on the JobManager.")); stateWithExecutionGraph.deliverOperatorEventToCoordinator(taskExecution, operator, evt); }
@Test void testDeliverOperatorEventToCoordinatorFailsInIllegalState() throws Exception { final AdaptiveScheduler scheduler = new AdaptiveSchedulerBuilder( createJobGraph(), mainThreadExecutor, EXECUTOR_RESOURCE.getExecutor()) .build(); assertThatThrownBy( () -> scheduler.deliverOperatorEventToCoordinator( createExecutionAttemptId(), new OperatorID(), new TestOperatorEvent())) .isInstanceOf(TaskNotRunningException.class); }
public static KTableHolder<GenericKey> build( final KGroupedStreamHolder groupedStream, final StreamAggregate aggregate, final RuntimeBuildContext buildContext, final MaterializedFactory materializedFactory) { return build( groupedStream, aggregate, buildContext, materializedFactory, new AggregateParamsFactory() ); }
@Test public void shouldBuildValueSerdeCorrectlyForWindowedAggregate() { for (final Runnable given : given()) { // Given: clearInvocations(groupedStream, timeWindowedStream, sessionWindowedStream, aggregated, buildContext); given.run(); // When: windowedAggregate.build(planBuilder, planInfo); // Then: verify(buildContext) .buildValueSerde(VALUE_FORMAT, PHYSICAL_AGGREGATE_SCHEMA, MATERIALIZE_CTX); } }
public static String escape(String text) { return encode(text); }
@Test public void escapeTest2() { final char c = ' '; // 不断开空格(non-breaking space,缩写nbsp。) assertEquals(c, 160); final String html = "<html><body> </body></html>"; final String escape = HtmlUtil.escape(html); assertEquals("&lt;html&gt;&lt;body&gt;&nbsp;&lt;/body&gt;&lt;/html&gt;", escape); assertEquals(" ", HtmlUtil.unescape("&nbsp;")); }
static InetSocketAddress parse( final String value, final String uriParamName, final boolean isReResolution, final NameResolver nameResolver) { if (Strings.isEmpty(value)) { throw new NullPointerException("input string must not be null or empty"); } final String nameAndPort = nameResolver.lookup(value, uriParamName, isReResolution); ParseResult result = tryParseIpV4(nameAndPort); if (null == result) { result = tryParseIpV6(nameAndPort); } if (null == result) { throw new IllegalArgumentException("invalid format: " + nameAndPort); } final InetAddress inetAddress = nameResolver.resolve(result.host, uriParamName, isReResolution); return null == inetAddress ? InetSocketAddress.createUnresolved(result.host, result.port) : new InetSocketAddress(inetAddress, result.port); }
@Test void shouldRejectOnMissingPort() { assertThrows(IllegalArgumentException.class, () -> SocketAddressParser.parse( "192.168.1.20", ENDPOINT_PARAM_NAME, false, DEFAULT_RESOLVER)); }
public static <T> PTransform<PCollection<T>, PCollection<Long>> globally() { return Combine.globally(new CountFn<T>()); }
@Test @Category(NeedsRunner.class) public void testCountGloballyBasic() { PCollection<String> input = p.apply(Create.of(WORDS)); PCollection<Long> output = input.apply(Count.globally()); PAssert.that(output).containsInAnyOrder(13L); p.run(); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("brick.listing.chunksize")); }
@Test public void testListRootDefaultChunkSize() throws Exception { final AttributedList<Path> list = new BrickListService(session).list(new Path("/", EnumSet.of(directory)), new DisabledListProgressListener()); assertNotSame(AttributedList.emptyList(), list); }
public static SerializableFunction<Row, TableRow> toTableRow() { return ROW_TO_TABLE_ROW; }
@Test public void testToTableRow_flat() { TableRow row = toTableRow().apply(FLAT_ROW); assertThat(row.size(), equalTo(27)); assertThat(row, hasEntry("id", "123")); assertThat(row, hasEntry("value", "123.456")); assertThat(row, hasEntry("timestamp_variant1", "2019-08-16 13:52:07.000 UTC")); assertThat(row, hasEntry("timestamp_variant2", "2019-08-17 14:52:07.123 UTC")); assertThat(row, hasEntry("timestamp_variant3", "2019-08-18 15:52:07.123 UTC")); assertThat(row, hasEntry("timestamp_variant4", "1970-01-01 00:02:03.456 UTC")); assertThat(row, hasEntry("timestamp_variant5", "2024-08-10 16:52:07.100 UTC")); assertThat(row, hasEntry("timestamp_variant6", "2024-08-10 16:52:07.120 UTC")); assertThat(row, hasEntry("timestamp_variant7", "2024-08-10 16:52:07.123 UTC")); assertThat(row, hasEntry("timestamp_variant8", "2024-08-10 16:52:07.123 UTC")); assertThat(row, hasEntry("datetime", "2020-11-02T12:34:56.789876")); assertThat(row, hasEntry("datetime0ms", "2020-11-02T12:34:56")); assertThat(row, hasEntry("datetime0s_ns", "2020-11-02T12:34:00.789876")); assertThat(row, hasEntry("datetime0s_0ns", "2020-11-02T12:34:00")); assertThat(row, hasEntry("date", "2020-11-02")); assertThat(row, hasEntry("time", "12:34:56.789876")); assertThat(row, hasEntry("time0ms", "12:34:56")); assertThat(row, hasEntry("time0s_ns", "12:34:00.789876")); assertThat(row, hasEntry("time0s_0ns", "12:34:00")); assertThat(row, hasEntry("name", "test")); assertThat(row, hasEntry("valid", "false")); assertThat(row, hasEntry("binary", "ABCD1234")); assertThat(row, hasEntry("raw_bytes", "ABCD1234")); assertThat(row, hasEntry("numeric", "123.456")); assertThat(row, hasEntry("boolean", "true")); assertThat(row, hasEntry("long", "123")); assertThat(row, hasEntry("double", "123.456")); }
@Override @SuppressWarnings({"unchecked", "rawtypes"}) public void executeUpdate(final UnlockClusterStatement sqlStatement, final ContextManager contextManager) { checkState(contextManager); LockContext lockContext = contextManager.getComputeNodeInstanceContext().getLockContext(); GlobalLockDefinition lockDefinition = new GlobalLockDefinition(GlobalLockNames.CLUSTER_LOCK.getLockName()); if (lockContext.tryLock(lockDefinition, 3000L)) { try { checkState(contextManager); contextManager.getPersistServiceFacade().getStatePersistService().updateClusterState(ClusterState.OK); // TODO unlock snapshot info if locked } finally { lockContext.unlock(lockDefinition); } } }
@Test void assertExecuteUpdateWithNotLockedCluster() { ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS); when(contextManager.getStateContext().getClusterState()).thenReturn(ClusterState.OK); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); assertThrows(NotLockedClusterException.class, () -> executor.executeUpdate(new UnlockClusterStatement(), contextManager)); }
@Override public void setMonochrome(boolean monochrome) { formats = monochrome ? monochrome() : ansi(); }
@Test void should_print_table() { Feature feature = TestFeatureParser.parse("path/test.feature", "" + "Feature: Test feature\n" + " Scenario: Test Scenario\n" + " Given first step\n" + " | key1 | key2 |\n" + " | value1 | value2 |\n" + " | another1 | another2 |\n"); ByteArrayOutputStream out = new ByteArrayOutputStream(); Runtime.builder() .withFeatureSupplier(new StubFeatureSupplier(feature)) .withAdditionalPlugins(new PrettyFormatter(out)) .withRuntimeOptions(new RuntimeOptionsBuilder().setMonochrome().build()) .withBackendSupplier(new StubBackendSupplier( new StubStepDefinition("first step", "path/step_definitions.java:7", DataTable.class))) .build() .run(); assertThat(out, bytes(equalToCompressingWhiteSpace("" + "\n" + "Scenario: Test Scenario # path/test.feature:2\n" + " Given first step # path/step_definitions.java:7\n" + " | key1 | key2 |\n" + " | value1 | value2 |\n" + " | another1 | another2 |\n"))); }
public final Sensor clientLevelSensor(final String sensorName, final RecordingLevel recordingLevel, final Sensor... parents) { synchronized (clientLevelSensors) { final String fullSensorName = CLIENT_LEVEL_GROUP + SENSOR_NAME_DELIMITER + sensorName; final Sensor sensor = metrics.getSensor(fullSensorName); if (sensor == null) { clientLevelSensors.push(fullSensorName); return metrics.sensor(fullSensorName, recordingLevel, parents); } return sensor; } }
@Test public void shouldGetNewClientLevelSensor() { final Metrics metrics = mock(Metrics.class); final RecordingLevel recordingLevel = RecordingLevel.INFO; setupGetNewSensorTest(metrics, recordingLevel); final StreamsMetricsImpl streamsMetrics = new StreamsMetricsImpl(metrics, CLIENT_ID, VERSION, time); final Sensor actualSensor = streamsMetrics.clientLevelSensor(SENSOR_NAME_1, recordingLevel); assertThat(actualSensor, is(equalToObject(sensor))); }
public void begin(InterpretationContext ec, String localName, Attributes attributes) { if ("substitutionProperty".equals(localName)) { addWarn("[substitutionProperty] element has been deprecated. Please use the [property] element instead."); } String name = attributes.getValue(NAME_ATTRIBUTE); String value = attributes.getValue(VALUE_ATTRIBUTE); String scopeStr = attributes.getValue(SCOPE_ATTRIBUTE); Scope scope = ActionUtil.stringToScope(scopeStr); if (checkFileAttributeSanity(attributes)) { String file = attributes.getValue(FILE_ATTRIBUTE); file = ec.subst(file); try { FileInputStream istream = new FileInputStream(file); loadAndSetProperties(ec, istream, scope); } catch (FileNotFoundException e) { addError("Could not find properties file [" + file + "].", e); } catch (IOException e1) { addError("Could not read properties file [" + file + "].", e1); } } else if (checkResourceAttributeSanity(attributes)) { String resource = attributes.getValue(RESOURCE_ATTRIBUTE); resource = ec.subst(resource); URL resourceURL = Loader.getResourceBySelfClassLoader(resource); if (resourceURL == null) { addError("Could not find resource [" + resource + "]."); } else { try { InputStream istream = resourceURL.openStream(); loadAndSetProperties(ec, istream, scope); } catch (IOException e) { addError("Could not read resource file [" + resource + "].", e); } } } else if (checkValueNameAttributesSanity(attributes)) { value = RegularEscapeUtil.basicEscape(value); // now remove both leading and trailing spaces value = value.trim(); value = ec.subst(value); ActionUtil.setProperty(ec, name, value, scope); } else { addError(INVALID_ATTRIBUTES); } }
@Test public void testFileNotLoaded() { atts.setValue("file", "toto"); atts.setValue("value", "work"); propertyAction.begin(ec, null, atts); assertEquals(1, context.getStatusManager().getCount()); assertTrue(checkError()); }
public void shutdown() { isShutdown = true; responseHandlerSupplier.shutdown(); for (ClientInvocation invocation : invocations.values()) { //connection manager and response handler threads are closed at this point. invocation.notifyExceptionWithOwnedPermission(new HazelcastClientNotActiveException()); } }
@Test public void testInvokeUrgent_whenThereAreNoCompactSchemas_andClientIsNotInitializedOnCluster() { UUID memberUuid = member.getLocalEndpoint().getUuid(); member.shutdown(); makeSureDisconnectedFromServer(client, memberUuid); // No compact schemas, no need to check urgent invocations assertFalse(client.shouldCheckUrgentInvocations()); // client is disconnected, so not initialized on cluster assertTrueEventually(() -> assertFalse(client.getConnectionManager().clientInitializedOnCluster())); ClientConnection connection = mockConnection(); // Urgent invocations should be done ClientInvocation pingInvocation = checkUrgentInvocation_withNoData(connection); ClientInvocation setAddInvocation = checkUrgentInvocation_withData(connection); verify(connection, times(1)).write(pingInvocation.getClientMessage()); verify(connection, times(1)).write(setAddInvocation.getClientMessage()); }
@Override public ListOffsetsResult listOffsets(Map<TopicPartition, OffsetSpec> topicPartitionOffsets, ListOffsetsOptions options) { AdminApiFuture.SimpleAdminApiFuture<TopicPartition, ListOffsetsResultInfo> future = ListOffsetsHandler.newFuture(topicPartitionOffsets.keySet()); Map<TopicPartition, Long> offsetQueriesByPartition = topicPartitionOffsets.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> getOffsetFromSpec(e.getValue()))); ListOffsetsHandler handler = new ListOffsetsHandler(offsetQueriesByPartition, options, logContext); invokeDriver(handler, future, options.timeoutMs); return new ListOffsetsResult(future.all()); }
@Test public void testListOffsetsEarliestLocalSpecMinVersion() throws Exception { Node node = new Node(0, "localhost", 8120); List<Node> nodes = Collections.singletonList(node); List<PartitionInfo> pInfos = new ArrayList<>(); pInfos.add(new PartitionInfo("foo", 0, node, new Node[]{node}, new Node[]{node})); final Cluster cluster = new Cluster( "mockClusterId", nodes, pInfos, Collections.emptySet(), Collections.emptySet(), node); final TopicPartition tp0 = new TopicPartition("foo", 0); try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(cluster, AdminClientConfig.RETRIES_CONFIG, "2")) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); env.kafkaClient().prepareResponse(prepareMetadataResponse(env.cluster(), Errors.NONE)); env.adminClient().listOffsets(Collections.singletonMap(tp0, OffsetSpec.earliestLocal())); TestUtils.waitForCondition(() -> env.kafkaClient().requests().stream().anyMatch(request -> request.requestBuilder().apiKey().messageType == ApiMessageType.LIST_OFFSETS && request.requestBuilder().oldestAllowedVersion() == 9 ), "no listOffsets request has the expected oldestAllowedVersion"); } }
@PublicAPI(usage = ACCESS) public Properties getExtensionProperties(String extensionIdentifier) { String propertyPrefix = getFullExtensionPropertyPrefix(extensionIdentifier); return getSubProperties(propertyPrefix); }
@Test public void if_no_extension_properties_are_found_empty_properties_are_returned() { ArchConfiguration configuration = testConfiguration(PROPERTIES_FILE_NAME); assertThat(configuration.getExtensionProperties("not-there")).isEmpty(); }