method2testcases
stringlengths
118
6.63k
### 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: PropertiesConverter implements PropertyConverter { @Override public CompletionStage<PropertyContext<?>> convert(final CompletionStage<PropertyContext<?>> cs) { return cs.thenCompose(context -> { final SimplePropertyDefinition property = context.getProperty(); if ("object".equalsIgnoreCase(property.getType())) { final Map<String, Object> childDefaults = new HashMap<>(); defaults.put(property.getName(), childDefaults); final PropertiesConverter propertiesConverter = new PropertiesConverter(jsonb, childDefaults, properties); return CompletableFuture .allOf(context .findDirectChild(properties) .map(it -> new PropertyContext<>(it, context.getRootContext(), context.getConfiguration())) .map(CompletionStages::toStage) .map(propertiesConverter::convert) .toArray(CompletableFuture[]::new)) .thenApply(done -> context); } ofNullable(property.getMetadata().getOrDefault("ui::defaultvalue::value", property.getDefaultValue())) .ifPresent(value -> { if ("number".equalsIgnoreCase(property.getType())) { defaults.put(property.getName(), Double.parseDouble(value)); } else if ("boolean".equalsIgnoreCase(property.getType())) { defaults.put(property.getName(), Boolean.parseBoolean(value)); } else if ("array".equalsIgnoreCase(property.getType())) { defaults.put(property.getName(), jsonb.fromJson(value, Object[].class)); } else if ("object".equalsIgnoreCase(property.getType())) { defaults.put(property.getName(), jsonb.fromJson(value, Map.class)); } else { if ("string".equalsIgnoreCase(property.getType()) && property .getMetadata() .keySet() .stream() .anyMatch(k -> k.equalsIgnoreCase("action::suggestions") || k.equalsIgnoreCase("action::dynamic_values"))) { defaults.putIfAbsent("$" + property.getName() + "_name", value); } defaults.put(property.getName(), value); } }); return CompletableFuture.completedFuture(context); }); } @Override CompletionStage<PropertyContext<?>> convert(final CompletionStage<PropertyContext<?>> cs); }### Answer: @Test void datalistDefault() throws Exception { final Map<String, Object> values = new HashMap<>(); try (final Jsonb jsonb = JsonbBuilder.create()) { new PropertiesConverter(jsonb, values, emptyList()) .convert(completedFuture(new PropertyContext<>(new SimplePropertyDefinition("configuration.foo.bar", "bar", "Bar", "STRING", "def", new PropertyValidation(), singletonMap("action::suggestionS", "yes"), null, new LinkedHashMap<>()), null, new PropertyContext.Configuration()))) .toCompletableFuture() .get(); } assertEquals(2, values.size()); assertEquals("def", values.get("bar")); assertEquals("def", values.get("$bar_name")); }
### 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: AbstractWidgetConverter implements PropertyConverter { protected UiSchema.Trigger toTrigger(final Collection<SimplePropertyDefinition> properties, final SimplePropertyDefinition prop, final ActionReference ref) { final UiSchema.Trigger trigger = new UiSchema.Trigger(); trigger .setAction(prop .getMetadata() .entrySet() .stream() .filter(it -> matchAction(it, ref)) .findFirst() .map(Map.Entry::getValue) .orElseGet(ref::getName)); trigger.setFamily(ref.getFamily()); trigger.setType(ref.getType()); trigger .setParameters(toParams(properties, prop, ref, prop.getMetadata().get("action::" + ref.getType() + "::parameters"))); return trigger; } }### Answer: @Test void triggerArrayParameters() throws Exception { try (final Jsonb jsonb = JsonbBuilder.create(); final InputStream stream = Thread .currentThread() .getContextClassLoader() .getResourceAsStream("object-array-in-parameter.json")) { final ComponentDetail details = jsonb.fromJson(stream, ComponentDetail.class); final AtomicReference<UiSchema.Trigger> trigger = new AtomicReference<>(); new AbstractWidgetConverter(new ArrayList<>(), details.getProperties(), emptyList(), new JsonSchema(), "en") { @Override public CompletionStage<PropertyContext<?>> convert(final CompletionStage<PropertyContext<?>> context) { throw new UnsupportedOperationException(); } { trigger .set(toTrigger(details.getProperties(), details .getProperties() .stream() .filter(it -> it.getName().equals("filterAdvancedValueWrapper")) .findFirst() .orElseThrow(IllegalArgumentException::new), details .getActions() .stream() .filter(it -> it.getName().equals("updatableFilterAdvanced")) .findFirst() .orElseThrow(IllegalArgumentException::new))); } }; final UiSchema.Parameter parameter = trigger .get() .getParameters() .stream() .filter(it -> it.getPath().equals("configuration.selectionFilter.filterLines")) .findFirst() .orElseThrow(IllegalStateException::new); assertEquals("filterLines", parameter.getKey()); } } @Test void triggerWithParameters() { final AtomicReference<UiSchema.Trigger> trigger = new AtomicReference<>(); final Set<SimplePropertyDefinition> singleton = singleton(new SimplePropertyDefinition("foo", "foo", null, "enum", null, new PropertyValidation(), new HashMap<String, String>() { { put("action::ty", "other::foo(bar=dummy)"); } }, null, new LinkedHashMap<>())); new AbstractWidgetConverter(new ArrayList<>(), singleton, emptyList(), new JsonSchema(), "en") { @Override public CompletionStage<PropertyContext<?>> convert(final CompletionStage<PropertyContext<?>> context) { throw new UnsupportedOperationException(); } { trigger .set(toTrigger(singleton, singleton.iterator().next(), new ActionReference("fam", "other::foo", "ty", null, emptyList()))); } }; final UiSchema.Trigger output = trigger.get(); assertEquals("fam", output.getFamily()); assertEquals("ty", output.getType()); assertEquals("other::foo(bar=dummy)", output.getAction()); }
### 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: JavaProxyEnricherFactory { public Object asSerializable(final ClassLoader loader, final String plugin, final String key, final Object instanceToWrap) { final Class<?>[] interfaces = instanceToWrap.getClass().getInterfaces(); final boolean isSerializable = Stream.of(interfaces).anyMatch(i -> i == Serializable.class || i == Externalizable.class); if (isSerializable && !instanceToWrap.getClass().getName().startsWith("org.apache.johnzon.core.")) { return instanceToWrap; } final Class[] api = isSerializable ? interfaces : Stream.concat(Stream.of(Serializable.class), Stream.of(interfaces)).toArray(Class[]::new); return Proxy .newProxyInstance(selectLoader(api, loader), api, new DelegatingSerializableHandler(instanceToWrap, plugin, key)); } Object asSerializable(final ClassLoader loader, final String plugin, final String key, final Object instanceToWrap); }### Answer: @Test void serialization() throws IOException, ClassNotFoundException { final ClassLoader loader = Thread.currentThread().getContextClassLoader(); final JavaProxyEnricherFactory factory = new JavaProxyEnricherFactory(); final Translator proxyBased = Translator.class .cast(factory .asSerializable(loader, getClass().getSimpleName(), Translator.class.getName(), new InternationalizationServiceFactory(Locale::getDefault) .create(Translator.class, loader))); assertEquals("ok", proxyBased.message()); DynamicContainerFinder.SERVICES.put(Translator.class, proxyBased); DynamicContainerFinder.LOADERS.put(getClass().getSimpleName(), Thread.currentThread().getContextClassLoader()); try { final Translator fromApi = Serializer.roundTrip(proxyBased); assertEquals(fromApi, proxyBased); assertSame(Proxy.getInvocationHandler(fromApi), Proxy.getInvocationHandler(proxyBased)); } finally { DynamicContainerFinder.LOADERS.clear(); DynamicContainerFinder.SERVICES.remove(Translator.class); } } @Test void defaultMethod() { final ClassLoader loader = Thread.currentThread().getContextClassLoader(); final JavaProxyEnricherFactory factory = new JavaProxyEnricherFactory(); final SomeDefault proxyBased = SomeDefault.class .cast(factory .asSerializable(loader, getClass().getSimpleName(), SomeDefault.class.getName(), new SomeDefault() { @Override public String get() { return "ok"; } })); assertEquals("ok", proxyBased.get()); }
### Question: DefaultValueInspector { public Instance createDemoInstance(final Object rootInstance, final ParameterMeta param) { if (rootInstance != null) { final Object field = findField(rootInstance, param); if (field != null) { return new Instance(field, false); } } final Type javaType = param.getJavaType(); if (Class.class.isInstance(javaType)) { return new Instance(tryCreatingObjectInstance(javaType), true); } else if (ParameterizedType.class.isInstance(javaType)) { final ParameterizedType pt = ParameterizedType.class.cast(javaType); final Type rawType = pt.getRawType(); if (Class.class.isInstance(rawType) && Collection.class.isAssignableFrom(Class.class.cast(rawType)) && pt.getActualTypeArguments().length == 1 && Class.class.isInstance(pt.getActualTypeArguments()[0])) { final Object instance = tryCreatingObjectInstance(pt.getActualTypeArguments()[0]); final Class<?> collectionType = Class.class.cast(rawType); if (Set.class == collectionType) { return new Instance(singleton(instance), true); } if (SortedSet.class == collectionType) { return new Instance(new TreeSet<>(singletonList(instance)), true); } if (List.class == collectionType || Collection.class == collectionType) { return new Instance(singletonList(instance), true); } return null; } } return null; } Instance createDemoInstance(final Object rootInstance, final ParameterMeta param); String findDefault(final Object instance, final ParameterMeta param); }### Answer: @Test void createListInstance() { final DefaultValueInspector inspector = new DefaultValueInspector(); final DefaultValueInspector.Instance demoInstance = inspector .createDemoInstance(new Wrapper(), new ParameterMeta(null, new JohnzonParameterizedType(List.class, Foo.class), ARRAY, "foos", "foos", null, singletonList(new ParameterMeta(null, Foo.class, OBJECT, "foos[${index}]", "foos[${index}]", null, singletonList(new ParameterMeta(null, Foo.class, STRING, "foos[${index}].name", "name", null, emptyList(), null, emptyMap(), false)), null, emptyMap(), false)), null, emptyMap(), false)); assertNotNull(demoInstance.getValue()); assertTrue(demoInstance.isCreated()); assertTrue(Collection.class.isInstance(demoInstance.getValue())); final Collection<?> list = Collection.class.cast(demoInstance.getValue()); assertEquals(1, list.size()); final Object first = list.iterator().next(); assertNotNull(first); assertTrue(Foo.class.isInstance(first)); assertNull(Foo.class.cast(first).name); }
### 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: ValidationParameterEnricher extends BaseParameterEnricher { @Override public Map<String, String> onParameterAnnotation(final String parameterName, final Type parameterType, final Annotation annotation) { final Class<?> asClass = toClass(parameterType); return ofNullable(annotation.annotationType().getAnnotation(Validations.class)) .map(v -> Stream.of(v.value())) .orElseGet(() -> ofNullable(annotation.annotationType().getAnnotation(Validation.class)) .map(Stream::of) .orElseGet(Stream::empty)) .filter(v -> Stream.of(v.expectedTypes()).anyMatch(t -> asClass != null && t.isAssignableFrom(asClass))) .findFirst() .map(v -> singletonMap(META_PREFIX + v.name(), getValueString(annotation))) .orElseGet(Collections::emptyMap); } @Override Map<String, String> onParameterAnnotation(final String parameterName, final Type parameterType, final Annotation annotation); static final String META_PREFIX; }### Answer: @Test void minValue() { assertEquals(singletonMap("tcomp::validation::min", "5.0"), enricher.onParameterAnnotation("testParam", int.class, new Min() { @Override public Class<? extends Annotation> annotationType() { return Min.class; } @Override public double value() { return 5; } })); } @Test void maxValue() { assertEquals(singletonMap("tcomp::validation::max", "5.0"), enricher.onParameterAnnotation("testParam", int.class, new Max() { @Override public Class<? extends Annotation> annotationType() { return Max.class; } @Override public double value() { return 5; } })); } @Test void minCollection() { assertEquals(singletonMap("tcomp::validation::minItems", "5.0"), enricher.onParameterAnnotation("testParam", Collection.class, new Min() { @Override public Class<? extends Annotation> annotationType() { return Min.class; } @Override public double value() { return 5; } })); } @Test void maxCollection() { assertEquals(singletonMap("tcomp::validation::maxItems", "5.0"), enricher.onParameterAnnotation("testParam", Collection.class, new Max() { @Override public Class<? extends Annotation> annotationType() { return Max.class; } @Override public double value() { return 5; } })); } @Test void minlength() { assertEquals(singletonMap("tcomp::validation::minLength", "5.0"), enricher.onParameterAnnotation("testParam", String.class, new Min() { @Override public Class<? extends Annotation> annotationType() { return Min.class; } @Override public double value() { return 5; } })); } @Test void maxLength() { assertEquals(singletonMap("tcomp::validation::maxLength", "5.0"), enricher.onParameterAnnotation("testParam", String.class, new Max() { @Override public Class<? extends Annotation> annotationType() { return Max.class; } @Override public double value() { return 5; } })); } @Test void pattern() { assertEquals(singletonMap("tcomp::validation::pattern", "test"), enricher.onParameterAnnotation("testParam", String.class, new Pattern() { @Override public Class<? extends Annotation> annotationType() { return Pattern.class; } @Override public String value() { return "test"; } })); } @Test void required() { assertEquals(singletonMap("tcomp::validation::required", "true"), enricher.onParameterAnnotation("testParam", Collection.class, new Required() { @Override public Class<? extends Annotation> annotationType() { return Required.class; } })); } @Test void unique() { assertEquals(singletonMap("tcomp::validation::uniqueItems", "true"), enricher.onParameterAnnotation("testParam", Collection.class, new Uniques() { @Override public Class<? extends Annotation> annotationType() { return Uniques.class; } })); } @Test void enumType() { assertEquals(singletonMap("tcomp::validation::uniqueItems", "true"), enricher.onParameterAnnotation("testParam", Collection.class, new Uniques() { @Override public Class<? extends Annotation> annotationType() { return Uniques.class; } })); }
### Question: ActionParameterEnricher extends BaseParameterEnricher { @Override public Map<String, String> onParameterAnnotation(final String parameterName, final Type parameterType, final Annotation annotation) { final Class<? extends Annotation> annotationType = annotation.annotationType(); final ActionRef ref = annotationType.getAnnotation(ActionRef.class); if (ref == null) { return emptyMap(); } final Class<?> actionType = ref.value(); if (actionType == Object.class) { return singletonMap( META_PREFIX + clientActionsMapping.computeIfAbsent(annotationType.getSimpleName(), this::toSnakeCase), getClientActionName(annotation)); } final String type = actionType.getAnnotation(ActionType.class).value(); return new HashMap<String, String>() { { put(META_PREFIX + type, getValueString(ref.ref(), annotation)); ofNullable(getParametersString(annotation)).ifPresent(v -> put(META_PREFIX + type + "::parameters", v)); Stream .of(annotationType.getMethods()) .filter(it -> annotationType == it.getDeclaringClass() && Stream.of("parameters", "value").noneMatch(v -> it.getName().equalsIgnoreCase(v))) .forEach(m -> put(META_PREFIX + type + "::" + m.getName(), getString(m, annotation))); } }; } @Override Map<String, String> onParameterAnnotation(final String parameterName, final Type parameterType, final Annotation annotation); static final String META_PREFIX; }### Answer: @Test void update() { assertEquals(new HashMap<String, String>() { { put("tcomp::action::update", "test"); put("tcomp::action::update::parameters", ".,foo,/bar/dummy"); put("tcomp::action::update::after", "propertyX"); } }, new ActionParameterEnricher().onParameterAnnotation("testParam", String.class, new Updatable() { @Override public String value() { return "test"; } @Override public String after() { return "propertyX"; } @Override public String[] parameters() { return new String[] { ".", "foo", "/bar/dummy" }; } @Override public Class<? extends Annotation> annotationType() { return Updatable.class; } })); } @Test void builtInSuggestion() { assertEquals(singletonMap("tcomp::action::built_in_suggestable", "INCOMING_SCHEMA_ENTRY_NAMES"), new ActionParameterEnricher() .onParameterAnnotation("testParam", String.class, new BuiltInSuggestable() { @Override public Name value() { return Name.INCOMING_SCHEMA_ENTRY_NAMES; } @Override public String name() { return ""; } @Override public Class<? extends Annotation> annotationType() { return BuiltInSuggestable.class; } })); } @Test void builtInSuggestionCustom() { assertEquals(singletonMap("tcomp::action::built_in_suggestable", "alternate"), new ActionParameterEnricher() .onParameterAnnotation("testParam", String.class, new BuiltInSuggestable() { @Override public Name value() { return Name.CUSTOM; } @Override public String name() { return "alternate"; } @Override public Class<? extends Annotation> annotationType() { return BuiltInSuggestable.class; } })); } @Test void suggestion() { assertEquals(new HashMap<String, String>() { { put("tcomp::action::suggestions", "test"); put("tcomp::action::suggestions::parameters", ".,foo,/bar/dummy"); } }, new ActionParameterEnricher().onParameterAnnotation("testParam", String.class, new Suggestable() { @Override public String value() { return "test"; } @Override public String[] parameters() { return new String[] { ".", "foo", "/bar/dummy" }; } @Override public Class<? extends Annotation> annotationType() { return Suggestable.class; } })); } @Test void condition() { assertEquals(new HashMap<String, String>() { { put("tcomp::action::dynamic_values", "test"); } }, new ActionParameterEnricher().onParameterAnnotation("testParam", String.class, new Proposable() { @Override public String value() { return "test"; } @Override public Class<? extends Annotation> annotationType() { return Proposable.class; } })); }
### Question: VisibilityService { public ConditionGroup build(final ParameterMeta param) { final boolean and = "AND".equalsIgnoreCase(param.getMetadata().getOrDefault("tcomp::condition::ifs::operator", "AND")); return new ConditionGroup(param .getMetadata() .entrySet() .stream() .filter(meta -> meta.getKey().startsWith("tcomp::condition::if::target")) .map(meta -> { final String[] split = meta.getKey().split("::"); final String index = split.length == 5 ? "::" + split[split.length - 1] : ""; final String valueKey = "tcomp::condition::if::value" + index; final String negateKey = "tcomp::condition::if::negate" + index; final String evaluationStrategyKey = "tcomp::condition::if::evaluationStrategy" + index; final String absoluteTargetPath = pathResolver.resolveProperty(param.getPath(), meta.getValue()); return new Condition(toPointer(absoluteTargetPath), Boolean.parseBoolean(param.getMetadata().getOrDefault(negateKey, "false")), param.getMetadata().getOrDefault(evaluationStrategyKey, "DEFAULT").toUpperCase(ROOT), param.getMetadata().getOrDefault(valueKey, "true").split(",")); }) .collect(toList()), and ? stream -> stream.allMatch(i -> i) : stream -> stream.anyMatch(i -> i)); } ConditionGroup build(final ParameterMeta param); }### Answer: @Test void one() { final Map<String, String> metadata = new HashMap<>(); metadata.put("tcomp::condition::if::target", "the_target"); metadata.put("tcomp::condition::if::value", "a,b,c"); metadata.put("tcomp::condition::if::negate", "false"); metadata.put("tcomp::condition::if::evaluationStrategy", "DEFAULT"); final VisibilityService.ConditionGroup conditionGroup = service .build(new ParameterMeta(null, String.class, ParameterMeta.Type.STRING, "foo", "foo", null, emptyList(), emptyList(), metadata, false)); assertTrue(conditionGroup.isVisible(Json.createObjectBuilder().add("the_target", "a").build())); assertTrue(conditionGroup.isVisible(Json.createObjectBuilder().add("the_target", "c").build())); assertFalse(conditionGroup.isVisible(Json.createObjectBuilder().build())); } @Test void two() { final Map<String, String> metadata = new HashMap<>(); metadata.put("tcomp::condition::if::target::0", "the_target1"); metadata.put("tcomp::condition::if::value::0", "a,b,c"); metadata.put("tcomp::condition::if::negate::0", "false"); metadata.put("tcomp::condition::if::evaluationStrategy::0", "DEFAULT"); metadata.put("tcomp::condition::if::target::1", "the_target2"); metadata.put("tcomp::condition::if::value::1", "1"); metadata.put("tcomp::condition::if::negate::1", "true"); metadata.put("tcomp::condition::if::evaluationStrategy::1", "LENGTH"); final VisibilityService.ConditionGroup conditionGroup = service .build(new ParameterMeta(null, String.class, ParameterMeta.Type.STRING, "foo", "foo", null, emptyList(), emptyList(), metadata, false)); assertTrue(conditionGroup.isVisible(Json.createObjectBuilder().add("the_target1", "a").build())); assertTrue(conditionGroup .isVisible(Json.createObjectBuilder().add("the_target1", "a").add("the_target2", "aa").build())); assertFalse(conditionGroup .isVisible(Json.createObjectBuilder().add("the_target1", "d").add("the_target2", "a").build())); assertFalse(conditionGroup .isVisible(Json.createObjectBuilder().add("the_target1", "d").add("the_target2", "aa").build())); }
### Question: PayloadMapper { public JsonObject visitAndMap(final Collection<ParameterMeta> parameters, final Map<String, String> payload) { return unflatten("", ofNullable(parameters).orElseGet(Collections::emptyList), payload == null ? emptyMap() : payload); } JsonObject visitAndMap(final Collection<ParameterMeta> parameters, final Map<String, String> payload); }### Answer: @Test void simpleDirectValue() throws NoSuchMethodException { final List<ParameterMeta> params = service .buildParameterMetas(MethodsHolder.class.getMethod("primitives", String.class, String.class, int.class), "def", new BaseParameterEnricher.Context(new LocalConfigurationService(emptyList(), "test"))); final Map<String, String> payload = new HashMap<>(); payload.put("url", "http: final JsonValue value = extractorFactory.visitAndMap(params, payload); assertEquals("{\"url\":\"http: } @Test void simpleListValue() throws NoSuchMethodException { final List<ParameterMeta> params = service .buildParameterMetas(MethodsHolder.class.getMethod("collections", List.class, List.class, Map.class), "def", new BaseParameterEnricher.Context(new LocalConfigurationService(emptyList(), "test"))); final Map<String, String> payload = new HashMap<>(); payload.put("ports[0]", "1"); payload.put("ports[1]", "2"); final JsonValue value = extractorFactory.visitAndMap(params, payload); assertEquals("{\"ports\":[1,2]}", value.toString()); } @Test void complex() throws NoSuchMethodException { final List<ParameterMeta> params = service .buildParameterMetas(Model.class.getConstructor(Complex.class), "def", new BaseParameterEnricher.Context(new LocalConfigurationService(emptyList(), "test"))); final Map<String, String> payload = new TreeMap<>(); payload.put("configuration.objects[0].simple", "s"); payload.put("configuration.objects[0].otherObjects[0].value", "o11"); payload.put("configuration.objects[0].otherObjects[1].value", "o12"); payload.put("configuration.objects[1].otherObjects[0].value", "o21"); payload.put("configuration.objects[2].strings[0]", "s1"); payload.put("configuration.objects[2].strings[1]", "s2"); payload.put("configuration.simple", "rs"); payload.put("configuration.strings[0]", "rs1"); payload.put("configuration.other.value", "done"); final JsonValue value = extractorFactory.visitAndMap(params, payload); assertEquals("{\"configuration\":{\"objects\":[{\"otherObjects\":[{\"value\":\"o11\"},{\"value\":\"o12\"}]," + "\"simple\":\"s\"},{\"otherObjects\":[{\"value\":\"o21\"}]},{\"strings\":[\"s1\",\"s2\"]}]," + "\"other\":{\"value\":\"done\"},\"simple\":\"rs\",\"strings\":[\"rs1\"]}}", value.toString()); }
### Question: RecordConverters implements Serializable { public <T> T coerce(final Class<T> expectedType, final Object value, final String name) { if (value == null) { return null; } if (Long.class.isInstance(value) && expectedType != Long.class) { if (expectedType == ZonedDateTime.class) { final long epochMilli = Number.class.cast(value).longValue(); if (epochMilli == -1L) { return null; } return expectedType.cast(ZonedDateTime.ofInstant(Instant.ofEpochMilli(epochMilli), UTC)); } if (expectedType == Date.class) { return expectedType.cast(new Date(Number.class.cast(value).longValue())); } } if (!expectedType.isInstance(value)) { if (Number.class.isInstance(value) && Number.class.isAssignableFrom(expectedType)) { return mapNumber(expectedType, Number.class.cast(value)); } if (String.class.isInstance(value)) { if (ZonedDateTime.class == expectedType) { return expectedType.cast(ZonedDateTime.parse(String.valueOf(value))); } if (byte[].class == expectedType) { return expectedType.cast(Base64.getDecoder().decode(String.valueOf(value))); } } throw new IllegalArgumentException(name + " can't be converted to " + expectedType); } return expectedType.cast(value); } T mapNumber(final Class<T> expected, final Number from); Record toRecord(final MappingMetaRegistry registry, final T data, final Supplier<Jsonb> jsonbProvider, final Supplier<RecordBuilderFactory> recordBuilderProvider); static Schema toSchema(final RecordBuilderFactory factory, final Object next); Object toType(final MappingMetaRegistry registry, final Object data, final Class<?> parameterType, final Supplier<JsonBuilderFactory> factorySupplier, final Supplier<JsonProvider> providerSupplier, final Supplier<Jsonb> jsonbProvider, final Supplier<RecordBuilderFactory> recordBuilderProvider); Object toType(final MappingMetaRegistry registry, final Object data, final Class<?> parameterType, final Supplier<JsonBuilderFactory> factorySupplier, final Supplier<JsonProvider> providerSupplier, final Supplier<Jsonb> jsonbProvider, final Supplier<RecordBuilderFactory> recordBuilderProvider, final java.util.Map<String, String> metadata); T coerce(final Class<T> expectedType, final Object value, final String name); }### Answer: @Test void convertDateToString() { final ZonedDateTime dateTime = ZonedDateTime.of(2017, 7, 17, 9, 0, 0, 0, ZoneId.of("GMT")); final String stringValue = dateTime.format(ISO_ZONED_DATE_TIME); new RecordConverters().coerce(ZonedDateTime.class, stringValue, "foo"); final ZonedDateTime asDate = new RecordConverters().coerce(ZonedDateTime.class, stringValue, "foo"); assertEquals(dateTime, asDate); final String asString = new RecordConverters().coerce(String.class, stringValue, "foo"); assertEquals(stringValue, asString); }
### Question: ResolverImpl implements Resolver, Serializable { @Override public ClassLoaderDescriptor mapDescriptorToClassLoader(final InputStream descriptor) { final Collection<URL> urls = new ArrayList<>(); final Collection<String> nested = new ArrayList<>(); final Collection<String> resolved = new ArrayList<>(); final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final ClassLoader loader = ofNullable(classLoader).map(ClassLoader::getParent).orElseGet(ClassLoader::getSystemClassLoader); try { new MvnDependencyListLocalRepositoryResolver(null, fileResolver) .resolveFromDescriptor(descriptor) .forEach(artifact -> { final String path = artifact.toPath(); final Path file = fileResolver.apply(path); if (Files.exists(file)) { try { urls.add(file.toUri().toURL()); resolved.add(artifact.toCoordinate()); } catch (final MalformedURLException e) { throw new IllegalStateException(e); } } else if (loader.getResource("MAVEN-INF/repository/" + path) != null) { nested.add(path); resolved.add(artifact.toCoordinate()); } }); final ConfigurableClassLoader volatileLoader = new ConfigurableClassLoader(plugin + "#volatile-resolver", urls.toArray(new URL[0]), classLoader, it -> false, it -> true, nested.toArray(new String[0]), ConfigurableClassLoader.class.isInstance(classLoader) ? ConfigurableClassLoader.class.cast(classLoader).getJvmMarkers() : new String[] { "" }); return new ClassLoaderDescriptorImpl(volatileLoader, resolved); } catch (final IOException e) { throw new IllegalArgumentException(e); } } @Override ClassLoaderDescriptor mapDescriptorToClassLoader(final InputStream descriptor); @Override Collection<File> resolveFromDescriptor(final InputStream descriptor); }### Answer: @Test void createClassLoader(@TempDir final Path temporaryFolder) throws Exception { final File root = temporaryFolder.toFile(); root.mkdirs(); final String dep = "org.apache.tomee:arquillian-tomee-codi-tests:jar:7.0.5"; final File nestedJar = new File(root, UUID.randomUUID().toString() + ".jar"); try (final JarOutputStream out = new JarOutputStream(new FileOutputStream(nestedJar))) { addDepToJar(dep, out); } final Thread thread = Thread.currentThread(); final ClassLoader contextClassLoader = thread.getContextClassLoader(); final URLClassLoader appLoader = new URLClassLoader(new URL[] { nestedJar.toURI().toURL() }, contextClassLoader); final ConfigurableClassLoader componentLoader = new ConfigurableClassLoader("test", new URL[0], appLoader, it -> true, it -> false, new String[0], new String[0]); thread.setContextClassLoader(componentLoader); try (final Resolver.ClassLoaderDescriptor desc = new ResolverImpl(null, coord -> PathFactory.get("maven2").resolve(coord)) .mapDescriptorToClassLoader(singletonList(dep))) { assertNotNull(desc); assertNotNull(desc.asClassLoader()); assertEquals(singletonList(dep), desc.resolvedDependencies()); final Properties props = new Properties(); try (final InputStream in = desc .asClassLoader() .getResourceAsStream( "META-INF/maven/org.apache.tomee/arquillian-tomee-codi-tests/pom.properties")) { assertNotNull(in); props.load(in); } assertEquals("arquillian-tomee-codi-tests", props.getProperty("artifactId")); } finally { thread.setContextClassLoader(contextClassLoader); appLoader.close(); } }
### 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: URLConst { public static void init(String e) { String t = "login.weixin.qq.com"; String o = "file.wx.qq.com"; String n = "webpush.weixin.qq.com"; if (e.indexOf("wx2.qq.com") > -1) { t = "login.wx2.qq.com"; o = "file.wx2.qq.com"; n = "webpush.wx2.qq.com"; } else if (e.indexOf("wx8.qq.com") > -1) { t = "login.wx8.qq.com"; o = "file.wx8.qq.com"; n = "webpush.wx8.qq.com"; } else if (e.indexOf("qq.com") > -1) { t = "login.wx.qq.com"; o = "file.wx.qq.com"; n = "webpush.wx.qq.com"; } else if (e.indexOf("web2.wechat.com") > -1) { t = "login.web2.wechat.com"; o = "file.web2.wechat.com"; n = "webpush.web2.wechat.com"; } else if (e.indexOf("wechat.com") > -1) { t = "login.web.wechat.com"; o = "file.web.wechat.com"; n = "webpush.web.wechat.com"; } HOST = SCHEMA + e; BASE = SCHEMA + e + PATH; SYNC_CHECK = SCHEMA + n + PATH + "synccheck"; MEDIA_GET = SCHEMA + o + PATH + "webwxgetmedia"; MEDIA_UPLOAD = SCHEMA + o + PATH + "webwxuploadmedia"; } static void init(String e); static String SCHEMA; static String PATH; static String BASE; static String BASE_O; static String BASE_N; static String HOST; static String SYNC_CHECK; static String MEDIA_UPLOAD; static String MEDIA_GET; }### Answer: @Test public void test() { BaseApi api = URLConst.API.INIT; assertEquals("https: URLConst.init("wx2.qq.com"); assertTrue(api == URLConst.API.INIT); assertEquals("https: }
### 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: QNUploader { public UploadInfo upload(String qq, File file, String ak, String sk, String bucket, Zone zone) throws Exception { String key = String.format("%s/%s", qq, file.getName()); AuthInfo authInfo = getToken(qq, ak, sk, bucket, key); System.out.println(authInfo); if (authInfo.limit > 0 && file.length() > authInfo.limit) { throw new RuntimeException("今日上传流量不足,剩余流量:" + authInfo.limit); } Configuration cfg = new Configuration( zone == null ? Zone.autoZone() : zone); UploadManager uploadManager = new UploadManager(cfg); com.qiniu.http.Response response = uploadManager .put(file.getAbsolutePath(), key, authInfo.token); if (!response.isOK()) { throw new RuntimeException( response.error + "(code=" + response.statusCode + ")"); } UploadInfo putRet = new Gson().fromJson(response.bodyString(), UploadInfo.class); if (authInfo.domain != null && !authInfo.domain.isEmpty()) { putRet.domain = authInfo.domain; } if (authInfo.limit > 0) { callback(qq, putRet); } return putRet; } 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 testUpload() { QNUploader uploader = new QNUploader(); try { String ak = ""; String sk = ""; String bucket = "temp"; File f = new File("pom.xml"); Zone zone = null; UploadInfo info = uploader.upload("testqq", f, ak, sk, bucket, zone); System.out.println(info); assertEquals("testqq/pom.xml", info.key); assertEquals("temp", info.bucket); assertEquals(f.length(), info.fsize); assertEquals("http: info.getUrl("http: AuthInfo auth = uploader.getToken("testqq", "", "", "", "pom.xml"); System.out.println(auth); assertNotNull(auth); assertNotNull(auth.token); assertEquals("http: assertEquals(1, auth.days); assertTrue((8 << 20) >= auth.limit); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testUpload2() { QNUploader uploader = new QNUploader(); String ak = ""; String sk = ""; String bucket = ""; File f = new File("C:\\Users\\Jamling\\Desktop\\a.txt"); Zone zone = null; try { UploadInfo info = uploader.upload("157250921", f, ak, sk, bucket, zone); System.out.println(info); } catch (Exception e) { e.printStackTrace(); } }
### 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: IMUtils { public static String autoLink(String input) { Pattern p = Patterns.WEB_URL; Matcher m = p.matcher(input); 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(input); 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); String http = null; String ucs = ""; String rg = UCS_REGEX_BEGIN.matcher(g).replaceAll("$2"); if (g.length() > rg.length()) { ucs = g.substring(0, g.length() - rg.length()); g = rg; s = s + ucs.length(); } rg = UCS_REGEX_END.matcher(g).replaceAll("$1"); if (g.length() > rg.length()) { ucs = g.substring(rg.length()); g = rg; e = e - ucs.length(); } if (!PROTOCOL.matcher(g).find()) { boolean f = g.startsWith("www.") || g.endsWith(".com") || g.endsWith(".cn"); if (!f) { continue; } else { http = "http: } } int pos = offset + s; if (pos > 2) { char c = sb.charAt(pos - 1); if (c == '\'' || c == '"') { c = sb.charAt(pos - 2); if (c == '=') { continue; } } else if (c == '>') { continue; } } sb.delete(offset + s, offset + e); String link = http == null ? g : http + g; String ng = g; if (IMG_EXTS.indexOf(FileUtils.getExtension(g).toLowerCase()) >= 0) { ng = String.format("<a href=\"%s\"><img src=\"%s\" alt=\"%s\" border=\"0\"/></a>", link, link, "无法预览,请尝试点击"); } else { ng = String.format("<a href=\"%s\">%s</a>", link, g); } sb.insert(offset + s, ng); offset += ng.length() - g.length(); } return sb.toString(); } return input; } static String getName(String path); static String formatFileSize(long length); static boolean isEmpty(CharSequence text); static boolean isEmpty(Collection<?> list); static String encodeHtml(String msg); static String formatMsg(long time, String name, CharSequence msg); static boolean isMySendMsg(String raw); static String formatHtmlMsg(String msg, boolean encodeHtml); static String formatHtmlMsg(long time, String name, CharSequence msg); static String formatHtmlMyMsg(long time, String name, CharSequence msg); static String formatHtmlMsg(boolean my, boolean encodeHtml, long time, String name, String msg); static String autoReviewLink(String input); static String autoLink(String input); static final String DIV_SENDER_FORMAT; static final String DIV_CONTENT_FORMAT; static final String DIV_ROW_FORMAT; static final List<String> IMG_EXTS; static final String CODE_REGEX; static final String LINK_REGEX; static final String UCS_CHAR; static final Pattern UCS_REGEX_END; static final Pattern UCS_REGEX_BEGIN; static final Pattern PROTOCOL; }### Answer: @Test public void testAutoLink() { String msg = "普通文本abc"; String html = IMUtils.autoLink(msg); System.out.println(html); assertEquals(msg, html); msg = "中 www.baidu.com abc"; html = IMUtils.autoLink(msg); System.out.println(html); assertEquals("中 <a href=\"http: html); html = IMUtils.autoLink(html); System.out.println(html); assertEquals("中 <a href=\"http: html); msg = "<a href=\"file: html = IMUtils.autoLink(msg); assertEquals(msg, html); }
### 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())); }
### Question: ArtemisRegistryHttpClient extends ArtemisHttpClient { public void register(final Set<Instance> instances) { try { Preconditions.checkArgument(!CollectionUtils.isEmpty(instances), "instances"); final RegisterRequest request = new RegisterRequest(Lists.newArrayList(instances)); final RegisterResponse response = this.request(RestPaths.REGISTRY_REGISTER_FULL_PATH, request, RegisterResponse.class); if (ResponseStatusUtil.isFail(response.getResponseStatus())) { _logger.error("register instances failed. Response:" + JacksonJsonSerializer.INSTANCE.serialize(response)); } else if (ResponseStatusUtil.isPartialFail(response.getResponseStatus())) { _logger.warn("register instances patial failed. Response:" + JacksonJsonSerializer.INSTANCE.serialize(response)); } logEvent(response.getResponseStatus(), "registry", "register"); } catch (final Throwable e) { _logger.warn("register instances failed", e); logEvent("registry", "register"); } } ArtemisRegistryHttpClient(final ArtemisClientConfig config); void register(final Set<Instance> instances); void unregister(final Set<Instance> instances); }### Answer: @Test public void testRegister() throws Exception { client.register(Instances.newInstances(3)); }
### Question: ArtemisRegistryHttpClient extends ArtemisHttpClient { public void unregister(final Set<Instance> instances) { try { Preconditions.checkArgument(!CollectionUtils.isEmpty(instances), "instances"); final UnregisterRequest request = new UnregisterRequest(Lists.newArrayList(instances)); final UnregisterResponse response = this.request(RestPaths.REGISTRY_UNREGISTER_FULL_PATH, request, UnregisterResponse.class); if (ResponseStatusUtil.isFail(response.getResponseStatus())) { _logger.error("unregister instances failed. Response:" + JacksonJsonSerializer.INSTANCE.serialize(response)); } else if (ResponseStatusUtil.isPartialFail(response.getResponseStatus())) { _logger.warn("unregister instances patial failed. Response:" + JacksonJsonSerializer.INSTANCE.serialize(response)); } logEvent(response.getResponseStatus(), "registry", "unregister"); } catch (final Throwable e) { _logger.warn("unregister instances failed", e); logEvent("registry", "unregister"); } } ArtemisRegistryHttpClient(final ArtemisClientConfig config); void register(final Set<Instance> instances); void unregister(final Set<Instance> instances); }### Answer: @Test public void testUnregister() throws Exception { client.unregister(Instances.newInstances(3)); }
### Question: InstanceRepository { public void register(final Set<Instance> instances) { if (CollectionUtils.isEmpty(instances)) { return; } _client.unregister(instances); updateInstances(instances, RegisterType.register); } InstanceRepository(final ArtemisClientConfig config); Set<Instance> getAvailableInstances(); TextMessage getHeartbeatMessage(); void registerToRemote(final Set<Instance> instances); void register(final Set<Instance> instances); void unregister(final Set<Instance> instances); }### Answer: @Test public void testRegister() { final Set<Instance> instances = Instances.newInstances(2); repository.register(instances); Assert.assertTrue(_instances.get().containsAll(instances)); } @Test public void registerToServicesRegistry() throws InterruptedException { final Set<Instance> instances = Instances.newInstances(2); repository.register(instances); Assert.assertTrue(_instances.get().containsAll(instances)); }
### Question: InstanceRepository { public void unregister(final Set<Instance> instances) { if (CollectionUtils.isEmpty(instances)) { return; } _client.unregister(instances); updateInstances(instances, RegisterType.unregister); } InstanceRepository(final ArtemisClientConfig config); Set<Instance> getAvailableInstances(); TextMessage getHeartbeatMessage(); void registerToRemote(final Set<Instance> instances); void register(final Set<Instance> instances); void unregister(final Set<Instance> instances); }### Answer: @Test public void testUnregister() { final Set<Instance> instances = Instances.newInstances(2); repository.register(instances); Assert.assertTrue(_instances.get().containsAll(instances)); repository.unregister(instances); for (final Instance instance : instances) { Assert.assertFalse(_instances.get().contains(instance)); } }
### Question: AddressManager { public AddressContext getContext() { AddressContext context = _addressContext.get(); if (!context.isAavailable() || context.isExpired()) { context = newAddressContext(); _addressContext.set(context); } return context; } AddressManager(final ArtemisClientManagerConfig managerConfig, final AddressRepository addressRepository); AddressContext getContext(); static AddressManager getDiscoveryAddressManager(final String clientId, final ArtemisClientManagerConfig managerConfig); static AddressManager getRegistryAddressManager(final String clientId, final ArtemisClientManagerConfig managerConfig); }### Answer: @Test public void testMarkUnavailable() throws InterruptedException, ExecutionException, TimeoutException{ final AddressContext context = addr.getContext(); Assert.assertTrue(context.isAavailable()); context.markUnavailable(); Assert.assertFalse(context.isAavailable()); final AddressContext newContext = addr.getContext(); Assert.assertFalse(context == newContext); Assert.assertNotNull(newContext.getHttpUrl()); }
### Question: AddressContext { public String getHttpUrl() { return _httpUrl; } AddressContext(final String clientId, final ArtemisClientManagerConfig managerConfig); AddressContext(final String clientId, final ArtemisClientManagerConfig managerConfig, final String httpUrl, final String wsEndpointSuffix); String getHttpUrl(); String customHttpUrl(final String path); String getWebSocketEndPoint(); boolean isAavailable(); boolean isExpired(); void markUnavailable(); }### Answer: @Test public void testGetHttpUrl() { final AddressContext context = newAddressContext("http: Assert.assertEquals("http: Assert.assertEquals("http: }
### Question: ServiceContext { public synchronized boolean deleteInstance(Instance instance) { if (instance == null) return false; List<Instance> instances = service.getInstances(); if (instances == null) return false; return instances.remove(instance); } 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 testDeleteInstance() { ServiceContext context = new ServiceContext(_discoveryConfig); Instance instance1 = Instances.newInstance(_serviceId); Assert.assertTrue(context.addInstance(instance1)); Assert.assertEquals(1, context.newService().getInstances().size()); Assert.assertTrue(context.deleteInstance(instance1)); Assert.assertEquals(0, context.newService().getInstances().size()); Assert.assertFalse(context.deleteInstance(instance1)); }
### Question: AddressContext { public String getWebSocketEndPoint() { return _webSocketEndpoint; } AddressContext(final String clientId, final ArtemisClientManagerConfig managerConfig); AddressContext(final String clientId, final ArtemisClientManagerConfig managerConfig, final String httpUrl, final String wsEndpointSuffix); String getHttpUrl(); String customHttpUrl(final String path); String getWebSocketEndPoint(); boolean isAavailable(); boolean isExpired(); void markUnavailable(); }### Answer: @Test public void testGetWebSocketEndPoint() { final AddressContext context = newAddressContext("http: Assert.assertEquals("ws: }
### Question: AddressContext { public boolean isExpired() { return System.currentTimeMillis() >= (_ttl.typedValue() + _createTime); } AddressContext(final String clientId, final ArtemisClientManagerConfig managerConfig); AddressContext(final String clientId, final ArtemisClientManagerConfig managerConfig, final String httpUrl, final String wsEndpointSuffix); String getHttpUrl(); String customHttpUrl(final String path); String getWebSocketEndPoint(); boolean isAavailable(); boolean isExpired(); void markUnavailable(); }### Answer: @Test public void testIsRetired() { final AddressContext context = newAddressContext("http: Assert.assertFalse(context.isExpired()); }
### Question: AddressRepository { protected void refresh() { try { _logger.info("start refresh service urls"); String domainUrl = _domainUrl.typedValue(); if (StringValues.isNullOrWhitespace(domainUrl)) { _logger.error("domain url should not be null or empty for artemis client"); return; } final List<String> urls = getUrlsFromService(domainUrl); if (!CollectionUtils.isEmpty(urls)) { _avlSvcUrls.set(urls); } } catch (final Throwable e) { _logger.warn("refesh service urls failed", e); } finally { _logger.info("end refresh service urls"); } } AddressRepository(final String clientId, final ArtemisClientManagerConfig managerConfig, final String path); String get(); }### Answer: @Test public void testRefresh() { _addressRepository.refresh(); Assert.assertNotNull(_addressRepository.get()); }
### Question: Conditions { public static boolean verifyInstance(final Instance instance) { return (instance != null) && !StringValues.isNullOrWhitespace(instance.getInstanceId()) && !StringValues.isNullOrWhitespace(instance.getServiceId()) && !StringValues.isNullOrWhitespace(instance.getUrl()); } static boolean verifyInstance(final Instance instance); static boolean verifyInstances(final Instance[] instances); static boolean verifyInstances(final Collection<Instance> instances); static boolean verifyService(final Service service); static boolean verifyServices(final Collection<Service> services); }### Answer: @Test public void verifyInstance() { { Assert.assertFalse(Conditions.verifyInstance(new Instance())); } { Assert.assertTrue(Conditions.verifyInstance(Instances.newInstance())); } }
### Question: Conditions { public static boolean verifyInstances(final Instance[] instances) { if ((instances == null) || (instances.length == 0)) { return false; } for (final Instance instance : instances) { if (!verifyInstance(instance)) { return false; } } return true; } static boolean verifyInstance(final Instance instance); static boolean verifyInstances(final Instance[] instances); static boolean verifyInstances(final Collection<Instance> instances); static boolean verifyService(final Service service); static boolean verifyServices(final Collection<Service> services); }### Answer: @Test public void verifyInstances() { { final Instance[] instances = new Instance[]{Instances.newInstance(), new Instance()}; Assert.assertFalse(Conditions.verifyInstances(instances)); Assert.assertFalse(Conditions.verifyInstances(Lists.newArrayList(instances))); } { final Instance[] instances = new Instance[]{Instances.newInstance()}; Assert.assertTrue(Conditions.verifyInstances(instances)); Assert.assertTrue(Conditions.verifyInstances(Lists.newArrayList(instances))); } }
### Question: Conditions { public static boolean verifyService(final Service service) { return (service != null) && !StringValues.isNullOrWhitespace(service.getServiceId()); } static boolean verifyInstance(final Instance instance); static boolean verifyInstances(final Instance[] instances); static boolean verifyInstances(final Collection<Instance> instances); static boolean verifyService(final Service service); static boolean verifyServices(final Collection<Service> services); }### Answer: @Test public void verifyService() { { Assert.assertFalse(Conditions.verifyService(new Service())); } { Assert.assertTrue(Conditions.verifyService(new Service(Services.newServiceId()))); } }
### Question: Conditions { public static boolean verifyServices(final Collection<Service> services) { if (CollectionUtils.isEmpty(services)) { return false; } for (final Service service : services) { if (!verifyService(service)) { return false; } } return true; } static boolean verifyInstance(final Instance instance); static boolean verifyInstances(final Instance[] instances); static boolean verifyInstances(final Collection<Instance> instances); static boolean verifyService(final Service service); static boolean verifyServices(final Collection<Service> services); }### Answer: @Test public void verifyServices() { { Assert.assertFalse(Conditions.verifyServices(Lists.newArrayList(new Service(), new Service(Services.newServiceId())))); } { Assert.assertTrue(Conditions.verifyServices(Lists.newArrayList(new Service(Services.newServiceId()), new Service(Services.newServiceId())))); } }
### Question: WebSocketSessionContext { protected void connect() { if (_isConnecting.compareAndSet(false, true)) { try { if (rateLimiter.isRateLimited("connect")) { _logger.error("WebSocketSessionContext reconnect times exceed expected value for a period time"); return; } final AddressContext context = _addressManager.getContext(); if (!context.isAavailable()) { return; } ListenableFuture<WebSocketSession> future = _wsClient.doHandshake(_handler, context.getWebSocketEndPoint()); future.addCallback(new WebSocketSessionCallback(this, context)); try { WebSocketSession session = future.get(_connectTimeout.typedValue(), TimeUnit.MILLISECONDS); final WebSocketSession oldSession = _session.getAndSet(session); _lastUpdatedTime = System.currentTimeMillis(); _addressContext.set(context); disconnect(oldSession); WebSocketSessionContext.this.afterConnectionEstablished(session); _logger.info("WebSocketSessionContext connected to: " + context.getWebSocketEndPoint()); } catch (Throwable ex) { context.markUnavailable(); _logger.warn("get WebSocketSession failed within the time specified", ex); } } catch (final Throwable e) { _addressContext.get().markUnavailable(); _logger.warn("connect to websocket endpoint failed", e); } finally { _isConnecting.set(false); } } } WebSocketSessionContext(final ArtemisClientConfig config); void start(); static void disconnect(final WebSocketSession session); WebSocketSession get(); void checkHealth(); void markdown(); void shutdown(); }### Answer: @Test(timeout=5000) public void testConnect() { final WebSocketSession session = registrySessionContext.get(); if (registrySessionContext.isAvailable()) { WebSocketSessionContext.disconnect(session); Assert.assertFalse(session.isOpen()); } Assert.assertTrue(registrySessionContext.isAvailable()); registrySessionContext.connect(); Assert.assertTrue(registrySessionContext.isAvailable()); }
### Question: WebSocketSessionContext { protected boolean isExpired() { return System.currentTimeMillis() >= (_lastUpdatedTime + _ttl.typedValue()); } WebSocketSessionContext(final ArtemisClientConfig config); void start(); static void disconnect(final WebSocketSession session); WebSocketSession get(); void checkHealth(); void markdown(); void shutdown(); }### Answer: @Test public void testIsExpired() { Assert.assertFalse(registrySessionContext.isExpired()); }
### Question: WebSocketSessionContext { public void checkHealth() { if (_isChecking.compareAndSet(false, true)) { try { boolean available = _addressContext.get().isAavailable() && !isExpired() && isAvailable(); if (!available) { connect(); } } catch (final Throwable e) { _logger.warn("WebSocketSession check health failed", e); } finally { _isChecking.set(false); } } } WebSocketSessionContext(final ArtemisClientConfig config); void start(); static void disconnect(final WebSocketSession session); WebSocketSession get(); void checkHealth(); void markdown(); void shutdown(); }### Answer: @Test public void testCheckHealth() { registrySessionIsExpired.set(true); registrySessionContext.checkHealth(); registrySessionIsExpired.set(false); }
### Question: ServiceContext { public synchronized boolean addInstance(Instance instance) { if (instance == null) { return false; } String instanceServiceId = instance.getServiceId(); if (instanceServiceId == null || !serviceId.equals(instanceServiceId.toLowerCase())) { return false; } List<Instance> instances = service.getInstances(); if (instances == null) { instances = new ArrayList<>(); } deleteInstance(instance); instances.add(instance); service.setInstances(instances); return true; } 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 testAddInstance() { ServiceContext context = new ServiceContext(_discoveryConfig); Instance instance1 = Instances.newInstance(_serviceId); Assert.assertTrue(context.addInstance(instance1)); Assert.assertEquals(1, context.newService().getInstances().size()); Instance instance2 = instance1.clone(); instance2.setServiceId(instance1.getServiceId().toUpperCase()); Assert.assertTrue(context.addInstance(instance2)); Assert.assertEquals(1, context.newService().getInstances().size()); Assert.assertFalse(context.addInstance(Instances.newInstance())); Assert.assertEquals(1, context.newService().getInstances().size()); Assert.assertTrue(context.addInstance(Instances.newInstance(_serviceId))); Assert.assertEquals(2, context.newService().getInstances().size()); }
### Question: WebSocketSessionContext { public WebSocketSession get() { return _session.get(); } WebSocketSessionContext(final ArtemisClientConfig config); void start(); static void disconnect(final WebSocketSession session); WebSocketSession get(); void checkHealth(); void markdown(); void shutdown(); }### Answer: @Test public void testGet() { Assert.assertNotNull(registrySessionContext.get()); }
### Question: ZoneRepository { protected boolean refreshCache() { Set<String> changedServices; try { changedServices = refreshZoneOperations(); } catch (Throwable ex) { logger.error("zone operation cache refresh failed", ex); return false; } for (String serviceKey : changedServices) { registryRepository.addInstanceChange(InstanceChanges.newReloadInstanceChange(serviceKey)); } return true; } private ZoneRepository(); static ZoneRepository getInstance(); boolean isZoneDown(ZoneKey zoneKey); List<ZoneOperations> getAllZoneOperations(String regionId); ZoneOperations getZoneOperations(ZoneKey zoneKey); List<ZoneOperations> getServiceZoneOperations(String serviceId); List<ZoneOperations> getZoneOperationsList(ZoneOperationModel filter); void operateGroupOperations(OperationContext operationContext, List<ZoneOperationModel> zoneOperations, boolean isOperationComplete); boolean isLastRefreshSuccess(); long getLastRefreshTime(); }### Answer: @Test public void testRefreshCache() { zoneRepository.operateGroupOperations(operationContext, zoneOperations, false); int allZoneOperationsSize = zoneRepository.getAllZoneOperations(DeploymentConfig.regionId()).size(); zoneRepository.refreshCache(); Assert.assertEquals(allZoneOperationsSize + zoneOperations.size(), zoneRepository.getAllZoneOperations(DeploymentConfig.regionId()).size()); for (ZoneOperationModel model : zoneOperations) { ZoneKey zoneKey = new ZoneKey(model.getRegionId(), model.getServiceId(), model.getZoneId()); ZoneOperations zoneOperations = zoneRepository.getZoneOperations(zoneKey); Assert.assertEquals(zoneKey, zoneOperations.getZoneKey()); Assert.assertEquals(1, zoneOperations.getOperations().size()); Assert.assertEquals(model.getOperation(), zoneOperations.getOperations().get(0)); Assert.assertEquals(1, zoneRepository.getServiceZoneOperations(model.getServiceId()).size()); zoneOperations = zoneRepository.getServiceZoneOperations(model.getServiceId()).get(0); Assert.assertEquals(zoneKey, zoneOperations.getZoneKey()); Assert.assertEquals(1, zoneOperations.getOperations().size()); Assert.assertEquals(model.getOperation(), zoneOperations.getOperations().get(0)); } zoneRepository.operateGroupOperations(operationContext, zoneOperations, true); zoneRepository.refreshCache(); Assert.assertEquals(allZoneOperationsSize, zoneRepository.getAllZoneOperations(DeploymentConfig.regionId()).size()); for (ZoneOperationModel model : zoneOperations) { ZoneKey zoneKey = new ZoneKey(model.getRegionId(), model.getServiceId(), model.getZoneId()); Assert.assertNull(zoneRepository.getZoneOperations(zoneKey)); Assert.assertEquals(0, zoneRepository.getServiceZoneOperations(model.getServiceId()).size()); } }
### Question: ServerLogDao { public void insert(final ServerLogModel... logs) { if ((logs == null) || (logs.length == 0)) { return; } this.insert(Lists.newArrayList(logs)); } private ServerLogDao(); List<ServerOperationLog> select(ServerLogModel filter, Boolean complete); List<ServerOperationLog> query(final String condition, final List<String> args); void insert(final ServerLogModel... logs); void insert(final List<ServerLogModel> logs); static final ServerLogDao INSTANCE; }### Answer: @Test public void testInsert() { final ServerLogModel log1 = ServerLogModels.newServerLogModel(); final ServerLogModel log2 = ServerLogModels.newServerLogModel(); final List<ServerLogModel> logs = Lists.newArrayList(log1, log2); log1.setComplete(true); log2.setComplete(true); _serverLogDao.insert(log1, log2); for (final ServerLogModel log : logs) { final List<ServerOperationLog> logModels = query(log); Assert.assertEquals(1, logModels.size()); ServerLogModels.assertServerLog(log, logModels.get(0)); } log1.setComplete(false); log2.setComplete(false); _serverLogDao.insert(log1, log2); for (final ServerLogModel log : logs) { final List<ServerOperationLog> logModels = query(log); Assert.assertEquals(1, logModels.size()); ServerLogModels.assertServerLog(log, logModels.get(0)); } }
### Question: ServerDao { public void insert(final ServerModel... servers) { if ((servers == null) || (servers.length == 0)) { return; } this.insert(Lists.newArrayList(servers)); } private ServerDao(); List<ServerModel> queryServer(final String regionId, final String serverId); List<ServerModel> queryServers(final String regionId); List<ServerModel> queryServers(); List<ServerModel> query(final String condition, final String... args); void delete(final Long... ids); void delete(final ServerModel... servers); void delete(final List<ServerModel> serverList); void destroyServers(final List<ServerKey> serverKeys); void insert(final ServerModel... servers); void insert(final List<ServerModel> serverList); static final ServerDao INSTANCE; }### Answer: @Test public void testInsert() { final ServerModel server1 = ServerModels.newServerModel(); final ServerModel server2 = ServerModels.newServerModel(); final List<ServerModel> servers = Lists.newArrayList(server1, server2); serverDao.insert(server1, server2); serverDao.insert(servers); for (final ServerModel server : servers) { final List<ServerModel> serverModels = query(server); Assert.assertTrue(serverModels.size() == 1); ServerModels.assertServer(server, serverModels.get(0)); server.setToken(ServerModels.newServerModel().getToken()); server.setOperatorId(ServerModels.newServerModel().getOperatorId()); } serverDao.insert(servers); for (final ServerModel server : servers) { final List<ServerModel> serverModels = query(server); Assert.assertTrue(serverModels.size() == 1); ServerModels.assertServer(server, serverModels.get(0)); } }
### Question: ServerDao { public void destroyServers(final List<ServerKey> serverKeys) { if (CollectionUtils.isEmpty(serverKeys)) { return; } DataConfig.jdbcTemplate().batchUpdate("delete from server where region_id=? and server_id=?", new BatchPreparedStatementSetter() { @Override public int getBatchSize() { return serverKeys.size(); } @Override public void setValues(final PreparedStatement ps, final int index) throws SQLException { ServerKey serverKey = serverKeys.get(index); ps.setString(1, serverKey.getRegionId()); ps.setString(2, serverKey.getServerId()); } }); } private ServerDao(); List<ServerModel> queryServer(final String regionId, final String serverId); List<ServerModel> queryServers(final String regionId); List<ServerModel> queryServers(); List<ServerModel> query(final String condition, final String... args); void delete(final Long... ids); void delete(final ServerModel... servers); void delete(final List<ServerModel> serverList); void destroyServers(final List<ServerKey> serverKeys); void insert(final ServerModel... servers); void insert(final List<ServerModel> serverList); static final ServerDao INSTANCE; }### Answer: @Test public void testDestroyServers() { final ServerModel server1 = ServerModels.newServerModel(); final ServerModel server2 = ServerModels.newServerModel(); serverDao.insert(server1, server2); Assert.assertTrue(query(server1).size() == 1); Assert.assertTrue(query(server2).size() == 1); List<ServerKey> serverKeys = Lists.newArrayList(new ServerKey(server1.getRegionId(), server1.getServerId()), new ServerKey(server2.getRegionId(), server2.getServerId())); serverDao.destroyServers(serverKeys); Assert.assertTrue(query(server1).size() == 0); Assert.assertTrue(query(server2).size() == 0); }
### Question: InstanceLogDao { public void insert(final InstanceLogModel... logs) { if ((logs == null) || (logs.length == 0)) { return; } this.insert(Lists.newArrayList(logs)); } private InstanceLogDao(); List<InstanceOperationLog> select(InstanceLogModel filter, Boolean complete); List<InstanceOperationLog> query(final String condition, final List<String> args); void insert(final InstanceLogModel... logs); void insert(final List<InstanceLogModel> logs); static final InstanceLogDao INSTANCE; }### Answer: @Test public void testInsert() { final InstanceLogModel log1 = InstanceLogModels.newInstanceLogModel(); final InstanceLogModel log2 = InstanceLogModels.newInstanceLogModel(); log1.setComplete(true); log2.setComplete(true); final List<InstanceLogModel> logs = Lists.newArrayList(log1, log2); _instanceLogDao.insert(log1, log2); for (final InstanceLogModel log : logs) { final List<InstanceOperationLog> logModels = query(log); Assert.assertEquals(1, logModels.size()); InstanceLogModels.assertInstanceLog(log, logModels.get(0)); } log1.setComplete(false); log2.setComplete(false); _instanceLogDao.insert(log1, log2); for (final InstanceLogModel log : logs) { final List<InstanceOperationLog> logModels = query(log); Assert.assertEquals(1, logModels.size()); InstanceLogModels.assertInstanceLog(log, logModels.get(0)); } }
### Question: InstanceDao { public void insert(final InstanceModel... instances) { if ((instances == null) || (instances.length == 0)) { return; } this.insert(Lists.newArrayList(instances)); } private InstanceDao(); List<InstanceModel> queryInstance(final String regionId, final String serviceId, final String instanceId); List<InstanceModel> queryInstances(final String regionId); List<InstanceModel> queryInstances(); List<InstanceModel> queryInstances(final String regionId, final List<String> serviceIds); List<InstanceModel> query(final String condition, final String... args); void delete(final Long... ids); void delete(final InstanceModel... instances); void delete(final List<InstanceModel> instances); void destroyServers(final List<ServerKey> serverKeys); void insert(final InstanceModel... instances); void insert(final List<InstanceModel> instances); static final InstanceDao INSTANCE; }### Answer: @Test public void testInsert() { final InstanceModel instance1 = InstanceModels.newInstanceModel(); final InstanceModel instance2 = InstanceModels.newInstanceModel(); final List<InstanceModel> instances = Lists.newArrayList(instance1, instance2); instanceDao.insert(instance1, instance2); instanceDao.insert(instances); for (final InstanceModel instance : instances) { final List<InstanceModel> instanceModels = query(instance); Assert.assertTrue(instanceModels.size() == 1); InstanceModels.assertInstance(instance, instanceModels.get(0)); instance.setOperatorId(InstanceModels.newInstanceModel().getOperatorId()); instance.setToken(InstanceModels.newInstanceModel().getToken()); } instanceDao.insert(instances); for (final InstanceModel instance : instances) { final List<InstanceModel> instanceModels = query(instance); Assert.assertTrue(instanceModels.size() == 1); InstanceModels.assertInstance(instance, instanceModels.get(0)); } }
### Question: InstanceDao { public void destroyServers(final List<ServerKey> serverKeys) { if (CollectionUtils.isEmpty(serverKeys)) { return; } DataConfig.jdbcTemplate().batchUpdate("delete from instance where region_id=? and instance_id=?", new BatchPreparedStatementSetter() { @Override public int getBatchSize() { return serverKeys.size(); } @Override public void setValues(final PreparedStatement ps, final int index) throws SQLException { ServerKey serverKey = serverKeys.get(index); ps.setString(1, serverKey.getRegionId()); ps.setString(2, serverKey.getServerId()); } }); } private InstanceDao(); List<InstanceModel> queryInstance(final String regionId, final String serviceId, final String instanceId); List<InstanceModel> queryInstances(final String regionId); List<InstanceModel> queryInstances(); List<InstanceModel> queryInstances(final String regionId, final List<String> serviceIds); List<InstanceModel> query(final String condition, final String... args); void delete(final Long... ids); void delete(final InstanceModel... instances); void delete(final List<InstanceModel> instances); void destroyServers(final List<ServerKey> serverKeys); void insert(final InstanceModel... instances); void insert(final List<InstanceModel> instances); static final InstanceDao INSTANCE; }### Answer: @Test public void testDestroyServers() { final InstanceModel instance1 = InstanceModels.newInstanceModel(); final InstanceModel instance2 = InstanceModels.newInstanceModel(); final List<InstanceModel> instances = Lists.newArrayList(instance1, instance2); instanceDao.insert(instances); List<ServerKey> serverKeys = Lists.newArrayList(); for (final InstanceModel instance : instances) { serverKeys.add(new ServerKey(instance.getRegionId(), instance.getInstanceId())); List<InstanceModel> instanceModels = query(instance); Assert.assertEquals(1, instanceModels.size()); } instanceDao.destroyServers(serverKeys); for (final InstanceModel instance : instances) { List<InstanceModel> instanceModels = query(instance); Assert.assertEquals(0, instanceModels.size()); } }
### Question: RouteRuleLogDao { public void insert(final RouteRuleLogModel... logs) { if ((logs == null) || (logs.length == 0)) { return; } this.insert(Lists.newArrayList(logs)); } private RouteRuleLogDao(); List<RouteRuleLog> select(RouteRuleLogModel filter); List<RouteRuleLog> query(final String condition, final List<Object> args); void insert(final RouteRuleLogModel... logs); void insert(final List<RouteRuleLogModel> logs); static final RouteRuleLogDao INSTANCE; }### Answer: @Test public void testInsert() { final RouteRuleLogModel log1 = newModel(); final RouteRuleLogModel log2 = newModel(); final List<RouteRuleLogModel> logs = Lists.newArrayList(log1, log2); routeRuleLogDao.insert(log1, log2); for (final RouteRuleLogModel log : logs) { final List<RouteRuleLog> logModels = query(log); Assert.assertEquals(1, logModels.size()); assertLog(log, logModels.get(0)); } }
### Question: GroupDao { protected GroupModel generateGroup(GroupModel group) { GroupModel filter = new GroupModel(); filter.setServiceId(group.getServiceId()); filter.setRegionId(group.getRegionId()); filter.setZoneId(group.getZoneId()); filter.setName(group.getName()); List<GroupModel> newGroups = select(filter); if (newGroups.size() == 0) { insert(group); newGroups = select(filter); } return newGroups.get(0); } private GroupDao(); List<GroupModel> query(); List<GroupModel> select(GroupModel filter); List<GroupModel> select(List<Long> groupIds); static final GroupDao INSTANCE; }### Answer: @Test public void testGenerateGroup() { GroupModel group = newGroup(); GroupModel newGroup = groupDao.generateGroup(group); Assert.assertNotNull(newGroup.getId()); assertGroup(newGroup, group); }