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:com.fluidops.iwb.deepzoom.CXMLServlet.java

@SuppressWarnings(value = "DM_CONVERT_CASE", justification = "checked")
private void renderCollection(Map<URI, Map<URI, Set<Value>>> graph, Vector<URI> predicates,
        HashMap<URI, Integer> facetCountMap, String collection, String collectionName, PrintStream httpOut,
        String q, HttpServletRequest req, int maxEntities, int maxFacets)
        throws FileNotFoundException, IOException {

    PrintStream resultCache = new PrintStream(new FileOutputStream(getCacheFile("resultCache", hash(q))), false,
            "UTF-8");

    PrintStream out = new PrintStream(new DualOutputStream(httpOut, resultCache), false, "UTF-8");

    out.println("<?xml  version=\"1.0\"  encoding=\"utf-8\"?>");
    //out.println("<?xml-stylesheet type=\"text/xsl\" href=\"/int/pivot/pivot.xsl\"?>");
    out.println("<Collection Name=\"" + XML.escape(collectionName) + "\" SchemaVersion=\"1.0\"");
    out.println(" xmlns=\"http://schemas.microsoft.com/collection/metadata/2009\"");
    out.println(" xmlns:p=\"http://schemas.microsoft.com/livelabs/pivot/collection/2009\"");
    out.println(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
    out.println(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");

    Dimension d = new Dimension(200, 200);

    Writer collectionWriter = null;
    try {//ww  w.  j a  v a  2  s . c o  m
        collectionWriter = new OutputStreamWriter(
                new FileOutputStream(getCacheFile("collectionCache", hash(q))), "UTF-8");
    } catch (IOException e) {
        logger.warn(e.getMessage());
    }

    collectionWriter.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
            + "<Collection MaxLevel=\"8\" TileSize=\"256\" Format=\"jpg\" NextItemId=\"1001\" ServerFormat=\"Default\" xmlns=\"http://schemas.microsoft.com/deepzoom/2009\">\n"
            + "<Items>\n");

    // render facet categories
    out.println("<FacetCategories>");
    List<URI> displayedFacets = new LinkedList<URI>();

    // We limit the number of displayed facets (maxPivotFacets)
    // We rank facets by the number of entities that have a value for the given facet
    // The ranking only needs to be performed if maxFacets>0 (0 disables limitation)
    // and the number of facets is actually greater than maxFacets

    if (facetCountMap != null && maxFacets > 0 && facetCountMap.size() > maxFacets) {
        Set<Entry<URI, Integer>> s = facetCountMap.entrySet();

        for (int i = 0; i < maxFacets; i++) {
            int max = 0;
            Entry<URI, Integer> maxEntry = null;
            for (Entry<URI, Integer> e : s) {
                if (e.getValue() > max) {
                    maxEntry = e;
                    max = e.getValue();
                }
            }
            if (maxEntry == null)
                break;

            displayedFacets.add(maxEntry.getKey());
            s.remove(maxEntry);
        }
    } else
        displayedFacets = predicates;
    Vector<URI> facetNames = new Vector<URI>();
    Vector<String> facetLabels = new Vector<String>();

    // we may use any sort order here; currently, we sort alphabetically,
    // with the exception that the type facet is always on top
    Collections.sort(predicates, new Comparator<URI>() {
        public int compare(URI o1, URI o2) {
            if (o1.equals(RDF.TYPE))
                return -1;
            else if (o2.equals(RDF.TYPE))
                return 1;
            else
                return o1.stringValue().compareTo(o2.stringValue());
        }
    });

    for (URI predicate : predicates) {
        ReadDataManager dm = EndpointImpl.api().getDataManager();
        if (dm.getLabel(predicate).equals("name") || facetNames.contains(predicate))
            continue; // labels of names are unfortunately not unique, but must not occur as duplicates
        facetNames.add(predicate);

        if (displayedFacets.contains(predicate)) {
            String name = dm.getLabel(predicate);
            name = escape(name).trim();

            // TODO: only quick fix, has to be handled properly
            // facet labels need to be unique, disregarding capitalization
            if (!facetLabels.contains(name.toLowerCase())) {
                facetLabels.add(name.toLowerCase());

                String type;

                URI range = predicateTypes.get(predicate);
                if (range == null)
                    range = XMLSchema.STRING;
                if (range.equals(XMLSchema.DATETIME) || range.equals(XMLSchema.DATE))
                    type = "DateTime";
                else if (range.equals(XMLSchema.FLOAT) || range.equals(XMLSchema.DOUBLE)
                        || range.equals(XMLSchema.INT) || range.equals(XMLSchema.INTEGER)
                        || range.equals(XMLSchema.LONG))
                    type = "Number";
                else
                    type = "String"; //default

                out.println("<FacetCategory Name=\"" + XML.escape(name) + "\" Type=\"" + type
                        + "\" p:IsFilterVisible=\"true\"  p:IsMetaDataVisible=\"false\" />");
                out.println("<FacetCategory Name=\"" + XML.escape(name)
                        + ":\" Type=\"Link\" p:IsFilterVisible=\"false\" p:IsMetaDataVisible=\"true\" />");

            }
        }
    }
    out.println(
            "<FacetCategory Name=\"Home\" Type=\"Link\" p:IsFilterVisible=\"false\" p:IsMetaDataVisible=\"true\" />");
    out.println("</FacetCategories>");

    // render items in collection
    String collectionID = "collection" + hash(q) + ".xml";
    out.println("<Items ImgBase=\"" + collection + "/" + collectionID + "\">");

    int counter = 0;
    Vector<String> imageVector = new Vector<String>();
    //        queryImageVector.put(hash(q), imageVector);

    ImageLoader loader = new ImageLoader(api().getRequestMapper().getInternalUrlWithoutContext(req));

    for (Entry<URI, Map<URI, Set<Value>>> entry : graph.entrySet()) {
        Resource entity = entry.getKey();
        if (counter >= maxEntities)
            break;

        Map<URI, Set<Value>> facets = entry.getValue();

        // We assume that all entities are URIs. Perhaps need to re-evaluate this assumption
        URI uri = (URI) entity;

        String img = null;

        if (IWBCmsUtil.isUploadedFile(uri) && ImageResolver.isImage(uri.stringValue()))
            img = getImageURLForValue(uri);
        else {

            // verify if there is an image in the facets using image properties
            // given by ImageResolver (e.g. foaf:img)
            for (URI imageProperty : ImageResolver.getDefaultImageResolver().getImageProperties()) {
                Set<Value> imgForProperty = facets.get(imageProperty);
                if (imgForProperty != null && imgForProperty.size() > 0) {
                    img = getImageURLForValue(imgForProperty.iterator().next());
                    break; // found an image
                }
            }

            // fallback, no image found: indicates that ID card should be generated
            if (img == null)
                img = "id:" + entity.stringValue() + ".jpg";
        }
        String filename = ImageLoader.filename(img);
        if (!imageVector.contains(img)) //only need to load the image once
        {
            loader.createImageThreaded(uri, facets, img, collection);
            imageVector.add(img);
            int imgID = imageVector.indexOf(img);
            collectionWriter.write("<I Id=\"" + imgID + "\" N=\"" + imgID + "\" Source=\"dzimages/"
                    + ImageLoader.subdir(filename) + "/"
                    + ((filename.lastIndexOf(".") > -1) ? filename.substring(0, filename.lastIndexOf("."))
                            : filename)
                    + ".xml\">" + "<Size Width=\"" + d.width + "\" Height=\"" + d.height + "\"/></I>");

        }

        int imgID = imageVector.indexOf(img);

        ReadDataManager dm = EndpointImpl.api().getDataManager();
        String label = cleanLabel(dm.getLabel(uri));
        if (label.length() == 0)
            continue;
        out.println("<Item Img=\"#" + imgID + "\" Id=\"" + counter + "\" Href=\""
                + EndpointImpl.api().getRequestMapper().getRequestStringFromValue(uri) + "\" Name=\"" + label
                + "\">");

        String facetString = "";// temp string as we do not know whether there are any facet values 

        for (Entry<URI, Set<Value>> facetEntry : facets.entrySet()) {
            URI predicate = facetEntry.getKey();
            if (predicate.equals(Vocabulary.DBPEDIA_ONT.THUMBNAIL))
                continue;

            String name = dm.getLabel(predicate);
            if (name.equals("name"))
                continue;
            Set<Value> facetValues = facetEntry.getValue();

            String values = "";
            String exploreValues = "";

            int facetValueCounter = 0;
            for (Value value : facetValues) {
                if (value == null)
                    continue;
                if (facetValueCounter++ > 1000)
                    break; //TODO: temp hack to prevent scalability problems, improve logic
                label = cleanLabel(dm.getLabel(value));

                if (label.equals(""))
                    continue;
                String href = EndpointImpl.api().getRequestMapper().getRequestStringFromValue(value);

                if ((value instanceof Literal) && !Config.getConfig().getLinkLiterals()) {
                    href = "#";
                }

                if (label.toLowerCase().startsWith("category:")) {
                    label = label.substring(9);
                }

                URI range = predicateTypes.get(predicate);
                if (range == null)
                    values += "<String Value=\"" + label + "\"/>";
                else if (range.equals(XMLSchema.FLOAT) || range.equals(XMLSchema.DOUBLE)
                        || range.equals(XMLSchema.INT) || range.equals(XMLSchema.INTEGER)
                        || range.equals(XMLSchema.LONG)) {

                    try {
                        // Need to be compliant with xsd:decimal
                        values += "<Number Value=\""
                                + (new BigDecimal(Double.parseDouble(label))).toPlainString() + "\"/>";
                    } catch (Exception e) {
                        logger.warn("Parsing problem with: " + label);
                    }
                } else if (range.equals(XMLSchema.DATETIME) || range.equals(XMLSchema.DATE)) {

                    Date date = null;
                    // Loop over supported date formats
                    for (DateFormat formatter : formatters) {
                        try {
                            date = (Date) formatter.parse(label);
                            break;
                        }
                        // If date format is not supported..
                        catch (ParseException e) {
                            logger.debug("Date format not supported: " + label + ". Using today instead.");
                        }
                    }
                    if (date != null) {
                        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                        values += "<DateTime Value=\"" + format.format(date) + "\"/>";
                    }
                } else
                    values += "<String Value=\"" + label + "\"/>";
                exploreValues += "<Link Href=\"" + href + "\" Name=\"" + label + "\"/>";

            }
            name = escape(name).trim();
            //                values = values.replace("]", "");
            if (values.length() > 0 && displayedFacets.contains(predicate))
                facetString += "<Facet Name=\"" + XML.escape(name) + "\">" + values + "</Facet>";
            if (exploreValues.length() > 0 && displayedFacets.contains(predicate))
                facetString += "<Facet Name=\"" + XML.escape(name) + ":\">" + exploreValues + "</Facet>";

        }

        /*  
        //Query for related elements, currently not used 
        String href = "CONSTRUCT { ?uri <http://dbpedia.org/ontology/thumbnail> ?img . ?uri ?p ?o . } WHERE {  { ?uri ?relationship  <"+uri.stringValue()+"> } UNION {  <"+uri.stringValue()+"> ?relationship  ?uri  }  . ?uri <http://dbpedia.org/ontology/thumbnail> ?img . ?uri ?p ?o }";
                
        try
        {
        href=URLEncoder.encode(href, "UTF-8");
        }
        catch (UnsupportedEncodingException e)
        {
        logger.error(e.getMessage(), e);
        }
        facetString+="<Facet Name=\"Related\"><Link Href=\"query.cxml?q="+href+"\" Name=\"Explore Related\"/></Facet>";
         */

        if (!facetString.isEmpty())
            out.println("<Facets>" + facetString + "</Facets>");
        out.println("</Item>");
        counter++;
    }

    if (counter == 0) {
        // should show some image indicating that nothing has been found, for now we just show a text
        out.println("<Item Img=\"#0\" Id=\"0\" Name=\"Nothing found\">");
        out.println("</Item>");

        URI uri = ValueFactoryImpl.getInstance().createURI("http://www.fluidops.com/Nothing Found");
        // id: indicates that ID card should be generated
        String img = "id:" + uri.stringValue() + ".jpg";

        String filename = ImageLoader.filename(img);

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

        loader.createImageThreaded(uri, facets, img, collection);
        imageVector.add(img);
        int imgID = 0;
        collectionWriter.write("<I Id=\"" + imgID + "\" N=\"" + imgID + "\" Source=\"dzimages/"
                + ImageLoader.subdir(filename) + "/"
                + ((filename.lastIndexOf(".") > -1) ? filename.substring(0, filename.lastIndexOf("."))
                        : filename)
                + ".xml\">" + "<Size Width=\"" + d.width + "\" Height=\"" + d.height + "\"/></I>");

    }

    try {
        writeImageListToFile("imageCache", hash(q), imageVector);
    } catch (IOException e) {
        logger.warn(e.getMessage(), e);
    }

    // We wait until all image loading threads have finished, but at most one minute
    long wait = 0;
    while (loader.threadCounter > 0 && wait < 60000) {
        try {
            Thread.sleep(10);
            wait += 10;
        } catch (InterruptedException e1) {
            logger.debug(e1.toString());
        }
    }

    collectionWriter.write("</Items>\n</Collection>");
    collectionWriter.close();

    out.println("</Items>");
    out.println("</Collection>");
    out.close();

}

From source file:org.trianacode.taskgraph.util.FileUtils.java

/**
 * This function splits up the CLASSPATH and the TOOLBOXES environment variables into the various specified paths. A
 * Vector is returned containing the paths found.  We also take into account that paths can be internet address also
 * by including an internet address in the following form in your environment variables :- </p>
 * <p/>/*from ww w  .j  ava 2 s .c  om*/
 * <center> protocol://server/directory<br> for example<br> http://www.astro.cf.ac.uk/pub/Ian.Taylor/Triana/Release/classes<br>
 * </center>
 */
public static Vector splitPath(String path) {
    if (path == null) {
        return null;
    }

    Vector paths = new Vector(10);
    // 10's quite a lot, should be OK

    String separator = System.getProperty("path.separator");

    String newpath;
    URL urlPath;

    // get rid of colons as they are confusing as they act
    // as path separators as well. Put the http and ftp etc in just
    // in case some accidentally put // in as a local directory after
    // a deliminator e.g. path://usr/local/path

    path.replace("http://", "http+//");
    path.replace("ftp://", "ftp+//");
    path.replace("file://", "file+//");

    StringTokenizer st = new StringTokenizer(correctURL(path), separator);

    while (st.hasMoreTokens()) {
        newpath = st.nextToken();

        int aNetwork = newpath.indexOf("+");

        if (aNetwork != -1) { // an internet directory
            if ((!newpath.endsWith("/")) && (!newpath.endsWith(".tbx")) && (!newpath.endsWith(".html"))) {
                newpath = newpath + "/";
            }
            path.replace("+", ":"); // swap +'s with :'s
            try {
                urlPath = new URL(newpath);
                paths.addElement(urlPath);
            } catch (MalformedURLException me) {
                System.err.println("Network Path " + newpath + " NOT FOUND!");
            }
        } else { // local directory or zipfile
            ZipFile z = null;
            if (newpath.indexOf(".zip") != -1) { // a zip file
                try {
                    if (newpath != null) {
                        z = new ZipFile(newpath);
                    }
                    if (z != null) {
                        if (!paths.contains(z)) {
                            paths.addElement(z);
                        }
                    }
                } catch (IOException io) {
                    // System.out.println(newpath + " not a zipfile!");
                }
            } else {
                if ((!newpath.endsWith(File.separator)) && (!newpath.endsWith(".tbx"))
                        && (!newpath.endsWith(".html"))) {
                    newpath = newpath + File.separator;
                }
                paths.addElement(newpath);
            }
        }
    }

    return paths;
}

From source file:oscar.oscarRx.util.RxUtil.java

public static String findInterDrugStr(final UserPropertyDAO propDAO, String provider,
        final RxSessionBean bean) {
    //quiry mydrugref database to get a vector with all interacting drugs
    //if effect is not null or effect is not empty string
    //get a list of all pending prescriptions' ATC codes
    //compare if anyone match,
    //if yes, get it's randomId and set an session attribute
    //if not, do nothing

    UserProperty prop = propDAO.getProp(provider, UserProperty.MYDRUGREF_ID);
    String myDrugrefId = null;//  w w w  . j  av  a  2 s  .c  o  m
    if (prop != null) {
        myDrugrefId = prop.getValue();
        MiscUtils.getLogger().debug("3myDrugrefId" + myDrugrefId);
    }
    RxPrescriptionData.Prescription[] rxs = bean.getStash();
    //acd contains all atccodes in stash
    Vector<String> acd = new Vector<String>();
    for (RxPrescriptionData.Prescription rxItem : rxs) {
        acd.add(rxItem.getAtcCode());
    }
    logger.debug("3acd=" + acd);

    String[] str = new String[] { "warnings_byATC,bulletins_byATC,interactions_byATC,get_guidelines" }; //NEW more efficent way of sending multiple requests at the same time.
    Vector allInteractions = new Vector();
    for (String command : str) {
        try {
            Vector v = getMyDrugrefInfo(command, acd, myDrugrefId);
            MiscUtils.getLogger().debug("2v in for loop: " + v);
            if (v != null && v.size() > 0) {
                allInteractions.addAll(v);
            }
            MiscUtils.getLogger().debug("3after all.addAll(v): " + allInteractions);
        } catch (Exception e) {
            log2.debug("3command :" + command + " " + e.getMessage());
            MiscUtils.getLogger().error("Error", e);
        }
    }
    String retStr = "";
    HashMap rethm = new HashMap();
    for (RxPrescriptionData.Prescription rxItem : rxs) {
        MiscUtils.getLogger().debug("rxItem=" + rxItem.getDrugName());
        Vector uniqueDrugNameList = new Vector();
        for (int i = 0; i < allInteractions.size(); i++) {
            Hashtable hb = (Hashtable) allInteractions.get(i);
            String interactingAtc = (String) hb.get("atc");
            String interactingDrugName = (String) hb.get("drug2");
            String effectStr = (String) hb.get("effect");
            String sigStr = (String) hb.get("significance");
            MiscUtils.getLogger().debug("findInterDrugStr=" + hb);
            if (sigStr != null) {
                if (sigStr.equals("1")) {
                    sigStr = "minor";
                } else if (sigStr.equals("2")) {
                    sigStr = "moderate";
                } else if (sigStr.equals("3")) {
                    sigStr = "major";
                } else {
                    sigStr = "unknown";
                }
            } else {
                sigStr = "unknown";
            }
            if (interactingAtc != null && interactingDrugName != null
                    && rxItem.getAtcCode().equals(interactingAtc) && effectStr != null && effectStr.length() > 0
                    && !effectStr.equalsIgnoreCase("N") && !effectStr.equals(" ")) {
                MiscUtils.getLogger().debug("interactingDrugName=" + interactingDrugName);
                RxPrescriptionData.Prescription rrx = findRxFromDrugNameOrGN(rxs, interactingDrugName);

                if (rrx != null && !uniqueDrugNameList.contains(rrx.getDrugName())) {
                    MiscUtils.getLogger().debug("rrx.getDrugName()=" + rrx.getDrugName());
                    uniqueDrugNameList.add(rrx.getDrugName());

                    String key = sigStr + "_" + rxItem.getRandomId();

                    if (rethm.containsKey(key)) {
                        String val = (String) rethm.get(key);
                        val += ";" + rrx.getDrugName();
                        rethm.put(key, val);
                    } else {
                        rethm.put(key, rrx.getDrugName());
                    }

                    key = sigStr + "_" + rrx.getRandomId();
                    if (rethm.containsKey(key)) {
                        String val = (String) rethm.get(key);
                        val += ";" + rxItem.getDrugName();
                        rethm.put(key, val);
                    } else {
                        rethm.put(key, rxItem.getDrugName());
                    }
                }
            }
        }
        MiscUtils.getLogger().debug("***next rxItem***");
    }
    MiscUtils.getLogger().debug("rethm=" + rethm);
    retStr = rethm.toString();
    retStr = retStr.replace("}", "");
    retStr = retStr.replace("{", "");

    return retStr;
}

From source file:net.sf.l2j.gameserver.model.entity.L2JOneoRusEvents.CTF.java

public static void CheckRestoreFlags() {
    Vector<Integer> teamsTakenFlag = new Vector<Integer>();
    try {/*from w  w  w .  j  ava2s.c  om*/
        for (L2PcInstance player : _players) { // if there's a player with a flag
                                               // add the index of the team who's FLAG WAS TAKEN to the list
            if (player != null) {
                if (player.isOnline() == 0 && player._haveFlagCTF) { // logged off with a flag in his hands
                    Announcements(_eventName + "(CTF): " + player.getName() + " logged off with a CTF flag!");
                    player._haveFlagCTF = false;
                    if (_teams.indexOf(player._teamNameHaveFlagCTF) >= 0)
                        if (_flagsTaken.get(_teams.indexOf(player._teamNameHaveFlagCTF))) {
                            _flagsTaken.set(_teams.indexOf(player._teamNameHaveFlagCTF), false);
                            spawnFlag(player._teamNameHaveFlagCTF);
                            Announcements(_eventName + "(CTF): " + player._teamNameHaveFlagCTF
                                    + " flag now returned to place.");
                        }
                    removeFlagFromPlayer(player);
                    player._teamNameHaveFlagCTF = null;
                    return;
                } else if (player._haveFlagCTF)
                    teamsTakenFlag.add(_teams.indexOf(player._teamNameHaveFlagCTF));
            }
        }
        // Go over the list of ALL teams
        for (String team : _teams) {
            if (team == null)
                continue;
            int index = _teams.indexOf(team);
            if (!teamsTakenFlag.contains(index)) {
                if (_flagsTaken.get(index)) {
                    _flagsTaken.set(index, false);
                    spawnFlag(team);
                    Announcements(_eventName + "(CTF): " + team + " flag returned due to player error.");
                }
            }
        }
        // Check if a player ran away from the event holding a flag:
        for (L2PcInstance player : _players)
            if (player != null && player._haveFlagCTF) {
                if (isOutsideCTFArea(player)) {
                    Announcements(_eventName + "(CTF): " + player.getName()
                            + " escaped from the event holding a flag!");
                    player._haveFlagCTF = false;
                    if (_teams.indexOf(player._teamNameHaveFlagCTF) >= 0)
                        if (_flagsTaken.get(_teams.indexOf(player._teamNameHaveFlagCTF))) {
                            _flagsTaken.set(_teams.indexOf(player._teamNameHaveFlagCTF), false);
                            spawnFlag(player._teamNameHaveFlagCTF);
                            Announcements(_eventName + "(CTF): " + player._teamNameHaveFlagCTF
                                    + " flag now returned to place.");
                        }
                    removeFlagFromPlayer(player);
                    player._teamNameHaveFlagCTF = null;
                    player.teleToLocation(_teamsX.get(_teams.indexOf(player._teamNameCTF)),
                            _teamsY.get(_teams.indexOf(player._teamNameCTF)),
                            _teamsZ.get(_teams.indexOf(player._teamNameCTF)));
                    player.sendMessage("You have been returned to your team spawn");
                    return;
                }
            }
    } catch (Exception e) {
        _log.info("CTF.restoreFlags() Error:" + e.toString());
        return;
    }
}

From source file:org.geworkbench.engine.ccm.ComponentConfigurationManager.java

/**
 * Removes the component with resourceName.
 * /*  w  ww . j a v  a  2s  .  c  o  m*/
 * @param folderName
 * @param ccmFileName
 * @return Returns false if component was not successfully removed, else
 *         true.
 */
@SuppressWarnings("unchecked")
public boolean removeComponent(String folderName, String filename) {

    /*
     * Container Summary:
     * 
     * ComponentRegistry Section listeners = new TypeMap<List>(); 
     * acceptors = new HashMap<Class, List<Class>>(); 
     * synchModels = new HashMap<Class, SynchModel>(); 
     * components = new ArrayList(); 
     * idToDescriptor = new HashMap<String, PluginDescriptor>(); 
     * nameToComponentResource = new HashMap<String, ComponentResource>();
     */

    ComponentRegistry componentRegistry = ComponentRegistry.getRegistry();

    /* validation */
    if (StringUtils.isEmpty(folderName)) {
        log.error("Input resource is null.  Returning ...");
        return false;
    }

    List<String> list = Arrays.asList(files);
    if (!list.contains(folderName)) {
        return false;
    }

    // FIXME why parse again? can't we get this info another way?
    /* parse the ccm.xml file */
    PluginComponent ccmComponent = null;
    if (filename.endsWith(COMPONENT_DESCRIPTOR_EXTENSION)) {
        ccmComponent = getPluginsFromFile(new File(filename));
    } else {
        return false;
    }

    if (ccmComponent == null)
        return false;

    /* GET THE VARIOUS MAPS/VECTORS FROM THE PLUGIN REGISTRY */

    /* plugin registry component vector */
    Vector<PluginDescriptor> componentVector = PluginRegistry.getComponentVector();

    /* plugin registry visual area map */
    HashMap<PluginDescriptor, String> visualAreaMap = PluginRegistry.getVisualAreaMap();

    /* plugin registry used ids */
    Vector<String> usedIds = PluginRegistry.getUsedIds();

    // FIXME Can't we get the PluginDesriptor we want other than from the
    // ccm.xml file?
    // beginning of processing the plugin
    final String pluginClazzName = ccmComponent.getClazz();
    PluginDescriptor pluginDescriptor = PluginRegistry.getPluginDescriptor(ccmComponent.getPluginId());

    if (pluginDescriptor != null) {

        /* START THE REMOVAL PROCESS IN THE PLUGIN REGISTRY */
        /* PluginRegistry.visualAreaMap */
        for (Entry<PluginDescriptor, String> entry : visualAreaMap.entrySet()) {
            Object pluginDescriptor1 = entry.getKey();
            Class<?> clazz = pluginDescriptor1.getClass();
            String proxiedClazzName = clazz.getName();

            // TODO Replace $$ parse methods with clazzName = clazz.getSuperclass() 
            String[] temp = StringUtils.split(proxiedClazzName, "$$");
            String clazzName = temp[0];

            if (StringUtils.equals(pluginClazzName, clazzName)) {
                visualAreaMap.remove(entry.getKey());
                break;
            }
        }

        /* PluginRegistry.visualAreaMap */
        String id = ccmComponent.getPluginId();
        if (PluginDescriptor.idExists(id)) {
            usedIds.remove(id);
        }

        /* PluginRegistry.compontentVector */
        if (componentVector.contains(pluginDescriptor)) {
            componentVector.remove(pluginDescriptor);
        }

        /* START THE REMOVAL PROCESS IN THE COMPONENT REGISTRY */

        componentRegistry.removeComponent(pluginClazzName);
        componentRegistry.removePlugin(ccmComponent.getPluginId());

    } // end of processing the plugin

    /* ComponentRegistry.idToDescriptor */
    /* If other Plugins are using the same Component Resource, don't remove the Resource */
    int foldersInUse = 0;
    for (int i = 0; i < componentVector.size(); i++) {
        PluginDescriptor pd = componentVector.get(i);
        if (pd == null) {
            continue;
        }

        ComponentResource componentResource = pd.getResource();
        if (componentResource == null) {
            continue;
        }

        String name = componentResource.getName();
        if (name == null) {
            continue;
        }

        if (name.equalsIgnoreCase(folderName)) {
            foldersInUse++;
        }
    }

    if (foldersInUse < 1) {
        componentRegistry.removeComponentResource(folderName);
    }

    return true;
}

From source file:imapi.OnlineDatabaseActions.java

int getUris(String query, Vector<String> mergeVals) {

    InputStream answerStream = performDatabaseQuery(query);
    if (answerStream == null) {
        return ApiConstants.IMAPIFailCode;
    }/*  ww w. ja  va2s  . c  om*/

    Vector<String> tempVec = new Vector<String>();
    int ret = this.readJsonUriVals(answerStream, tempVec);

    if (ret != ApiConstants.IMAPISuccessCode) {
        return ret;
    }

    for (int i = 0; i < tempVec.size(); i++) {
        String val = tempVec.get(i);
        if (mergeVals.contains(val) == false) {
            mergeVals.add(val);
        }
    }

    return ApiConstants.IMAPISuccessCode;
}

From source file:org.codehaus.mojo.webstart.JnlpMojo.java

protected void removeSignatures(File currentJar, String shortName) throws IOException {
    // We should remove any previous signature information.  This
    // can screw up the packing code, and if it is signed with 2 signatures
    // it can not be verified.
    ZipFile currentJarZipFile = new ZipFile(currentJar);
    Enumeration entries = currentJarZipFile.entries();

    // There might be more valid extensions but this is what we've seen so far 
    // the ?i makes it case insensitive       
    Pattern signatureChecker = Pattern.compile("(?i)^meta-inf/.*((\\.sf)|(\\.rsa))$");

    getLog().debug("checking for old signature : " + shortName);
    Vector signatureFiles = new Vector();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        Matcher matcher = signatureChecker.matcher(entry.getName());
        if (matcher.find()) {
            // we found a old signature in the file
            signatureFiles.add(entry.getName());
            getLog().warn("found signature: " + entry.getName());
        }//  w w  w.jav  a 2s .  co  m
    }

    if (signatureFiles.size() == 0) {
        // no old files were found
        currentJarZipFile.close();
        return;
    }

    // We found some old signature files, write out the file again without
    // them    
    File outFile = new File(currentJar.getParent(), currentJar.getName() + ".unsigned");
    ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(outFile));

    entries = currentJarZipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        if (signatureFiles.contains(entry.getName())) {
            continue;
        }
        InputStream entryInStream = currentJarZipFile.getInputStream(entry);
        ZipEntry newEntry = new ZipEntry(entry);
        zipOutStream.putNextEntry(newEntry);
        IOUtil.copy(entryInStream, zipOutStream);
        entryInStream.close();
    }

    zipOutStream.close();
    currentJarZipFile.close();

    FileUtils.rename(outFile, currentJar);

    getLog().info("removed signature");
}

