Example usage for java.util Collections emptySet

List of usage examples for java.util Collections emptySet

Introduction

In this page you can find the example usage for java.util Collections emptySet.

Prototype

@SuppressWarnings("unchecked")
public static final <T> Set<T> emptySet() 

Source Link

Document

Returns an empty set (immutable).

Usage

From source file:ca.uhn.fhir.jpa.term.BaseHapiTerminologySvc.java

@Transactional(propagation = Propagation.REQUIRED)
@Override/*from   w w  w  . j  a v  a 2 s. c o  m*/
public Set<TermConcept> findCodesBelow(Long theCodeSystemResourcePid, Long theCodeSystemVersionPid,
        String theCode) {
    Stopwatch stopwatch = Stopwatch.createStarted();

    TermConcept concept = fetchLoadedCode(theCodeSystemResourcePid, theCodeSystemVersionPid, theCode);
    if (concept == null) {
        return Collections.emptySet();
    }

    Set<TermConcept> retVal = new HashSet<TermConcept>();
    retVal.add(concept);

    fetchChildren(concept, retVal);

    ourLog.info("Fetched {} codes below code {} in {}ms",
            new Object[] { retVal.size(), theCode, stopwatch.elapsed(TimeUnit.MILLISECONDS) });
    return retVal;
}

From source file:com.ikanow.aleph2.graph.titan.services.TestTitanGraphBuilderEnrichmentService.java

