src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
DebtDetailPresenter implements DebtDetailContract.Presenter, LoaderManager.LoaderCallbacks<PersonDebt> { @Override public void deletePayment(@NonNull Payment payment) { checkNotNull(payment); EspressoIdlingResource.increment(); mDebtsRepository.deletePayment(payment); mDebtDetailView.showPaymentDeleted(); refreshPaymen...
@Test public void shouldBeAbleToDeletePayment() { Payment payment = TestUtil.createAndGetADebtPayment1(mDebt.getId()); when(mRepository.getPersonDebt(anyString(), anyInt())).thenReturn(mPersonDebt); mDebtDetailPresenter.deletePayment(payment); verify(mRepository).deletePayment(eq(payment)); verify(mView).showPersonDebt...
ConfigPropertySource extends PropertySource<Object> { @Override public Object getProperty(String name) { return containsProperty(name) ? config.getAnyRef(name) : null; } ConfigPropertySource(Config config, String name); @Override boolean containsProperty(String name); @Override Object getProperty(String name); }
@Test public void getRequiredProperty_resolve_stringProperty() throws Exception { ctx.refresh(); String value = ctx.getEnvironment().getProperty("foo"); assertEquals("bar", value); assertEquals(Integer.valueOf(1), ctx.getEnvironment().getProperty("number", Integer.class)); }
RelationResolver extends AbstractResolver<Relation> { @SuppressWarnings("unchecked") public Class<? extends Concept> getTargetEntityClass(final Class<? extends Relation> clazz) { if (TARGETS_CACHE.containsKey(checkNotNull(clazz))) { return (Class<? extends Concept>) TARGETS_CACHE.get(clazz); } @SuppressWarnings("unchec...
@Test public void testGetTargetWithInvalidRelation() { final RelationResolver resolver = new RelationResolver(); try { final Class<? extends Concept> conceptClass = resolver.getTargetEntityClass(TestRelation.class); fail(); } catch (final KasperException e) { } } @Test public void testGetTargetWithValidRelation() { fin...
EventResolver extends AbstractResolver<Event> { @Override @SuppressWarnings("unchecked") public Optional<Class<? extends Domain>> getDomainClass(final Class<? extends Event> clazz) { if (DOMAINS_CACHE.containsKey(checkNotNull(clazz))) { return Optional.<Class<? extends Domain>>of(DOMAINS_CACHE.get(clazz)); } final Opti...
@Test public void testGetDomainFromDomainEvent() { final EventResolver resolver = new EventResolver(); final Optional<Class<? extends Domain>> domain = resolver.getDomainClass(TestDomainEvent.class); assertTrue(domain.isPresent()); assertEquals(TestDomain.class, domain.get()); } @Test public void testGetDomainFromGener...
EntityResolver extends AbstractResolver<Entity> { public List<Class<? extends Concept>> getComponentConcepts(final Class<? extends AggregateRoot> conceptClazz) { final List<Class<? extends Concept>> linkedConcepts = Lists.newArrayList(); for (final Field field : checkNotNull(conceptClazz).getDeclaredFields()) { if (Lin...
@Test public void testGetComponentConcepts() { final EntityResolver resolver = new EntityResolver(); final List<Class<? extends Concept>> links = resolver.getComponentConcepts(TestConcept.class); assertEquals(1, links.size()); assertEquals(TestConcept2.class, links.get(0)); }
QueryHandlerResolver extends AbstractResolver<QueryHandler> { @Override @SuppressWarnings("unchecked") public Optional<Class<? extends Domain>> getDomainClass(final Class<? extends QueryHandler> clazz) { if (DOMAINS_CACHE.containsKey(checkNotNull(clazz))) { return Optional.<Class<? extends Domain>>of(DOMAINS_CACHE.get(...
@Test public void testGetDomainWithDecoratedQueryHandler() { final QueryHandlerResolver resolver = new QueryHandlerResolver(); final Optional<Class<? extends Domain>> domain = resolver.getDomainClass(TestQueryHandler.class); assertTrue(domain.isPresent()); assertEquals(TestDomain.class, domain.get()); } @Test public vo...
QueryHandlerResolver extends AbstractResolver<QueryHandler> { @SuppressWarnings("unchecked") public Class<? extends Query> getQueryClass(final Class<? extends QueryHandler> clazz) { if (QUERY_CACHE.containsKey(checkNotNull(clazz))) { return QUERY_CACHE.get(clazz); } @SuppressWarnings("unchecked") final Optional<Class<?...
@Test public void testGetQueryFromValidService() { final QueryHandlerResolver resolver = new QueryHandlerResolver(); final Class<? extends Query> query = resolver.getQueryClass(TestQueryHandler3.class); assertEquals(TestQuery.class, query); } @Test public void testGetQueryFromInvalidHandler() { final QueryHandlerResolv...
QueryHandlerResolver extends AbstractResolver<QueryHandler> { @SuppressWarnings("unchecked") public Class<? extends QueryResult> getQueryResultClass(final Class<? extends QueryHandler> clazz) { if (RESULT_CACHE.containsKey(checkNotNull(clazz))) { return RESULT_CACHE.get(clazz); } @SuppressWarnings("unchecked") final Op...
@Test public void testGetQueryResultFromValidHandler() { final QueryHandlerResolver resolver = new QueryHandlerResolver(); final Class<? extends QueryResult> queryResult = resolver.getQueryResultClass(TestQueryHandler3.class); assertEquals(TestQueryResult.class, queryResult); } @Test public void testGetQueryResultFromI...
AbstractKasperID implements KasperID { @Override public boolean equals(final Object otherId) { if (this == checkNotNull(otherId)) { return true; } if (KasperID.class.isAssignableFrom(otherId.getClass())) { final KasperID other = (KasperID) otherId; return this.toString().equals(other.toString()); } return this.id.equal...
@Test public void testID() { final TestID id1 = new TestID(INT_ID_A); final TestID id2 = new TestID(INT_ID_A); final TestID id3 = new TestID(INT_ID_B); assertTrue(id1.equals(id1)); assertTrue(id1.equals(id2)); assertTrue(id1.equals(INT_ID_A)); assertFalse(id1.equals(id3)); assertFalse(id1.equals(INT_ID_B)); }
EventListenerResolver extends AbstractResolver<EventListener> { @Override @SuppressWarnings("unchecked") public Optional<Class<? extends Domain>> getDomainClass(final Class<? extends EventListener> clazz) { if (DOMAINS_CACHE.containsKey(checkNotNull(clazz))) { return Optional.<Class<? extends Domain>>of(DOMAINS_CACHE.g...
@Test public void testGetDomainFromEventListener() { final EventListenerResolver resolver = new EventListenerResolver(); final Optional<Class<? extends Domain>> domain = resolver.getDomainClass(TestEventListener.class); assertTrue(domain.isPresent()); assertEquals(TestDomain.class, domain.get()); }
EventListenerResolver extends AbstractResolver<EventListener> { public Class<? extends Event> getEventClass(final Class<? extends EventListener> clazz) { if (cacheEvents.containsKey(checkNotNull(clazz))) { return cacheEvents.get(clazz); } final Optional<Class<? extends Event>> eventClazz = (Optional<Class<? extends Eve...
@Test public void testGetEventFromValidHandler() { final EventListenerResolver resolver = new EventListenerResolver(); final Class<? extends Event> command = resolver.getEventClass(TestEventListener2.class); assertEquals(TestEvent.class, command); } @Test public void testGetEventFromInvalidHandler() { final EventListen...
QueryResultResolver extends AbstractResolver<QueryResult> { @Override @SuppressWarnings("unchecked") public Optional<Class<? extends Domain>> getDomainClass(final Class<? extends QueryResult> clazz) { if (DOMAINS_CACHE.containsKey(checkNotNull(clazz))) { return Optional.<Class<? extends Domain>>of(DOMAINS_CACHE.get(cla...
@Test public void testGetDomain() { final QueryHandler queryHandler = mock(QueryHandler.class); when( queryHandlersLocator.getHandlersFromQueryResultClass(TestQueryResult.class) ) .thenReturn(Collections.singletonList(queryHandler) ); when( queryHandlerResolver.getDomainClass(queryHandler.getClass()) ) .thenReturn(Opti...
QueryResultResolver extends AbstractResolver<QueryResult> { @SuppressWarnings("unchecked") public Class<? extends QueryResult> getElementClass(final Class<? extends CollectionQueryResult> clazz) { if (cacheElements.containsKey(clazz)) { return cacheElements.get(clazz); } @SuppressWarnings("unchecked") final Optional<Cl...
@Test(expected = KasperException.class) public void getElementClass_fromQueryResult_throwException() { resolver.getElementClass(UnknownCollectionQueryResult.class); } @Test public void getElementClass_fromCollectionQueryResult_returnElementClass() { final Class<? extends QueryResult> elementClass = resolver.getElementC...
ConceptResolver extends AbstractResolver<Concept> { @SuppressWarnings("unchecked") @Override public Optional<Class<? extends Domain>> getDomainClass(final Class<? extends Concept> clazz) { if (DOMAINS_CACHE.containsKey(checkNotNull(clazz))) { return Optional.<Class<? extends Domain>>of(DOMAINS_CACHE.get(clazz)); } fina...
@Test public void testGetDomainWithDecoratedConcept() { final ConceptResolver resolver = new ConceptResolver(); final Optional<Class<? extends Domain>> domain = resolver.getDomainClass(TestConcept.class); assertTrue(domain.isPresent()); assertEquals(TestDomain.class, domain.get()); } @Test public void testGetDomainWith...
CommandHandlerResolver extends AbstractResolver<CommandHandler> { @Override @SuppressWarnings("unchecked") public Optional<Class<? extends Domain>> getDomainClass(final Class<? extends CommandHandler> clazz) { if (DOMAINS_CACHE.containsKey(checkNotNull(clazz))) { return Optional.<Class<? extends Domain>>of(DOMAINS_CACH...
@Test public void testGetDomainFromCommandHandler() { final CommandHandlerResolver resolver = new CommandHandlerResolver(); final Optional<Class<? extends Domain>> domain = resolver.getDomainClass(TestCommandHandler.class); assertTrue(domain.isPresent()); assertEquals(TestDomain.class, domain.get()); }
AbstractKasperID implements KasperID { @Override public int hashCode() { return this.id.hashCode(); } protected AbstractKasperID(); protected AbstractKasperID(final T id); @Override boolean equals(final Object otherId); @Override int hashCode(); @Override T getId(); @Override String toString(); }
@Test public void testHashCode() { final TestID id1 = new TestID(INT_ID_A); final TestID id2 = new TestID(INT_ID_A); final TestID id3 = new TestID(INT_ID_B); assertEquals(id1.hashCode(), id1.hashCode()); assertEquals(id1.hashCode(), id2.hashCode()); assertNotSame(id1.hashCode(), id3.hashCode()); }
CommandHandlerResolver extends AbstractResolver<CommandHandler> { @SuppressWarnings("unchecked") public Class<? extends Command> getCommandClass(final Class<? extends CommandHandler> clazz) { if (cacheCommands.containsKey(checkNotNull(clazz))) { return cacheCommands.get(clazz); } @SuppressWarnings("unchecked") final Op...
@Test public void testGetCommandFromValidHandler() { final CommandHandlerResolver resolver = new CommandHandlerResolver(); final Class<? extends Command> command = resolver.getCommandClass(TestCommandHandler2.class); assertEquals(TestCommand.class, command); } @Test public void testGetCommandFromInvalidHandler() { fina...
QueryAttributesKeyGenerator implements QueryCacheKeyGenerator<Q> { final Set<String> retainMissingNames(final Set<String> expectedFieldNames, final Set<Field> discoveredFields) { final Set<String> discoveredNames = Sets.newHashSet( Iterables.transform( discoveredFields, new Function<Field, String>() { @Override public ...
@Test public void testSetDifference() throws NoSuchFieldException { final Set<String> missingNames; missingNames = keyGenerator.retainMissingNames( Sets.newHashSet("str", "integer"), Sets.newHashSet(SomeQuery.class.getDeclaredField("str")) ); assertIterableEquals(Lists.newArrayList("integer"), missingNames); }
InterceptorChain { @SafeVarargs public static <I, O> InterceptorChain<I, O> makeChain(final Interceptor<I, O>...chain) { return makeChain(Lists.newArrayList(checkNotNull(chain))); } InterceptorChain(); @SuppressWarnings("unchecked") // TAIL is generic InterceptorChain(final Interceptor<INPUT, OUTPUT> actor); Intercep...
@Test public void testIteratorToChain() { final DummyInterceptor d1 = new DummyInterceptor(); final DummyInterceptor d2 = new DummyInterceptor(); final Iterable<DummyInterceptor> chain = Lists.newArrayList(null, d1, null, d2, null); final InterceptorChain<Query, QueryResult> actualChain = InterceptorChain.makeChain(cha...
InterceptorChain { public Optional<Interceptor<INPUT, OUTPUT>> last() { if (next.isPresent() && next.get().actor.isPresent()) { return next.get().last(); } else { return actor; } } InterceptorChain(); @SuppressWarnings("unchecked") // TAIL is generic InterceptorChain(final Interceptor<INPUT, OUTPUT> actor); Intercept...
@Test public void last_fromEmptyChain_shouldReturnAbsent(){ final InterceptorChain<Query, QueryResult> chain = new InterceptorChain<>(); final Optional<Interceptor<Query,QueryResult>> optionalLastInterceptor = chain.last(); assertFalse(optionalLastInterceptor.isPresent()); }
KasperDocResource implements Resource { private static Optional<AbstractDomainElement> get(final DocumentedDomain documentedDomain, final DocumentedElementType type, final String name) { for (final AbstractDomainElement documentedDomainElement : get(documentedDomain, type)) { if (documentedDomainElement.getName().equal...
@Test public void test() throws IOException, JSONException, URISyntaxException { final Predicate<String> filter = new FilterBuilder().include(".*\\.json"); final Reflections reflections = new Reflections( new ConfigurationBuilder() .filterInputsBy(filter) .setScanners(new ResourcesScanner()) .setUrls(Arrays.asList(Clas...
ObjectMapperProvider { public ObjectWriter objectWriter() { return mapper.writer(); } ObjectMapperProvider(); static ObjectMapperProvider defaults(); ObjectWriter objectWriter(); ObjectReader objectReader(); ObjectMapper mapper(); static final ObjectMapperProvider INSTANCE; }
@Test public void queryResponseSuccessRoundTrip() throws IOException { final QueryResponse<SomeResult> expected = new QueryResponse<SomeResult>(new SomeResult("foo")); final String json = ObjectMapperProvider.INSTANCE.objectWriter().writeValueAsString( expected ); final QueryResponse<SomeResult> actual = objectReader.r...
RepositoryResolver extends AbstractResolver<Repository> { @Override @SuppressWarnings("unchecked") public Optional<Class<? extends Domain>> getDomainClass(final Class<? extends Repository> clazz) { if (DOMAINS_CACHE.containsKey(checkNotNull(clazz))) { return Optional.<Class<? extends Domain>>of(DOMAINS_CACHE.get(clazz)...
@Test public void testGetDomainFromGenericRepository() { final RepositoryResolver resolver = new RepositoryResolver(); try { resolver.getDomainClass(TestGenericRepository.class); fail(); } catch (final KasperException e) { } }
ObjectMapperProvider { public ObjectMapper mapper() { return mapper; } ObjectMapperProvider(); static ObjectMapperProvider defaults(); ObjectWriter objectWriter(); ObjectReader objectReader(); ObjectMapper mapper(); static final ObjectMapperProvider INSTANCE; }
@Test public void serializeDateTimeToISO8601() throws IOException { final DateTime dateTime = new DateTime(2013, 8, 6, 7, 35, 0, 123, DateTimeZone.UTC); final String actual = ObjectMapperProvider.INSTANCE.mapper().writeValueAsString(dateTime); assertEquals("\"2013-08-06T07:35:00.123Z\"", actual); } @Test public void de...
DomainResolver implements Resolver<Domain> { @Override @SuppressWarnings("unchecked") public Optional<Class<? extends Domain>> getDomainClass(final Class<? extends Domain> clazz) { return Optional.<Class<? extends Domain>>of(checkNotNull(clazz)); } @Override String getTypeName(); @Override String getLabel(final Class<...
@Test public void testGetDomain() { final DomainResolver domainResolver = new DomainResolver(); final Optional<Class<? extends Domain>> domain = domainResolver.getDomainClass(TestDomain.class); assertTrue(domain.isPresent()); assertEquals(TestDomain.class, domain.get()); }
RelationResolver extends AbstractResolver<Relation> { @Override @SuppressWarnings("unchecked") public Optional<Class<? extends Domain>> getDomainClass(final Class<? extends Relation> clazz) { if (DOMAINS_CACHE.containsKey(checkNotNull(clazz))) { return Optional.<Class<? extends Domain>>of(DOMAINS_CACHE.get(clazz)); } f...
@Test public void testGetDomainWithDecoratedRelation() { final RelationResolver resolver = new RelationResolver(); final Optional<Class<? extends Domain>> domain = resolver.getDomainClass(TestRelation.class); assertTrue(domain.isPresent()); assertEquals(TestDomain.class, domain.get()); } @Test public void testGetDomain...
RelationResolver extends AbstractResolver<Relation> { @SuppressWarnings("unchecked") public Class<? extends Concept> getSourceEntityClass(final Class<? extends Relation> clazz) { if (SOURCES_CACHE.containsKey(checkNotNull(clazz))) { return (Class<? extends Concept>) SOURCES_CACHE.get(clazz); } @SuppressWarnings("unchec...
@Test public void testGetSourceWithValidRelation() { final RelationResolver resolver = new RelationResolver(); final Class<? extends Concept> conceptClass = resolver.getSourceEntityClass(TestRelation2.class); assertEquals(TestRootConceptSource.class, conceptClass); } @Test public void testGetSourceWithInvalidRelation()...
ASTGenerator { public ASTJb generateAST() { ASTJb ast = new ASTJb(); BlockNode rootNode = this.useBlockProduction(); ast.setRootNode(rootNode); return ast; } ASTGenerator(List<TargetGrammar.Reduction> reductions); ASTJb generateAST(); }
@Test public void testSimpleDeclaration(){ List<Token> tList=new LinkedList<>(); Token l_token=new TokenJb(TokenType.LONG_SYMBOL, "long"); tList.add(l_token); Token id_token=new TokenJb(TokenType.ID, "i"); tList.add(id_token); Token sem_token=new TokenJb(TokenType.SEMICOLON,";"); tList.add(sem_token); TargetGrammar.Sou...
SLRAutomaton { public int getNStates() { return states.size(); } SLRAutomaton(Grammar<T, NT> referenceGrammar); void setAmbiguityPolicy(AMBIGUITY_POLICY policy); List<Production<T, NT>> getDerivationASsSequence( Word<T, NT> word_total); int getNStates(); }
@Test public void testAutomaton(){ SLRAutomaton<SimpleT, SimpleNT> automaton=new SLRAutomaton<>(g1); assertEquals("should have exact this number of states",13,automaton.getNStates()); }
SLRAutomaton { public List<Production<T, NT>> getDerivationASsSequence( Word<T, NT> word_total) { Stack<State> state_stack = new Stack<>(); Stack<Symbol> symbol_stack = new Stack<>(); state_stack.push(initialState); symbol_stack.push(g.word_end); List<Production<T, NT>> productions = new LinkedList<>(); Queue<T> word =...
@Test public void testDerivationSequenceSimple(){ SLRAutomaton<SimpleT, SimpleNT> automaton=new SLRAutomaton<>(g1); Word<SimpleT,SimpleNT> original=new Word<SimpleT,SimpleNT>(g1, listTok(T_ID)); List<Production<SimpleT,SimpleNT>> productions=automaton.getDerivationASsSequence(original); Collections.reverse(productions)...
CastingAst2CodeConverter extends AbstractAst2CodeConverter { protected IdentifierData cast(Type goalType, IdentifierData oldId) throws IntermediateCodeGeneratorException { if (oldId.getIdentifier().startsWith("#")) { IdentifierData tmpId = icg.generateTempIdentifier(oldId.getType()); icg.addQuadruple(QuadrupleFactoryJb...
@Test public void testCastLongToDouble() { try { when(converter.icg.generateTempIdentifier(any(DoubleType.class))) .thenReturn(new IdentifierData("tmp", new DoubleType())); converter.cast(new DoubleType(), new IdentifierData("test", new LongType())); verify(converter.icg).addQuadruple( new QuadrupleJb(Operator.LONG_TO_...
JavabiteConfig extends Properties { public Set<ConfigCategory> getConfigCategories() { Set<ConfigCategory> categories = new HashSet<>(); for (String key : this.stringPropertyNames()) { if (key.contains(".")) { categories.add(new ConfigCategory(key.substring(0, key.indexOf(".")))); } else { categories.add(new ConfigCate...
@Test public void testGetConfigCategories() { Set<ConfigCategory> categories = config.getConfigCategories(); assertEquals(3, categories.size()); Iterator<ConfigCategory> it = categories.iterator(); ConfigCategory cc = it.next(); assertEquals("syntaxHighlighting", cc.getName()); assertEquals("Syntax Highlighting", cc.to...
JavabiteConfig extends Properties { public Set<ConfigKey> getConfigKeys(ConfigCategory category) { return getConfigKeys(category.getName()); } JavabiteConfig(); JavabiteConfig(String path); static JavabiteConfig getDefaultConfig(); void configurationChanges(); static void registerConfigurable(Configurable config); @O...
@Test public void testGetConfigKeys() { Set<ConfigKey> keys = config.getConfigKeys("syntaxHighlighting"); assertEquals(2, keys.size()); Iterator<ConfigKey> it = keys.iterator(); ConfigKey ck = it.next(); assertEquals("syntaxHighlighting.string", ck.getName()); assertEquals("String", ck.toString()); ck = it.next(); asse...
HtmlReportWriter implements ReportWriter { @Override public String write(Report report) { try (final StringWriter writer = new StringWriter()) { reportTemplate.process(report, writer); return writer.toString(); } catch (TemplateException e) { throw new RuntimeException("Error populating default report HTML template '"+...
@Test public void testWriteToString() { final String htmlReport = reportWriter.write(report); Assert.assertTrue(true); }
CollectionManagementService { protected void checkAndInstallConfiguration(String configName) throws IOException { this.checkAndInstallConfiguration(configName, false); } CollectionManagementService(List<String> zkHosts); CollectionManagementService(List<String> zkHost, String ... repositories); protected CollectionMa...
@Test public void checkAndInstallConfigurationTest() throws IOException { String configName = "com.rbmhtechnology.vind:backend-solr:1.1.2"; service.checkAndInstallConfiguration(configName); assertTrue(service.configurationIsDeployed(configName)); }
CollectionManagementService { protected List<String> listRuntimeDependencies(String collectionName) throws IOException, SolrServerException { logger.debug("Checking runtime-dependencies for collection {}", collectionName); ModifiableSolrParams params = new ModifiableSolrParams().set("file",RUNTIME_LIB_FILE_NAME); SolrR...
@Test public void listRuntimeDependenciesTest() throws IOException, SolrServerException { List<String> runtimeDependencies = service.listRuntimeDependencies("my-collection"); assertThat(runtimeDependencies, contains("org.apache.solr:solr-cell:6.1.0", "com.rbmhtechnology.solr.test:test-jar:1.0")); }
CollectionManagementService { public Long getVersionAndInstallIfNecessary(String dependency) { try (CloudSolrClient client = createCloudSolrClient()) { SolrQuery query = new SolrQuery("blobName:"+Utils.toBlobName(dependency)); query.setSort("version", SolrQuery.ORDER.desc); QueryResponse response = client.query(".syste...
@Test public void getVersionAndInstallIfNecessaryTest() { Long version = service.getVersionAndInstallIfNecessary("com.rbmhtechnology.solr.test:test-jar:1.0"); assertEquals(1L, version, 0); } @Test public void getVersionAndInstallIfNecessaryTest2() { Long version = service.getVersionAndInstallIfNecessary("org.apache.sol...
CollectionManagementService { protected Map<String,Long> checkAndInstallRuntimeDependencies(String collectionName) { List<String> dependencies = Collections.emptyList(); try { dependencies = listRuntimeDependencies(collectionName); } catch (SolrServerException | IOException e) { logger.warn("Cannot get runtime dependen...
@Test public void checkAndInstallRuntimeDependenciesTest() { Map<String,Long> dependencies = service.checkAndInstallRuntimeDependencies("my-collection"); assertThat(dependencies, hasEntry("org.apache.solr_solr-cell_6.1.0", 1L)); assertThat(dependencies, hasEntry("com.rbmhtechnology.solr.test_test-jar_1.0",1L)); }
CollectionManagementService { protected void addOrUpdateRuntimeDependencies(Map<String, Long> runtimeDependencies, String collectionName) { logger.info("Adding runtime-dependencies for {}", collectionName); for(String blobName : runtimeDependencies.keySet()) { RuntimeLibRequest request = new RuntimeLibRequest(RuntimeLi...
@Test public void addOrUpdateRuntimeDependenciesTest() { service.addOrUpdateRuntimeDependencies(Collections.singletonMap("com.rbmhtechnology.solr.test_test-jar_1.0",1L),"my-collection"); }
SolrSearchServer extends SmartSearchServerBase { @Override public boolean execute(Update update,DocumentFactory factory) { final boolean isUpdatable = factory.isUpdatable() && factory.getFields().values().stream() .allMatch( descriptor -> descriptor.isUpdate()); if (isUpdatable) { final SolrInputDocument sdoc = getSolr...
@Test public void testSearch() throws Exception { final DocumentFactoryBuilder docFactoryBuilder = new DocumentFactoryBuilder("asset"); FieldDescriptor descriptor = new FieldDescriptorBuilder().setFacet(true).buildTextField("text"); docFactoryBuilder.addField(descriptor); DocumentFactory documents = docFactoryBuilder.b...
SolrSearchServer extends SmartSearchServerBase { @Override public IndexResult index(Document ... docs) { Asserts.notNull(docs,"Document to index should not be null."); Asserts.check(docs.length > 0, "Should be at least one document to index."); return indexMultipleDocuments(Arrays.asList(docs), -1); } SolrSearchServer(...
@Test public void testIndex() throws Exception { FieldDescriptor<String> title = new FieldDescriptorBuilder<>().setFullText(true).buildTextField("title"); SingleValueFieldDescriptor.DateFieldDescriptor<ZonedDateTime> created = new FieldDescriptorBuilder<>().setFacet(true).buildDateField("created"); MultiValueFieldDescr...
ChildrenFilterSerializer { public String serialize(Filter filter){ final Filter normalizedFilter = normalize(filter); if (AndFilter.class.isAssignableFrom(normalizedFilter.getClass())) return serialize((AndFilter)normalizedFilter); else if (OrFilter.class.isAssignableFrom(normalizedFilter.getClass())) return serialize(...
@Test @Ignore public void testFilterSerialization() { final ChildrenFilterSerializer serializer = new ChildrenFilterSerializer(parent, child, null, false, true); final Filter.DescriptorFilter<String> parentFilter = new Filter.DescriptorFilter<>(parent_value, "p_v", Scope.Facet); final Filter.DescriptorFilter<String> sh...
ChildrenFilterSerializer { private Filter normalize(AndFilter filter){ final Set<Filter> normalizedFilters = filter.getChildren().stream() .map(this::normalize) .collect(Collectors.toSet()); final Set<Filter> normalizedChildren = normalizedFilters.stream() .filter(f -> !f.getType().equals(filter.getType()) && !f.getTyp...
@Test public void testNormalization() { final ChildrenFilterSerializer serializer = new ChildrenFilterSerializer(parent, child, null, false, false); Filter parentValueFilter = new OrFilter(eq(parent_value,"value1"), eq(parent_value,"value2")); Filter sharedValueFilter = new OrFilter(new OrFilter(eq(shared_value,"shared...
JsonReportWriter implements ReportWriter { @Override public String write(Report report) { try { return mapper.writeValueAsString(report); } catch (JsonProcessingException e) { log.error("Error writing report as Json string: {}", e.getMessage(), e); return null; } } JsonReportWriter(); @Override String write(Report repo...
@Test public void testWriteToString() { final String jsonReport = reportWriter.write(report); Assert.assertTrue(true); }
FacetMapper { public static <T> Facet stringQuery2FacetMapper(FieldDescriptor<T> field,String facetName, Map<String,String> query) { final String stringQuery = query.values().iterator().next(); Class<T> type = field.getType(); if (ComplexFieldDescriptor.class.isAssignableFrom(field.getClass())) { type = ((ComplexFieldD...
@Test public void test() throws SyntaxError { HashMap<String, String> dateIntervals = new HashMap<>(); dateIntervals.put("after","[NOW+23DAYS/DAY TO *]"); dateIntervals.put("before","[* TO NOW+23DAYS/DAY]"); HashMap<String, String> numberIntervals = new HashMap<>(); numberIntervals.put("bigger","[23 TO *]"); numberInte...
RESTMetadataProvider implements MetadataProvider { @Override public Document getDocument(Document document, DocumentFactory factory) throws IOException { HttpMethod request = new GetMethod(baseURL); request.addRequestHeader("Authorization", String.format("Bearer %s", bearerToken)); request.setPath(path + document.getId...
@Test @Ignore public void testGetDocument() throws Exception { MetadataProvider p = new RESTMetadataProvider( "https: "rbmh", "admin", "global", "1315204862832-1123067022", "asset", "user", "passw" ); Asset a = p.getObject("1359078847993-766700833",Asset.class); Assert.assertEquals("Sean Pettit - Portrait", a.getTitle(...
ElasticWriter extends MonitoringWriter { @Override public void log(MonitoringEntry log) { logger.debug("Indexing log entry: {}", log.toJson()); elasticClient.put(log.toJson()); } ElasticWriter(String elasticHost, String elasticPort, String elasticIndex); @Override void log(MonitoringEntry log); }
@Test @Ignore public void logTest(){ final ElasticWriter elasticWriter = new ElasticWriter("localhost", "9200", "logindex"); elasticWriter.log(new FullTextEntry()); }
DocumentFactory { public Document createDoc(String id) { return new DocumentImpl(id, this.type); } protected DocumentFactory(String type,boolean updatable, Map<String, FieldDescriptor<?>> fields); protected DocumentFactory(String type,boolean updatable, Map<String, FieldDescriptor<?>> fields, Map<String, FieldDescrip...
@Test public void setValuesTest() { Document doc = factory.createDoc("idTest"); doc.setValues("multipleStringField","1","2","3"); Collection<Object> values = new ArrayList<>(); values.add("4"); values.add("5"); doc.setValues("multipleStringField", values); Collection<Object> invalidValues = new ArrayList<>(); invalidVa...
ElasticSearchServer extends SmartSearchServerBase { @Override public IndexResult index(Document... docs) { Asserts.notNull(docs,"Document to index should not be null."); Asserts.check(docs.length > 0, "Should be at least one document to index."); return indexMultipleDocuments(Arrays.asList(docs), -1); } ElasticSearchSe...
@Test public void indexTest(){ server.clearIndex(); final DocumentFactoryBuilder docFactoryBuilder = new DocumentFactoryBuilder("TestDoc"); final FieldDescriptor descriptor = new FieldDescriptorBuilder().setFacet(true).buildTextField("title"); docFactoryBuilder.addField(descriptor); final DocumentFactory documents = do...
ElasticSearchServer extends SmartSearchServerBase { @Override public DeleteResult delete(Document doc) { return deleteWithin(doc, -1); } ElasticSearchServer(); ElasticSearchServer(ElasticVindClient client); protected ElasticSearchServer(ElasticVindClient client, boolean check); @Override Object getBackend(); @Overrid...
@Test public void deleteTest(){ server.clearIndex(); final DocumentFactoryBuilder docFactoryBuilder = new DocumentFactoryBuilder("TestDoc"); final SingleValueFieldDescriptor.TextFieldDescriptor<String> descriptor = new FieldDescriptorBuilder() .setFacet(true) .setFullText(true) .buildTextField("title"); docFactoryBuild...
CollectionManagementService { protected boolean configurationIsDeployed(String configName) throws IOException { logger.debug("Checking if config '{}' is present", configName); ConfigSetAdminRequest.List list = new ConfigSetAdminRequest.List(); try (CloudSolrClient client = createCloudSolrClient()) { final ConfigSetAdmi...
@Test public void configurationIsDeployedTest() throws IOException { assertTrue(service.configurationIsDeployed("com.rbmhtechnology.solr.test:test-config:1.0")); assertFalse(service.configurationIsDeployed("com.rbmhtechnology.solr.test:wrong-config:1.0")); }
MacroContext implements MacroValueProvider { public MacroContext(final String names_and_values) throws Exception { pushMacros(names_and_values); } MacroContext(final String names_and_values); void pushMacros(final String names_and_values); void popMacros(); @Override String getValue(final String name); String resolveMa...
@Test public void testMacroContext() throws Exception { final MacroContext context = new MacroContext("A=a1, B=b1"); assertThat(context.getValue("A"), equalTo("a1")); assertThat(context.getValue("B"), equalTo("b1")); context.pushMacros("A=a2"); assertThat(context.getValue("A"), equalTo("a2")); assertThat(context.getVal...
ConfigPv implements Comparable<ConfigPv> { @Override public String toString() { return new StringBuffer() .append("PV name=").append(pvName) .append(", readback PV name=").append(readbackPvName) .append(", readOnly=").append(readOnly) .toString(); } @Override boolean equals(Object other); @Override int hashCode(); @Ov...
@Test public void testToString() { assertNotNull(ConfigPv.builder().build().toString()); assertNotNull(ConfigPv.builder().readbackPvName("a").build().toString()); assertNotNull(ConfigPv.builder().readbackPvName("").build().toString()); }
ConfigPv implements Comparable<ConfigPv> { @Override public int compareTo(ConfigPv other) { return pvName.compareTo(other.getPvName()); } @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); @Override int compareTo(ConfigPv other); }
@Test public void testCompareTo(){ ConfigPv configPV1 = ConfigPv.builder().pvName("a").readbackPvName("b").readOnly(true).build(); ConfigPv configPV2 = ConfigPv.builder().pvName("a").readbackPvName("b").readOnly(true).build(); ConfigPv configPV3 = ConfigPv.builder().pvName("b").readbackPvName("b").readOnly(true).build(...
SnapshotItem { @Override public String toString() { return new StringBuffer() .append("value=") .append(value != null ? value.toString() : "READ FAILED") .append(", config pv=").append(configPv.toString()) .append(readbackValue != null ? (", readback pv=" + readbackValue.toString()) : (", readback pv=READ_FAILED")) .to...
@Test public void testToString() { SnapshotItem item = SnapshotItem.builder() .configPv(ConfigPv.builder().pvName("pvname").build()) .build(); assertNotNull(item.toString()); item.setValue(VType.toVType(1)); assertNotNull(item.toString()); item.setReadbackValue(VType.toVType(1.1)); assertNotNull(item.toString()); asser...
SafeMultiply { public static Number multiply(Number a, Number b) throws UnsupportedOperationException { if (a instanceof Double && b instanceof Double) { return multiply((Double) a, (Double) b); } else if (a instanceof Float && b instanceof Float) { return multiply((Float) a, (Float) b); } else if (a instanceof ULong &...
@Test public void TestMultiplyDouble() { assertEquals(0d, SafeMultiply.multiply(3d, 0d)); assertEquals(18d, SafeMultiply.multiply(3d, 6d)); assertEquals(-18d, SafeMultiply.multiply(-3d, 6d)); assertEquals(18d, SafeMultiply.multiply(-3d, -6d)); assertEquals(Double.MAX_VALUE, SafeMultiply.multiply(Double.MAX_VALUE, 6d));...
Services implements IServices { @Override @Transactional public void deleteNode(String nodeId) { logger.info("Deleting node id={}", nodeId); nodeDAO.deleteNode(nodeId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snaps...
@Test public void testDeleteConfiguration() { services.deleteNode("a"); verify(nodeDAO, atLeast(1)).deleteNode("a"); reset(nodeDAO); } @Test public void testDeleteFolder() { services.deleteNode("a"); verify(nodeDAO, atLeast(1)).deleteNode("a"); reset(nodeDAO); }
Services implements IServices { @Override @Transactional public Node moveNode(String nodeId, String targetNodeId, String userName) { logger.info("Moving node id {} to raget node id {}", nodeId, targetNodeId); return nodeDAO.moveNode(nodeId, targetNodeId, userName); } @Override Node getParentNode(String uniqueNodeId); ...
@Test public void testMoveNode() { services.moveNode("a", "b", "username"); verify(nodeDAO, atLeast(1)).moveNode("a", "b", "username"); reset(nodeDAO); }
PathWrangler { public PathWrangler(final String removals) { for (String remove : removals.split(",")) this.removals.add(Pattern.compile(remove)); } PathWrangler(final String removals); String wrangle(String path); }
@Test public void testPathWrangler() { final PathWrangler wrangler = new PathWrangler("phoebus\\.app/Content/.*,phoebus\\.app/,phoebus-[^/]+/,product-[^/]+/,jdk/.*"); assertThat(wrangler.wrangle("phoebus-0.0.1/doc/applications.html"), equalTo("doc/applications.html")); assertThat(wrangler.wrangle("product-sns-0.0.1/lib...
PVPool { public static Collection<String> getSupportedPrefixes() { return factories.keySet(); } private PVPool(); static Collection<String> getSupportedPrefixes(); static PV getPV(final String name); static void releasePV(final PV pv); static Collection<ReferencedEntry<PV>> getPVReferences(); static final String DEFAU...
@Test public void listPrefixes() { final Collection<String> prefs = PVPool.getSupportedPrefixes(); System.out.println("Prefixes: " + prefs); assertThat(prefs, hasItem("ca")); assertThat(prefs, hasItem("sim")); }
IndexNameHelper { public String getIndexName(Instant time) { if (dateSpanValue < 1) return baseIndexName; if (null != time && (null == spanEnd || time.isAfter(spanEnd))) { setDateSpanStartAndEnd(time); currentDateSpan = parseCurrentDateSpan(); } return baseIndexName + "_" + currentDateSpan; } IndexNameHelper(final Stri...
@Test public void dateSpanValueZero() throws Exception { IndexNameHelper inh = new IndexNameHelper("test_index", "y", 0); String indexName = inh.getIndexName(Instant.now()); assertEquals("test_index", indexName); } @Test public void dateSpanValueLessThanZero() throws Exception { IndexNameHelper inh = new IndexNameHelpe...
FileExtensionUtil { public static File enforceFileExtension(final File file, final String desiredExtension) { final String path = file.getPath(); final int sep = path.lastIndexOf('.'); if (sep < 0){ return new File(path + "." + desiredExtension); } final String ext = path.substring(sep + 1); if (! ext.equals(desiredExt...
@Test public void testFile() throws Exception { File bob = new File("/some/path/file.bob"); File file = FileExtensionUtil.enforceFileExtension(new File("/some/path/file"), "bob"); assertThat(file, equalTo(bob)); file = FileExtensionUtil.enforceFileExtension(new File("/some/path/file.abc"), "bob"); assertThat(file, equa...
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static ...
@Test public void sec1() { Duration duration = TimeDuration.ofSeconds(1.0); assertThat(duration.getNano(), equalTo(0)); assertThat(duration.getSeconds(), equalTo(1L)); } @Test public void sec2() { Duration duration = TimeDuration.ofSeconds(0.123456789); assertThat(duration.getNano(), equalTo(123456789)); assertThat(dur...
Services implements IServices { @Override public Node updateNode(Node nodeToUpdate) { return updateNode(nodeToUpdate, false); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(Str...
@Test public void testUpdateNode() { Node node = Node.builder().build(); services.updateNode(node); verify(nodeDAO, atLeast(1)).updateNode(node, false); reset(nodeDAO); }
TimeDuration { public static Duration ofMinutes(double min) { return Duration.ofNanos((long) (min * 60 * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); st...
@Test public void min1() { Duration duration = TimeDuration.ofMinutes(1.0); assertThat(duration.getNano(), equalTo(0)); assertThat(duration.getSeconds(), equalTo(60L)); } @Test public void min2() { Duration duration = TimeDuration.ofMinutes(0.123456789); assertThat(duration.getNano(), equalTo(407407340)); assertThat(du...
TimeDuration { public static Duration ofHours(double hour) { return Duration.ofNanos((long) (hour * 60 * 60 * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min...
@Test public void hour1() { Duration duration = TimeDuration.ofHours(1.0); assertThat(duration.getNano(), equalTo(0)); assertThat(duration.getSeconds(), equalTo(3600L)); } @Test public void hour2() { Duration duration = TimeDuration.ofHours(0.123456789); assertThat(duration.getNano(), equalTo(444440399)); assertThat(du...
TimeDuration { public static Duration ofHertz(double hz) { if (hz <= 0.0) { throw new IllegalArgumentException("Frequency has to be greater than 0.0"); } return Duration.ofNanos((long) (1000000000.0 / hz)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double d...
@Test public void hz1() { Duration duration = TimeDuration.ofHertz(1.0); assertThat(duration.getNano(), equalTo(0)); assertThat(duration.getSeconds(), equalTo(1L)); } @Test public void hz2() { Duration duration = TimeDuration.ofHertz(100.0); assertThat(duration.getNano(), equalTo(10000000)); assertThat(duration.getSeco...
Services implements IServices { @Override @Transactional public Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs) { logger.info("Updating configuration unique id: {}", configToUpdate.getUniqueId()); return nodeDAO.updateConfiguration(configToUpdate, configPvs); } @Override Node getParentNode(Stri...
@Test public void testUpdateConfiguration() { when(nodeDAO.updateConfiguration(config1, configPvList)).thenReturn(config1); assertNotNull(services.updateConfiguration(config1, configPvList)); }
Services implements IServices { @Override public List<SnapshotItem> getSnapshotItems(String snapshotUniqueId) { logger.info("Getting snapshot items for snapshot id {}", snapshotUniqueId); return nodeDAO.getSnapshotItems(snapshotUniqueId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSna...
@Test public void testGetSnapshotItems() { when(nodeDAO.getSnapshotItems("a")).thenReturn(Collections.emptyList()); assertNotNull(services.getSnapshotItems("a")); }
TimeDuration { public static String toSecondString(Duration duration){ return duration.getSeconds() + "." + format.format(duration.getNano()); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMin...
@Test public void toString1() { Duration duration = Duration.ofMillis(10); assertThat(TimeDuration.toSecondString(duration), equalTo("0.010000000")); }
Services implements IServices { @Override public Node getParentNode(String uniqueNodeId) { return nodeDAO.getParentNode(uniqueNodeId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node creat...
@Test public void testgetParentNode() { Node parentNode = Node.builder().name("a").uniqueId("u").build(); when(nodeDAO.getParentNode("u")).thenReturn(parentNode); assertNotNull(services.getParentNode("u")); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); boolean contains(Instant instant); static TimeInterval between(Instant start, Instant end); TimeInterval minus(Duration duration); static TimeInterval...
@Test public void equals1() { TimeInterval interval = TimeInterval.between(Instant.ofEpochSecond(0, 0), Instant.ofEpochSecond(3600, 0)); assertThat(interval, equalTo(TimeInterval.between(Instant.ofEpochSecond(0, 0), Instant.ofEpochSecond(3600, 0)))); } @Test public void equals2() { TimeInterval interval = TimeInterval....
Services implements IServices { @Override public List<Node> getChildNodes(String nodeUniqueId) { logger.info("Getting child nodes for node unique id={}", nodeUniqueId); return nodeDAO.getChildNodes(nodeUniqueId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUnique...
@Test public void testGetChildNodes() { when(nodeDAO.getChildNodes("a")).thenReturn(Arrays.asList(Node.builder().build())); assertNotNull(services.getChildNodes("a")); }
TimeParser { @Deprecated public static Instant getInstant(String time) { if (time.equalsIgnoreCase(NOW)) { return Instant.now(); } else { Matcher nUnitsAgoMatcher = timeQuantityUnitsPattern.matcher(time); while (nUnitsAgoMatcher.find()) { return Instant.now().minus(parseDuration(nUnitsAgoMatcher.group(1))); } DateTimeF...
@Test public void getNow() { Instant ts = TimeParser.getInstant("now"); assertTrue("Failed to obtain Timestamp corresponding to now ", ts != null && ts instanceof Instant); }
TimeParser { @Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equal...
@Test public void getDuration() { Duration lastMin = TimeParser.parseDuration("1 min"); assertEquals("Failed to get Duration for last min", Duration.ofSeconds(60), lastMin); Duration lastHour = TimeParser.parseDuration("1 hour"); assertEquals("Failed to get Duration for last hour", Duration.ofHours(1), lastHour); Tempo...
TimeParser { public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; whi...
@Test public void parse() { Instant now = Instant.now(); TimeRelativeInterval interval = TimeRelativeInterval.of(TimeParser.parseTemporalAmount("1 min"), now); assertEquals(now.minusSeconds(60), interval.toAbsoluteInterval().getStart()); assertEquals(now, interval.toAbsoluteInterval().getEnd()); } @Test public void par...
Services implements IServices { @Override public Node getRootNode() { return nodeDAO.getRootNode(); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node ...
@Test public void testGetRootNode() { when(nodeDAO.getRootNode()).thenReturn(Node.builder().build()); assertNotNull(services.getRootNode()); }
TimeParser { public static String format(final TemporalAmount amount) { final StringBuilder buf = new StringBuilder(); if (amount instanceof Period) { final Period period = (Period) amount; if (period.isZero()) return NOW; if (period.getYears() == 1) buf.append("1 year "); else if (period.getYears() > 1) buf.append(per...
@Test public void testFormatTemporalAmount() { String text = TimeParser.format(Duration.ofHours(2)); assertEquals("2 hours", text); text = TimeParser.format(Period.of(1, 2, 3)); assertEquals("1 year 2 months 3 days", text); text = TimeParser.format(Duration.ofSeconds(2*24*60*60 + 1*60*60 + 10, 123000000L)); assertEqual...
CommandExecutor implements Callable<Integer> { public static List<String> splitCmd(final String cmd) { final List<String> items = new ArrayList<>(); final int len = cmd.length(); int i = 0; final StringBuilder line = new StringBuilder(); while (i < len) { char c = cmd.charAt(i); if (c == ' ' || c == '\t') { items.add(l...
@Test public void testCommandSplit() throws Exception { List<String> cmd = CommandExecutor.splitCmd("path/cmd"); System.out.println(cmd); assertThat(cmd, equalTo(Arrays.asList("path/cmd"))); cmd = CommandExecutor.splitCmd("path/cmd arg1"); System.out.println(cmd); assertThat(cmd, equalTo(Arrays.asList("path/cmd", "arg1...
CommandExecutor implements Callable<Integer> { @Override public Integer call() throws Exception { String cmd = process_builder.command().get(0); final int sep = cmd.lastIndexOf('/'); if (sep >= 0) cmd = cmd.substring(sep+1); process = process_builder.start(); final Thread stdout = new LogWriter(process.getInputStream()...
@Test public void testShortCommand() throws Exception { if (is_windows) return; final String cmd = "./cmd_short.sh \"With one arg\" another_arg"; final Integer status = new CommandExecutor(cmd, examples_dir).call(); final String log = getLoggedMessages(); assertThat(log, containsString("Example warning")); assertThat(l...
ResourceParser { public static URI createResourceURI(final String resource) throws Exception { try { final URI uri = URI.create(resource); if (uri.getScheme() != null) return uri; else { final Path fileResource = Paths.get(resource); return fileResource.toUri(); } } catch (Throwable ex) { try { return new File(resource...
@Test public void checkWebToURI() throws Exception { URI uri = createResourceURI("http: System.out.println(uri); assertThat(uri.getScheme(), equalTo("http")); assertThat(uri.getHost(), equalTo("some.site")); assertThat(uri.getPath(), equalTo("/file/path")); }
SimProposal extends Proposal { public SimProposal(final String name, final String... arguments) { super(name); this.arguments = arguments; } SimProposal(final String name, final String... arguments); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
@Test public void testSimProposal() { Proposal proposal = new SimProposal("sim: assertThat(proposal.getDescription(), equalTo("sim: assertThat(proposal.apply("sine"), equalTo("sim: assertThat(proposal.apply("sim: equalTo("sim: assertThat(proposal.apply("sin(-10, 10, 2)"), equalTo("sim: assertThat(proposal.apply("sin(-1...
SimProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final List<String> split = splitNameAndParameters(text); if (split.isEmpty()) return List.of(); final List<MatchSegment> segs = new ArrayList<>(split.size()); final String noparm_text = split.get(0); final int match = value...
@Test public void testMatch() { Proposal proposal = new SimProposal("sim: List<MatchSegment> match = proposal.getMatch("sine"); assertThat(match, equalTo(List.of(MatchSegment.normal("sim: MatchSegment.match("sine"), MatchSegment.comment("(min, max, update_seconds)")))); match = proposal.getMatch("sim: assertThat(match,...
History implements ProposalProvider { public History() { this(10); } History(); History(final int max_size); @Override String getName(); synchronized void add(final Proposal proposal); @Override synchronized List<Proposal> lookup(String text); }
@Test public void testHistory() { final History history = new History(); List<Proposal> proposals = history.lookup("test"); assertThat(proposals.size(), equalTo(0)); history.add(new Proposal("Test1")); history.add(new Proposal("Other")); history.add(new Proposal("Test2")); proposals = history.lookup("test"); assertThat...
FormulaFunctionProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final int match = text.indexOf(function.getName()); if (match < 0) return List.of(MatchSegment.normal(getDescription())); final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.n...
@Test public void testMatch() { Proposal proposal = new FormulaFunctionProposal(new Sin()); List<MatchSegment> match = proposal.getMatch("=sin("); assertThat(match, equalTo(List.of(MatchSegment.normal("="), MatchSegment.match("sin"), MatchSegment.match("("), MatchSegment.comment("", "angle")))); match = proposal.getMat...
Services implements IServices { @Override public List<ConfigPv> getConfigPvs(String configUniqueId) { logger.info("Getting config pvs config id id {}", configUniqueId); return nodeDAO.getConfigPvs(configUniqueId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqu...
@Test public void testGetConfigPvs() { when(nodeDAO.getConfigPvs("a")).thenReturn(Arrays.asList(ConfigPv.builder().build())); assertNotNull(services.getConfigPvs("a")); }
ScanCommandImplTool { @SuppressWarnings("unchecked") public static <C extends ScanCommand> ScanCommandImpl<C> implement(final C command, final JythonSupport jython) throws Exception { for (ScanCommandImplFactory factory : factories) { ScanCommandImpl<?> impl = factory.createImplementation(command, jython); if (impl != ...
@Test public void testImplementation() throws Exception { final ScanCommand cmd = new CommentCommand("Test"); final ScanCommandImpl<ScanCommand> impl = ScanCommandImplTool.implement(cmd, null); System.out.println(impl); assertThat(impl, instanceOf(CommentCommandImpl.class)); }
Proposal { public String apply(final String text) { final StringBuilder result = new StringBuilder(); final List<MatchSegment> match = getMatch(text); for (MatchSegment seg : match) if (seg.getType() != MatchSegment.Type.COMMENT) result.append(seg.getText()); return result.toString(); } Proposal(final String value); St...
@Test public void testPlainProposal() { Proposal proposal = new Proposal("Test1"); assertThat(proposal.apply("est"), equalTo("Test1")); assertThat(proposal.apply("anything"), equalTo("Test1")); }
Proposal { public List<MatchSegment> getMatch(final String text) { final int match = value.indexOf(text); if (match < 0) return List.of(MatchSegment.normal(value)); else { final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(value.substring(0, match))); if (! text.isEmpty()) se...
@Test public void testMatch() { Proposal proposal = new Proposal("Test1"); List<MatchSegment> match = proposal.getMatch("es"); assertThat(match, equalTo(List.of(MatchSegment.normal("T"), MatchSegment.match("es"), MatchSegment.normal("t1")))); match = proposal.getMatch("Tes"); assertThat(match, equalTo(List.of(MatchSegm...
LocProposal extends Proposal { static List<String> splitNameTypeAndInitialValues(final String text) { final List<String> result = new ArrayList<>(); int sep = text.indexOf('<'); if (sep >= 0) { result.add(text.substring(0, sep).trim()); int pos = text.indexOf('>', sep+1); if (pos < 0) result.add(text.substring(sep+1).t...
@Test public void testArguments() { List<String> split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(...
LocProposal extends Proposal { public LocProposal(final String name, final String type, final String... initial_values) { super(name); this.type = type; this.initial_values = initial_values; } LocProposal(final String name, final String type, final String... initial_values); @Override String getDescription(); @Override...
@Test public void testLocProposal() { Proposal proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: proposal = new Loc...
LocProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { if (! text.startsWith("loc")) return List.of(MatchSegment.normal(getDescription())); final List<String> split = splitNameTypeAndInitialValues(text); if (split.size() < 1) return List.of(); final List<MatchSegment> segs = ne...
@Test public void testMatch() { Proposal proposal = new LocProposal("loc: List<MatchSegment> match = proposal.getMatch("loc: assertThat(match, equalTo(List.of( MatchSegment.match("loc: MatchSegment.comment("<VType>"), MatchSegment.comment("(initial value)")))); match = proposal.getMatch(""); assertThat(match, equalTo(L...
PreferencesReader { static String replaceProperties(final String value) { if (value == null) return value; String result = value; Matcher matcher = PROP_PATTERN.matcher(value); while (matcher.find()) { final String prop_spec = matcher.group(); final String prop_name = prop_spec.substring(2, prop_spec.length()-1); final...
@Test public void testProperties() { System.out.println(PreferencesReader.replaceProperties("Running on Java $(java.version) in $(java.home)")); System.out.println("Expect warning about undefined property"); assertThat(PreferencesReader.replaceProperties("$(VeryUnlikelyToExist)"), equalTo("$(VeryUnlikelyToExist)")); Sy...
UpdateThrottle { public UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update) { this(dormant_time, unit, update, TIMER); } UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update); UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable updat...
@Test(timeout=5000) public void testUpdateThrottle() throws Exception { final Runnable update = new Runnable() { @Override public void run() { System.out.println("<- Update!"); updates.incrementAndGet(); synchronized (this) { notifyAll(); } } }; final UpdateThrottle throttle = new UpdateThrottle(1L, TimeUnit.SECONDS, u...
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = format...
@Test public void testNaNInf() throws Exception { VType number = VDouble.of(Double.NaN, Alarm.none(), Time.now(), display); String text = FormatOptionHandler.format(number, FormatOption.DEFAULT, -1, true); System.out.println(text); assertThat(text, equalTo("NaN V")); number = VDouble.of(Double.POSITIVE_INFINITY, Alarm....
Services implements IServices { @Override public Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment) { logger.info("Saving snapshot for config id {}", configUniqueId); logger.info("Snapshot name: {}, values:", snapshotName); for (SnapshotItem ...
@Test public void testSaveSnapshot() { when(nodeDAO.saveSnapshot("a", Collections.emptyList(), "b", "c", "d")).thenReturn(Node.builder().nodeType(NodeType.SNAPSHOT).build()); assertNotNull(services.saveSnapshot("a", Collections.emptyList(), "b", "d", "c")); }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.st...
@Test public void testHexParse() throws Exception { final VType number = VDouble.of(65535.0, Alarm.none(), Time.now(), display); Object parsed = FormatOptionHandler.parse(number, "0xFF", FormatOption.HEX); System.out.println(parsed); assertThat(parsed, instanceOf(Number.class)); assertThat(((Number)parsed).intValue(), ...
Services implements IServices { @Override public List<Node> getFromPath(String path){ return nodeDAO.getFromPath(path); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String pa...
@Test public void testGetFromPath(){ Node node = Node.builder().name("SomeFolder").build(); when(nodeDAO.getFromPath("path")).thenReturn(Arrays.asList(node)); assertEquals("SomeFolder", services.getFromPath("path").get(0).getName()); }
ArrayScalarDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array1 = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; return VNumberArray.of( ListMath.rescale(array1.getData(), 1d / ...
@Test public void compute(){ ArrayScalarDivisionFunction arrayScalarDivisionFunction = new ArrayScalarDivisionFunction(); assertEquals("arrayDivScalar", arrayScalarDivisionFunction.getName()); assertEquals("array", arrayScalarDivisionFunction.getCategory()); VType array = VNumberArray.of(ArrayDouble.of(2.0, 10.0, 30.0)...
ArrayMinFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMin(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } ...
@Test public void compute() { ArrayMinFunction arrayMinFunction = new ArrayMinFunction(); assertEquals("arrayMin", arrayMinFunction.getName()); assertEquals("array", arrayMinFunction.getCategory()); VNumberArray doubleArray = VNumberArray.of(ArrayDouble.of(-1.0, 0, 1.0, 2.0, 3.0, 4.0, 5), Alarm.none(), Time.now(), Disp...