From source file:hu.sztaki.lpds.pgportal.services.asm.ASMService.java

/**
 * //from  w  w w .j a  v a 2  s .  c  om
 * Gets list of the users who have exported anything to the repository
 * 
 * @param type
 *            - type of the exported workflow
 * @return - vector of userIds - Developers of Workflows that have already exported to the local repository
 * @throws Exception
 */

public synchronized Vector<String> getWorkflowDevelopers(String type) throws Exception {
    // get repository workflow item list from wfs...
    Hashtable hsh = new Hashtable();

    ServiceType st = InformationBase.getI().getService("wfs", "portal", hsh, new Vector());
    PortalWfsClient wfsClient = (PortalWfsClient) Class.forName(st.getClientObject()).newInstance();
    wfsClient.setServiceURL(st.getServiceUrl());
    wfsClient.setServiceID(st.getServiceID());

    RepositoryWorkflowBean bean = new RepositoryWorkflowBean();
    Long id = new Long(0);
    bean.setId(id);

    bean.setWorkflowType(type);
    //
    Vector<RepositoryWorkflowBean> wfList = wfsClient.getRepositoryItems(bean);
    if (wfList == null) {
        throw new ASM_UnknownErrorException();

    }

    Vector<String> owners = new Vector<String>();
    for (int i = 0; i < wfList.size(); ++i) {
        String userId = wfList.get(i).getUserID();

        if (!owners.contains(new String(userId)))
            owners.add(userId);
    }

    return owners;
}

