Example usage for java.util Vector contains

List of usage examples for java.util Vector contains

Introduction

In this page you can find the example usage for java.util Vector contains.

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this vector contains the specified element.

Usage

From source file:edu.ku.brc.specify.conversion.ConvertTaxonHelper.java

/**
 * Converts the taxonomy tree definition from the old taxonomicunittype table to the new table
 * pair: TaxonTreeDef & TaxonTreeDefItems.
 * /*from w  w w  .  j  a  v  a  2s .  c  o  m*/
 * @param taxonomyTypeId the tree def id in taxonomicunittype
 * @return the TaxonTreeDef object
 * @throws SQLException
 */
public void convertTaxonTreeDefinition(final CollectionInfo colInfo) {
    if (!colInfo.isInUse()) {
        return;
    }

    TaxonTreeDef taxonTreeDef = newTaxonInfoHash.get(colInfo.getTaxonNameId());
    if (taxonTreeDef != null) {
        colInfo.setTaxonTreeDef(taxonTreeDef);
        return;
    }

    Integer oldTaxonRootId = colInfo.getTaxonNameId();
    Integer taxonomyTypeId = colInfo.getTaxonomyTypeId();

    try {
        Statement st = oldDBConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

        taxonTreeDef = new TaxonTreeDef();
        taxonTreeDef.initialize();

        String sql = "SELECT TaxonomyTypeName, KingdomID FROM taxonomytype WHERE TaxonomyTypeID = "
                + taxonomyTypeId;
        log.debug(sql);
        ResultSet rs = st.executeQuery(sql);
        rs.next();
        String taxonomyTypeName = rs.getString(1);
        int kingdomID = rs.getInt(2);
        rs.close();

        taxonTreeDef.setName(taxonomyTypeName + " taxonomy tree");
        taxonTreeDef.setRemarks("Tree converted from " + oldDBName);
        taxonTreeDef.setFullNameDirection(TreeDefIface.FORWARD);

        sql = String.format(
                "SELECT RankID, RankName, RequiredParentRankID, TaxonomicUnitTypeID FROM taxonomicunittype "
                        + "WHERE TaxonomyTypeID = %d AND (Kingdom = %d  OR RankID = 0) ORDER BY RankID",
                taxonomyTypeId, kingdomID);
        log.debug(sql);
        rs = st.executeQuery(sql);

        Hashtable<Integer, Integer> rankId2TxnUntTypId = new Hashtable<Integer, Integer>();
        int rank;
        String name;
        int requiredRank;

        Vector<TaxonTreeDefItem> items = new Vector<TaxonTreeDefItem>();
        Vector<Integer> enforcedRanks = new Vector<Integer>();

        while (rs.next()) {
            rank = rs.getInt(1);
            name = rs.getString(2);
            requiredRank = rs.getInt(3);

            int taxUnitTypeId = rs.getInt(4);

            if (StringUtils.isEmpty(name) || (rank > 0 && requiredRank == 0)) {
                continue;
            }

            if (rankId2TxnUntTypId.get(rank) != null) {
                String msg = String.format(
                        "Old TreeDef has two of the same Rank %d, throwing it out.\n\nYou must fix this before proceeding.",
                        rank);
                tblWriter.logError(msg);
                log.debug(msg);
                UIRegistry.displayErrorDlg(msg);
                System.exit(0);
            }
            rankId2TxnUntTypId.put(rank, taxUnitTypeId);

            log.debug(rank + "  " + name + "  TaxonomicUnitTypeID: " + taxUnitTypeId);

            TaxonTreeDefItem ttdi = new TaxonTreeDefItem();
            ttdi.initialize();
            ttdi.setName(name);
            ttdi.setFullNameSeparator(" ");
            ttdi.setRankId(rank);
            ttdi.setTreeDef(taxonTreeDef);
            taxonTreeDef.getTreeDefItems().add(ttdi);

            ttdi.setIsInFullName(rank >= TaxonTreeDef.GENUS);

            // setup the parent/child relationship
            if (items.isEmpty()) {
                ttdi.setParent(null);
            } else {
                ttdi.setParent(items.lastElement());
            }
            items.add(ttdi);
            enforcedRanks.add(requiredRank);
        }
        rs.close();

        for (TaxonTreeDefItem i : items) {
            i.setIsEnforced(enforcedRanks.contains(i.getRankId()));
        }

        try {
            Session session = HibernateUtil.getNewSession();
            Transaction trans = session.beginTransaction();
            session.save(taxonTreeDef);
            trans.commit();
            session.close();

        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }

        IdMapperMgr idMapperMgr = IdMapperMgr.getInstance();
        IdMapperIFace tutMapper = idMapperMgr.get("TaxonomicUnitType", "TaxonomicUnitTypeID");
        IdMapperIFace taxonomyTypeMapper = idMapperMgr.get("TaxonomyType", "TaxonomyTypeID");

        //tutMapper.reset();

        //if (taxonomyTypeMapper.get(taxonomyTypeId) == null)
        //{
        taxonomyTypeMapper.put(taxonomyTypeId, taxonTreeDef.getId());
        //}

        for (TaxonTreeDefItem ttdi : taxonTreeDef.getTreeDefItems()) {
            int ttdiId = rankId2TxnUntTypId.get(ttdi.getRankId());
            log.debug("Mapping " + ttdiId + " -> " + ttdi.getId() + "  RankId: " + ttdi.getRankId());
            tutMapper.put(ttdiId, ttdi.getId());
        }

        newTaxonInfoHash.put(oldTaxonRootId, taxonTreeDef);

        CollectionInfo ci = getCIByTaxonTypeId(taxonomyTypeId);
        ci.setTaxonTreeDef(taxonTreeDef);

        taxonTreeDefHash.put(taxonomyTypeId, taxonTreeDef);
        log.debug("Hashing taxonomyTypeId: " + taxonomyTypeId + " ->  taxonTreeDefId:" + taxonTreeDef.getId());

    } catch (SQLException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}

From source file:oscar.oscarRx.data.RxPrescriptionData.java

public Vector getCurrentATCCodesByPatient(int demographicNo) {
    Vector vec = new Vector();
    Prescription[] p = getPrescriptionsByPatientHideDeleted(demographicNo);
    for (int i = 0; i < p.length; i++) {
        if (p[i].isCurrent()) {
            logger.debug(p[i].getAtcCode() + " " + p[i].getBrandName());
            if (!vec.contains(p[i].getAtcCode())) {
                logger.debug("Actually Adding " + p[i].getAtcCode() + " " + p[i].getBrandName());
                if (p[i].isValidAtcCode()) {
                    vec.add(p[i].getAtcCode());
                }/*from  w ww  .j a  v a2 s.c o m*/
            }
        }
    }
    return vec;
}

From source file:org.apache.rampart.PolicyBasedResultsValidator.java

protected void validateSignedPartsHeaders(ValidatorData data, Vector signatureParts, Vector results)
        throws RampartException {

    RampartMessageData rmd = data.getRampartMessageData();

    Node envelope = rmd.getDocument().getFirstChild();

    WSSecurityEngineResult[] actionResults = fetchActionResults(results, WSConstants.SIGN);

    // Find elements that are signed
    Vector actuallySigned = new Vector();
    if (actionResults != null) {
        for (int j = 0; j < actionResults.length; j++) {

            WSSecurityEngineResult actionResult = actionResults[j];
            List wsDataRefs = (List) actionResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS);

            // if header was encrypted before it was signed, protected
            // element is 'EncryptedHeader.' the actual element is
            // first child element

            for (Iterator k = wsDataRefs.iterator(); k.hasNext();) {
                WSDataRef wsDataRef = (WSDataRef) k.next();
                Element protectedElement = wsDataRef.getProtectedElement();
                if (protectedElement.getLocalName().equals("EncryptedHeader")) {
                    NodeList nodeList = protectedElement.getChildNodes();
                    for (int x = 0; x < nodeList.getLength(); x++) {
                        if (nodeList.item(x).getNodeType() == Node.ELEMENT_NODE) {
                            String ns = ((Element) nodeList.item(x)).getNamespaceURI();
                            String ln = ((Element) nodeList.item(x)).getLocalName();
                            actuallySigned.add(new QName(ns, ln));
                            break;
                        }//from  w w w. j  a  v a 2  s.c  o m
                    }
                } else {
                    String ns = protectedElement.getNamespaceURI();
                    String ln = protectedElement.getLocalName();
                    actuallySigned.add(new QName(ns, ln));
                }
            }

        }
    }

    for (int i = 0; i < signatureParts.size(); i++) {
        WSEncryptionPart wsep = (WSEncryptionPart) signatureParts.get(i);

        if (wsep.getType() == WSConstants.PART_TYPE_BODY) {

            QName bodyQName;

            if (WSConstants.URI_SOAP11_ENV.equals(envelope.getNamespaceURI())) {
                bodyQName = new SOAP11Constants().getBodyQName();
            } else {
                bodyQName = new SOAP12Constants().getBodyQName();
            }

            if (!actuallySigned.contains(bodyQName) && !rmd.getPolicyData().isSignBodyOptional()) {
                // soap body is not signed
                throw new RampartException("bodyNotSigned");
            }

        } else if (wsep.getType() == WSConstants.PART_TYPE_HEADER
                || wsep.getType() == WSConstants.PART_TYPE_ELEMENT) {

            Element element = (Element) WSSecurityUtil.findElement(envelope, wsep.getName(),
                    wsep.getNamespace());

            if (element == null) {
                // The signedpart header or element we are checking is not present in
                // soap envelope - this is allowed
                continue;
            }

            // header or the element present in soap envelope - verify that it is part of
            // signature
            if (actuallySigned.contains(new QName(element.getNamespaceURI(), element.getLocalName()))) {
                continue;
            }

            String msg = wsep.getType() == WSConstants.PART_TYPE_HEADER ? "signedPartHeaderNotSigned"
                    : "signedElementNotSigned";

            // header or the element defined in policy is present but not signed
            throw new RampartException(msg, new String[] { wsep.getNamespace() + ":" + wsep.getName() });

        }
    }
}

