method2testcases
stringlengths
118
6.63k
### Question: Roaring64Bitmap implements Externalizable, LongBitmapDataProvider { public void flip(final long x) { byte[] high = LongUtils.highPart(x); ContainerWithIndex containerWithIndex = highLowContainer.searchContainer(high); if (containerWithIndex == null) { addLong(x); } else { char low = LongUtils.lowPart(x); ...
### Question: Roaring64NavigableMap implements Externalizable, LongBitmapDataProvider { public void addInt(int x) { addLong(Util.toUnsignedLong(x)); } Roaring64NavigableMap(); Roaring64NavigableMap(boolean signedLongs); Roaring64NavigableMap(boolean signedLongs, boolean cacheCardinalities); Roaring64NavigableMap(Bit...
### Question: Roaring64NavigableMap implements Externalizable, LongBitmapDataProvider { @Override public LongIterator getLongIterator() { final Iterator<Map.Entry<Integer, BitmapDataProvider>> it = highToBitmap.entrySet().iterator(); return toIterator(it, false); } Roaring64NavigableMap(); Roaring64NavigableMap(boolea...
### Question: Roaring64NavigableMap implements Externalizable, LongBitmapDataProvider { private int compare(int x, int y) { if (signedLongs) { return Integer.compare(x, y); } else { return RoaringIntPacking.compareUnsigned(x, y); } } Roaring64NavigableMap(); Roaring64NavigableMap(boolean signedLongs); Roaring64Naviga...
### Question: Roaring64NavigableMap implements Externalizable, LongBitmapDataProvider { @Override public long getLongCardinality() { if (doCacheCardinalities) { if (highToBitmap.isEmpty()) { return 0L; } int indexOk = ensureCumulatives(highestHigh()); if (highToBitmap.isEmpty()) { return 0L; } return sortedCumulatedCar...
### Question: Roaring64NavigableMap implements Externalizable, LongBitmapDataProvider { public void add(long... dat) { for (long oneLong : dat) { addLong(oneLong); } } Roaring64NavigableMap(); Roaring64NavigableMap(boolean signedLongs); Roaring64NavigableMap(boolean signedLongs, boolean cacheCardinalities); Roaring6...
### Question: Roaring64NavigableMap implements Externalizable, LongBitmapDataProvider { @Override public void trim() { for (BitmapDataProvider bitmap : highToBitmap.values()) { bitmap.trim(); } } Roaring64NavigableMap(); Roaring64NavigableMap(boolean signedLongs); Roaring64NavigableMap(boolean signedLongs, boolean ca...
### Question: Roaring64NavigableMap implements Externalizable, LongBitmapDataProvider { @Override public long select(final long j) throws IllegalArgumentException { if (!doCacheCardinalities) { return selectNoCache(j); } int indexOk = ensureCumulatives(highestHigh()); if (highToBitmap.isEmpty()) { return throwSelectInv...
### Question: Container implements Iterable<Character>, Cloneable, Externalizable, WordStorage<Container> { public String getContainerName() { if (this instanceof BitmapContainer) { return ContainerNames[0]; } else if (this instanceof ArrayContainer) { return ContainerNames[1]; } else { return ContainerNames[2]...
### Question: Container implements Iterable<Character>, Cloneable, Externalizable, WordStorage<Container> { abstract int numberOfRuns(); static Container rangeOfOnes(final int start, final int last); abstract Container add(int begin, int end); abstract Container add(char x); abstract Container and(ArrayContain...
### Question: Container implements Iterable<Character>, Cloneable, Externalizable, WordStorage<Container> { public abstract Container add(int begin, int end); static Container rangeOfOnes(final int start, final int last); abstract Container add(int begin, int end); abstract Container add(char x); abstract Cont...
### Question: BitSetUtil { public static RoaringBitmap bitmapOf(final BitSet bitSet) { return bitmapOf(bitSet.toLongArray()); } static RoaringBitmap bitmapOf(final BitSet bitSet); static RoaringBitmap bitmapOf(final long[] words); static boolean equals(final BitSet bitset, final RoaringBitmap bitmap); }### Answer: @T...
### Question: RunContainer extends Container implements Cloneable { @Override public int first() { assertNonEmpty(numberOfRuns() == 0); return (valueslength[0]); } RunContainer(); protected RunContainer(ArrayContainer arr, int nbrRuns); RunContainer(final int firstOfRun, final int lastOfRun); protected RunContainer(...
### Question: FastAggregation { @Deprecated public static RoaringBitmap horizontal_or(Iterator<? extends RoaringBitmap> bitmaps) { return naive_or(bitmaps); } private FastAggregation(); static RoaringBitmap and(Iterator<? extends RoaringBitmap> bitmaps); static RoaringBitmap and(RoaringBitmap... bitmaps); static Roari...
### Question: FastAggregation { public static RoaringBitmap or(Iterator<? extends RoaringBitmap> bitmaps) { return naive_or(bitmaps); } private FastAggregation(); static RoaringBitmap and(Iterator<? extends RoaringBitmap> bitmaps); static RoaringBitmap and(RoaringBitmap... bitmaps); static RoaringBitmap and(long[] agg...
### Question: Util { public static int iterateUntil(char[] array, int pos, int length, int min) { while (pos < length && (array[pos]) < min) { pos++; } return pos; } private Util(); static Container[] addOffset(Container source, char offsets); static int advanceUntil(char[] array, int pos, int length, char min); stati...
### Question: FastAggregation { public static RoaringBitmap and(Iterator<? extends RoaringBitmap> bitmaps) { return naive_and(bitmaps); } private FastAggregation(); static RoaringBitmap and(Iterator<? extends RoaringBitmap> bitmaps); static RoaringBitmap and(RoaringBitmap... bitmaps); static RoaringBitmap and(long[] a...
### Question: FastAggregation { public static RoaringBitmap naive_and(Iterator<? extends RoaringBitmap> bitmaps) { if (!bitmaps.hasNext()) { return new RoaringBitmap(); } RoaringBitmap answer = bitmaps.next().clone(); while (bitmaps.hasNext() && !answer.isEmpty()) { answer.and(bitmaps.next()); } return answer; } privat...
### Question: FastAggregation { public static RoaringBitmap naive_or(Iterator<? extends RoaringBitmap> bitmaps) { RoaringBitmap answer = new RoaringBitmap(); while (bitmaps.hasNext()) { answer.naivelazyor(bitmaps.next()); } answer.repairAfterLazy(); return answer; } private FastAggregation(); static RoaringBitmap and(...
### Question: FastAggregation { public static RoaringBitmap naive_xor(Iterator<? extends RoaringBitmap> bitmaps) { RoaringBitmap answer = new RoaringBitmap(); while (bitmaps.hasNext()) { answer.xor(bitmaps.next()); } return answer; } private FastAggregation(); static RoaringBitmap and(Iterator<? extends RoaringBitmap>...
### Question: RunContainer extends Container implements Cloneable { @Override public void clear() { nbrruns = 0; } RunContainer(); protected RunContainer(ArrayContainer arr, int nbrRuns); RunContainer(final int firstOfRun, final int lastOfRun); protected RunContainer(BitmapContainer bc, int nbrRuns); RunContainer(f...
### Question: ThreadContextImpl implements ThreadContextPlus { @Override public TraceEntry startTransaction(String transactionType, String transactionName, MessageSupplier messageSupplier, TimerName timerName) { return startTransaction(transactionType, transactionName, messageSupplier, timerName, AlreadyInTransactionBe...
### Question: ThreadContextImpl implements ThreadContextPlus { private TraceEntryImpl startAsyncTraceEntry(long startTick, MessageSupplier messageSupplier, TimerImpl syncTimer, AsyncTimerImpl asyncTimer) { TraceEntryImpl entry = traceEntryComponent.pushEntry(startTick, messageSupplier, syncTimer, asyncTimer, null, 0); ...
### Question: ThreadContextImpl implements ThreadContextPlus { @Override public Timer startTimer(TimerName timerName) { if (timerName == null) { logger.error("startTimer(): argument 'timerName' must be non-null"); return NopTimer.INSTANCE; } if (currentTimer == null) { logger.warn("startTimer(): called on completed thr...
### Question: Reflection { @SuppressWarnings("unchecked") public static <T> T invokeWithDefault(@Nullable Method method, Object obj, T defaultValue) { if (method == null) { return defaultValue; } try { Object value = method.invoke(obj); if (value == null) { return defaultValue; } return (T) value; } catch (Throwable t)...
### Question: Transaction { @VisibleForTesting static String buildTraceId(long startTime) { byte[] bytes = new byte[10]; random.nextBytes(bytes); return lowerSixBytesHex(startTime) + BaseEncoding.base16().lowerCase().encode(bytes); } Transaction(long startTime, long startTick, String transactionType, String transaction...
### Question: Transaction { @VisibleForTesting static String lowerSixBytesHex(long startTime) { long mask = 1L << 48; return Long.toHexString(mask | (startTime & (mask - 1))).substring(1); } Transaction(long startTime, long startTick, String transactionType, String transactionName, MessageSupplier messageSu...
### Question: TimerNameCache { public TimerName getTimerName(Class<?> adviceClass) { if (adviceClass == null) { logger.error("getTimerName(): argument 'adviceClass' must be non-null"); return unknownTimerName; } Pointcut pointcut = adviceClass.getAnnotation(Pointcut.class); if (pointcut == null) { logger.warn("advice h...
### Question: Strings { public static List<String> split(String string) { List<String> list = new ArrayList<String>(); int lastFoundIndex = -1; int nextFoundIndex; while ((nextFoundIndex = string.indexOf(',', lastFoundIndex + 1)) != -1) { String value = string.substring(lastFoundIndex + 1, nextFoundIndex).trim(); if (!...
### Question: ToolMain { @VisibleForTesting static @Nullable File getGlowrootJarFile(@Nullable CodeSource codeSource) throws URISyntaxException { if (codeSource == null) { return null; } File codeSourceFile = new File(codeSource.getLocation().toURI()); if (codeSourceFile.getName().endsWith(".jar")) { return codeSourceF...
### Question: ServletMessageSupplier extends MessageSupplier implements ServletRequestInfo { static @Nullable String maskRequestQueryString(@Nullable String requestQueryString, List<Pattern> maskPatterns) { if (requestQueryString == null) { return null; } if (maskPatterns.isEmpty()) { return requestQueryString; } Strin...
### Question: LazySecretKeyImpl implements LazySecretKey { @Override public SecretKey getOrCreate() throws Exception { synchronized (secretFile) { if (secretKey == null) { if (secretFile.exists()) { secretKey = loadKey(secretFile); } else { secretKey = Encryption.generateNewKey(); Files.write(secretKey.getEncoded(), se...
### Question: LazySecretKeyImpl implements LazySecretKey { @Override public @Nullable SecretKey getExisting() throws Exception { synchronized (secretFile) { if (secretKey == null && secretFile.exists()) { secretKey = loadKey(secretFile); } return secretKey; } } LazySecretKeyImpl(File secretFile); @Override @Nullable Se...
### Question: ScheduledRunnable implements Runnable, Cancellable { public void scheduleWithFixedDelay(ScheduledExecutorService scheduledExecutor, long period, TimeUnit unit) { scheduleWithFixedDelay(scheduledExecutor, 0, period, unit); } void scheduleWithFixedDelay(ScheduledExecutorService scheduledExecutor, long peri...
### Question: ScheduledRunnable implements Runnable, Cancellable { @Override public void cancel() { if (future != null) { future.cancel(false); } } void scheduleWithFixedDelay(ScheduledExecutorService scheduledExecutor, long period, TimeUnit unit); void scheduleWithFixedDelay(ScheduledExecutorService sched...
### Question: ScheduledRunnable implements Runnable, Cancellable { @Override public void run() { try { runInternal(); } catch (TerminateSubsequentExecutionsException e) { logger.debug(e.getMessage(), e); throw e; } catch (Throwable t) { logger.error(t.getMessage(), t); } } void scheduleWithFixedDelay(ScheduledExecutor...
### Question: SystemProperties { public static List<String> maskJvmArgs(List<String> jvmArgs, List<String> maskSystemProperties) { if (maskSystemProperties.isEmpty()) { return jvmArgs; } List<Pattern> maskSystemPropertyPatterns = buildPatternList(maskSystemProperties); List<String> maskedJvmArgs = Lists.newArrayList();...
### Question: SystemProperties { public static Map<String, String> maskSystemProperties(Map<String, String> systemProperties, List<String> maskSystemProperties) { if (maskSystemProperties.isEmpty()) { return systemProperties; } List<Pattern> maskPatterns = buildPatternList(maskSystemProperties); Map<String, String> mas...
### Question: Version { public static String getVersion(Class<?> baseClass) { Manifest manifest; try { manifest = getManifest(baseClass); } catch (IOException e) { logger.error(e.getMessage(), e); return UNKNOWN_VERSION; } return getVersion(manifest); } private Version(); static String getVersion(Class<?> baseClass); ...
### Question: Version { @VisibleForTesting static @Nullable Manifest getManifest(Class<?> clazz) throws IOException { URL classURL = clazz.getResource(clazz.getSimpleName() + ".class"); if (classURL == null) { logger.warn("url for class is unexpectedly null: {}", clazz); return null; } String externalForm = classURL.to...
### Question: GrpcCommon { static String convertFromV09AgentRollupId(String v09AgentRollupId) { return v09AgentRollupId.replaceAll(" */ *", "::").trim() + "::"; } GrpcCommon(AgentConfigDao agentConfigDao, V09AgentRollupDao v09AgentRollupDao); }### Answer: @Test public void test() { assertThat(GrpcCommon.convertFromV0...
### Question: TraceCommonService { @VisibleForTesting static @Nullable String entriesToJson(List<Trace.Entry> entries) throws IOException { if (entries.isEmpty()) { return null; } StringBuilder sb = new StringBuilder(); JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb)); try { writeEntries(jg, ent...
### Question: ResponseInvoker { static @Nullable Class<?> getServletResponseClass(Class<?> clazz) { try { return Class.forName("javax.servlet.ServletResponse", false, clazz.getClassLoader()); } catch (ClassNotFoundException e) { logger.warn(e.getMessage(), e); } return null; } ResponseInvoker(Class<?> clazz); }### An...
### Question: ResponseInvoker { boolean hasGetContentTypeMethod() { return getContentTypeMethod != null; } ResponseInvoker(Class<?> clazz); }### Answer: @Test public void shouldNotFindGetContentTypeMethod() { assertThat(new ResponseInvoker(Object.class).hasGetContentTypeMethod()).isFalse(); }
### Question: ResourceMethodMeta { static String combine(@Nullable String classPath, @Nullable String methodPath) { if (classPath == null || classPath.isEmpty() || classPath.equals("/")) { return normalize(methodPath); } if (methodPath == null || methodPath.isEmpty() || methodPath.equals("/")) { return normalize(classP...
### Question: RateLimitedLogger { @VisibleForTesting static @Nullable Object[] newArgsWithCountSinceLastWarning( Object[] args, int countSinceLastWarning) { if (args.length == 0) { return new Object[] {countSinceLastWarning}; } @Nullable Object[] argsPlus = new Object[args.length + 1]; if (args[args.length - 1] instanc...
### Question: JavaVersion { @VisibleForTesting static boolean parseIsJava6(@Nullable String javaVersion) { return javaVersion != null && javaVersion.startsWith("1.6"); } private JavaVersion(); static boolean isJava6(); static boolean isGreaterThanOrEqualToJava9(); static boolean isIbmJvm(); static boolean isJRockitJvm...
### Question: CollectorProxy implements Collector { @Override public void collectAggregates(AggregateReader aggregateReader) throws Exception { if (instance == null) { earlyAggregateReaders.offer(aggregateReader); if (instance != null) { earlyAggregateReaders.remove(aggregateReader); instance.collectAggregates(aggregat...
### Question: CollectorProxy implements Collector { @Override public void collectGaugeValues(List<GaugeValue> gaugeValues) throws Exception { if (instance == null) { earlyGaugeValues.offer(gaugeValues); if (instance != null) { earlyGaugeValues.remove(gaugeValues); instance.collectGaugeValues(gaugeValues); } } else { in...
### Question: CollectorProxy implements Collector { @Override public void collectTrace(TraceReader traceReader) throws Exception { if (instance == null) { earlyTraceReaders.offer(traceReader); if (instance != null) { earlyTraceReaders.remove(traceReader); instance.collectTrace(traceReader); } } else { instance.collectT...
### Question: CollectorProxy implements Collector { @Override public void log(LogEvent logEvent) throws Exception { if (instance == null) { earlyLogEvents.offer(logEvent); if (instance != null) { earlyLogEvents.remove(logEvent); instance.log(logEvent); } } else { instance.log(logEvent); } } @Override void init(File co...
### Question: MainEntryPoint { private static void upgradeToCollectorAddressIfNeeded(File propFile) throws IOException { List<String> lines = readPropertiesFile(propFile); List<String> newLines = upgradeToCollectorAddressIfNeeded(lines); if (!newLines.equals(lines)) { writePropertiesFile(propFile, newLines); } } privat...
### Question: PluginDescriptor { public abstract String name(); abstract String id(); abstract String name(); abstract ImmutableList<PropertyDescriptor> properties(); @JsonProperty("instrumentation") abstract ImmutableList<InstrumentationConfig> instrumentationConfigs(); abstract ImmutableList<String> aspects(); stati...
### Question: CentralCollector implements Collector { @VisibleForTesting static String escapeHostName(String hostName) { hostName = hostName.replace("\\", "\\\\"); if (hostName.startsWith(":")) { hostName = "\\" + hostName; } while (hostName.contains("::")) { hostName = hostName.replace("::", ":\\:"); } return hostName...
### Question: LiveJvmServiceImpl implements LiveJvmService { @VisibleForTesting static @Nullable Long parseProcessId(String runtimeName) { int index = runtimeName.indexOf('@'); if (index > 0) { String pid = runtimeName.substring(0, index); try { return Long.parseLong(pid); } catch (NumberFormatException e) { logger.deb...
### Question: Reflection { public static @Nullable Method getMethod(@Nullable Class<?> clazz, String methodName) { if (clazz == null) { return null; } try { return clazz.getMethod(methodName); } catch (Exception e) { logger.debug(e.getMessage(), e); return null; } } private Reflection(); static @Nullable Method getMet...
### Question: InternationalizationServiceFactory { public <T> T create(final Class<T> api, final ClassLoader loader) { if (Mode.mode != Mode.UNSAFE) { if (!api.isInterface()) { throw new IllegalArgumentException(api + " is not an interface"); } if (Stream .of(api.getMethods()) .filter(m -> m.getDeclaringClass() != Obje...
### Question: InjectorImpl implements Serializable, Injector { @Override public <T> T inject(final T instance) { if (instance == null) { return null; } doInject(instance.getClass(), unwrap(instance)); return instance; } @Override T inject(final T instance); }### Answer: @Test void configurationInjection() { final Sup...
### Question: LocalConfigurationService implements LocalConfiguration, Serializable { @Override public String get(final String key) { return rawDelegates .stream() .map(d -> read(d, plugin + "." + key)) .filter(Objects::nonNull) .findFirst() .orElseGet(() -> rawDelegates .stream() .map(d -> read(d, key)) .filter(Object...
### Question: LocalConfigurationService implements LocalConfiguration, Serializable { private String read(final LocalConfiguration d, final String entryKey) { return ofNullable(d.get(entryKey)).orElseGet(() -> d.get(entryKey.replace('.', '_'))); } @Override String get(final String key); @Override Set<String> keys(); ...
### Question: LocalConfigurationService implements LocalConfiguration, Serializable { @Override public Set<String> keys() { return rawDelegates .stream() .flatMap(d -> d.keys().stream()) .flatMap(k -> !k.startsWith(plugin + '.') ? Stream.of(k) : Stream.of(k, k.substring(plugin.length() + 1))) .collect(toSet()); } @Ove...
### Question: RecordServiceImpl implements RecordService, Serializable { @Override public Record create(final Schema schema, final Record fallbackRecord, final BiFunction<Schema.Entry, Record.Builder, Boolean> customHandler, final BiConsumer<Record.Builder, Boolean> beforeFinish) { return fallbackRecord .getSchema() .g...
### Question: DSLParser { private static Map<String, String> parseQuery(final String query) { final Map<String, String> parameters = new HashMap<>(); if (query == null || query.trim().isEmpty()) { return parameters; } final byte[] bytes = query.getBytes(StandardCharsets.UTF_8); int pos = 0; int end = bytes.length; Stri...
### Question: RepositoryModelBuilder { private ConfigKey getKey(final String family, final Map<String, String> meta) { final String configName = meta.get("tcomp::configurationtype::name"); final String configType = meta.get("tcomp::configurationtype::type"); return new ConfigKey(family, configName, configType); } Repo...
### Question: RepositoryModelBuilder { public RepositoryModel create(final ComponentManager.AllServices services, final Collection<ComponentFamilyMeta> familyMetas, final MigrationHandlerFactory migrationHandlerFactory) { final List<Family> families = familyMetas .stream() .map(familyMeta -> createConfigForFamily(servi...
### Question: PartitionMapperFlowsFactory implements FlowsFactory { @Override public Collection<String> getInputFlows() { return Collections.emptySet(); } @Override Collection<String> getInputFlows(); @Override Collection<String> getOutputFlows(); }### Answer: @Test void testGetInputFlows() { PartitionMapperFlowsFact...
### Question: PartitionMapperFlowsFactory implements FlowsFactory { @Override public Collection<String> getOutputFlows() { return Collections.singleton(Branches.DEFAULT_BRANCH); } @Override Collection<String> getInputFlows(); @Override Collection<String> getOutputFlows(); }### Answer: @Test void testGetOutputFlows() ...
### Question: ProcessorFlowsFactory implements FlowsFactory { @Override public Collection<String> getInputFlows() { return getListener() .map(m -> Stream.of(m.getParameters())) .orElseGet(() -> getAfterGroup().map(it -> Stream.of(it.getParameters())).orElseGet(Stream::empty)) .filter(this::isInput) .map(this::mapInputN...
### Question: ProcessorFlowsFactory implements FlowsFactory { @Override public Collection<String> getOutputFlows() { return concat( getListener() .map(listener -> concat(getReturnedBranches(listener), getOutputParameters(listener))) .orElseGet(Stream::empty), getAfterGroup().map(this::getOutputParameters).orElseGet(Str...
### Question: QueueMapper implements Mapper, JobStateAware, Supplier<DIPipeline>, Delegated { @Override public List<Mapper> split(final long desiredSize) { return singletonList(this); } QueueMapper(final String plugin, final String family, final String name, final PTransform<PBegin, PCollection<Record>> tra...
### Question: InMemoryQueueIO { public static PTransform<PBegin, PCollection<Record>> from(final LoopState state) { return Read.from(new UnboundedQueuedInput(state.id)); } static PTransform<PBegin, PCollection<Record>> from(final LoopState state); static PTransform<PCollection<Record>, PCollection<Void>> to(final Loop...
### Question: InMemoryQueueIO { public static PTransform<PCollection<Record>, PCollection<Void>> to(final LoopState state) { return new QueuedOutputTransform(state.id); } static PTransform<PBegin, PCollection<Record>> from(final LoopState state); static PTransform<PCollection<Record>, PCollection<Void>> to(final LoopS...
### Question: PartitionMapperImpl extends LifecycleImpl implements Mapper, Delegated { @Override public List<Mapper> split(final long desiredSize) { lazyInit(); return ((Collection<?>) doInvoke(split, splitArgSupplier.apply(desiredSize))) .stream() .map(Serializable.class::cast) .map(mapper -> new PartitionMapperImpl(r...
### Question: MvnDependencyListLocalRepositoryResolver implements Resolver { @Override public Stream<Artifact> resolve(final ClassLoader rootLoader, final String artifact) { return Stream .of(readDependencies(ofNullable(getJar(artifact)) .filter(Files::exists) .map(this::findDependenciesFile) .orElseGet(() -> { final b...
### Question: PartitionMapperImpl extends LifecycleImpl implements Mapper, Delegated { @Override public Input create() { lazyInit(); final Serializable input = Serializable.class.cast(doInvoke(inputFactory)); if (isStream()) { return new StreamingInputImpl(rootName(), inputName, plugin(), input, loadRetryConfiguration(...
### Question: ConfigurableClassLoader extends URLClassLoader { public List<InputStream> findContainedResources(final String name) { try { return Stream.concat(ofNullable(super.findResources(name)).map(urls -> list(urls).stream().map(url -> { try { return url.openStream(); } catch (final IOException e) { throw new Illeg...
### Question: ConfigurableClassLoader extends URLClassLoader { @Override public InputStream getResourceAsStream(final String name) { return ofNullable(doGetResourceAsStream(name)) .orElseGet(() -> ofNullable(resources.get(name)) .filter(s -> s.size() > 0) .map(s -> s.iterator().next().resource) .map(ByteArrayInputStrea...
### Question: BufferizedProducerSupport { public T next() { if (current == null || !current.hasNext()) { current = supplier.get(); } return current != null && current.hasNext() ? current.next() : null; } T next(); }### Answer: @Test void iterate() { final Iterator<List<String>> strings = asList(asList("a", "b"), asLi...
### Question: SvgValidator { private String pathsAreClosed(final SVGOMSVGElement icon) { return browseDom(icon, node -> { if ("path".equals(node.getNodeName())) { final Node d = node.getAttributes() == null ? null : node.getAttributes().getNamedItem("d"); if (d == null || d.getNodeValue() == null) { return "Missing 'd'...
### Question: SvgValidator { private String noEmbedStyle(final SVGOMSVGElement icon) { return browseDom(icon, node -> node.getNodeName().equals("style") ? "Forbidden <style> in icon" : null); } Stream<String> validate(final Path path); }### Answer: @Test void noEmbedStyle() { final String error = doValidate("embedded...
### Question: SvgValidator { private String noDisplayNone(final SVGOMSVGElement icon) { return browseDom(icon, node -> { final Node display = node.getAttributes() == null ? null : node.getAttributes().getNamedItem("display"); if (display != null && display.getNodeValue() != null) { return display.getNodeValue().replace...
### Question: SVG2Png implements Runnable { @Override public void run() { try { Files.walkFileTree(iconsFolder, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { final String fileName = file.getFileName().toString(); if (fil...
### Question: ScanTask implements Runnable { @Override public void run() { output.getParentFile().mkdirs(); try (final OutputStream stream = new FileOutputStream(output)) { final Properties properties = new Properties(); properties.setProperty("classes.list", scanList().collect(joining(","))); properties.store(stream, ...
### Question: IO { public void set() { System.setIn(stdin); System.setOut(stdout); System.setErr(stderr); } IO(); void set(); }### Answer: @Test void stashIo() throws UnsupportedEncodingException { final IO testIO = new IO(); final ByteArrayOutputStream stdout = new ByteArrayOutputStream(); final PrintStream stdoutPs ...
### Question: Singer { public synchronized void writeRecord(final String stream, final JsonObject record) { final JsonObject json = builderFactory .createObjectBuilder() .add("type", "RECORD") .add("stream", requireNonNull(stream, "stream can't be null")) .add("time_extracted", formatDate(dateTimeSupplier.get())) .add(...
### Question: Singer { public synchronized void writeSchema(final String stream, final JsonObject schema, final JsonArray keys, final JsonArray bookmarks) { final JsonObject json = builderFactory .createObjectBuilder() .add("type", "SCHEMA") .add("stream", requireNonNull(stream, "stream can't be null")) .add("schema", ...
### Question: Singer { public synchronized void writeState(final JsonObject state) { final JsonObject json = builderFactory.createObjectBuilder().add("type", "STATE").add("value", state).build(); runIo.getStdout().println(json); } Singer(); String formatDate(final ZonedDateTime dateTime); synchronized void writeState(f...
### Question: Kitap implements Runnable { private void discover(final Mapper mapper) { final JsonObject schema = records(mapper) .findFirst() .map(record -> new JsonSchemaGenerator(record.getSchema().getEntries(), jsonBuilderFactory).get()) .orElseThrow(() -> new IllegalArgumentException( "No record found for " + mappe...
### Question: LocalPartitionMapper extends Named implements Mapper, Delegated { @Override public List<Mapper> split(final long desiredSize) { return new ArrayList<>(singletonList(this)); } protected LocalPartitionMapper(); LocalPartitionMapper(final String rootName, final String name, final String plugin, ...
### Question: JsonSchemaGenerator implements Supplier<JsonObject> { @Override public JsonObject get() { final JsonObjectBuilder json = jsonBuilderFactory.createObjectBuilder(); json.add("type", jsonBuilderFactory.createArrayBuilder().add("null").add("object").build()); json.add("additionalProperties", false); json.add(...
### Question: RecordJsonMapper implements Function<Record, JsonObject> { @Override public JsonObject apply(final Record record) { return service.visit(new JsonVisitor(singer, service, jsonBuilderFactory), record); } @Override JsonObject apply(final Record record); }### Answer: @Test void map() { final JsonObject obje...
### Question: ComponentResourceImpl implements ComponentResource { @Override public Dependencies getDependencies(final String[] ids) { if (ids.length == 0) { return new Dependencies(emptyMap()); } final Map<String, DependencyDefinition> dependencies = new HashMap<>(); for (final String id : ids) { if (virtualComponents...
### Question: ComponentResourceImpl implements ComponentResource { @Override public StreamingOutput getDependency(final String id) { final ComponentFamilyMeta.BaseMeta<?> component = componentDao.findById(id); final Supplier<InputStream> streamProvider; if (component != null) { final Path file = componentManagerService...
### Question: ComponentResourceImpl implements ComponentResource { @Override public ComponentIndices getIndex(final String language, final boolean includeIconContent, final String query) { final Locale locale = localeMapper.mapLocale(language); caches.evictIfNeeded(indicesPerRequest, configuration.getMaxCacheSize() - 1...
### Question: ComponentResourceImpl implements ComponentResource { @Override public Map<String, String> migrate(final String id, final int version, final Map<String, String> config) { if (virtualComponents.isExtensionEntity(id)) { return config; } return ofNullable(componentDao.findById(id)) .orElseThrow(() -> new WebA...
### Question: EnvironmentResourceImpl implements EnvironmentResource { @Override public Environment get() { return new Environment(latestApiVersion, version, commit, time, configuration.getChangeLastUpdatedAtStartup() ? findLastUpdated() : service.findLastUpdated()); } @Override Environment get(); }### Answer: @Test ...
### Question: ActionResourceImpl implements ActionResource { @Override public CompletionStage<Response> execute(final String family, final String type, final String action, final String lang, final Map<String, String> params) { return virtualActions .getAction(family, type, action) .map(it -> it.getHandler().apply(para...
### Question: LocalPartitionMapper extends Named implements Mapper, Delegated { @Override public Input create() { return Input.class.isInstance(input) ? Input.class.cast(input) : new InputImpl(rootName(), name(), plugin(), input); } protected LocalPartitionMapper(); LocalPartitionMapper(final String rootName, final S...
### Question: ConfigurationTypeResourceImpl implements ConfigurationTypeResource { @Override public Map<String, String> migrate(final String id, final int version, final Map<String, String> config) { if (virtualComponents.isExtensionEntity(id)) { return config; } final Config configuration = ofNullable(configurations.f...
### Question: CustomCollectors { public static <T, K, V> Collector<T, ?, LinkedHashMap<K, V>> toLinkedMap( final Function<? super T, ? extends K> keyMapper, final Function<? super T, ? extends V> valueMapper) { return toMap(keyMapper, valueMapper, (v1, v2) -> { throw new IllegalArgumentException("conflict on key " + v1...