From source file:org.apache.axis.wsdl.toJava.JavaGeneratorFactory.java

/**
 * If a binding's type is not TYPE_SOAP, then we don't use that binding
 * or that binding's portType.//  w w  w. ja  v a2s  .  c  o m
 *
 * @param symbolTable
 */
protected void ignoreNonSOAPBindings(SymbolTable symbolTable) {

    // Look at all uses of the portTypes.  If none of the portType's bindings are of type
    // TYPE_SOAP, then turn off that portType's isReferenced flag.
    Vector unusedPortTypes = new Vector();
    Vector usedPortTypes = new Vector();
    Iterator it = symbolTable.getHashMap().values().iterator();

    while (it.hasNext()) {
        Vector v = (Vector) it.next();

        for (int i = 0; i < v.size(); ++i) {
            SymTabEntry entry = (SymTabEntry) v.elementAt(i);

            if (entry instanceof BindingEntry) {
                BindingEntry bEntry = (BindingEntry) entry;
                Binding binding = bEntry.getBinding();
                PortType portType = binding.getPortType();
                PortTypeEntry ptEntry = symbolTable.getPortTypeEntry(portType.getQName());

                if (bEntry.getBindingType() == BindingEntry.TYPE_SOAP) {

                    // If a binding is of type TYPE_SOAP, then mark its portType used
                    // (ie., add it to the usedPortTypes list.  If the portType was
                    // previously marked as unused, unmark it (in other words, remove it
                    // from the unusedPortTypes list).
                    usedPortTypes.add(ptEntry);

                    if (unusedPortTypes.contains(ptEntry)) {
                        unusedPortTypes.remove(ptEntry);
                    }
                } else {
                    bEntry.setIsReferenced(false);

                    // If a binding is not of type TYPE_SOAP, then mark its portType as
                    // unused ONLY if it hasn't already been marked as used.
                    if (!usedPortTypes.contains(ptEntry)) {
                        unusedPortTypes.add(ptEntry);
                    }
                }
            }
        }
    }

    // Go through all the portTypes that are marked as unused and set their isReferenced flags
    // to false.
    for (int i = 0; i < unusedPortTypes.size(); ++i) {
        PortTypeEntry ptEntry = (PortTypeEntry) unusedPortTypes.get(i);

        ptEntry.setIsReferenced(false);
    }
}