@SuppressWarnings("unchecked")
@Test/* w ww  .  j  a va 2 s  .c  om*/
public void test_TitanGraphBuilderEnrichmentService() throws InterruptedException {

    final TitanGraphBuilderEnrichmentService graph_enrich_service = new TitanGraphBuilderEnrichmentService();

    final MockServiceContext service_context = new MockServiceContext();
    final MockSecurityService mock_security = new MockSecurityService();
    mock_security.setGlobalMockRole("nobody:DataBucketBean:read,write:test:end:2:end:*", true);
    service_context.addService(ISecurityService.class, Optional.empty(), mock_security);
    service_context.addService(IGraphService.class, Optional.empty(), _mock_graph_db_service);
    final IEnrichmentModuleContext context = Mockito.mock(IEnrichmentModuleContext.class);
    Mockito.when(context.getServiceContext()).thenReturn(service_context);
    Mockito.when(context.getNextUnusedId()).thenReturn(0L);

    final EnrichmentControlMetadataBean control_merge = BeanTemplateUtils
            .build(EnrichmentControlMetadataBean.class)
            .with(EnrichmentControlMetadataBean::entry_point, SimpleGraphMergeService.class.getName()).done()
            .get();

    final EnrichmentControlMetadataBean control_decomp = BeanTemplateUtils
            .build(EnrichmentControlMetadataBean.class)
            .with(EnrichmentControlMetadataBean::entry_point, SimpleGraphDecompService.class.getName())
            .with(EnrichmentControlMetadataBean::config, BeanTemplateUtils.toMap(BeanTemplateUtils
                    .build(SimpleDecompConfigBean.class)
                    .with(SimpleDecompConfigBean::elements, Arrays.asList(
                            BeanTemplateUtils.build(SimpleDecompElementBean.class)
                                    .with(SimpleDecompElementBean::edge_name, "test_edge_1")
                                    .with(SimpleDecompElementBean::from_fields,
                                            Arrays.asList("int_ip1", "int_ip2"))
                                    .with(SimpleDecompElementBean::from_type, "ip")
                                    .with(SimpleDecompElementBean::to_fields, Arrays.asList("host1", "host2"))
                                    .with(SimpleDecompElementBean::to_type, "host").done().get(),
                            BeanTemplateUtils.build(SimpleDecompElementBean.class)
                                    .with(SimpleDecompElementBean::edge_name, "test_edge_2")
                                    .with(SimpleDecompElementBean::from_fields, Arrays.asList("missing"))
                                    .with(SimpleDecompElementBean::from_type, "ip")
                                    .with(SimpleDecompElementBean::to_fields, Arrays.asList("host1", "host2"))
                                    .with(SimpleDecompElementBean::to_type, "host").done().get()))
                    .done().get()))
            .done().get();

    final GraphSchemaBean graph_schema = BeanTemplateUtils.build(GraphSchemaBean.class)
            .with(GraphSchemaBean::custom_decomposition_configs, Arrays.asList(control_decomp))
            .with(GraphSchemaBean::custom_merge_configs, Arrays.asList(control_merge)).done().get();

    final DataBucketBean bucket = BeanTemplateUtils
            .build(DataBucketBean.class).with(DataBucketBean::full_name, "/test/end/2/end")
            .with(DataBucketBean::owner_id, "nobody").with(DataBucketBean::data_schema, BeanTemplateUtils
                    .build(DataSchemaBean.class).with(DataSchemaBean::graph_schema, graph_schema).done().get())
            .done().get();

    _mock_graph_db_service.onPublishOrUpdate(bucket, Optional.empty(), false,
            ImmutableSet.of(GraphSchemaBean.name), Collections.emptySet());

    final EnrichmentControlMetadataBean control = BeanTemplateUtils.build(EnrichmentControlMetadataBean.class)
            .done().get();

    // Initialize
    {
        graph_enrich_service.onStageInitialize(context, bucket, control, null, Optional.empty());
    }

    // First batch vs an empty graph
    {
        final Stream<Tuple2<Long, IBatchRecord>> batch = Stream
                .<ObjectNode>of(_mapper.createObjectNode().put("int_ip1", "ipA").put("host1", "dY"))
                .map(o -> Tuples._2T(0L, new BatchRecordUtils.JsonBatchRecord(o)));

        graph_enrich_service.onObjectBatch(batch, Optional.empty(), Optional.empty());
        System.out.println("Sleeping 2s to wait for ES to refresh");
        Thread.sleep(2000L);

        // Check graph
        final TitanTransaction tx = _titan.buildTransaction().start();
        assertEquals(2, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "get_everything").vertices()).count());
        assertEquals(1, StreamUtils.stream(tx.query().has(GraphAnnotationBean.type, "ip").vertices()).count());
        assertEquals(1,
                StreamUtils.stream(tx.query().has(GraphAnnotationBean.type, "host").vertices()).count());
        assertEquals(1, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "get_everything").edges()).count());
        tx.commit();

        // Check stats:
        assertEquals(2L, graph_enrich_service._mutable_stats.get().vertices_created);
        assertEquals(0L, graph_enrich_service._mutable_stats.get().vertices_updated);
        assertEquals(2L, graph_enrich_service._mutable_stats.get().vertices_emitted);
        assertEquals(0L, graph_enrich_service._mutable_stats.get().vertex_matches_found);
        assertEquals(0L, graph_enrich_service._mutable_stats.get().vertex_errors);
        assertEquals(1L, graph_enrich_service._mutable_stats.get().edges_created);
        assertEquals(0L, graph_enrich_service._mutable_stats.get().edges_updated);
        assertEquals(1L, graph_enrich_service._mutable_stats.get().edges_emitted);
        assertEquals(0L, graph_enrich_service._mutable_stats.get().edge_matches_found);
        assertEquals(0L, graph_enrich_service._mutable_stats.get().edge_errors);
    }

    // Second batch vs the results of the previous batch
    {
        // Create some recoverable errors:
        {
            final PermanentLockingException outer = Mockito.mock(PermanentLockingException.class);
            Mockito.when(outer.getStackTrace()).thenReturn(new StackTraceElement[0]);
            graph_enrich_service._MUTABLE_TEST_ERRORS.push(new TitanException("test", outer));
        }
        {
            final TemporaryBackendException inner = Mockito.mock(TemporaryBackendException.class);
            Mockito.when(inner.getStackTrace()).thenReturn(new StackTraceElement[0]);
            final TitanException outer = Mockito.mock(TitanException.class);
            Mockito.when(outer.getCause()).thenReturn(inner);
            Mockito.when(outer.getStackTrace()).thenReturn(new StackTraceElement[0]);

            graph_enrich_service._MUTABLE_TEST_ERRORS.push(new TitanException("test", outer));
        }

        final Stream<Tuple2<Long, IBatchRecord>> batch = Stream
                .<ObjectNode>of(
                        _mapper.createObjectNode().put("int_ip1", "ipA").put("int_ip2", "ipB")
                                .put("host1", "dX").put("host2", "dY"),
                        _mapper.createObjectNode().put("int_ip1", "ipA").put("host1", "dZ").put("host2", "dY"))
                .map(o -> Tuples._2T(0L, new BatchRecordUtils.JsonBatchRecord(o)));

        graph_enrich_service.onObjectBatch(batch, Optional.empty(), Optional.empty());
        System.out.println("Sleeping 2s to wait for ES to refresh");
        Thread.sleep(2000L);

        // Check graph
        final TitanTransaction tx = _titan.buildTransaction().start();
        assertEquals(5, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "get_everything").vertices()).count());
        assertEquals(2, StreamUtils.stream(tx.query().has(GraphAnnotationBean.type, "ip").vertices()).count());
        assertEquals(3,
                StreamUtils.stream(tx.query().has(GraphAnnotationBean.type, "host").vertices()).count());
        assertEquals(5, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "get_everything").edges()).count());
        tx.commit();

        // Check stats:
        assertEquals(5L, graph_enrich_service._mutable_stats.get().vertices_created);
        assertEquals(2L, graph_enrich_service._mutable_stats.get().vertices_updated);
        assertEquals(7L, graph_enrich_service._mutable_stats.get().vertices_emitted);
        assertEquals(2L, graph_enrich_service._mutable_stats.get().vertex_matches_found);
        assertEquals(0L, graph_enrich_service._mutable_stats.get().vertex_errors);
        assertEquals(5L, graph_enrich_service._mutable_stats.get().edges_created);
        assertEquals(1L, graph_enrich_service._mutable_stats.get().edges_updated);
        assertEquals(7L, graph_enrich_service._mutable_stats.get().edges_emitted);
        assertEquals(1L, graph_enrich_service._mutable_stats.get().edge_matches_found);
        assertEquals(0L, graph_enrich_service._mutable_stats.get().edge_errors);
    }
    // Check error case:
    {
        graph_enrich_service._MUTABLE_TEST_ERRORS.push(new TitanException("test"));
        try {
            graph_enrich_service.onObjectBatch(Stream.empty(), Optional.empty(), Optional.empty());
            fail("Should have errored");
        } catch (Exception e) {
        }
    }

    // Now we'll insert some more vertices and check that calling onStageComplete removes them:
    {
        final TitanTransaction tx = _titan.buildTransaction().start();

        assertEquals(5, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "get_everything").vertices()).count());

        {
            final Vertex v = tx.addVertex("to_merge");
            v.property(GraphAnnotationBean.a2_p, "/test/end/2/end");
            v.property(GraphAnnotationBean.a2_p, "/test/other/bucket"); // (ensures will be winner)
            v.property(GraphAnnotationBean.a2_tc, 0L);
            v.property(GraphAnnotationBean.a2_tm, 0L);
            v.property(GraphAnnotationBean.name, "ipB");
            v.property(GraphAnnotationBean.type, "ip");
            v.property("other", true);
        }
        {
            final Vertex v = tx.addVertex("to_merge_leave");
            v.property(GraphAnnotationBean.a2_p, "/test/end/2/end");
            v.property(GraphAnnotationBean.a2_p, "/test/other/bucket"); // (ensures will be winner)
            v.property(GraphAnnotationBean.name, "ipB");
            v.property(GraphAnnotationBean.type, "not_an_ip");
        }

        //(create another vertex that has a different type)
        Thread.sleep(1100); // (just give index enough time to finish)
        assertEquals(7, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "get_everything").vertices()).count());

        tx.commit();
    }

    // (this should tidy up any duplicate edges)
    graph_enrich_service.onStageComplete(true);

    // check results
    {
        Thread.sleep(1100); // (just give index enough time to finish)
        final TitanTransaction tx = _titan.buildTransaction().start();
        assertEquals(6, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "get_everything").vertices()).count());
        tx.commit();
    }
}