From source file:org.codecover.eclipse.views.RedundancyGraphView.java

private edu.uci.ics.jung.graph.Graph<RedundancyGraphNode, RedundancyGraphLink> createGraph() {

    if (this.selectedTestCases.size() != 0) {
        edu.uci.ics.jung.graph.Graph<RedundancyGraphNode, RedundancyGraphLink> graph = new SparseMultigraph<RedundancyGraphNode, RedundancyGraphLink>();
        Vector<RedundancyGraphNode> TestItems = new Vector<RedundancyGraphNode>();
        Vector<String> TestItemsId = new Vector<String>();
        String TestNodeName = "";
        // GraphConnection connection;

        int NumofNodes = 0;
        try {//from ww w.  j  a  v a 2 s . co  m

            // Drawing Suite Redundancy:
            for (int i = 0; i < this.selectedTestCases.size(); i++) {
                TestCase tc = this.selectedTestCases.get(i);
                TestNodeName = tc.getName();

                RedundancyGraphNode node = new RedundancyGraphNode(TestNodeName,
                        this.SuiteRedundancy.get(TestNodeName));
                TestItemsId.add(TestNodeName);
                TestItems.add(node);
                graph.addVertex(node);
                NumofNodes++;

                // I don't know how to set color for each node (change it later):
                if (this.SuiteRedundancy.get(TestNodeName) == 1 && this.RedundantTestCases.contains(tc)) {
                    node.type = "Red";
                } else if (this.SuiteRedundancy.get(TestNodeName) == 1) {
                    node.type = "Yellow";
                } else if (this.SuiteRedundancy.get(TestNodeName).isNaN()) {
                    node.type = "Black";
                } else {
                    node.type = "Green";
                }
            }

            // Drawing Pair Redundancy:
            List<TestCasePair> PairList = new ArrayList<TestCasePair>(this.PairRedundancy.keySet());
            for (int i = 0; i < PairList.size(); i++) {
                Double d = this.PairRedundancy.get(PairList.get(i));
                if (PairList.get(i).selected) {
                    if (d != 0 && !d.isNaN()) {
                        RedundancyGraphNode WithRespectToNode = null;
                        if (!TestItemsId.contains(PairList.get(i).WithRespectTo)) {
                            WithRespectToNode = new RedundancyGraphNode(PairList.get(i).WithRespectTo, 1000.0);
                            TestItemsId.add(PairList.get(i).WithRespectTo);
                            TestItems.add(WithRespectToNode);
                            graph.addVertex(WithRespectToNode);
                            NumofNodes++;
                            WithRespectToNode.type = "White";
                        } else {
                            for (int k = 0; k < NumofNodes; k++) {
                                if (TestItems.get(k).TestName.compareTo(PairList.get(i).WithRespectTo) == 0) {
                                    WithRespectToNode = TestItems.get(k);
                                }
                            }
                        }
                        RedundancyGraphNode CurrentTestNode = null;
                        for (int k = 0; k < NumofNodes; k++) {
                            if (TestItems.get(k).TestName.compareTo(PairList.get(i).CurrentTest) == 0) {
                                CurrentTestNode = TestItems.get(k);
                            }
                        }

                        RedundancyGraphLink link = new RedundancyGraphLink(i, d);
                        graph.addEdge(link, CurrentTestNode, WithRespectToNode, EdgeType.DIRECTED);
                    }
                }

            }
        } catch (Exception ex) {
        }
        return graph;
    }
    return null;
}