From source file:org.kepler.kar.KARCacheManager.java

/**
 * Update the KAR cache tables to reflect the kar files on disk.
 * //from  ww w  .j  a va 2 s. c  om
 * @return boolean true if the cache was changed because of the
 *         synchronization.
 */
public boolean synchronizeKARCacheWithLocalRepositories() {
    boolean contentsOnDiskHaveChanged = false;

    LocalRepositoryManager lrm = LocalRepositoryManager.getInstance();
    lrm.scanReposForKarFiles();
    Vector<File> karFiles = lrm.getKarFiles();

    if (isDebugging)
        log.debug("loop through all the kar files and make sure they are in the cache");
    for (int k = 0; k < karFiles.size(); k++) {

        try {
            File f = karFiles.elementAt(k);

            final long time = getLastModifiedTimeOfFileInCache(f.toString());

            // see if the last modified time is different than the time
            // when added to the cache
            if (time != f.lastModified()) {

                // they are different, so update the cache.

                // see if the file was previously cached
                if (time > 0) {
                    log.debug(f + " has a different modified time than in cache; will update cache.");
                    // remove previous version
                    removeKARFromCache(f);
                } else {
                    log.debug(f + " is not in cache.");
                }

                KARFile kFile = new KARFile(f);
                // This KAR is not cached, go ahead and cache it
                boolean allDependenciesSatisfied = kFile.areAllModuleDependenciesSatisfied();
                if (allDependenciesSatisfied) {
                    kFile.cacheKARContents();
                } else {
                    insertKARError(kFile);
                }
                contentsOnDiskHaveChanged = true;
            }
        } catch (Exception e) {
            log.warn("Unable to process kar file \"" + karFiles.elementAt(k).toString() + "\".", e);
        }
    }

    if (isDebugging)
        log.debug("loop through the cache and make sure there are matching KAR files");
    try {

        ResultSet rs = _allKarsInCache.executeQuery();
        if (rs != null) {
            while (rs.next()) {
                String cachedFileStr = rs.getString(1);
                File cachedKar = new File(cachedFileStr);
                if (!karFiles.contains(cachedKar)) {
                    removeKARFromCache(cachedKar);
                    contentsOnDiskHaveChanged = true;
                }
            }
            rs.close();
        }
    } catch (Exception sqle) {
        sqle.printStackTrace();
    }

    // free up the kar files
    karFiles = null;

    if (contentsOnDiskHaveChanged) {
        log.info("The Cache was out of sync with KAR files in Local Repositories.");
        log.info("The Cache has been synchronized with KAR files in Local Repositories.");
    } else {
        log.info("The Cache is in sync with KAR files in Local Repositories.");
    }
    return contentsOnDiskHaveChanged;
}