From source file:org.agiso.tempel.support.file.provider.AppTemplateProviderElement.java

@Override
protected Set<String> getRepositoryClassPath() {
    File[] libraries = new File(librariesPath).listFiles();
    if (libraries != null && libraries.length > 0) {
        Set<String> classPath = new LinkedHashSet<String>(libraries.length);
        for (File library : libraries)
            try {
                classPath.add(library.getCanonicalPath());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }//w ww.ja  v  a  2 s . com
        return classPath;
    }

    return Collections.emptySet();
}

From source file:de.uniba.wiai.kinf.pw.projects.lillytab.reasoner.tbox.AssertedRBox.java

@Override
public Collection<R> getRoles(final RoleProperty property) {
    final Collection<R> value = _propertyRoleMap.get(property);
    if (value != null) {
        return Collections.unmodifiableCollection(value);
    } else {// ww  w.  j  a va 2 s .  com
        return Collections.emptySet();
    }
}

From source file:myfightinglayoutbugs.WebPage.java

public Collection<RectangularRegion> getRectangularRegionsCoveredBy(Collection<String> jQuerySelectors) {
    if (jQuerySelectors.isEmpty()) {
        return Collections.emptySet();
    }/*from   ww  w  .  j a va  2s. co  m*/
    // 1.) Assemble JavaScript to select elements ...
    Iterator<String> i = jQuerySelectors.iterator();
    String js = "jQuery('" + i.next().replace("'", "\\'");
    while (i.hasNext()) {
        js += "').add('" + i.next().replace("'", "\\'");
    }
    js += "').filter(':visible')";
    // 2.) Assemble JavaScript function to fill an array with rectangular region of each selected element ...
    js = "function() { " + "var a = new Array(); " + js + ".each(function(i, e) { " + "var j = jQuery(e); "
            + "var o = j.offset(); "
            + "a.push({ top: o.top, left: o.left, width: j.width(), height: j.height() }); " + "}); "
            + "return a; " + "}";
    // 3.) Execute JavaScript function ...
    @SuppressWarnings("unchecked")
    List<Map<String, Number>> list = (List<Map<String, Number>>) executeJavaScript("return (" + js + ")()");
    // 4.) Convert JavaScript return value to Java return value ...
    if (list.isEmpty()) {
        return Collections.emptySet();
    }
    Collection<RectangularRegion> result = new ArrayList<RectangularRegion>(list.size());
    for (Map<String, Number> map : list) {
        double left = map.get("left").doubleValue();
        double width = map.get("width").doubleValue();
        double top = map.get("top").doubleValue();
        double height = map.get("height").doubleValue();
        if (height > 0 && width > 0) {
            int x1 = (int) left;
            int y1 = (int) top;
            int x2 = (int) Math.round(left + width - 0.5000001);
            int y2 = (int) Math.round(top + height - 0.5000001);
            if (x2 >= 0 && y2 >= 0) {
                if (x1 < 0) {
                    x1 = 0;
                }
                if (y1 < 0) {
                    y1 = 0;
                }
                if (x1 <= x2 && y1 <= y2) {
                    result.add(new RectangularRegion(x1, y1, x2, y2));
                }
            }
        }
    }
    return result;
}

