method2testcases
stringlengths 118
3.08k
|
---|
### 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.collectTrace(traceReader); } } @Override void init(File confDir, @Nullable File sharedConfDir, Environment environment,
AgentConfig agentConfig, AgentConfigUpdater agentConfigUpdater); @Override void collectAggregates(AggregateReader aggregateReader); @Override void collectGaugeValues(List<GaugeValue> gaugeValues); @Override void collectTrace(TraceReader traceReader); @Override void log(LogEvent logEvent); @VisibleForTesting void setInstance(Collector instance); }### Answer:
@Test public void testCollectTrace() throws Exception { CollectorProxy collectorProxy = new CollectorProxy(); TraceReader traceReader1 = mock(TraceReader.class); TraceReader traceReader2 = mock(TraceReader.class); TraceReader traceReader3 = mock(TraceReader.class); collectorProxy.collectTrace(traceReader1); collectorProxy.collectTrace(traceReader2); Collector collector = mock(Collector.class); collectorProxy.setInstance(collector); collectorProxy.collectTrace(traceReader3); InOrder inOrder = Mockito.inOrder(collector); inOrder.verify(collector).collectTrace(traceReader1); inOrder.verify(collector).collectTrace(traceReader2); inOrder.verify(collector).collectTrace(traceReader3); } |
### 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 confDir, @Nullable File sharedConfDir, Environment environment,
AgentConfig agentConfig, AgentConfigUpdater agentConfigUpdater); @Override void collectAggregates(AggregateReader aggregateReader); @Override void collectGaugeValues(List<GaugeValue> gaugeValues); @Override void collectTrace(TraceReader traceReader); @Override void log(LogEvent logEvent); @VisibleForTesting void setInstance(Collector instance); }### Answer:
@Test public void testLog() throws Exception { CollectorProxy collectorProxy = new CollectorProxy(); LogEvent logEvent1 = LogEvent.newBuilder() .setMessage("one") .build(); LogEvent logEvent2 = LogEvent.newBuilder() .setMessage("two") .build(); LogEvent logEvent3 = LogEvent.newBuilder() .setMessage("three") .build(); collectorProxy.log(logEvent1); collectorProxy.log(logEvent2); Collector collector = mock(Collector.class); collectorProxy.setInstance(collector); collectorProxy.log(logEvent3); InOrder inOrder = Mockito.inOrder(collector); inOrder.verify(collector).log(logEvent1); inOrder.verify(collector).log(logEvent2); inOrder.verify(collector).log(logEvent3); } |
### 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(); static PluginDescriptor readValue(String content); static String writeValue(List<PluginDescriptor> pluginDescriptors); }### Answer:
@Test public void testSorting() { List<PluginDescriptor> pluginDescriptors = Lists.newArrayList(); pluginDescriptors.add(pluginDescriptorWithName("Zzz")); pluginDescriptors.add(pluginDescriptorWithName("Yyy Plugin")); pluginDescriptors.add(pluginDescriptorWithName("Xxx plugin")); pluginDescriptors.add(pluginDescriptorWithName("Aaa Plugin")); pluginDescriptors.add(pluginDescriptorWithName("Bbb")); List<PluginDescriptor> sortedPluginDescriptors = new PluginDescriptorOrdering().sortedCopy(pluginDescriptors); assertThat(sortedPluginDescriptors.get(0).name()).isEqualTo("Aaa Plugin"); assertThat(sortedPluginDescriptors.get(1).name()).isEqualTo("Bbb"); assertThat(sortedPluginDescriptors.get(2).name()).isEqualTo("Xxx plugin"); assertThat(sortedPluginDescriptors.get(3).name()).isEqualTo("Yyy Plugin"); assertThat(sortedPluginDescriptors.get(4).name()).isEqualTo("Zzz"); } |
### 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 getMethod(@Nullable Class<?> clazz, String methodName); static @Nullable Field getDeclaredField(@Nullable Class<?> clazz, String fieldName); @SuppressWarnings("unchecked") static T invoke(@Nullable Method method, Object obj); @SuppressWarnings("unchecked") static T invokeWithDefault(@Nullable Method method, Object obj, T defaultValue); static @Nullable Object getFieldValue(@Nullable Field field, Object obj); }### Answer:
@Test public void shouldReturnNullMethodWhenClassIsNull() { assertThat(Reflection.getMethod(null, null)).isNull(); }
@Test public void shouldReturnNullMethodWhenMethodNotFound() { assertThat(Reflection.getMethod(String.class, "thereWillNeverBeMethodWithThisName")) .isNull(); } |
### 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() != Object.class) .anyMatch(m -> m.getReturnType() != String.class)) { throw new IllegalArgumentException(api + " methods must return a String"); } if (Stream .of(api.getMethods()) .flatMap(m -> Stream.of(m.getParameters())) .anyMatch(p -> p.isAnnotationPresent(Language.class) && p.getType() != Locale.class)) { throw new IllegalArgumentException("@Language can only be used with Locales"); } } final String pck = api.getPackage().getName(); return api .cast(Proxy .newProxyInstance(loader, new Class<?>[] { api }, new InternationalizedHandler(api.getName() + '.', api.getSimpleName() + '.', (pck == null || pck.isEmpty() ? "" : (pck + '.')) + "Messages", localeSupplier))); } T create(final Class<T> api, final ClassLoader loader); }### Answer:
@Test void objectMethods() { assertEquals(translate, translate); assertEquals(translate.hashCode(), translate.hashCode()); final Translate other = new InternationalizationServiceFactory(Locale::getDefault) .create(Translate.class, Translate.class.getClassLoader()); assertNotSame(translate, other); } |
### 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 Supplier<MyConfig> config = injector.inject(new InjectedConfig()).config; assertNotNull(config); final MyConfig configuration = config.get(); assertEquals("ok", configuration.getValue()); }
@Test void inject() { final Injected instance = new Injected(); injector.inject(instance); assertNotNull(instance.cache); assertNotNull(instance.caches); assertEquals(2, instance.caches.size()); }
@Test void injectWithProxy() throws Exception { final Map<Class<?>, Object> services = new HashMap<>(1); LocalCache localCache = new LocalCacheService("LocalCacheServiceTest", System::currentTimeMillis, this.executor); services.put(LocalCache.class, localCache); final InjectedCache instance = new InjectedCache(); ProxyGenerator proxyGenerator = new ProxyGenerator(); final Class<?> proxyClass = proxyGenerator .generateProxy(Thread.currentThread().getContextClassLoader(), InjectedCache.class, "injector", InjectedCache.class.getName()); final InjectedCache proxy = InjectedCache.class.cast(proxyClass.getConstructor().newInstance()); proxyGenerator.initialize(proxy, new InterceptorHandlerFacade(instance, services)); injector.inject(proxy); assertEquals("false", proxy.getString()); assertTrue(proxy.getClass().getName().endsWith("$TalendServiceProxy")); }
@Test void invalidConfigurationInjectionSupplier() { assertThrows(IllegalArgumentException.class, () -> injector.inject(new InvalidInjectedConfig1())); }
@Test void invalidConfigurationInjectionDirectConfig() { assertThrows(IllegalArgumentException.class, () -> injector.inject(new InvalidInjectedConfig2())); } |
### 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(Objects::nonNull) .findFirst() .orElse(null)); } @Override String get(final String key); @Override Set<String> keys(); }### Answer:
@Test void nullDoesntFail() { assertNull(new LocalConfigurationService(singletonList(systemProperties), "LocalConfigurationServiceTest") .get("test.foo.missing")); }
@Test void readGlobal() { System.setProperty("test.foo.LocalConfigurationServiceTest", "1"); try { assertEquals("1", new LocalConfigurationService(singletonList(systemProperties), "LocalConfigurationServiceTest") .get("test.foo.LocalConfigurationServiceTest")); } finally { System.clearProperty("test.foo.LocalConfigurationServiceTest"); } } |
### 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(); }### Answer:
@Test void read() { System.setProperty("LocalConfigurationServiceTest.test.foo", "1"); try { assertEquals("1", new LocalConfigurationService(singletonList(systemProperties), "LocalConfigurationServiceTest") .get("test.foo")); } finally { System.clearProperty("LocalConfigurationServiceTest.test.foo"); } } |
### 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()); } @Override String get(final String key); @Override Set<String> keys(); }### Answer:
@Test void keys() { System.setProperty("LocalConfigurationServiceTest.test.foo", "1"); System.setProperty("LocalConfigurationServiceTest.test.bar", "1"); try { assertEquals(Stream.of("test.foo", "test.bar").collect(toSet()), new LocalConfigurationService(singletonList(systemProperties), "LocalConfigurationServiceTest") .keys() .stream() .filter(it -> it.startsWith("test")) .collect(toSet())); } finally { System.clearProperty("LocalConfigurationServiceTest.test.foo"); System.clearProperty("LocalConfigurationServiceTest.test.bar"); } } |
### 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); } RepositoryModel create(final ComponentManager.AllServices services,
final Collection<ComponentFamilyMeta> familyMetas, final MigrationHandlerFactory migrationHandlerFactory); }### Answer:
@Test void complexTree() { try (final ComponentManager manager = new ComponentManager(new File("target/foo"), "deps.txt", null)) { final String plugin = manager.addPlugin(jarLocation(RepositoryModelBuilderTest.class).getAbsolutePath()); final RepositoryModel model = manager.findPlugin(plugin).orElseThrow(IllegalArgumentException::new).get(RepositoryModel.class); final Family theTestFamily = model .getFamilies() .stream() .filter(f -> f.getMeta().getName().equals("TheTestFamily")) .findFirst() .orElseThrow(IllegalArgumentException::new); assertEquals(3, theTestFamily.getConfigs().get().size(), theTestFamily .getConfigs() .get() .stream() .map(c -> c.getKey().getConfigName()) .collect(joining(", "))); theTestFamily .getConfigs() .get() .forEach(it -> assertTrue(it.getKey().getConfigName().startsWith("Connection-"), it.getKey().getConfigName())); } } |
### 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(services, migrationHandlerFactory, familyMeta)) .collect(toList()); return new RepositoryModel(families); } RepositoryModel create(final ComponentManager.AllServices services,
final Collection<ComponentFamilyMeta> familyMetas, final MigrationHandlerFactory migrationHandlerFactory); }### Answer:
@Test void notRootConfig() { final PropertyEditorRegistry registry = new PropertyEditorRegistry(); final RepositoryModel model = new RepositoryModelBuilder() .create(new ComponentManager.AllServices(emptyMap()), singleton(new ComponentFamilyMeta("test", emptyList(), "noicon", "test", "test") { { final ParameterMeta store = new ParameterMeta(null, DataStore1.class, ParameterMeta.Type.OBJECT, "config.store", "store", new String[0], emptyList(), emptyList(), new HashMap<String, String>() { { put("tcomp::configurationtype::type", "datastore"); put("tcomp::configurationtype::name", "testDatastore"); } }, false); final ParameterMeta wrapper = new ParameterMeta(null, WrappingStore.class, ParameterMeta.Type.OBJECT, "config", "config", new String[0], singletonList(store), emptyList(), emptyMap(), false); getPartitionMappers() .put("test", new PartitionMapperMeta(this, "mapper", "noicon", 1, PartitionMapper1.class, () -> singletonList(wrapper), m -> null, () -> (a, b) -> null, true, false) { }); } }), new MigrationHandlerFactory( new ReflectionService(new ParameterModelService(registry), registry))); final List<Config> configs = model.getFamilies().stream().flatMap(f -> f.getConfigs().get().stream()).collect(toList()); assertEquals(1, configs.size()); } |
### Question:
PartitionMapperFlowsFactory implements FlowsFactory { @Override public Collection<String> getInputFlows() { return Collections.emptySet(); } @Override Collection<String> getInputFlows(); @Override Collection<String> getOutputFlows(); }### Answer:
@Test void testGetInputFlows() { PartitionMapperFlowsFactory factory = new PartitionMapperFlowsFactory(); Assertions.assertTrue(factory.getInputFlows().isEmpty()); } |
### 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() { PartitionMapperFlowsFactory factory = new PartitionMapperFlowsFactory(); Collection<String> outputs = factory.getOutputFlows(); Assertions.assertEquals(1, outputs.size()); Assertions.assertTrue(outputs.contains("__default__")); } |
### 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::mapInputName) .collect(toList()); } @Override Collection<String> getInputFlows(); @Override Collection<String> getOutputFlows(); }### Answer:
@Test void testGetInputFlows() { final ProcessorFlowsFactory factory = new ProcessorFlowsFactory(TestProcessor.class); final Collection<String> inputs = factory.getInputFlows(); assertEquals(2, inputs.size()); assertTrue(inputs.contains("__default__")); assertTrue(inputs.contains("REJECT")); } |
### 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(Stream::empty)).distinct().collect(toList()); } @Override Collection<String> getInputFlows(); @Override Collection<String> getOutputFlows(); }### Answer:
@Test void testGetOutputFlows() { final ProcessorFlowsFactory factory = new ProcessorFlowsFactory(TestProcessor.class); final Collection<String> outputs = factory.getOutputFlows(); assertEquals(2, outputs.size()); assertTrue(outputs.contains("__default__")); assertTrue(outputs.contains("OUTPUT")); }
@Test void testGetMergeOutputFlows() { final ProcessorFlowsFactory factory = new ProcessorFlowsFactory(TestProcessorMergeOutputs.class); final Collection<String> outputs = factory.getOutputFlows(); assertEquals(2, outputs.size()); assertTrue(outputs.contains("__default__")); assertTrue(outputs.contains("OUTPUT")); } |
### 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>> transform); String getStateId(); @Override long assess(); @Override List<Mapper> split(final long desiredSize); @Override Input create(); @Override boolean isStream(); @Override String plugin(); @Override String rootName(); @Override String name(); @Override void start(); @Override void stop(); @Override void setState(final State state); @Override DIPipeline get(); @Override Object getDelegate(); }### Answer:
@Test void split() { final QueueMapper mapper = new QueueMapper("test", "test", "test", null); try { mapper.setState(new JobStateAware.State()); } catch (final NullPointerException npe) { } final List<Mapper> split = mapper.split(mapper.assess()); assertEquals(1, split.size()); assertEquals(mapper, split.iterator().next()); } |
### 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 LoopState state); }### Answer:
@Test(timeout = 60000) public void input() { INPUT_OUTPUTS.clear(); final PipelineResult result; try (final LoopState state = LoopState.newTracker(null)) { IntStream.range(0, 2).forEach(i -> state.push(new RowStruct(i))); pipeline.apply(InMemoryQueueIO.from(state)).apply(ParDo.of(new DoFn<Record, Void>() { @ProcessElement public void onElement(@Element final Record record) { INPUT_OUTPUTS.add(record); } })); result = pipeline.run(); IntStream.range(2, 5).forEach(i -> state.push(new RowStruct(i))); state.end(); final long end = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(2); long lastLog = System.currentTimeMillis(); while (INPUT_OUTPUTS.size() < 5 && end - System.currentTimeMillis() >= 0) { try { if (lastLog - System.currentTimeMillis() > TimeUnit.SECONDS.toMillis(10)) { log.info("Not yet 5 records: {}, waiting", INPUT_OUTPUTS.size()); } sleep(150); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } } } result.waitUntilFinish(); assertEquals(5, INPUT_OUTPUTS.size()); assertEquals(IntStream.range(0, 5).boxed().collect(toSet()), INPUT_OUTPUTS.stream().mapToInt(o -> o.getInt("id")).boxed().collect(toSet())); } |
### 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 LoopState state); }### Answer:
@Test(timeout = 60000) public void output() { final Collection<Record> objects = new ArrayList<>(); try (final LoopState state = LoopState.newTracker(null)) { pipeline .apply(Create.of(IntStream.range(0, 5).mapToObj(RowStruct::new).collect(toList()))) .setCoder(SerializableCoder.of(RowStruct.class)) .apply(ParDo.of(new DoFn<RowStruct, Record>() { @ProcessElement public void onElement(final ProcessContext context) { final Record record = ComponentManager .instance() .getRecordBuilderFactoryProvider() .apply(null) .newRecordBuilder() .withInt("id", context.element().id) .build(); context.output(record); } })) .setCoder(SchemaRegistryCoder.of()) .apply(InMemoryQueueIO.to(state)); pipeline.run().waitUntilFinish(); Record next; do { next = state.next(); if (next != null) { objects.add(next); } } while (next != null); } assertEquals(5, objects.size()); assertEquals(IntStream.range(0, 5).boxed().collect(toSet()), objects.stream().mapToInt(o -> o.getInt("id")).boxed().collect(toSet())); } |
### 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(rootName(), name(), inputName, plugin(), stream, mapper)) .collect(toList()); } PartitionMapperImpl(final String rootName, final String name, final String inputName, final String plugin,
final boolean stream, final Serializable instance); protected PartitionMapperImpl(); @Override long assess(); @Override List<Mapper> split(final long desiredSize); @Override Input create(); @Override boolean isStream(); @Override Object getDelegate(); }### Answer:
@Test void split() { final Mapper mapper = new PartitionMapperImpl("Root", "Test", null, "Plugin", false, new SampleMapper()); assertEquals(10, mapper.assess()); final List<Mapper> split = mapper.split(3); assertEquals(3, split.stream().distinct().count()); split.forEach(s -> { assertTrue(PartitionMapperImpl.class.isInstance(s)); assertNotSame(mapper, s); assertInput(s); }); } |
### 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()); } return new InputImpl(rootName(), inputName, plugin(), input); } PartitionMapperImpl(final String rootName, final String name, final String inputName, final String plugin,
final boolean stream, final Serializable instance); protected PartitionMapperImpl(); @Override long assess(); @Override List<Mapper> split(final long desiredSize); @Override Input create(); @Override boolean isStream(); @Override Object getDelegate(); }### Answer:
@Test void create() { assertInput(new PartitionMapperImpl("Root", "Test", null, "Plugin", false, new SampleMapper())); }
@Test void createStreaming() { final PartitionMapperImpl mapper = new PartitionMapperImpl("Root", "Test", null, "Plugin", true, new SampleMapper()); final Input input = mapper.create(); assertTrue(StreamingInputImpl.class.isInstance(input)); } |
### 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"), asList("c"), asList("d", "e", "f")).iterator(); final BufferizedProducerSupport<String> support = new BufferizedProducerSupport<>(() -> strings.hasNext() ? strings.next().iterator() : null); assertEquals("a", support.next()); assertEquals("b", support.next()); assertEquals("c", support.next()); assertEquals("d", support.next()); assertEquals("e", support.next()); assertEquals("f", support.next()); assertNull(support.next()); } |
### 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' in a path"; } if (!d.getNodeValue().toLowerCase(Locale.ROOT).endsWith("z")) { return "All path must be closed so end with 'z', found value: '" + d.getNodeValue() + '\''; } } return null; }); } Stream<String> validate(final Path path); }### Answer:
@Test void pathsAreClosed() { final String error = doValidate("closedpath", 1).iterator().next(); assertTrue(error.startsWith("[closedpath.svg] All path must be closed so end with 'z', found value:"), error); } |
### 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("embeddedstyle", 1).iterator().next(); assertTrue(error.startsWith("[embeddedstyle.svg] Forbidden <style> in icon"), error); } |
### 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().replaceAll(" +", "").equalsIgnoreCase("none") ? "'display:none' is forbidden in SVG icons" : null; } return null; }); } Stream<String> validate(final Path path); }### Answer:
@Test void noDisplayNone() { final String error = doValidate("displaynone", 1).iterator().next(); assertTrue(error.startsWith("[displaynone.svg] 'display:none' is forbidden in SVG icons"), error); } |
### 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 (fileName.endsWith(".svg")) { final Path svg = file .getParent() .resolve(fileName.substring(0, fileName.length() - ".svg".length()) + "_icon32.png"); if (!Files.exists(svg)) { createPng(file, svg); log.info("Created " + svg); } } return super.visitFile(file, attrs); } }); } catch (final IOException e) { throw new IllegalStateException(e); } } SVG2Png(final Path iconsFolder, final boolean activeWorkarounds, final Object log); @Override void run(); }### Answer:
@Test void convert() throws IOException { final Path resolved = jarLocation(SVG2PngTest.class).toPath().resolve("test/icons"); final Path expected = resolved.resolve("logo_icon32.png"); if (Files.exists(expected)) { Files.delete(expected); } new SVG2Png(resolved, true, log).run(); assertTrue(Files.exists(expected)); } |
### 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, "generated by " + getClass() + " at " + new Date()); } catch (final IOException e) { throw new IllegalStateException(e.getMessage(), e); } } @Override void run(); }### Answer:
@Test void run(@TempDir final File output) throws Exception { final File out = new File(output, "my.props"); new ScanTask(singletonList(new File("target/test-classes")), singletonList("org.talend.test.valid.update.UpdateService"), singletonList("org.talend.test.valid.*"), "include-exclude", out).run(); final Properties properties = new Properties(); try (final InputStream stream = new FileInputStream(out)) { properties.load(stream); } assertEquals(1, properties.size()); assertEquals("org.talend.test.valid.MyComponent," + "org.talend.test.valid.MyInternalization,org.talend.test.valid.MySource," + "org.talend.test.valid.customicon.MyComponent," + "org.talend.test.valid.customiconapi.MyComponent," + "org.talend.test.valid.datasetassourceconfig.MyComponent," + "org.talend.test.valid.datasetintwosourceswithonewithadditionalrequired.MyComponent," + "org.talend.test.valid.datasetintwosourceswithonewithadditionalrequired.MyComponent2," + "org.talend.test.valid.datastore.MyService," + "org.talend.test.valid.localconfiguration.MyComponent," + "org.talend.test.valid.nestedconfigtypes.WithNestedConfigTypes," + "org.talend.test.valid.nesteddataset.MyComponent," + "org.talend.test.valid.update.Comp,org.talend.test.valid.wording.MyComponent", properties.getProperty("classes.list")); } |
### 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 = new PrintStream(stdout); final ByteArrayOutputStream stderr = new ByteArrayOutputStream(); final PrintStream stderrPs = new PrintStream(stderr); final IO overridenIO = new IO(new InputStream() { @Override public int read() { return -1; } }, stdoutPs, stderrPs); overridenIO.set(); try { System.out.println("test out stash"); stdoutPs.flush(); System.err.println("test err stash"); stderrPs.flush(); assertEquals("test out stash\n", stdout.toString("UTF-8")); assertEquals("test err stash\n", stderr.toString("UTF-8")); } finally { testIO.set(); } } |
### 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("record", record) .build(); runIo.getStdout().println(json); } Singer(); String formatDate(final ZonedDateTime dateTime); synchronized void writeState(final JsonObject state); synchronized void writeSchema(final String stream, final JsonObject schema, final JsonArray keys,
final JsonArray bookmarks); synchronized void writeRecord(final String stream, final JsonObject record); synchronized void stdout(final String message); synchronized void stderr(final String message); }### Answer:
@Test void writeRecord() throws UnsupportedEncodingException { write(s -> s.writeRecord("test_stream", Json.createObjectBuilder().add("id", 1).add("name", "Test").build()), "{\"type\":\"RECORD\",\"stream\":\"test_stream\",\"time_extracted\":\"2019-08-23T11:26:00.000Z\",\"record\":{\"id\":1,\"name\":\"Test\"}}"); } |
### 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", schema) .add("key_properties", keys) .add("bookmark_properties", bookmarks) .build(); runIo.getStdout().println(json); } Singer(); String formatDate(final ZonedDateTime dateTime); synchronized void writeState(final JsonObject state); synchronized void writeSchema(final String stream, final JsonObject schema, final JsonArray keys,
final JsonArray bookmarks); synchronized void writeRecord(final String stream, final JsonObject record); synchronized void stdout(final String message); synchronized void stderr(final String message); }### Answer:
@Test void writeShema() throws UnsupportedEncodingException { write(s -> s .writeSchema("test_stream", Json.createObjectBuilder().add("id", 1).add("name", "Test").build(), Json.createArrayBuilder().add("foo").build(), Json.createArrayBuilder().add("bar").build()), "{\"type\":\"SCHEMA\",\"stream\":\"test_stream\",\"schema\":{\"id\":1,\"name\":\"Test\"},\"key_properties\":[\"foo\"],\"bookmark_properties\":[\"bar\"]}"); } |
### 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(final JsonObject state); synchronized void writeSchema(final String stream, final JsonObject schema, final JsonArray keys,
final JsonArray bookmarks); synchronized void writeRecord(final String stream, final JsonObject record); synchronized void stdout(final String message); synchronized void stderr(final String message); }### Answer:
@Test void writeState() throws UnsupportedEncodingException { write(s -> s.writeState(Json.createObjectBuilder().add("offset", 1).build()), "{\"type\":\"STATE\",\"value\":{\"offset\":1}}"); } |
### 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,
final Serializable instance); @Override long assess(); @Override List<Mapper> split(final long desiredSize); @Override Input create(); @Override boolean isStream(); @Override void start(); @Override void stop(); @Override Object getDelegate(); }### Answer:
@Test void split() { final Mapper mapper = new LocalPartitionMapper("Root", "Test", "Plugin", null); assertEquals(1, mapper.assess()); assertEquals(singletonList(mapper), mapper.split(1)); assertEquals(singletonList(mapper), mapper.split(10)); assertEquals(singletonList(mapper), mapper.split(-159)); } |
### 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("properties", properties.stream().map(this::toJson).collect(toJsonObject())); return json.build(); } @Override JsonObject get(); }### Answer:
@Test void generateSchema() { final Schema schema = factory .newSchemaBuilder(Schema.Type.RECORD) .withEntry(factory.newEntryBuilder().withType(Schema.Type.STRING).withName("name").build()) .withEntry(factory.newEntryBuilder().withType(Schema.Type.INT).withName("id").build()) .withEntry(factory .newEntryBuilder() .withType(Schema.Type.RECORD) .withName("nested") .withElementSchema(factory .newSchemaBuilder(Schema.Type.RECORD) .withEntry(factory .newEntryBuilder() .withType(Schema.Type.LONG) .withName("counter") .build()) .build()) .build()) .build(); final JsonObject object = new JsonSchemaGenerator(schema.getEntries(), Json.createBuilderFactory(emptyMap())).get(); assertEquals( "{\"type\":[\"null\",\"object\"],\"additionalProperties\":false,\"properties\":{\"name\":{\"type\":[\"string\"]},\"id\":{\"type\":[\"integer\"]},\"nested\":{\"type\":[\"null\",\"object\"],\"additionalProperties\":false,\"properties\":{\"counter\":{\"type\":[\"integer\"]}}}}}", object.toString()); } |
### 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 object = new RecordJsonMapper(Json.createBuilderFactory(emptyMap()), new Singer(new IO(), ZonedDateTime::now)) .apply(factory .newRecordBuilder() .withString("name", "hello") .withInt("age", 1) .withBoolean("toggle", true) .withDateTime("date", ZonedDateTime.of(2019, 8, 23, 16, 31, 0, 0, ZoneId.of("UTC"))) .withLong("lg", 2L) .withBytes("bytes", "test".getBytes(StandardCharsets.UTF_8)) .withRecord("nested", factory .newRecordBuilder() .withString("value", "set") .withRecord("nested2", factory.newRecordBuilder().withInt("l2", 2).build()) .build()) .withArray(factory .newEntryBuilder() .withType(Schema.Type.ARRAY) .withName("array") .withElementSchema(factory.newSchemaBuilder(Schema.Type.STRING).build()) .build(), singleton("value-from-array")) .build()); assertEquals("{" + "\"name\":\"hello\"," + "\"age\":1," + "\"toggle\":true," + "\"date\":\"2019-08-23T16:31:00.000Z\"," + "\"lg\":2," + "\"bytes\":\"dGVzdA==\"," + "\"array\":[\"value-from-array\"]," + "\"nested\":{\"value\":\"set\",\"nested2\":{\"l2\":2}}}", object.toString()); } |
### 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.isExtensionEntity(id)) { final DependencyDefinition deps = ofNullable(virtualComponents.getDependenciesFor(id)) .orElseGet(() -> new DependencyDefinition(emptyList())); dependencies.put(id, deps); } else { final ComponentFamilyMeta.BaseMeta<Object> meta = componentDao.findById(id); dependencies.put(meta.getId(), getDependenciesFor(meta)); } } return new Dependencies(dependencies); } void clearCache(@Observes final DeployedComponent deployedComponent); @Override Dependencies getDependencies(final String[] ids); @Override StreamingOutput getDependency(final String id); @Override ComponentIndices getIndex(final String language, final boolean includeIconContent, final String query); @Override Response familyIcon(final String id); @Override Response icon(final String id); @Override Map<String, String> migrate(final String id, final int version, final Map<String, String> config); @Override // TODO: max ids.length ComponentDetailList getDetail(final String language, final String[] ids); }### Answer:
@Test void getDependencies() { final String compId = client.getJdbcId(); final Dependencies dependencies = base .path("component/dependencies") .queryParam("identifier", compId) .request(APPLICATION_JSON_TYPE) .get(Dependencies.class); assertEquals(1, dependencies.getDependencies().size()); final DependencyDefinition definition = dependencies.getDependencies().get(compId); assertNotNull(definition); assertEquals(1, definition.getDependencies().size()); assertEquals("org.apache.tomee:ziplock:jar:7.0.5", definition.getDependencies().iterator().next()); } |
### 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); return indicesPerRequest.computeIfAbsent(new RequestKey(locale, includeIconContent, query), k -> { final Predicate<ComponentIndex> filter = queryLanguageCompiler.compile(query, componentEvaluators); return new ComponentIndices(Stream .concat(findDeployedComponents(includeIconContent, locale), virtualComponents .getDetails() .stream() .map(detail -> new ComponentIndex(detail.getId(), detail.getDisplayName(), detail.getId().getFamily(), new Icon(detail.getIcon(), null, null), new Icon(virtualComponents.getFamilyIconFor(detail.getId().getFamilyId()), null, null), detail.getVersion(), singletonList(detail.getId().getFamily()), detail.getLinks()))) .filter(filter) .collect(toList())); }); } void clearCache(@Observes final DeployedComponent deployedComponent); @Override Dependencies getDependencies(final String[] ids); @Override StreamingOutput getDependency(final String id); @Override ComponentIndices getIndex(final String language, final boolean includeIconContent, final String query); @Override Response familyIcon(final String id); @Override Response icon(final String id); @Override Map<String, String> migrate(final String id, final int version, final Map<String, String> config); @Override // TODO: max ids.length ComponentDetailList getDetail(final String language, final String[] ids); }### Answer:
@Test void getIndex() { assertIndex(client.fetchIndex()); } |
### 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 WebApplicationException(Response .status(Response.Status.NOT_FOUND) .entity(new ErrorPayload(ErrorDictionary.COMPONENT_MISSING, "Didn't find component " + id)) .build())) .getMigrationHandler() .get() .migrate(version, config); } void clearCache(@Observes final DeployedComponent deployedComponent); @Override Dependencies getDependencies(final String[] ids); @Override StreamingOutput getDependency(final String id); @Override ComponentIndices getIndex(final String language, final boolean includeIconContent, final String query); @Override Response familyIcon(final String id); @Override Response icon(final String id); @Override Map<String, String> migrate(final String id, final int version, final Map<String, String> config); @Override // TODO: max ids.length ComponentDetailList getDetail(final String language, final String[] ids); }### Answer:
@Test void migrate() { final Map<String, String> migrated = base .path("component/migrate/{id}/{version}") .resolveTemplate("id", client.getJdbcId()) .resolveTemplate("version", 1) .request(APPLICATION_JSON_TYPE) .post(entity(new HashMap<String, String>() { { } }, APPLICATION_JSON_TYPE), new GenericType<Map<String, String>>() { }); assertEquals(1, migrated.size()); assertEquals("true", migrated.get("migrated")); } |
### 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 void environment() { final Environment environment = base.path("environment").request(APPLICATION_JSON_TYPE).get(Environment.class); assertEquals(1, environment.getLatestApiVersion()); Stream .of(environment.getCommit(), environment.getTime(), environment.getVersion()) .forEach(Assertions::assertNotNull); assertTrue(environment.getLastUpdated().compareTo(new Date(0)) > 0); } |
### 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(params, lang).exceptionally(this::onError)) .orElseGet(() -> doExecuteLocalAction(family, type, action, lang, params)); } @Override CompletionStage<Response> execute(final String family, final String type, final String action,
final String lang, final Map<String, String> params); @Override ActionList getIndex(final String[] types, final String[] families, final String language); }### Answer:
@Test void execute() { final Response error = base .path("action/execute") .queryParam("type", "healthcheck") .queryParam("family", "chain") .queryParam("action", "default") .request(APPLICATION_JSON_TYPE) .post(Entity.entity(new HashMap<String, String>() { { put("dataSet.urls[0]", "empty"); } }, APPLICATION_JSON_TYPE)); assertEquals(200, error.getStatus()); assertEquals(HealthCheckStatus.Status.OK, error.readEntity(HealthCheckStatus.class).getStatus()); } |
### 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 String name, final String plugin,
final Serializable instance); @Override long assess(); @Override List<Mapper> split(final long desiredSize); @Override Input create(); @Override boolean isStream(); @Override void start(); @Override void stop(); @Override Object getDelegate(); }### Answer:
@Test void createReader() { final Mapper mapper = new LocalPartitionMapper("Root", "Test", "Plugin", new Component()); final Input input = mapper.create(); assertTrue(Record.class.isInstance(input.next())); assertNotSame(input.next(), input.next()); }
@Test void serialization() throws IOException, ClassNotFoundException { final LocalPartitionMapper mapper = Serializer.roundTrip(new LocalPartitionMapper("Root", "Test", "Plugin", new Component())); assertEquals("Root", mapper.rootName()); assertEquals("Test", mapper.name()); assertEquals("Plugin", mapper.plugin()); final Input input = mapper.create(); assertNotNull(input); } |
### 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.findById(id)) .orElseThrow(() -> new WebApplicationException(Response .status(Response.Status.NOT_FOUND) .entity(new ErrorPayload(ErrorDictionary.CONFIGURATION_MISSING, "Didn't find configuration " + id)) .build())); final Map<String, String> configToMigrate = new HashMap<>(config); final String versionKey = configuration.getMeta().getPath() + ".__version"; final boolean addedVersion = configToMigrate.putIfAbsent(versionKey, Integer.toString(version)) == null; final Map<String, String> migrated = configuration.getMigrationHandler().migrate(version, configToMigrate); if (addedVersion) { migrated.remove(versionKey); } return migrated; } void clearCache(@Observes final DeployedComponent deployedComponent); @Override ConfigTypeNodes getRepositoryModel(final String language, final boolean lightPayload, final String query); @Override ConfigTypeNodes getDetail(final String language, final String[] ids); @Override Map<String, String> migrate(final String id, final int version, final Map<String, String> config); }### Answer:
@Test void migrate() { final Map<String, String> config = ws .read(Map.class, "post", "/configurationtype/migrate/amRiYy1jb21wb25lbnQjamRiYyNkYXRhc2V0I2pkYmM/-2", "{}"); assertEquals("true", config.get("configuration.migrated")); assertEquals("1", config.get("configuration.size")); } |
### 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); }, LinkedHashMap::new); } static Collector<T, ?, LinkedHashMap<K, V>> toLinkedMap(
final Function<? super T, ? extends K> keyMapper, final Function<? super T, ? extends V> valueMapper); }### Answer:
@Test void ensureOrderIsPreserved() { final List<String> expected = asList("a", "b", "c"); assertIterableEquals(expected, expected.stream().collect(toLinkedMap(identity(), identity())).keySet()); } |
### Question:
LocaleMapper { public Locale mapLocale(final String requested) { return new Locale(getLanguage(requested).toLowerCase(ENGLISH)); } Locale mapLocale(final String requested); }### Answer:
@Test void mapFr() { assertEquals(Locale.FRENCH, mapper.mapLocale(Locale.FRANCE.toString())); assertEquals(Locale.FRENCH, mapper.mapLocale(Locale.CANADA_FRENCH.toString())); }
@Test void mapDefault() { assertEquals(Locale.ENGLISH, mapper.mapLocale(null)); } |
### Question:
ComponentManagerService { public String deploy(final String pluginGAV) { final String pluginPath = ofNullable(pluginGAV) .map(gav -> mvnCoordinateToFileConverter.toArtifact(gav)) .map(Artifact::toPath) .orElseThrow(() -> new IllegalArgumentException("Plugin GAV can't be empty")); final Path m2 = instance.getContainer().getRootRepositoryLocationPath(); final String plugin = instance.addWithLocationPlugin(pluginGAV, m2.resolve(pluginPath).toAbsolutePath().toString()); lastUpdated = new Date(); if (started) { deployedComponentEvent.fire(new DeployedComponent()); } return plugin; } void startupLoad(@Observes @Initialized(ApplicationScoped.class) final Object start); String deploy(final String pluginGAV); void undeploy(final String pluginGAV); Date findLastUpdated(); @Produces ComponentManager manager(); }### Answer:
@Test void deployExistingPlugin() { try { componentManagerService.deploy("org.talend.test1:the-test-component:jar:1.2.6:compile"); } catch (final IllegalArgumentException iae) { assertTrue(iae.getMessage().contains("Container 'the-test-component' already exists")); } } |
### Question:
ComponentManagerService { public void undeploy(final String pluginGAV) { if (pluginGAV == null || pluginGAV.isEmpty()) { throw new IllegalArgumentException("plugin maven GAV are required to undeploy a plugin"); } String pluginID = instance .find(c -> pluginGAV.equals(c.get(ComponentManager.OriginalId.class).getValue()) ? Stream.of(c.getId()) : empty()) .findFirst() .orElseThrow(() -> new IllegalArgumentException("No plugin found using maven GAV: " + pluginGAV)); instance.removePlugin(pluginID); lastUpdated = new Date(); } void startupLoad(@Observes @Initialized(ApplicationScoped.class) final Object start); String deploy(final String pluginGAV); void undeploy(final String pluginGAV); Date findLastUpdated(); @Produces ComponentManager manager(); }### Answer:
@Test void undeployNonExistingPlugin() { final String gav = "org.talend:non-existing-component:jar:0.0.0:compile"; try { componentManagerService.undeploy(gav); } catch (final RuntimeException re) { assertTrue(re.getMessage().contains("No plugin found using maven GAV: " + gav)); } } |
### Question:
InputImpl extends LifecycleImpl implements Input, Delegated { @Override public Object next() { if (next == null) { init(); } final Object record = readNext(); if (record == null) { return null; } final Class<?> recordClass = record.getClass(); if (recordClass.isPrimitive() || String.class == recordClass) { return record; } return converters.toRecord(registry, record, this::jsonb, this::recordBuilderFactory); } InputImpl(final String rootName, final String name, final String plugin, final Serializable instance); protected InputImpl(); @Override Object next(); @Override Object getDelegate(); }### Answer:
@Test void lifecycle() { final Component delegate = new Component(); final Input input = new InputImpl("Root", "Test", "Plugin", delegate); assertFalse(delegate.start); assertFalse(delegate.stop); assertEquals(0, delegate.count); input.start(); assertTrue(delegate.start); assertFalse(delegate.stop); assertEquals(0, delegate.count); IntStream.range(0, 10).forEach(i -> { final Object next = input.next(); assertTrue(Record.class.isInstance(next)); final Record record = Record.class.cast(next); assertEquals(Schema.Type.RECORD, record.getSchema().getType()); assertEquals(1, record.getSchema().getEntries().size()); final Schema.Entry data = record.getSchema().getEntries().iterator().next(); assertEquals("data", data.getName()); assertEquals(Schema.Type.DOUBLE, data.getType()); assertEquals(i, record.get(Double.class, "data").doubleValue()); assertTrue(delegate.start); assertFalse(delegate.stop); assertEquals(i + 1, delegate.count); }); input.stop(); assertTrue(delegate.start); assertTrue(delegate.stop); assertEquals(10, delegate.count); } |
### Question:
Defaults { public static boolean isDefaultAndShouldHandle(final Method method) { return method.isDefault(); } static boolean isDefaultAndShouldHandle(final Method method); static Object handleDefault(final Class<?> declaringClass, final Method method, final Object proxy,
final Object[] args); }### Answer:
@Test void isDefault() throws NoSuchMethodException { assertFalse(Defaults.isDefaultAndShouldHandle(SomeDefaultsOrNot.class.getMethod("foo"))); assertTrue(Defaults.isDefaultAndShouldHandle(SomeDefaultsOrNot.class.getMethod("defFoo"))); } |
### Question:
LifecycleImpl extends Named implements Lifecycle { @Override public void start() { invoke(PostConstruct.class); } LifecycleImpl(final Object delegate, final String rootName, final String name, final String plugin); protected LifecycleImpl(); @Override void start(); @Override void stop(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test void start() { final StartOnly delegate = new StartOnly(); final Lifecycle impl = new LifecycleImpl(delegate, "Root", "Test", "Plugin"); assertEquals(0, delegate.counter); impl.start(); assertEquals(1, delegate.counter); impl.stop(); assertEquals(1, delegate.counter); } |
### Question:
LifecycleImpl extends Named implements Lifecycle { @Override public void stop() { invoke(PreDestroy.class); } LifecycleImpl(final Object delegate, final String rootName, final String name, final String plugin); protected LifecycleImpl(); @Override void start(); @Override void stop(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test void stop() { final StopOnly delegate = new StopOnly(); final Lifecycle impl = new LifecycleImpl(delegate, "Root", "Test", "Plugin"); assertEquals(0, delegate.counter); impl.start(); assertEquals(0, delegate.counter); impl.stop(); assertEquals(1, delegate.counter); } |
### Question:
AbsolutePathResolver { public String resolveProperty(final String propPath, final String paramRef) { return doResolveProperty(propPath, normalizeParamRef(paramRef)); } String resolveProperty(final String propPath, final String paramRef); }### Answer:
@Test void resolveSibling() { assertEquals("dummy.foo.sibling", resolver.resolveProperty("dummy.foo.bar", "sibling")); }
@Test void resolveSiblingFromParent() { assertEquals("dummy.foo.sibling", resolver.resolveProperty("dummy.foo.bar", "../sibling")); }
@Test void resolveSiblingChild() { assertEquals("dummy.foo.sibling.child", resolver.resolveProperty("dummy.foo.bar", "../sibling/child")); }
@Test void resolveSiblingArray() { assertEquals("dummy.foo[].sibling", resolver.resolveProperty("dummy.foo[].bar", "sibling")); }
@Test void resolveMe() { assertEquals("dummy", resolver.resolveProperty("dummy", ".")); }
@Test void resolveParent() { assertEquals("dummy", resolver.resolveProperty("dummy.foo", "..")); }
@Test void resolveGrandParent() { assertEquals("foo.bar", resolver.resolveProperty("dummy.foo", "../../foo/bar")); }
@Test void resolveChild() { assertEquals("dummy.foo.child", resolver.resolveProperty("dummy.foo", "./child")); }
@Test void resolveGrandChild() { assertEquals("dummy.foo.child.grandchild", resolver.resolveProperty("dummy.foo", "./child/grandchild")); } |
### Question:
InvocationExceptionWrapper { public static RuntimeException toRuntimeException(final InvocationTargetException e) { final Set<Throwable> visited = new HashSet<>(); visited.add(e.getTargetException()); return mapException(e.getTargetException(), visited); } static RuntimeException toRuntimeException(final InvocationTargetException e); }### Answer:
@Test void ensureOriginalIsReplacedToGuaranteeSerializationAccrossClassLoaders() { final RuntimeException mapped = InvocationExceptionWrapper .toRuntimeException(new InvocationTargetException(new CustomException("custom for test"))); assertTrue(ComponentException.class.isInstance(mapped)); assertEquals("(" + CustomException.class.getName() + ") custom for test", mapped.getMessage()); assertTrue(ComponentException.class.isInstance(mapped.getCause())); assertEquals("(" + AnotherException.class.getName() + ") other", mapped.getCause().getMessage()); } |
### Question:
Ui { public static Builder ui() { return new Builder(); } static Builder ui(); }### Answer:
@Test void jsonSchemaTest() { final Ui form1 = ui() .withJsonSchema(jsonSchema() .withType("object") .withTitle("Comment") .withProperty("lastname", jsonSchema().withType("string").build()) .withProperty("firstname", jsonSchema().withType("string").build()) .withProperty("age", jsonSchema().withType("number").build()) .build()) .build(); final String json = jsonb.toJson(form1); assertEquals("{\"jsonSchema\":{\"properties\":{\"lastname\":{\"type\":\"string\"}," + "\"firstname\":{\"type\":\"string\"},\"age\":{\"type\":\"number\"}}," + "\"title\":\"Comment\",\"type\":\"object\"}}", json); }
@Test void uiSchemaTest() { final Ui form1 = ui() .withUiSchema(uiSchema() .withKey("multiSelectTag") .withRestricted(false) .withTitle("Simple multiSelectTag") .withDescription("This datalist accepts values that are not in the list of suggestions") .withTooltip("List of suggestions") .withWidget("multiSelectTag") .build()) .build(); final String json = jsonb.toJson(form1); assertEquals("{\"uiSchema\":[{\"description\":\"This datalist accepts values that are not in the list " + "of suggestions\",\"key\":\"multiSelectTag\",\"restricted\":false,\"title\":\"Simple multiSelectTag\"," + "\"tooltip\":\"List of suggestions\",\"widget\":\"multiSelectTag\"}]}", json); }
@Test void propertiesTest() { final Ui form1 = ui().withJsonSchema(JsonSchema.jsonSchemaFrom(Form1.class).build()).withProperties(new Form1()).build(); final String json = jsonb.toJson(form1); assertEquals("{\"jsonSchema\":{\"properties\":{\"name\":{\"type\":\"string\"}},\"title\":\"Form1\"," + "\"type\":\"object\"},\"properties\":{\"name\":\"foo\"}}", json); } |
### Question:
UiSpecMapperImpl implements UiSpecMapper { @Override public Supplier<Ui> createFormFor(final Class<?> clazz) { return doCreateForm(clazz); } @Override Supplier<Ui> createFormFor(final Class<?> clazz); }### Answer:
@Test void createForm() { final Supplier<Ui> form = new UiSpecMapperImpl(new UiSpecMapperImpl.Configuration(singletonList(new TitleMapProvider() { private int it = 0; @Override public String reference() { return "vendors"; } @Override public Collection<UiSchema.NameValue> get() { return asList(new UiSchema.NameValue.Builder().withName("k" + ++it).withValue("v" + it).build(), new UiSchema.NameValue.Builder().withName("k" + ++it).withValue("v" + it).build()); } }))).createFormFor(ComponentModel.class); IntStream.of(1, 2).forEach(it -> { try (final Jsonb jsonb = JsonbBuilder .create(new JsonbConfig() .withFormatting(true) .withPropertyOrderStrategy(PropertyOrderStrategy.LEXICOGRAPHICAL)); final BufferedReader reader = new BufferedReader(new InputStreamReader( Thread .currentThread() .getContextClassLoader() .getResourceAsStream("component-model-" + it + ".json"), StandardCharsets.UTF_8))) { assertEquals(reader.lines().collect(joining("\n")), jsonb.toJson(form.get())); } catch (final Exception e) { throw new IllegalStateException(e); } }); } |
### Question:
AutoValueFluentApiFactory implements Serializable { public <T> T create(final Class<T> base, final String factoryMethod, final Map<String, Object> config) { try { final Method method = findFactory(base, factoryMethod); return base.cast(setConfig(method.invoke(null), config, "")); } catch (final IllegalAccessException e) { throw new IllegalStateException(e); } catch (final InvocationTargetException e) { throw new IllegalStateException(e.getTargetException()); } } T create(final Class<T> base, final String factoryMethod, final Map<String, Object> config); }### Answer:
@Test void createJDBCInput() throws Exception { final CustomJdbcIO.Read read = new AutoValueFluentApiFactory().create(CustomJdbcIO.Read.class, "read", new HashMap<String, Object>() { { put("dataSourceConfiguration.driverClassName", "org.h2.Driver"); put("dataSourceConfiguration.url", "jdbc:h2:mem:test"); put("dataSourceConfiguration.username", "sa"); put("query", "select * from user"); put("rowMapper", (CustomJdbcIO.RowMapper<JsonObject>) resultSet -> null); } }); final CustomJdbcIO.DataSourceConfiguration dataSourceConfiguration = readField(read, "dataSourceConfiguration", CustomJdbcIO.DataSourceConfiguration.class); assertNotNull(dataSourceConfiguration); assertEquals("org.h2.Driver", readField(dataSourceConfiguration, "driverClassName", String.class)); assertEquals("jdbc:h2:mem:test", readField(dataSourceConfiguration, "url", String.class)); assertEquals("sa", readField(dataSourceConfiguration, "username", String.class)); assertNull(readField(dataSourceConfiguration, "password", String.class)); assertEquals("select * from user", readField(read, "query", ValueProvider.class).get()); assertNotNull(readField(read, "rowMapper", CustomJdbcIO.RowMapper.class)); } |
### Question:
RecordBranchUnwrapper extends DoFn<Record, Record> { public static PTransform<PCollection<Record>, PCollection<Record>> of(final String plugin, final String branchSelector) { return new RecordParDoTransformCoderProvider<>(SchemaRegistryCoder.of(), new RecordBranchUnwrapper(branchSelector)); } RecordBranchUnwrapper(final String branch); protected RecordBranchUnwrapper(); @ProcessElement void onElement(final ProcessContext context); static PTransform<PCollection<Record>, PCollection<Record>> of(final String plugin,
final String branchSelector); }### Answer:
@Test public void test() { PAssert .that(buildBasePipeline(pipeline).apply(RecordBranchMapper.of(null, "b1", "other"))) .satisfies(values -> { final List<Record> items = StreamSupport.stream(values.spliterator(), false).collect(toList()); assertEquals(2, items.size()); items.forEach(item -> { final Collection<Record> other = item.getArray(Record.class, "other"); assertNotNull(other); assertNotNull(other.iterator().next().getString("foo")); assertNull(item.get(Object.class, "b1")); assertNotNull(item.get(Object.class, "b2")); }); return null; }); assertEquals(PipelineResult.State.DONE, pipeline.run().waitUntilFinish()); } |
### Question:
AutoKVWrapper extends DoFn<Record, KV<String, Record>> { public static PTransform<PCollection<Record>, PCollection<KV<String, Record>>> of(final String plugin, final Function<GroupKeyProvider.GroupContext, String> idGenerator, final String component, final String branch) { return new RecordParDoTransformCoderProvider<>(KvCoder.of(StringUtf8Coder.of(), SchemaRegistryCoder.of()), new AutoKVWrapper(idGenerator, component, branch)); } protected AutoKVWrapper(); @ProcessElement void onElement(final ProcessContext context); static PTransform<PCollection<Record>, PCollection<KV<String, Record>>> of(final String plugin,
final Function<GroupKeyProvider.GroupContext, String> idGenerator, final String component,
final String branch); }### Answer:
@Test public void test() { PAssert .that(buildBasePipeline(pipeline) .apply(AutoKVWrapper .of(null, JobImpl.LocalSequenceHolder.cleanAndGet(getClass().getName() + ".test"), "", ""))) .satisfies(values -> { final List<KV<String, Record>> items = StreamSupport .stream(values.spliterator(), false) .sorted(comparing( k -> k.getValue().getArray(Record.class, "b1").iterator().next().getString("foo"))) .collect(toList()); assertEquals(2, items.size()); assertEquals(2, new HashSet<>(items).size()); assertEquals(asList("a", "b"), items .stream() .map(k -> k.getValue().getArray(Record.class, "b1").iterator().next().getString("foo")) .collect(toList())); return null; }); assertEquals(PipelineResult.State.DONE, pipeline.run().waitUntilFinish()); } |
### Question:
RecordBranchFilter extends DoFn<Record, Record> { public static PTransform<PCollection<Record>, PCollection<Record>> of(final String plugin, final String branchSelector) { final RecordBuilderFactory lookup = ServiceLookup.lookup(ComponentManager.instance(), plugin, RecordBuilderFactory.class); return new RecordParDoTransformCoderProvider<>(SchemaRegistryCoder.of(), new RecordBranchFilter(lookup, branchSelector)); } RecordBranchFilter(final RecordBuilderFactory factory, final String branch); protected RecordBranchFilter(); @ProcessElement void onElement(final ProcessContext context); static PTransform<PCollection<Record>, PCollection<Record>> of(final String plugin,
final String branchSelector); }### Answer:
@Test public void test() { PAssert.that(buildBasePipeline(pipeline).apply(RecordBranchFilter.of(null, "b1"))).satisfies(values -> { final List<Record> items = StreamSupport.stream(values.spliterator(), false).collect(toList()); assertEquals(2, items.size()); items.forEach(item -> { assertNull(item.get(Object.class, "b2")); final Object b1 = item.get(Object.class, "b1"); assertNotNull(b1); final Collection<Record> records = Collection.class.cast(b1); assertNotNull(records.stream().map(r -> r.getString("foo")).findFirst().get()); }); return null; }); assertEquals(PipelineResult.State.DONE, pipeline.run().waitUntilFinish()); } |
### Question:
RecordBranchMapper extends DoFn<Record, Record> { public static PTransform<PCollection<Record>, PCollection<Record>> of(final String plugin, final String fromBranch, final String toBranch) { final RecordBuilderFactory lookup = ServiceLookup.lookup(ComponentManager.instance(), plugin, RecordBuilderFactory.class); return new RecordParDoTransformCoderProvider<>(SchemaRegistryCoder.of(), new RecordBranchMapper(lookup, fromBranch, toBranch)); } RecordBranchMapper(final RecordBuilderFactory factory, final String sourceBranch,
final String targetBranch); protected RecordBranchMapper(); @ProcessElement void onElement(final ProcessContext context); static PTransform<PCollection<Record>, PCollection<Record>> of(final String plugin, final String fromBranch,
final String toBranch); }### Answer:
@Test public void test() { PAssert .that(buildBasePipeline(pipeline).apply(RecordBranchMapper.of(null, "b1", "other"))) .satisfies(values -> { final List<Record> items = StreamSupport.stream(values.spliterator(), false).collect(toList()); assertEquals(2, items.size()); items.forEach(item -> { final Collection<Record> other = Collection.class.cast(item.get(Object.class, "other")); assertNotNull(other); assertNotNull(other.iterator().next().getString("foo")); assertNull(item.get(Object.class, "b1")); assertNotNull(item.get(Object.class, "b2")); }); return null; }); assertEquals(PipelineResult.State.DONE, pipeline.run().waitUntilFinish()); } |
### Question:
EnhancedObjectInputStream extends ObjectInputStream { @Override protected Class<?> resolveClass(final ObjectStreamClass desc) throws ClassNotFoundException { final String name = desc.getName(); if (name.equals("boolean")) { return boolean.class; } if (name.equals("byte")) { return byte.class; } if (name.equals("char")) { return char.class; } if (name.equals("short")) { return short.class; } if (name.equals("int")) { return int.class; } if (name.equals("long")) { return long.class; } if (name.equals("float")) { return float.class; } if (name.equals("double")) { return double.class; } doSecurityCheck(name); try { return Class.forName(name, false, loader); } catch (final ClassNotFoundException e) { return Class.forName(name, false, getClass().getClassLoader()); } } protected EnhancedObjectInputStream(final InputStream in, final ClassLoader loader, final Predicate<String> filter); EnhancedObjectInputStream(final InputStream in, final ClassLoader loader); }### Answer:
@Test void whitelist() throws Exception { final byte[] serializationHeader = new byte[] { (byte) (((short) 0xaced >>> 8) & 0xFF), (byte) (((short) 0xaced) & 0xFF), (byte) (((short) 5 >>> 8) & 0xFF), (byte) (((short) 5) & 0xFF) }; final ObjectStreamClass desc = ObjectStreamClass.lookup(Ser.class); assertNotNull(new EnhancedObjectInputStream(new ByteArrayInputStream(serializationHeader), Thread.currentThread().getContextClassLoader(), name -> name .equals("org.talend.sdk.component.runtime.serialization.EnhancedObjectInputStreamTest$Ser")) { }.resolveClass(desc)); assertThrows(SecurityException.class, () -> new EnhancedObjectInputStream( new ByteArrayInputStream(serializationHeader), Thread.currentThread().getContextClassLoader(), name -> name.equals("org.talend.sdk.component.runtime.serialization.EnhancedObjectInputStream")) { }.resolveClass(desc)); } |
### Question:
ContextualSerializableCoder extends SerializableCoder<T> { public static <T extends Serializable> SerializableCoder<T> of(final Class<T> type, final String plugin) { return new ContextualSerializableCoder<>(type, TypeDescriptor.of(type), plugin); } protected ContextualSerializableCoder(); private ContextualSerializableCoder(final Class<T> type, final TypeDescriptor<T> typeDescriptor,
final String plugin); static SerializableCoder<T> of(final Class<T> type, final String plugin); @Override void encode(final T value, final OutputStream outStream); @Override T decode(final InputStream inStream); @Override boolean equals(final Object other); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void roundTrip() { final Ser ser = SerializableUtils .ensureSerializableByCoder(ContextualSerializableCoder.of(Ser.class, "test"), new Ser(5), "test"); assertEquals(5, ser.value); } |
### Question:
AvroRecord implements Record, AvroPropertyMapper, Unwrappable { @Override public Schema getSchema() { return schema; } AvroRecord(final IndexedRecord record); AvroRecord(final Record record); @Override Schema getSchema(); @Override T get(final Class<T> expectedType, final String name); @Override Collection<T> getArray(final Class<T> type, final String name); @Override T unwrap(final Class<T> type); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void providedSchemaGetSchema() { final Schema schema = new AvroSchemaBuilder() .withType(Schema.Type.RECORD) .withEntry(new SchemaImpl.EntryImpl.BuilderImpl() .withName("name") .withNullable(true) .withType(Schema.Type.STRING) .build()) .build(); assertEquals(schema, new AvroRecordBuilder(schema).withString("name", "ok").build().getSchema()); } |
### Question:
AvroRecord implements Record, AvroPropertyMapper, Unwrappable { @Override public <T> T get(final Class<T> expectedType, final String name) { if (expectedType == Collection.class) { return expectedType.cast(getArray(Object.class, name)); } return doGet(expectedType, name); } AvroRecord(final IndexedRecord record); AvroRecord(final Record record); @Override Schema getSchema(); @Override T get(final Class<T> expectedType, final String name); @Override Collection<T> getArray(final Class<T> type, final String name); @Override T unwrap(final Class<T> type); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void stringGetObject() { final GenericData.Record avro = new GenericData.Record(org.apache.avro.Schema .createRecord(getClass().getName() + ".StringTest", null, null, false, singletonList(new org.apache.avro.Schema.Field("str", org.apache.avro.Schema.create(org.apache.avro.Schema.Type.STRING), null, null)))); avro.put(0, new Utf8("test")); final Record record = new AvroRecord(avro); final Object str = record.get(Object.class, "str"); assertFalse(str.getClass().getName(), Utf8.class.isInstance(str)); assertEquals("test", str); } |
### Question:
AvroSchema implements org.talend.sdk.component.api.record.Schema, AvroPropertyMapper, Unwrappable { @Override public List<Entry> getEntries() { if (getActualDelegate().getType() != Schema.Type.RECORD) { return emptyList(); } if (entries != null) { return entries; } synchronized (this) { if (entries != null) { return entries; } entries = getActualDelegate().getFields().stream().filter(it -> it.schema().getType() != NULL).map(field -> { final Type type = mapType(field.schema()); final AvroSchema elementSchema = new AvroSchema( type == Type.ARRAY ? unwrapUnion(field.schema()).getElementType() : field.schema()); return new SchemaImpl.EntryImpl(field.name(), field.getProp(KeysForAvroProperty.LABEL), type, field.schema().getType() == UNION, field.defaultVal(), elementSchema, field.doc()); }).collect(toList()); } return entries; } @Override Type getType(); @Override org.talend.sdk.component.api.record.Schema getElementSchema(); @Override List<Entry> getEntries(); @Override T unwrap(final Class<T> type); }### Answer:
@Test void nullField() { final AvroSchema schema = new AvroSchema(Schema .createRecord(singletonList(new Schema.Field("nf", Schema.create(Schema.Type.NULL), null, null)))); assertTrue(schema.getEntries().isEmpty()); assertEquals("AvroSchema(delegate={\"type\":\"record\",\"fields\":[{\"name\":\"nf\",\"type\":\"null\"}]})", schema.toString()); } |
### Question:
AvroRecordBuilder extends RecordImpl.BuilderImpl { @Override public Record build() { return new AvroRecord(super.build()); } AvroRecordBuilder(); AvroRecordBuilder(final Schema providedSchema); @Override Record build(); }### Answer:
@Test void copySchema() { final Schema custom = factory .newSchemaBuilder(baseSchema) .withEntry(factory.newEntryBuilder().withName("custom").withType(STRING).build()) .build(); assertEquals("name/STRING/current name,age/INT/null,address/RECORD/@address,custom/STRING/null", custom .getEntries() .stream() .map(it -> it.getName() + '/' + it.getType() + '/' + it.getRawName()) .collect(joining(","))); }
@Test void copyRecord() { final Schema customSchema = factory .newSchemaBuilder(baseSchema) .withEntry(factory.newEntryBuilder().withName("custom").withType(STRING).build()) .build(); final Record baseRecord = factory .newRecordBuilder(baseSchema) .withString("name", "Test") .withInt("age", 33) .withRecord("address", factory.newRecordBuilder(address).withString("street", "here").withInt("number", 1).build()) .build(); final Record output = factory.newRecordBuilder(customSchema, baseRecord).withString("custom", "added").build(); assertEquals( "AvroRecord{delegate={\"name\": \"Test\", \"age\": 33, \"address\": {\"street\": \"here\", \"number\": 1}, \"custom\": \"added\"}}", output.toString()); } |
### Question:
BeamComponentExtension implements ComponentExtension { @Override public <T> T unwrap(final Class<T> type, final Object... args) { if ("org.talend.sdk.component.design.extension.flows.FlowsFactory".equals(type.getName()) && args != null && args.length == 1 && ComponentFamilyMeta.BaseMeta.class.isInstance(args[0])) { if (ComponentFamilyMeta.ProcessorMeta.class.isInstance(args[0])) { try { final FlowsFactory factory = FlowsFactory.get(ComponentFamilyMeta.BaseMeta.class.cast(args[0])); factory.getOutputFlows(); return type.cast(factory); } catch (final Exception e) { return type.cast(BeamFlowFactory.OUTPUT); } } } if (type.isInstance(this)) { return type.cast(this); } return null; } @Override boolean isActive(); @Override T unwrap(final Class<T> type, final Object... args); @Override Collection<ClassFileTransformer> getTransformers(); @Override void onComponent(final ComponentContext context); @Override boolean supports(final Class<?> componentType); @Override Map<Class<?>, Object> getExtensionServices(final String plugin); @Override T convert(final ComponentInstance instance, final Class<T> component); @Override Collection<String> getAdditionalDependencies(); }### Answer:
@Test void flowFactory() { final FlowsFactory factory = extension .unwrap(FlowsFactory.class, new ComponentFamilyMeta.ProcessorMeta( new ComponentFamilyMeta("test", emptyList(), null, "test", "test"), "beam", null, 1, BeamMapper.class, Collections::emptyList, null, null, true) { }); assertEquals(1, factory.getInputFlows().size()); assertEquals(asList("main1", "main2"), factory.getOutputFlows()); } |
### Question:
TCCLContainerFinder implements ContainerFinder { @Override public LightContainer find(final String plugin) { return DELEGATE; } @Override LightContainer find(final String plugin); }### Answer:
@Test void tccl() { assertEquals(Thread.currentThread().getContextClassLoader(), new TCCLContainerFinder().find(null).classloader()); } |
### Question:
BeamComponentExtension implements ComponentExtension { @Override public boolean supports(final Class<?> componentType) { return componentType == Mapper.class || componentType == Processor.class; } @Override boolean isActive(); @Override T unwrap(final Class<T> type, final Object... args); @Override Collection<ClassFileTransformer> getTransformers(); @Override void onComponent(final ComponentContext context); @Override boolean supports(final Class<?> componentType); @Override Map<Class<?>, Object> getExtensionServices(final String plugin); @Override T convert(final ComponentInstance instance, final Class<T> component); @Override Collection<String> getAdditionalDependencies(); }### Answer:
@Test void supports() { assertTrue(extension.supports(Mapper.class)); assertTrue(extension.supports(Processor.class)); } |
### Question:
LazyMap extends ConcurrentHashMap<A, B> { @Override public B get(final Object key) { B value = super.get(key); if (value == null) { final A castedKey = (A) (key); synchronized (this) { value = super.get(key); if (value == null) { final B created = lazyFactory.apply(castedKey); if (created != null) { put(castedKey, created); return created; } } } } return value; } LazyMap(final int capacity, final Function<A, B> lazyFactory); @Override B get(final Object key); }### Answer:
@Test void get() { LazyMap<Integer, Integer> map = new LazyMap<>(30, this::multiplyTwo); Assertions.assertEquals(2, map.get(1)); Assertions.assertEquals(1, this.multiplyTwoSollicitation); Assertions.assertEquals(2, map.get(1)); Assertions.assertEquals(1, this.multiplyTwoSollicitation); Assertions.assertEquals(8, map.get(4)); Assertions.assertEquals(2, this.multiplyTwoSollicitation); Assertions.assertEquals(null, map.get(0)); Assertions.assertEquals(3, this.multiplyTwoSollicitation); Assertions.assertEquals(null, map.get(0)); Assertions.assertEquals(4, this.multiplyTwoSollicitation); } |
### Question:
MemoizingSupplier implements Supplier<T> { @Override public T get() { if (value == null) { lock.lock(); try { if (value == null) { value = delegate.get(); } } finally { lock.unlock(); } } return value; } MemoizingSupplier(final Supplier<T> delegate); @Override T get(); }### Answer:
@Test void get() { MemoizingSupplier<String> supplier = new MemoizingSupplier<String>(this::hello); Runnable r = () -> supplier.get(); List<Thread> threads = new ArrayList<>(); for (int i = 0; i < 8; i++) { threads.add(new Thread(r)); } threads.forEach(Thread::start); threads.forEach((Thread t) -> { try { t.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); Assertions.assertEquals("Hello", supplier.get()); Assertions.assertEquals(1, n); } |
### Question:
ComponentManager implements AutoCloseable { public static ComponentManager instance() { return SingletonHolder.CONTEXTUAL_INSTANCE.get(); } ComponentManager(final File m2); ComponentManager(final File m2, final String dependenciesResource, final String jmxNamePattern); ComponentManager(final Path m2); ComponentManager(final Path m2, final String dependenciesResource, final String jmxNamePattern); static ComponentManager instance(); static Path findM2(); void addCallerAsPlugin(); Stream<T> find(final Function<Container, Stream<T>> mapper); Optional<Object> createComponent(final String plugin, final String name, final ComponentType componentType,
final int version, final Map<String, String> configuration); void autoDiscoverPlugins(final boolean callers, final boolean classpath); Optional<Mapper> findMapper(final String plugin, final String name, final int version,
final Map<String, String> configuration); Optional<org.talend.sdk.component.runtime.output.Processor> findProcessor(final String plugin,
final String name, final int version, final Map<String, String> configuration); boolean hasPlugin(final String plugin); Optional<Container> findPlugin(final String plugin); synchronized String addPlugin(final String pluginRootFile); String addWithLocationPlugin(final String location, final String pluginRootFile); void removePlugin(final String id); @Override void close(); List<String> availablePlugins(); }### Answer:
@Test void testInstance() throws InterruptedException { final ComponentManager[] managers = new ComponentManager[60]; Thread[] th = new Thread[managers.length]; for (int ind = 0; ind < th.length; ind++) { final int indice = ind; th[ind] = new Thread(() -> { managers[indice] = ComponentManager.instance(); }); th[ind].start(); } for (int ind = 0; ind < th.length; ind++) { th[ind].join(); } Assertions.assertNotNull(managers[0]); for (int i = 1; i < managers.length; i++) { Assertions.assertSame(managers[0], managers[i], "manager " + i + " is another instance"); } } |
### Question:
LocalDateConverter extends AbstractConverter { @Override protected Object toObjectImpl(final String text) { if (text.isEmpty()) { return null; } return ZonedDateTime.class.cast(new ZonedDateTimeConverter().toObjectImpl(text)).toLocalDate(); } LocalDateConverter(); }### Answer:
@Test void ensureItToleratesAnotherFormat() { final LocalDateTime localDateTime = LocalDateTime.now(); assertEquals(localDateTime.toLocalDate(), new LocalDateConverter().toObjectImpl(localDateTime.toString())); }
@Test void nativeFormat() { final LocalDate localDate = LocalDate.now(); assertEquals(localDate, new LocalDateConverter().toObjectImpl(localDate.toString())); } |
### Question:
IconFinder { public Optional<String> findDirectIcon(final AnnotatedElement type) { return ofNullable(type.getAnnotation(Icon.class)) .map(i -> i.value() == Icon.IconType.CUSTOM ? of(i.custom()).filter(s -> !s.isEmpty()).orElse("default") : i.value().getKey()); } String findIcon(final AnnotatedElement type); Optional<String> findIndirectIcon(final AnnotatedElement type); Optional<String> findDirectIcon(final AnnotatedElement type); boolean isCustom(final Annotation icon); Annotation extractIcon(final AnnotatedElement annotatedElement); }### Answer:
@Test void findDirectIcon() { assertFalse(finder.findDirectIcon(None.class).isPresent()); assertEquals("foo", finder.findDirectIcon(Direct.class).get()); } |
### Question:
IconFinder { public Optional<String> findIndirectIcon(final AnnotatedElement type) { return ofNullable(findMetaIconAnnotation(type) .map(this::getMetaIcon) .orElseGet(() -> findImplicitIcon(type).orElse(null))); } String findIcon(final AnnotatedElement type); Optional<String> findIndirectIcon(final AnnotatedElement type); Optional<String> findDirectIcon(final AnnotatedElement type); boolean isCustom(final Annotation icon); Annotation extractIcon(final AnnotatedElement annotatedElement); }### Answer:
@Test void findInDirectIcon() { assertFalse(finder.findDirectIcon(Indirect.class).isPresent()); assertEquals("yes", finder.findIndirectIcon(Indirect.class).get()); } |
### Question:
IconFinder { public String findIcon(final AnnotatedElement type) { return findDirectIcon(type).orElseGet(() -> findIndirectIcon(type).orElse("default")); } String findIcon(final AnnotatedElement type); Optional<String> findIndirectIcon(final AnnotatedElement type); Optional<String> findDirectIcon(final AnnotatedElement type); boolean isCustom(final Annotation icon); Annotation extractIcon(final AnnotatedElement annotatedElement); }### Answer:
@Test void findIcon() { assertEquals("foo", finder.findIcon(Direct.class)); assertEquals("yes", finder.findIcon(Indirect.class)); assertEquals("default", finder.findIcon(None.class)); } |
### Question:
ConfigurationTypeParameterEnricher extends BaseParameterEnricher { @Override public Map<String, String> onParameterAnnotation(final String parameterName, final Type parameterType, final Annotation annotation) { final ConfigurationType configType = annotation.annotationType().getAnnotation(ConfigurationType.class); if (configType != null) { final String type = configType.value(); final String name = getName(annotation); if (name != null) { return new HashMap<String, String>() { { put(META_PREFIX + "type", type); put(META_PREFIX + "name", name); } }; } } return emptyMap(); } @Override Map<String, String> onParameterAnnotation(final String parameterName, final Type parameterType,
final Annotation annotation); static final String META_PREFIX; }### Answer:
@Test void readConfigTypes() { final ConfigurationTypeParameterEnricher enricher = new ConfigurationTypeParameterEnricher(); assertEquals(new HashMap<String, String>() { { put("tcomp::configurationtype::type", "dataset"); put("tcomp::configurationtype::name", "test"); } }, enricher.onParameterAnnotation("testParam", null, new DataSet() { @Override public Class<? extends Annotation> annotationType() { return DataSet.class; } @Override public String value() { return "test"; } })); assertEquals(emptyMap(), enricher.onParameterAnnotation("testParam", null, new Override() { @Override public Class<? extends Annotation> annotationType() { return Override.class; } })); } |
### Question:
ResolverImpl implements Resolver, Serializable { @Override public Collection<File> resolveFromDescriptor(final InputStream descriptor) { try { return new MvnDependencyListLocalRepositoryResolver(null, fileResolver) .resolveFromDescriptor(descriptor) .map(Artifact::toPath) .map(fileResolver) .map(Path::toFile) .collect(toList()); } catch (final IOException e) { throw new IllegalArgumentException(e); } } @Override ClassLoaderDescriptor mapDescriptorToClassLoader(final InputStream descriptor); @Override Collection<File> resolveFromDescriptor(final InputStream descriptor); }### Answer:
@Test void resolvefromDescriptor() throws IOException { try (final InputStream stream = new ByteArrayInputStream("The following files have been resolved:\njunit:junit:jar:4.12:compile" .getBytes(StandardCharsets.UTF_8))) { final Collection<File> deps = new ResolverImpl(null, coord -> PathFactory.get("maven2").resolve(coord)) .resolveFromDescriptor(stream); assertEquals(1, deps.size()); assertEquals("maven2" + File.separator + "junit" + File.separator + "junit" + File.separator + "4.12" + File.separator + "junit-4.12.jar", deps.iterator().next().getPath()); } } |
### Question:
HttpRequest { public Optional<byte[]> getBody() { if (bodyCache != null) { return bodyCache; } synchronized (this) { if (bodyCache != null) { return bodyCache; } return bodyCache = doGetBody(); } } Optional<byte[]> getBody(); Configurer.ConfigurerConfiguration getConfigurationOptions(); }### Answer:
@Test void getBodyIsCalledOnce() { final AtomicInteger counter = new AtomicInteger(); final HttpRequest httpRequest = new HttpRequest("foo", "GET", emptyList(), emptyMap(), null, emptyMap(), (a, b) -> { assertEquals(0, counter.getAndIncrement()); return Optional.of(new byte[0]); }, new Object[0], null); assertEquals(0, counter.get()); IntStream.range(0, 3).forEach(idx -> { assertTrue(httpRequest.getBody().isPresent()); assertEquals(1, counter.get()); }); } |
### Question:
ObjectFactoryImpl implements ObjectFactory, Serializable { @Override public ObjectFactoryInstance createInstance(final String type) { final ObjectRecipe recipe = new ObjectRecipe(type); recipe.setRegistry(registry); return new ObjectFactoryInstanceImpl(recipe); } @Override ObjectFactoryInstance createInstance(final String type); }### Answer:
@Test void createDefaults() { assertEquals("test(setter)/0", factory .createInstance("org.talend.sdk.component.runtime.manager.service.ObjectFactoryImplTest$Created") .ignoreUnknownProperties() .withProperties(new HashMap<String, String>() { { put("name", "test"); put("age", "30"); } }) .create(Supplier.class) .get()); }
@Test void createFields() { assertEquals("test/30", factory .createInstance("org.talend.sdk.component.runtime.manager.service.ObjectFactoryImplTest$Created") .withFieldInjection() .withProperties(new HashMap<String, String>() { { put("name", "test"); put("age", "30"); } }) .create(Supplier.class) .get()); }
@Test void failOnUnknown() { assertThrows(IllegalArgumentException.class, () -> factory .createInstance("org.talend.sdk.component.runtime.manager.service.ObjectFactoryImplTest$Created") .withProperties(new HashMap<String, String>() { { put("name", "test"); put("age", "30"); } }) .create(Supplier.class)); } |
### Question:
AbstractContact implements IContact { public boolean isNewbie() { return newbie; } boolean isUnknown(); void setUnknown(boolean unknown); boolean isNewbie(); void setNewbie(boolean newbie); IMessage getLastMessage(); void setLastMessage(IMessage lastMessage); int getUnread(); void setUnread(int unread); void clearUnRead(); void increaceUnRead(); int compareTo(AbstractContact that); }### Answer:
@Test public void testIsNewbie() { assertEquals(false, contact.isNewbie()); } |
### Question:
AbstractContact implements IContact { public void setNewbie(boolean newbie) { this.newbie = newbie; } boolean isUnknown(); void setUnknown(boolean unknown); boolean isNewbie(); void setNewbie(boolean newbie); IMessage getLastMessage(); void setLastMessage(IMessage lastMessage); int getUnread(); void setUnread(int unread); void clearUnRead(); void increaceUnRead(); int compareTo(AbstractContact that); }### Answer:
@Test public void testSetNewbie() { contact.setNewbie(true); assertEquals(true, contact.isNewbie()); } |
### Question:
AbstractContact implements IContact { public IMessage getLastMessage() { return lastMessage; } boolean isUnknown(); void setUnknown(boolean unknown); boolean isNewbie(); void setNewbie(boolean newbie); IMessage getLastMessage(); void setLastMessage(IMessage lastMessage); int getUnread(); void setUnread(int unread); void clearUnRead(); void increaceUnRead(); int compareTo(AbstractContact that); }### Answer:
@Test public void testGetLastMessage() { assertEquals(null, contact.getLastMessage()); } |
### Question:
AbstractContact implements IContact { public void setLastMessage(IMessage lastMessage) { this.lastMessage = lastMessage; } boolean isUnknown(); void setUnknown(boolean unknown); boolean isNewbie(); void setNewbie(boolean newbie); IMessage getLastMessage(); void setLastMessage(IMessage lastMessage); int getUnread(); void setUnread(int unread); void clearUnRead(); void increaceUnRead(); int compareTo(AbstractContact that); }### Answer:
@Test public void testSetLastMessage() { MockMessage m = new MockMessage("m1"); contact.setLastMessage(m); MockMessage m2 = new MockMessage("m2"); contact.setLastMessage(m2); assertEquals(m2, contact.getLastMessage()); } |
### Question:
AbstractContact implements IContact { public int getUnread() { return unread; } boolean isUnknown(); void setUnknown(boolean unknown); boolean isNewbie(); void setNewbie(boolean newbie); IMessage getLastMessage(); void setLastMessage(IMessage lastMessage); int getUnread(); void setUnread(int unread); void clearUnRead(); void increaceUnRead(); int compareTo(AbstractContact that); }### Answer:
@Test public void testGetUnread() { assertEquals(0, contact.getUnread()); } |
### Question:
AbstractContact implements IContact { public void setUnread(int unread) { this.unread = unread; } boolean isUnknown(); void setUnknown(boolean unknown); boolean isNewbie(); void setNewbie(boolean newbie); IMessage getLastMessage(); void setLastMessage(IMessage lastMessage); int getUnread(); void setUnread(int unread); void clearUnRead(); void increaceUnRead(); int compareTo(AbstractContact that); }### Answer:
@Test public void testSetUnread() { contact.setUnread(1); assertEquals(1, contact.getUnread()); } |
### Question:
AbstractContact implements IContact { public void clearUnRead() { this.unread = 0; } boolean isUnknown(); void setUnknown(boolean unknown); boolean isNewbie(); void setNewbie(boolean newbie); IMessage getLastMessage(); void setLastMessage(IMessage lastMessage); int getUnread(); void setUnread(int unread); void clearUnRead(); void increaceUnRead(); int compareTo(AbstractContact that); }### Answer:
@Test public void testClearUnRead() { contact.setUnread(10); contact.clearUnRead(); assertEquals(0, contact.getUnread()); } |
### Question:
AbstractContact implements IContact { public void increaceUnRead() { this.unread += 1; } boolean isUnknown(); void setUnknown(boolean unknown); boolean isNewbie(); void setNewbie(boolean newbie); IMessage getLastMessage(); void setLastMessage(IMessage lastMessage); int getUnread(); void setUnread(int unread); void clearUnRead(); void increaceUnRead(); int compareTo(AbstractContact that); }### Answer:
@Test public void testIncreaceUnRead() { contact.increaceUnRead(); assertEquals(1, contact.getUnread()); contact.increaceUnRead(); assertEquals(2, contact.getUnread()); } |
### Question:
AbstractContact implements IContact { public int compareTo(AbstractContact that) { int ret = 0; if (this.lastMessage != null) { if (that.lastMessage != null) { IMessage m1 = this.lastMessage; IMessage m2 = that.lastMessage; long diff = (m2.getTime() - m1.getTime()); if (diff > 0) { ret = 1; } else if (diff < 0) { ret = -1; } } else { ret = -1; } } else if (that.lastMessage != null) { ret = 1; } return ret; } boolean isUnknown(); void setUnknown(boolean unknown); boolean isNewbie(); void setNewbie(boolean newbie); IMessage getLastMessage(); void setLastMessage(IMessage lastMessage); int getUnread(); void setUnread(int unread); void clearUnRead(); void increaceUnRead(); int compareTo(AbstractContact that); }### Answer:
@Test public void testCompareTo() { MockContact contact2 = new MockContact("K", "2"); List<MockContact> list = new ArrayList<>(); list.add(contact); list.add(contact2); Collections.sort(list); assertEquals(contact, list.get(0)); MockMessage m = new MockMessage("m1"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } MockMessage m2 = new MockMessage("m2"); System.out.println("m1 time:" + m.getTime() + " m2 time: " + m2.getTime()); contact2.setLastMessage(m2); Collections.sort(list); assertEquals(contact2, list.get(0)); contact.setLastMessage(m); Collections.sort(list); assertEquals(contact2, list.get(0)); contact2.setLastMessage(null); Collections.sort(list); assertEquals(contact, list.get(0)); } |
### Question:
QNUploader { public AuthInfo getToken(String qq, String ak, String sk, String bucket, String key) throws Exception { RequestBody body = new FormBody.Builder().add("key", key) .add("bucket", bucket).add("qq", qq).build(); Request.Builder builder = new Request.Builder().url(API_GET_TOKEN) .addHeader("accessKey", ak).addHeader("secretKey", sk) .post(body); Request request = builder.build(); Call call = this.client.newCall(request); Response response = call.execute(); AuthResponse info = null; String json = response.body().string(); System.out.println(json); if (response.code() == 200) { info = new Gson().fromJson(json, AuthResponse.class); } if (info == null) { throw new RuntimeException(response.message()); } if (info.code != 0 || info.data == null) { throw new RuntimeException(info.msg); } return info.data; } QNUploader(); AuthInfo getToken(String qq, String ak, String sk, String bucket,
String key); UploadInfo upload(String qq, File file, String ak, String sk,
String bucket, Zone zone); static String API_URL; static String API_GET_TOKEN; static String API_CALLBACK; }### Answer:
@Test public void testGetToken() { QNUploader uploader = new QNUploader(); try { AuthInfo auth = uploader.getToken("157250921_1", "", "", "", "qrcode.png"); System.out.println(auth); assertNotNull(auth); assertNotNull(auth.token); assertEquals("http: assertEquals(1, auth.days); assertEquals(8 << 20, auth.limit); auth = uploader.getToken("157250921_1", "ak", "sk", "", "qrcode.png"); System.out.println(auth); assertNotNull(auth); assertEquals(0, auth.days); assertEquals(0 << 20, auth.limit); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } |
### Question:
WechatMessageHandler implements MessageHandler<WechatMessage> { @Override public WechatMessage handle(JsonObject result) { WechatMessage msg = gson.fromJson(result, WechatMessage.class); msg.setRaw(result.toString()); return msg; } @Override WechatMessage handle(JsonObject result); @Override WechatMessage handle(String json); List<WechatMessage> handleAll(JsonObject dic); }### Answer:
@Test public void test() { String json = p.getProperty("m.init"); WechatMessage msg = (WechatMessage) handler.handle(json); assertEquals(WechatMessage.MSGTYPE_STATUSNOTIFY, msg.MsgType); System.out.println(msg.getText()); assertEquals("@b07a26ddbe1bc6a60c2d6f5cbe4c8581", msg.FromUserName); json = p.getProperty("m.g.me"); msg = (WechatMessage) handler.handle(json); gmInterceptor.handle(msg); assertEquals(WechatMessage.MSGTYPE_TEXT, msg.MsgType); System.out.println(msg.getText()); assertEquals("my msg", msg.getText()); assertEquals("@857308baac029b0748006b3432db8444", msg.FromUserName); assertTrue(msg.groupId.startsWith("@@")); json = p.getProperty("m.g.you"); msg = (WechatMessage) handler.handle(json); gmInterceptor.handle(msg); assertEquals(WechatMessage.MSGTYPE_TEXT, msg.MsgType); System.out.println(msg.getText()); assertEquals("other msg", msg.getText()); assertEquals("@88dcb5228fb45890df826b95671e770c", msg.src); assertTrue(msg.groupId.startsWith("@@")); } |
### Question:
UserInfoHandler extends AbstractContactHandler<UserInfo> { @Override public UserInfo handle(JsonObject result) { return gson.fromJson(result, UserInfo.class); } @Override UserInfo handle(JsonObject result); @Override List<UserInfo> handle(JsonArray array); }### Answer:
@Test public void testHandleJsonObject() { String json = FileUtils.readString(getClass().getResourceAsStream( "get_self_info2.json"), null); JsonObject obj = new JsonParser().parse(json).getAsJsonObject().getAsJsonObject("result"); UserInfo t = new UserInfoHandler().handle(obj); assertEquals("157250921", t.getAccount()); } |
### Question:
InitMsgXmlHandler extends AbstractMsgXmlHandler { public String getRecents() { try { Node node = root.element("op").element("username"); return node.getText().trim(); } catch (Exception e) { return null; } } InitMsgXmlHandler(); InitMsgXmlHandler(WechatMessage m); String getRecents(); }### Answer:
@Test public void testGetRecents() { String recents = handler.getRecents(); Assert.assertNotNull(recents); System.out.println(recents); String[] array = recents.split(","); System.out.println(Arrays.toString(array)); assertEquals("filehelper", array[0]); } |
### Question:
AppMsgXmlHandler extends AbstractMsgXmlHandler { public AppMsgInfo decode() { AppMsgInfo info = new AppMsgInfo(); try { Element node = root.element("appmsg"); info.appId = node.attributeValue("appid"); info.title = node.elementTextTrim("title"); info.desc = node.elementTextTrim("des"); String showType = node.elementTextTrim("showtype"); String type = node.elementTextTrim("type"); info.msgType = StringUtils.getInt(type, 0); info.showType = StringUtils.getInt(showType, 0); info.url = node.elementTextTrim("url"); if (info.url != null) { info.url = EncodeUtils.decodeXml(info.url); } node = root.element("appinfo"); info.appName = node.elementTextTrim("appname"); if (message != null) { message.AppMsgInfo = info; } } catch (Exception e) { return null; } return info; } AppMsgXmlHandler(); AppMsgXmlHandler(WechatMessage m); String encode(File file, String mediaId); AppMsgInfo decode(); String getHtml(String link); }### Answer:
@Test public void testGetRecents() { AppMsgInfo info = handler.decode(); Assert.assertEquals("南京abc.xlsx", info.title); System.out.println(info); WechatMessage m = from("appmsg-publisher.xml"); handler = new AppMsgXmlHandler(m); info = handler.decode(); Assert.assertEquals("谷歌开发者", info.appName); System.out.println(info); } |
### Question:
WXUtils { public static char getContactChar(IContact contact) { if (contact instanceof Contact) { Contact c = (Contact)contact; char ch = 'F'; if (c.isPublic()) { ch = 'P'; } else if (c.isGroup()) { ch = 'G'; } else if (c.is3rdApp() || c.isSpecial()) { ch = 'S'; } return ch; } return 0; } static char getContactChar(IContact contact); static String decodeEmoji(String src); static String getPureName(String name); static String formatHtmlOutgoing(String name, String msg, boolean encode); static String formatHtmlIncoming(WechatMessage m, AbstractFrom from); }### Answer:
@Test public void testGetContactChar() { Contact contact = new Contact(); contact.UserName = "@J"; char c = WXUtils.getContactChar(contact); assertEquals(c, 'F'); } |
### Question:
WXUtils { public static String decodeEmoji(String src) { String regex = EncodeUtils.encodeXml("<span class=\"emoji[\\w\\s]*\"></span>"); Pattern p = Pattern.compile(regex, Pattern.MULTILINE); Matcher m = p.matcher(src); List<String> groups = new ArrayList<>(); List<Integer> starts = new ArrayList<>(); List<Integer> ends = new ArrayList<>(); while (m.find()) { starts.add(m.start()); ends.add(m.end()); groups.add(m.group()); } if (!starts.isEmpty()) { StringBuilder sb = new StringBuilder(src); int offset = 0; for (int i = 0; i < starts.size(); i++) { int s = starts.get(i); int e = ends.get(i); String g = groups.get(i); int pos = offset + s; sb.delete(pos, offset + e); String ng = g; ng = EncodeUtils.decodeXml(g); sb.insert(pos, ng); offset += ng.length() - g.length(); } return sb.toString(); } return src; } static char getContactChar(IContact contact); static String decodeEmoji(String src); static String getPureName(String name); static String formatHtmlOutgoing(String name, String msg, boolean encode); static String formatHtmlIncoming(WechatMessage m, AbstractFrom from); }### Answer:
@Test public void testDecodeEmoji() { } |
### Question:
WXUtils { public static String getPureName(String name) { String regex = "<span class=\"emoji[\\w\\s]*\"></span>"; return name.replaceAll(regex, "").trim(); } static char getContactChar(IContact contact); static String decodeEmoji(String src); static String getPureName(String name); static String formatHtmlOutgoing(String name, String msg, boolean encode); static String formatHtmlIncoming(WechatMessage m, AbstractFrom from); }### Answer:
@Test public void testGetPureName() { String n = WXUtils .getPureName("一个emoji<span class=\"emoji emoji23434\"></span>"); assertEquals("一个emoji", n); n = WXUtils.getPureName( "2个emoji<span class=\"emoji emoji23434\"></span> <span class=\"emoji emoji23434\"></span>"); assertEquals("2个emoji", n); n = WXUtils.getPureName( "2个emoji<span class=\"emoji emoji23434\"></span>中<span class=\"emoji emoji23434\"></span>"); assertEquals("2个emoji中", n); n = WXUtils.getPureName( "一个emoji<span class=\"emoji emoji23434\"></span>一个emoji"); assertEquals("一个emoji一个emoji", n); } |
### Question:
AbstractContact implements IContact { public boolean isUnknown() { return unknown; } boolean isUnknown(); void setUnknown(boolean unknown); boolean isNewbie(); void setNewbie(boolean newbie); IMessage getLastMessage(); void setLastMessage(IMessage lastMessage); int getUnread(); void setUnread(int unread); void clearUnRead(); void increaceUnRead(); int compareTo(AbstractContact that); }### Answer:
@Test public void testIsUnknown() { assertEquals(false, contact.isUnknown()); } |
### Question:
AbstractContact implements IContact { public void setUnknown(boolean unknown) { this.unknown = unknown; } boolean isUnknown(); void setUnknown(boolean unknown); boolean isNewbie(); void setNewbie(boolean newbie); IMessage getLastMessage(); void setLastMessage(IMessage lastMessage); int getUnread(); void setUnread(int unread); void clearUnRead(); void increaceUnRead(); int compareTo(AbstractContact that); }### Answer:
@Test public void testSetUnknown() { contact.setUnknown(true); assertEquals(true, contact.isUnknown()); } |
### Question:
ServiceContext { public synchronized void addListener(final ServiceChangeListener listener) { if (listener == null) { return; } listeners.add(listener); } ServiceContext(DiscoveryConfig discoveryConfig); DiscoveryConfig getDiscoveryConfig(); synchronized Service newService(); synchronized void setService(Service service); synchronized boolean deleteInstance(Instance instance); synchronized boolean updateInstance(Instance instance); synchronized boolean addInstance(Instance instance); synchronized boolean isAvailable(); synchronized Set<ServiceChangeListener> getListeners(); synchronized void addListener(final ServiceChangeListener listener); ServiceChangeEvent newServiceChangeEvent(final String changeType); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object other); }### Answer:
@Test public void testAddListener() { final ServiceChangeListener listener1 = emptyListener(); context.addListener(listener1); Assert.assertEquals(1, context.getListeners().size()); Assert.assertTrue(context.getListeners().contains(listener1)); final ServiceChangeListener listener2 = emptyListener(); context.addListener(listener2); Assert.assertEquals(2, context.getListeners().size()); Assert.assertTrue(context.getListeners().contains(listener2)); } |
### Question:
ServiceDiscovery { protected void subscribe(final WebSocketSession session) { try { for (final DiscoveryConfig discoveryConfig : serviceRepository.getDiscoveryConfigs()) { subscribe(session, discoveryConfig); } } catch (final Throwable e) { logger.warn("subscribe services failed", e); } } ServiceDiscovery(final ServiceRepository serviceRepository, final ArtemisClientConfig config); void registerDiscoveryConfig(DiscoveryConfig config); Service getService(DiscoveryConfig config); }### Answer:
@Test public void testSubscribe() throws Exception { final ServiceRepository serviceRepository = new ServiceRepository(ArtemisClientConstants.DiscoveryClientConfig); final String serviceId = Services.newServiceId(); final DiscoveryConfig discoveryConfig = new DiscoveryConfig(serviceId); final Set<Instance> instances = Sets.newHashSet(Instances.newInstance(serviceId), Instances.newInstance(serviceId)); final CountDownLatch addCount = new CountDownLatch(instances.size() * 2); final CountDownLatch deleteCount = new CountDownLatch(instances.size()); final List<ServiceChangeEvent> serviceChangeEvents = Lists.newArrayList(); serviceRepository.registerServiceChangeListener(discoveryConfig, new ServiceChangeListener() { @Override public void onChange(ServiceChangeEvent event) { serviceChangeEvents.add(event); if (InstanceChange.ChangeType.DELETE.equals(event.changeType())) { deleteCount.countDown(); } if (InstanceChange.ChangeType.NEW.equals(event.changeType())) { addCount.countDown(); } } }); Threads.sleep(2000); final InstanceRepository instanceRepository = new InstanceRepository(ArtemisClientConstants.RegistryClientConfig); instanceRepository.register(instances); Assert.assertTrue(addCount.await(2, TimeUnit.SECONDS)); instanceRepository.unregister(instances); Assert.assertTrue(deleteCount.await(2, TimeUnit.SECONDS)); Assert.assertTrue(3 * instances.size() <= serviceChangeEvents.size()); } |
### Question:
ServiceRepository { public Service getService(final DiscoveryConfig discoveryConfig) { if (discoveryConfig == null) { return new Service(); } final String serviceId = StringValues.toLowerCase(discoveryConfig.getServiceId()); if (StringValues.isNullOrWhitespace(serviceId)) return new Service(); if (!containsService(serviceId)) registerService(discoveryConfig); return services.get(serviceId).newService(); } ServiceRepository(final ArtemisClientConfig config); protected ServiceRepository(final ArtemisClientConfig config, ServiceDiscovery serviceDiscovery); boolean containsService(final String serviceId); List<DiscoveryConfig> getDiscoveryConfigs(); DiscoveryConfig getDiscoveryConfig(final String serviceId); List<ServiceContext> getServices(); Service getService(final DiscoveryConfig discoveryConfig); void registerServiceChangeListener(final DiscoveryConfig discoveryConfig, final ServiceChangeListener listener); }### Answer:
@Test public void testGetService() { final DiscoveryConfig discoveryConfig = Services.newDiscoverConfig(); final String serviceId = discoveryConfig.getServiceId(); final Service service = _serviceRepository.getService(discoveryConfig); Assert.assertEquals(serviceId, service.getServiceId()); Assert.assertTrue(_serviceRepository.containsService(serviceId)); } |
### Question:
ServiceRepository { public void registerServiceChangeListener(final DiscoveryConfig discoveryConfig, final ServiceChangeListener listener) { if ((discoveryConfig == null) || (listener == null)) { return; } final String serviceId = StringValues.toLowerCase(discoveryConfig.getServiceId()); if (StringValues.isNullOrWhitespace(serviceId)) { return; } if (!containsService(serviceId)) { registerService(discoveryConfig); } services.get(serviceId).addListener(listener); } ServiceRepository(final ArtemisClientConfig config); protected ServiceRepository(final ArtemisClientConfig config, ServiceDiscovery serviceDiscovery); boolean containsService(final String serviceId); List<DiscoveryConfig> getDiscoveryConfigs(); DiscoveryConfig getDiscoveryConfig(final String serviceId); List<ServiceContext> getServices(); Service getService(final DiscoveryConfig discoveryConfig); void registerServiceChangeListener(final DiscoveryConfig discoveryConfig, final ServiceChangeListener listener); }### Answer:
@Test public void testRegisterServiceChangeListener() { final DiscoveryConfig discoveryConfig = Services.newDiscoverConfig(); _serviceRepository.registerServiceChangeListener(discoveryConfig, new DefaultServiceChangeListener()); Assert.assertTrue(_serviceRepository.containsService(discoveryConfig.getServiceId())); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.