From source file:com.fluidops.iwb.deepzoom.CXMLServlet.java

private void getUnstructuredSearchResult(String q, String collection, PrintStream out, HttpServletRequest req,
        int maxEntities, int maxFacets) {

    Map<URI, Map<URI, Set<Value>>> graph = new HashMap<URI, Map<URI, Set<Value>>>();

    HashMap<URI, Integer> facetCountMap = new HashMap<URI, Integer>();
    Vector<URI> predicates = new Vector<URI>();

    Set<String> uris = new HashSet<String>();

    if (q == null || q.trim().isEmpty()) {
        // nothing to do
    } else {/*from   w w  w .  j a v  a  2 s  .c  o m*/
        try {
            QueryResult<?> res = KeywordSearchAPI.search(q.trim());

            while (res.hasNext()) {
                BindingSet bindingSet = (BindingSet) res.next();
                uris.add(bindingSet.getValue("Subject").stringValue());
            }
        } catch (RuntimeException e) {
            logger.trace(e.getMessage(), e);
        } catch (Exception e) {
            logger.trace(e.getMessage(), e);
        }
    }
    RepositoryConnection con = null;

    try {
        con = Global.repository.getConnection();
    } catch (RepositoryException e) {
        logger.warn(e.getMessage(), e);
    }

    int counter = 0;
    ValueFactory f = ValueFactoryImpl.getInstance();

    for (String uriString : uris) {
        if (counter >= maxEntities)
            break;

        URI uri = f.createURI(uriString);

        URI subject = uri;
        Map<URI, Set<Value>> facets = null;

        facets = new HashMap<URI, Set<Value>>();
        graph.put(subject, facets);

        List<Statement> statements = null;
        try {
            statements = Iterations.asList(con.getStatements(uri, null, null, false));
        } catch (RepositoryException e) {
            logger.warn(e.getMessage(), e);
            statements = Collections.emptyList();
        }

        for (Statement s : statements) {

            if (notWantedProps.contains(s.getPredicate())) {
                continue;
            }

            URI predicate = s.getPredicate();

            Value range = EndpointImpl.api().getDataManager().getProp(predicate, RDFS.RANGE);
            if (range == null)
                range = XMLSchema.STRING;
            if (!(range instanceof URI))
                range = XMLSchema.STRING;
            predicateTypes.put(predicate, (URI) range);

            if (!predicates.contains(predicate)) {
                predicates.add(predicate);
                facetCountMap.put(predicate, 1);
            } else {
                facetCountMap.put(predicate, facetCountMap.get(predicate) + 1);
            }
            if (!notWantedObjs.contains(s.getObject())) {
                Set<Value> facet = null;
                if (facets.containsKey(predicate))
                    facet = facets.get(predicate);
                else {
                    facet = new HashSet<Value>();
                    facets.put(predicate, facet);
                }
                facet.add(s.getObject());
            }
        }

        counter++;
    }

    try {
        renderCollection(graph, predicates, facetCountMap, collection, q, out, q, req, maxEntities, maxFacets);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    //        queryCounter++;
}

From source file:org.roaringbitmap.TestRoaringBitmap.java

@Test
public void ortest3() {
    final HashSet<Integer> V1 = new HashSet<Integer>();
    final HashSet<Integer> V2 = new HashSet<Integer>();

    final RoaringBitmap rr = new RoaringBitmap();
    final RoaringBitmap rr2 = new RoaringBitmap();
    // For the first 65536: rr2 has a bitmap container, and rr has
    // an array container.
    // We will check the union between a BitmapCintainer and an
    // arrayContainer
    for (int k = 0; k < 4000; ++k) {
        rr2.add(k);//from  w  ww .ja va  2  s.co  m
        V1.add(k);
    }
    for (int k = 3500; k < 4500; ++k) {
        rr.add(k);
        V1.add(k);
    }
    for (int k = 4000; k < 65000; ++k) {
        rr2.add(k);
        V1.add(k);
    }

    // In the second node of each roaring bitmap, we have two bitmap
    // containers.
    // So, we will check the union between two BitmapContainers
    for (int k = 65536; k < 65536 + 10000; ++k) {
        rr.add(k);
        V1.add(k);
    }

    for (int k = 65536; k < 65536 + 14000; ++k) {
        rr2.add(k);
        V1.add(k);
    }

    // In the 3rd node of each Roaring Bitmap, we have an
    // ArrayContainer, so, we will try the union between two
    // ArrayContainers.
    for (int k = 4 * 65535; k < 4 * 65535 + 1000; ++k) {
        rr.add(k);
        V1.add(k);
    }

    for (int k = 4 * 65535; k < 4 * 65535 + 800; ++k) {
        rr2.add(k);
        V1.add(k);
    }

    // For the rest, we will check if the union will take them in
    // the result
    for (int k = 6 * 65535; k < 6 * 65535 + 1000; ++k) {
        rr.add(k);
        V1.add(k);
    }

    for (int k = 7 * 65535; k < 7 * 65535 + 2000; ++k) {
        rr2.add(k);
        V1.add(k);
    }

    final RoaringBitmap rror = RoaringBitmap.or(rr, rr2);
    boolean valide = true;

    // Si tous les elements de rror sont dans V1 et que tous les
    // elements de
    // V1 sont dans rror(V2)
    // alors V1 == rror

    final Object[] tab = V1.toArray();
    final Vector<Integer> vector = new Vector<Integer>();
    for (Object aTab : tab)
        vector.add((Integer) aTab);

    for (final int i : rror.toArray()) {
        if (!vector.contains(new Integer(i))) {
            valide = false;
        }
        V2.add(i);
    }
    for (int i = 0; i < V1.size(); i++)
        if (!V2.contains(vector.elementAt(i))) {
            valide = false;
        }

    Assert.assertEquals(valide, true);
}

From source file:org.roaringbitmap.TestRoaringBitmap.java

@Test
public void xortest1() {
    final HashSet<Integer> V1 = new HashSet<Integer>();
    final HashSet<Integer> V2 = new HashSet<Integer>();

    final RoaringBitmap rr = new RoaringBitmap();
    final RoaringBitmap rr2 = new RoaringBitmap();
    // For the first 65536: rr2 has a bitmap container, and rr has
    // an array container.
    // We will check the union between a BitmapCintainer and an
    // arrayContainer
    for (int k = 0; k < 4000; ++k) {
        rr2.add(k);//from   w ww  . j  a v  a 2 s  .  c  om
        if (k < 3500)
            V1.add(k);
    }
    for (int k = 3500; k < 4500; ++k) {
        rr.add(k);
    }
    for (int k = 4000; k < 65000; ++k) {
        rr2.add(k);
        if (k >= 4500)
            V1.add(k);
    }

    // In the second node of each roaring bitmap, we have two bitmap
    // containers.
    // So, we will check the union between two BitmapContainers
    for (int k = 65536; k < 65536 + 30000; ++k) {
        rr.add(k);
    }

    for (int k = 65536; k < 65536 + 50000; ++k) {
        rr2.add(k);
        if (k >= 65536 + 30000)
            V1.add(k);
    }

    // In the 3rd node of each Roaring Bitmap, we have an
    // ArrayContainer. So, we will try the union between two
    // ArrayContainers.
    for (int k = 4 * 65535; k < 4 * 65535 + 1000; ++k) {
        rr.add(k);
        if (k >= 4 * 65535 + 800)
            V1.add(k);
    }

    for (int k = 4 * 65535; k < 4 * 65535 + 800; ++k) {
        rr2.add(k);
    }

    // For the rest, we will check if the union will take them in
    // the result
    for (int k = 6 * 65535; k < 6 * 65535 + 1000; ++k) {
        rr.add(k);
        V1.add(k);
    }

    for (int k = 7 * 65535; k < 7 * 65535 + 2000; ++k) {
        rr2.add(k);
        V1.add(k);
    }

    final RoaringBitmap rrxor = RoaringBitmap.xor(rr, rr2);
    boolean valide = true;

    // Si tous les elements de rror sont dans V1 et que tous les
    // elements de
    // V1 sont dans rror(V2)
    // alors V1 == rror
    final Object[] tab = V1.toArray();
    final Vector<Integer> vector = new Vector<Integer>();
    for (Object aTab : tab)
        vector.add((Integer) aTab);

    for (final int i : rrxor.toArray()) {
        if (!vector.contains(new Integer(i))) {
            valide = false;
        }
        V2.add(i);
    }
    for (int i = 0; i < V1.size(); i++)
        if (!V2.contains(vector.elementAt(i))) {
            valide = false;
        }

    Assert.assertEquals(valide, true);
}

From source file:com.fluidops.iwb.deepzoom.CXMLServlet.java

private void getGraphResult(String q, URI uri, String collection, Repository repository, PrintStream out,
        HttpServletRequest req, int maxEntities, int maxFacets) {
    Vector<URI> predicates = new Vector<URI>();
    Map<URI, Map<URI, Set<Value>>> graph = new HashMap<URI, Map<URI, Set<Value>>>();
    HashMap<URI, Integer> facetCountMap = new HashMap<URI, Integer>();

    try {//from   w  w  w.  j a  va 2 s.co m
        ReadDataManager dm = EndpointImpl.api().getDataManager();
        GraphQueryResult queryRes = dm.sparqlConstruct(q, true);

        HashSet<Value> notWantedSubjs = new HashSet<Value>();

        // graph query result may contain duplicate statements
        // (actually a bug/feature of Sesame), so we filter them out
        // at the same time, we check whether the target URI is at the subject or object position
        // if it is at object position, we create an inverse statement
        //              while(queryRes.hasNext() && count++ < maxTriples)
        //              {
        //                  Statement s = queryRes.next();
        //                  queryResNoDups.add(s);
        //                  /* if(uri==null)
        //                      queryResNoDups.add(s);
        //                  else if(s.getSubject().equals(uri))
        //                      queryResNoDups.add(s);
        //                  else if(s.getObject().equals(uri))
        //                  {
        //                      URI predicate = s.getPredicate();
        //                      URI inverse = f.createURI(predicate.stringValue()+" of");
        //                        queryResNoDups.add(f.createStatement(s.getSubject(), inverse, uri));
        //                  }*/
        //              }
        while (queryRes.hasNext()) {

            Statement s = queryRes.next();

            Resource subject = s.getSubject();
            if (!(subject instanceof URI))
                continue;

            URI predicate = s.getPredicate();

            if (notWantedProps.contains(predicate)) {
                continue;
            }

            Map<URI, Set<Value>> facets = null;
            if (graph.containsKey(subject))
                facets = graph.get(subject);
            else {
                facets = new HashMap<URI, Set<Value>>();
                graph.put((URI) subject, facets);
            }

            if (!predicates.contains(predicate)) {

                Value range = dm.getProp(predicate, RDFS.RANGE);

                if (range == null)
                    range = XMLSchema.STRING;
                if (!(range instanceof URI))
                    range = XMLSchema.STRING;
                predicateTypes.put(predicate, (URI) range);

                predicates.add(predicate);
                facetCountMap.put(predicate, 1);
            } else
                facetCountMap.put(predicate, facetCountMap.get(predicate) + 1);

            Value object = s.getObject();

            if (!notWantedObjs.contains(object)) {
                Set<Value> facet = null;
                if (facets.containsKey(predicate))
                    facet = facets.get(predicate);
                else {
                    facet = new HashSet<Value>();
                    facets.put(predicate, facet);
                }
                facet.add(object);
            }
        }

        for (Value v : notWantedSubjs) {
            if (graph.containsKey(v)) {
                graph.remove(v);
            }
        }

        renderCollection(graph, predicates, facetCountMap, collection,
                EndpointImpl.api().getDataManager().getLabel(uri), out, q, req, maxEntities, maxFacets);

    } catch (RuntimeException e) {
        logger.error(e.getMessage(), e);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:ucar.unidata.idv.flythrough.Flythrough.java

/**
 * _more_//  www .j ava2s.  com
 *
 * @param pt _more_
 *
 * @return _more_
 */
private boolean showProperties(FlythroughPoint pt) {
    try {
        DateTime[] times = viewManager.getAnimationWidget().getTimes();
        JComboBox timeBox = null;
        JLabel timeLabel = GuiUtils.rLabel("Time:");
        Vector timesList = new Vector();
        timesList.add(0, new TwoFacedObject("None", null));
        if ((times != null) && (times.length > 0)) {
            timesList.addAll(Misc.toList(times));
        }
        if ((pt.getDateTime() != null) && !timesList.contains(pt.getDateTime())) {
            timesList.add(pt.getDateTime());
        }
        timeBox = new JComboBox(timesList);
        if (pt.getDateTime() != null) {
            timeBox.setSelectedItem(pt.getDateTime());
        }

        LatLonWidget llw = new LatLonWidget("Latitude: ", "Longitude: ", "Altitude: ", null) {
            protected String formatLatLonString(String latOrLon) {
                return latOrLon;
            }
        };

        EarthLocation el = pt.getEarthLocation();
        llw.setLatLon(el.getLatitude().getValue(CommonUnit.degree),
                el.getLongitude().getValue(CommonUnit.degree));
        llw.setAlt(getAlt(el));

        JTextArea textArea = new JTextArea("", 5, 100);
        if (pt.getDescription() != null) {
            textArea.setText(pt.getDescription());
        }
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setPreferredSize(new Dimension(400, 300));
        JComponent contents = GuiUtils.formLayout(new Component[] { GuiUtils.rLabel("Location:"), llw,
                timeLabel, GuiUtils.left(timeBox), GuiUtils.rLabel("Description:"), scrollPane });
        if (!GuiUtils.showOkCancelDialog(frame, "Point Properties", contents, null)) {
            return false;
        }
        pt.setDescription(textArea.getText());
        pt.setEarthLocation(makePoint(llw.getLat(), llw.getLon(), llw.getAlt()));
        Object selectedDate = timeBox.getSelectedItem();
        if (selectedDate instanceof TwoFacedObject) {
            pt.setDateTime(null);
        } else {
            pt.setDateTime((DateTime) selectedDate);
        }

        return true;
    } catch (Exception exc) {
        logException("Showing point properties", exc);
        return false;
    }

}

From source file:alter.vitro.vgw.wsiadapter.WsiUberDustCon.java

/**
 * Test function in order to debug resource discovery even when uberdust is not accessible
 * @param givGatewayInfo/*from   w ww  . j  a va 2 s.  c o m*/
 * @return
 */
private CGatewayWithSmartDevices DEBUG_offline_createWSIDescr(CGateway givGatewayInfo) {
    Vector<CSmartDevice> currSmartDevicesVec = new Vector<CSmartDevice>();
    CGatewayWithSmartDevices myGatewayForSmartDevs = new CGatewayWithSmartDevices(givGatewayInfo,
            currSmartDevicesVec);

    // An auxiliary structure that maps Unique Generic Capability Descriptions to Lists of SensorTypes ids.
    HashMap<String, Vector<Integer>> myAllCapabilitiesToSensorModelIds = new HashMap<String, Vector<Integer>>();

    String responseBodyFromHttpNodesGetStr = WsiUberDustCon.DEBUG_OFFLINE_STR_NODE_GETRESTSTATUS;
    String responseBodyFromHttpNodes_STATUS_Get = WsiUberDustCon.DEBUG_OFFLINE_STR_GETRESTSTATUS_RAW;
    String responseBodyFromHttpNodes_ADMINSTATUS_Get = WsiUberDustCon.DEBUG_OFFLINE_STR_BODY_ADMINSTATUS;
    try {
        //
        String[] nodeUrnsInUberdust = responseBodyFromHttpNodesGetStr.split("\\r?\\n");
        int totalNodeUrnsInUberdust = nodeUrnsInUberdust.length;

        String[] nodeAndLastCapReadingsUrnsInUberdust = responseBodyFromHttpNodes_STATUS_Get.split("\\r?\\n");
        int totalNodeWithCapsInUberdust = nodeAndLastCapReadingsUrnsInUberdust.length;

        //TODO: test this:
        Vector<String> allFaultyNodesUrns = getFaultyNodes();

        // LOOP OVER EVERY NODE (smart device), and for each node, get its capabilities from the second response (responseBody_STATUS_Str)

        logger.debug("Total nodes:" + String.valueOf(totalNodeUrnsInUberdust));
        for (String aNodeUrnsInUberdust : nodeUrnsInUberdust) {
            if (allFaultyNodesUrns.contains(aNodeUrnsInUberdust)) {
                logger.debug("Skiipping node: " + aNodeUrnsInUberdust);
                continue; //skip faulty nodes!
            }
            logger.debug("Discovering resources of node: " + aNodeUrnsInUberdust);

            Vector<Integer> sensorModels_IDs_OfSmartDevVector = new Vector<Integer>();// todo: fix this redundancy!
            Vector<CSensorModel> sensorModelsOfSmartDevVector = new Vector<CSensorModel>();
            CSmartDevice tmpSmartDev = new CSmartDevice(aNodeUrnsInUberdust, "", /* smart device type name */
                    "", /* location description e.g. room1*/
                    new GeodesicPoint(), /*  */
                    sensorModels_IDs_OfSmartDevVector);

            // TODO: Add an extra early for loop to update the fields for the attributes of the SmartDevice such as:
            //      Eventually if the SmartDev has NO other valid sensors (e.g. observation sensors or actuators) then it won't be added !
            String tmp_longitude = "";
            String tmp_latitude = "";
            String tmp_altitude = "";

            for (String aNodeAndLastCapReadingsUrnsInUberdust1 : nodeAndLastCapReadingsUrnsInUberdust) {
                //to update the device attributes!
                String[] nodeCapAndReadingRowItems = aNodeAndLastCapReadingsUrnsInUberdust1.split("\\t");
                if (nodeCapAndReadingRowItems.length > 3
                        && nodeCapAndReadingRowItems[0].compareToIgnoreCase(aNodeUrnsInUberdust) == 0) //we are at the capabilities of the current smartdevice
                {
                    logger.debug(" node id: " + nodeCapAndReadingRowItems[0]);
                    logger.debug(" capability: " + nodeCapAndReadingRowItems[1] != null
                            ? nodeCapAndReadingRowItems[1]
                            : "");
                    logger.debug(
                            " timestamp: " + nodeCapAndReadingRowItems[2] != null ? nodeCapAndReadingRowItems[2]
                                    : "");
                    logger.debug(" measurement: " + nodeCapAndReadingRowItems[3] != null
                            ? nodeCapAndReadingRowItems[3]
                            : "");
                    // [0] is mote (smart device) id
                    // [1] is capability
                    // [2] is timestamp
                    // [3] is measurement value
                    if ((nodeCapAndReadingRowItems[1] != null)
                            && !(nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase(""))) {
                        if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("room")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            {
                                tmpSmartDev.setLocationDesc(nodeCapAndReadingRowItems[3].trim());
                            }
                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("nodetype")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            tmpSmartDev.setName(nodeCapAndReadingRowItems[3].trim());
                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("description")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            //TODO: do we need this?

                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("x")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            //TODO: we need the function to derive a valid longitude from the uberdust value (pending)
                            tmp_longitude = nodeCapAndReadingRowItems[3].trim();
                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("y")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            //TODO: we need the function to derive a valid latitude)
                            tmp_latitude = nodeCapAndReadingRowItems[3].trim();
                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("z")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            //altitude is in meters (assumption)
                            tmp_altitude = nodeCapAndReadingRowItems[3].trim();

                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("phi")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            //TODO: do we need this?
                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("theta")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            //TODO: do we need this?
                        }
                    }

                }
            } // end of first round of for loop for attributes
            if (!tmp_latitude.equalsIgnoreCase("") && !tmp_longitude.equalsIgnoreCase("")
                    && !tmp_altitude.equalsIgnoreCase("")) {
                tmpSmartDev.setGplocation(new GeodesicPoint(tmp_latitude, tmp_longitude, tmp_altitude));
            }

            //
            // Again same loop for measurement and actuation capabilities!
            //
            for (String aNodeAndLastCapReadingsUrnsInUberdust : nodeAndLastCapReadingsUrnsInUberdust) {
                String[] nodeCapAndReadingRowItems = aNodeAndLastCapReadingsUrnsInUberdust.split("\\t");
                if (nodeCapAndReadingRowItems.length > 3
                        && nodeCapAndReadingRowItems[0].compareToIgnoreCase(aNodeUrnsInUberdust) == 0) //we are at the capabilities of the current smartdevice
                {
                    // [0] is mote (smart device) id
                    // [1] is capability
                    // [2] is measurement value
                    // [3] is timestamp
                    //                                        logger.debug(nodeCapAndReadingRowItems[1]);
                    // TODO: FILTER OUT UNSUPPORTED OR COMPLEX CAPABILITIES!!!!
                    // Since uberdust does not distinguish currenlty between sensing/actuating capabilities and properties, we need to filter out manually
                    // everything we don't consider a sensing/actuating capability.
                    // Another filtering out is done at a later stage with the SensorMLMessageAdapter, which will filter out the capabilities not supported by IDAS
                    // TODO: it could be nice to have this filtering unified.
                    if ((nodeCapAndReadingRowItems[1] != null)
                            && (nodeCapAndReadingRowItems[1].trim().compareTo("") != 0)
                            && !getSimpleCapForUberdustUrn(nodeCapAndReadingRowItems[1].trim())
                                    .equalsIgnoreCase("UnknownPhenomenon")) {

                        //todo: this is just to support actuation during the demo. The code should be improved later on:
                        // todo: replace with regex
                        //if(getSimpleCapForUberdustUrn(nodeCapAndReadingRowItems[1].trim()).equalsIgnoreCase("switchlight1")
                        //        || getSimpleCapForUberdustUrn(nodeCapAndReadingRowItems[1].trim()).equalsIgnoreCase("switchlight2")
                        //        ||  getSimpleCapForUberdustUrn(nodeCapAndReadingRowItems[1].trim()).equalsIgnoreCase("switchlight3")
                        //        ||getSimpleCapForUberdustUrn(nodeCapAndReadingRowItems[1].trim()).equalsIgnoreCase("switchlight4") )
                        //{

                        //}
                        // else
                        // {
                        //TODO: don't get light measurements from arduinos even if they advertise light as a capability

                        // The model id is set as the hashcode of the capability name appended with the model type of the device.
                        // Perhaps this should be changed to something MORE specific
                        // TODO: the units should be set here as we know them. Create a small dictionary to set them!
                        // TODO: the non-observation sensors/ non-actuation should be filtered here!! the Name for the others should be "UnknownPhenomenon"

                        String tmpGenericCapabilityForSensor = getSimpleCapForUberdustUrn(
                                nodeCapAndReadingRowItems[1].trim());
                        Integer thedigestInt = (tmpGenericCapabilityForSensor + "-" + tmpSmartDev.getName())
                                .hashCode();
                        if (thedigestInt < 0)
                            thedigestInt = thedigestInt * (-1);

                        CSensorModel tmpSensorModel = new CSensorModel(givGatewayInfo.getId(), /*Gateway Id*/
                                thedigestInt, /*Sensor Model Id */
                                (tmpGenericCapabilityForSensor + "-"
                                        + tmpSmartDev.getName()), /* Sensor Model name */
                                CSensorModel.numericDataType, /* Data type*/ // TODO: later on this should be adjustable!!!
                                CSensorModel.defaultAccuracy, /* Accuracy */
                                CSensorModel.defaultUnits) /* Units */; // TODO: this should be set when it is known!!!
                        //                                            if(!tmpGenericCapabilityForSensor.equalsIgnoreCase("UnknownPhenomenon" ))
                        //                                            {
                        sensorModelsOfSmartDevVector.add(tmpSensorModel);
                        sensorModels_IDs_OfSmartDevVector.add(tmpSensorModel.getSmid());
                        //logger.debug("HER HE R HER : Adding id: "+ Integer.toString(thedigestInt)+ " for cap: " + tmpGenericCapabilityForSensor);
                        //Integer thedigestIntAlt = (tmpGenericCapabilityForSensor).hashCode();
                        //if (thedigestIntAlt < 0) thedigestIntAlt = thedigestIntAlt * (-1);
                        //logger.debug("HER HE R HER : WHEREAS EXPERIMENT id: "+ Integer.toString(thedigestIntAlt)+ " for cap: " + tmpGenericCapabilityForSensor);

                        //                                            }

                        if (!myAllCapabilitiesToSensorModelIds.containsKey(tmpGenericCapabilityForSensor)) {
                            myAllCapabilitiesToSensorModelIds.put(tmpGenericCapabilityForSensor,
                                    new Vector<Integer>());
                            givGatewayInfo.getAllGwGenericCapabilities().put(tmpGenericCapabilityForSensor,
                                    new Vector<CSensorModel>());
                        }
                        // When we reach this part, we already have a key that corresponds to a unique sensor capability description
                        if (!myAllCapabilitiesToSensorModelIds.get(tmpGenericCapabilityForSensor)
                                .contains(Integer.valueOf(tmpSensorModel.getSmid()))) {
                            myAllCapabilitiesToSensorModelIds.get(tmpGenericCapabilityForSensor)
                                    .addElement(tmpSensorModel.getSmid());
                            givGatewayInfo.getAllGwGenericCapabilities().get(tmpGenericCapabilityForSensor)
                                    .addElement(tmpSensorModel);
                        }
                        // }
                    }
                }
            }
            if (!sensorModelsOfSmartDevVector.isEmpty()) {
                // TODO: FILTER OUT UNSUPPORTED OR COMPLEX NODES!!!!
                // For demo purposes let's keep only the first floor and iSense devices
                String isensePrefixTag = "isense";
                String arduinoTag = "arduino";
                String telosBTag = "telosb";
                String roomsOnZeroFloor_PartI_PrefixTag = "0.I.";
                String roomsOnZeroFloor_PartII_PrefixTag = "0.II.";

                if (!VitroGatewayService.getVitroGatewayService().getAssignedGatewayUniqueIdFromReg()
                        .equalsIgnoreCase("vitrogw_hai")) {
                    if ((!tmpSmartDev.getLocationDesc().isEmpty())
                            && ((tmpSmartDev.getLocationDesc().length() >= roomsOnZeroFloor_PartI_PrefixTag
                                    .length()
                                    && tmpSmartDev.getLocationDesc()
                                            .substring(0, roomsOnZeroFloor_PartI_PrefixTag.length())
                                            .equalsIgnoreCase(roomsOnZeroFloor_PartI_PrefixTag))
                                    || (tmpSmartDev.getLocationDesc()
                                            .length() >= roomsOnZeroFloor_PartII_PrefixTag.length()
                                            && tmpSmartDev.getLocationDesc()
                                                    .substring(0, roomsOnZeroFloor_PartII_PrefixTag.length())
                                                    .equalsIgnoreCase(roomsOnZeroFloor_PartII_PrefixTag)))
                            && (!tmpSmartDev.getName().isEmpty())
                            && ((tmpSmartDev.getName().length() >= isensePrefixTag.length()
                                    && tmpSmartDev.getName().substring(0, isensePrefixTag.length())
                                            .equalsIgnoreCase(isensePrefixTag))
                                    || (tmpSmartDev.getName().length() >= arduinoTag.length()
                                            && tmpSmartDev.getName().substring(0, arduinoTag.length())
                                                    .equalsIgnoreCase(arduinoTag)))) {
                        currSmartDevicesVec.addElement(tmpSmartDev);
                    }
                } else if (VitroGatewayService.getVitroGatewayService().getAssignedGatewayUniqueIdFromReg()
                        .equalsIgnoreCase("vitrogw_hai")) {
                    //logger.debug("I am hai");
                    if ((!tmpSmartDev.getLocationDesc().isEmpty())
                            && ((tmpSmartDev.getLocationDesc().length() >= roomsOnZeroFloor_PartI_PrefixTag
                                    .length()
                                    && tmpSmartDev.getLocationDesc()
                                            .substring(0, roomsOnZeroFloor_PartI_PrefixTag.length())
                                            .equalsIgnoreCase(roomsOnZeroFloor_PartI_PrefixTag))
                                    || (tmpSmartDev.getLocationDesc()
                                            .length() >= roomsOnZeroFloor_PartII_PrefixTag.length()
                                            && tmpSmartDev.getLocationDesc()
                                                    .substring(0, roomsOnZeroFloor_PartII_PrefixTag.length())
                                                    .equalsIgnoreCase(roomsOnZeroFloor_PartII_PrefixTag)))
                            && (!tmpSmartDev.getName().isEmpty())
                            && ((tmpSmartDev.getName().length() >= telosBTag.length() && tmpSmartDev.getName()
                                    .substring(0, telosBTag.length()).equalsIgnoreCase(telosBTag)))) {
                        String myoldid = tmpSmartDev.getId();
                        tmpSmartDev.setId(dictionaryUberdustUrnToHaiUrnName.get(myoldid));
                        currSmartDevicesVec.addElement(tmpSmartDev);
                    }
                }

                //#####################################
            }
        } // ends for loop over all smartdevices discovered!

    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }

    return myGatewayForSmartDevs;

}