From source file:eu.trentorise.smartcampus.permissionprovider.model.ClientDetailsEntity.java

@Override
public Collection<GrantedAuthority> getAuthorities() {
    if (authorities != null) {
        String[] arr = authorities.split(",");
        HashSet<GrantedAuthority> res = new HashSet<GrantedAuthority>();
        for (String s : arr) {
            res.add(new SimpleGrantedAuthority(s.trim()));
        }//from  w  w w . java2 s.com
        return res;
    }
    return Collections.emptySet();
}

From source file:ditl.sim.pnt.DominatingSetConverter.java

@Override
public void handle(long time, Collection<Object> events) throws IOException {
    if (started) {
        // first handle previous time period
        long t = time - _delay;
        purgeBeforeTime(t, departures); // remove those that departed a time periods ago
        purgeBeforeTime(t, arrivals);/*from  w w  w . ja va  2s. c  o m*/
        Set<Integer> ds = new DSCalculator().calculateNewDS();

        Set<Integer> prev_ds_nodes = curDSNodes();
        Set<Integer> joining = new HashSet<Integer>();
        if (prev_ds_nodes != null) {
            for (Integer i : ds)
                if (!prev_ds_nodes.contains(i))
                    joining.add(i);
            Set<Integer> leaving = new HashSet<Integer>();
            for (Integer i : prev_ds_nodes)
                if (!ds.contains(i))
                    leaving.add(i);

            if (!leaving.isEmpty())
                ds_writer.queue(t, new GroupEvent(ds_gid, GroupEvent.LEAVE, leaving));
        } else {
            joining.addAll(ds);
        }

        // handle new ds nodes that arrive or leave during the time period
        for (Iterator<Integer> i = joining.iterator(); i.hasNext();) {
            Integer k = i.next();
            Long arr_time = arrivals.get(k);
            Long dep_time = departures.get(k);
            if (arr_time != null) { // node was present at beginning of time period
                ds_writer.queue(arr_time, new GroupEvent(ds_gid, GroupEvent.JOIN, new Integer[] { k }));
                i.remove();
            }
            if (dep_time != null) { // node left during the time period
                ds_writer.queue(dep_time, new GroupEvent(ds_gid, GroupEvent.LEAVE, new Integer[] { k }));
            }
        }

        if (t == _ccs.minTime()) { // this should be the initial state   
            ds_writer.setInitState(min_time, Collections.singleton(new Group(ds_gid, joining)));
        } else {
            if (ds_writer.states().isEmpty())
                ds_writer.append(t, new GroupEvent(ds_gid, GroupEvent.NEW));
            if (!joining.isEmpty())
                ds_writer.queue(t, new GroupEvent(ds_gid, GroupEvent.JOIN, joining));
        }
        ds_writer.flush();

        // then clear state and prepare for new dominating set
        init();

    } else {
        started = true;
        init();
        if (min_time > _ccs.minTime()) // starting after min_time => empty initial state
            ds_writer.setInitState(_ccs.minTime(), Collections.<Group>emptySet());
    }

    queue(time + _delay, Collections.emptySet());
}

From source file:com.espertech.esper.epl.join.table.PropertySortedEventTable.java

public Set<EventBean> lookupGreaterEqual(Object keyStart) {
    if (keyStart == null) {
        return Collections.emptySet();
    }//from   w w  w  .  j  a v  a 2 s . c om
    keyStart = coerce(keyStart);
    return normalize(propertyIndex.tailMap(keyStart));
}

From source file:edu.sdsc.scigraph.vocabulary.VocabularyNeo4jImpl.java

@Override
public Collection<Concept> getConceptFromId(Query query) {
    QueryParser parser = getQueryParser();
    String idQuery = StringUtils.strip(query.getInput(), "\"");
    Optional<String> fullUri = curieUtil.getIri(idQuery);
    idQuery = QueryParser.escape(idQuery);

    String queryString = format("%s:%s", CommonProperties.FRAGMENT, idQuery);
    if (fullUri.isPresent()) {
        queryString += String.format(" %s:%s", CommonProperties.URI, QueryParser.escape(fullUri.get()));
    }//from ww  w .j a  v  a 2s  .  c  o  m
    IndexHits<Node> hits;
    try (Transaction tx = graph.beginTx()) {
        hits = graph.index().getNodeAutoIndexer().getAutoIndex().query(parser.parse(queryString));
        tx.success();
        return limitHits(hits, query);
    } catch (ParseException e) {
        logger.log(Level.WARNING, "Failed to parse an ID query", e);
        return Collections.emptySet();
    }

}

From source file:com.nextep.designer.vcs.services.impl.DependencyService.java

@SuppressWarnings("unchecked")
@Override/*  w  w  w.j a v a  2  s .c  o  m*/
public List<IReferencer> getDirectlyDependentObjects(MultiValueMap invRefMap, IReferenceable referenceable) {
    // Building inner referencers list as this method will not return internal dependencies
    List<IReferencer> innerReferencers = new ArrayList<IReferencer>();
    if (referenceable instanceof IReferencer) {
        innerReferencers.add((IReferencer) referenceable);
    }
    if (referenceable instanceof IReferenceContainer) {
        final Map<IReference, IReferenceable> referenceMap = ((IReferenceContainer) referenceable)
                .getReferenceMap();
        for (IReferenceable child : referenceMap.values()) {
            if (child instanceof IReferencer) {
                innerReferencers.add((IReferencer) child);
            }
        }
    }
    // Checking items removal
    // Retrieving this object's reverse dependencies
    Collection<IReferencer> revDeps = (Collection<IReferencer>) invRefMap
            .getCollection(referenceable.getReference());
    if (revDeps == null) {
        revDeps = Collections.emptySet();
    }

    // Retrieving referencers
    Collection<IReferencer> dependencies = getReferencersAfterDeletion(referenceable, revDeps,
            innerReferencers);
    List<IReferencer> directDependencies = new ArrayList<IReferencer>(dependencies);
    // Removing encapsulating dependencies : among all found dependencies, we remove those that
    // contains the others so that we only extract the 'direct' dependencies without
    // transitivity.
    // TODO: Check whether this processing should be done in getReferencersAfterDeletion or not
    // (regression check)
    for (IReferencer dep : dependencies) {
        if (dep instanceof IReferenceContainer) {
            // Getting all contained refs
            final Map<IReference, IReferenceable> containedRefs = ((IReferenceContainer) dep).getReferenceMap();
            // We check wether any of this contained element is a depedency
            for (IReferencer r : dependencies) {
                if (containedRefs.values().contains(r)) {
                    // If so, the current IReferencer is not a "direct" dependency so we remove
                    // it
                    directDependencies.remove(dep);
                }
            }
        }
    }
    return directDependencies;
}