Example usage for java.util Vector elements

List of usage examples for java.util Vector elements

Introduction

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

Prototype

public Enumeration<E> elements() 

Source Link

Document

Returns an enumeration of the components of this vector.

Usage

From source file:org.accada.reader.rprm.core.Source.java

/**
 * Performs multiple read cycles using all TagSelectors currently associated
 * with this Source. The number of read cycles performed shall be determined
 * by the value of the Source attribute ReadCyclesPerTrigger.The resulting
 * ReadReport is formatted according to the given DataSelector. If a tag is
 * seen in several read cycles, it shall only be reported once. Note that
 * this command does not use event generation.
 * @param dataselector/*from ww  w.  java  2 s. c o  m*/
 *           The data selector to use
 * @return The read report
 */
public ReadReport readIDs(final DataSelector dataselector) {

    DataSelector dataSelector;
    if (dataselector == null) {
        dataSelector = readerDevice.getCurrentDataSelector();
    } else {
        dataSelector = dataselector;
    }

    SourceReport sourceReport = new SourceReport();

    // get all relevant readers with their readpoints
    Vector closure = getReaderAndReadPoints();

    // temp variables
    Observation[] tempObservations;
    Vector allObservations = new Vector();

    // for time check
    Date date = new Date();
    long timeStart = date.getTime();

    // read cycles
    for (int readCycle = 0; readCycle < getReadCyclesPerTrigger(); readCycle++) {

        // closure
        Enumeration closureIterator = closure.elements();
        ReaderAndReadPoints curClosure;
        while (closureIterator.hasMoreElements()) {
            curClosure = (ReaderAndReadPoints) closureIterator.nextElement();

            try {
                tempObservations = curClosure.getReader().identify(curClosure.getAllReadPointsAsArray());
                for (int i = 0; i < tempObservations.length; i++) {
                    Observation observation = tempObservations[i];
                    if (observation.successful) {
                        allObservations.add(tempObservations[i]);
                    } else {
                        ReadPoint readPoint = (ReadPoint) readPoints.get(observation.getReadPointName());
                        if (readPoint instanceof AntennaReadPoint) {
                            ((AntennaReadPoint) readPoint).increaseFailedIdentificationCount();
                        }
                    }
                }
            } catch (HardwareException he) {
                log.error(he.getMessage());
            }

        }

        date = new Date();
        if (date.getTime() - timeStart > getReadTimeout()) {
            break;
        }

    }

    // add tags to read report
    Enumeration observationIterator = allObservations.elements();
    Observation curObservation;
    while (observationIterator.hasMoreElements()) {
        curObservation = (Observation) observationIterator.nextElement();

        // tags
        for (int i = 0; i < curObservation.getIds().length; i++) {
            try {
                if (!sourceReport.containsTag(curObservation.getIds()[i])) {
                    if (isRelevantTag(curObservation.getIds()[i], tagSelectors, closure)) {
                        addTagToReport(curObservation.getIds()[i], sourceReport, dataSelector, closure, null);
                    }
                }
            } catch (Exception e) {
                // TODO: catch the concrete exception and not Exception
                LOG.error(e.getMessage());
            }
        }

    }

    ReadReport readReport = new ReadReport();

    // Complete the report
    addReaderInfo(readReport, dataSelector);
    addSourceInfo(sourceReport, dataSelector);

    readReport.addSourceReport(sourceReport);

    // update read point counter
    updateAntennaReadPointIdentificationCount(allObservations);

    return readReport;

}

From source file:org.accada.reader.rprm.core.Source.java

/**
 * Kills the specified tag or group of tags. An list of TagSelector objects
 * can be specified with this command./*from   www . j  a v a2 s. c  om*/
 * @param passwords
 *           Not yet supported
 * @param tagSelectorList
 *           The tag selectors
 * @throws ReaderProtocolException
 *            "ERROR_MULTIPLE_TAGS", "ERROR_NO_TAG", "ERROR_UNKNOWN"
 */
public void kill(final String[] passwords, final TagSelector[] tagSelectorList) throws ReaderProtocolException {

    // passwords not supported in HardwareAbstraction

    Hashtable tagSelectors;
    if (tagSelectorList == null) {
        tagSelectors = this.tagSelectors;
    } else {
        tagSelectors = new Hashtable();
        for (int i = 0; i < tagSelectorList.length; i++) {
            tagSelectors.put(tagSelectorList[i].getName(), tagSelectorList[i]);
        }
    }

    // get all tags in range
    ReadReport report = rawReadIDs(null);

    if (report.getAllTags().size() >= 1) {
        throw new ReaderProtocolException("ERROR_MULTIPLE_TAGS", MessagingConstants.ERROR_MULTIPLE_TAGS);
    }

    if (report.getAllTags().size() < 1) {
        throw new ReaderProtocolException("ERROR_NO_TAG", MessagingConstants.ERROR_NO_TAG);
    }

    // possible exceptions : TagMemoryServiceException, HardwareException
    try {

        // get relevant readers
        Vector closure = getReaderAndReadPoints();

        // get relevant tags out of the report
        Hashtable tags = getRelevantTags(report, tagSelectors, closure);

        // tags
        Enumeration tagIterator = tags.elements();
        TagType curTag;
        while (tagIterator.hasMoreElements()) {
            curTag = (TagType) tagIterator.nextElement();

            // readers
            Enumeration readerIterator = closure.elements();
            HardwareAbstraction curHardwareAbstraction;
            ReaderAndReadPoints curClosure;
            while (readerIterator.hasMoreElements()) {
                curClosure = (ReaderAndReadPoints) readerIterator.nextElement();
                curHardwareAbstraction = curClosure.getReader();

                try {
                    // Where is the tag?
                    Observation[] observations = curHardwareAbstraction
                            .identify(curClosure.getAllReadPointsAsArray());
                    String readPointName = null;
                    for (int i = 0; i < observations.length; i++) {
                        if (observations[i].containsId(curTag.getId()))
                            readPointName = observations[i].getReadPointName();
                        break;
                    }

                    // Kill
                    curHardwareAbstraction.kill(readPointName, curTag.getId(), passwords);

                    // Increase the counter
                    if (readPointName != null) {
                        increaseAntennaReadPointKillCount(readPointName);
                    }
                } catch (HardwareException he) {
                    ReadPoint readPoint = (ReadPoint) readPoints.get(he.getMessage());
                    if ((readPoint != null) && (readPoint instanceof AntennaReadPoint)) {
                        ((AntennaReadPoint) readPoint).killFailureOccurred();
                    }
                    /*
                    ReadPoint readPoint = (ReadPoint) readPoints.get(he.getReadPointName());
                    if (readPoint instanceof AntennaReadPoint) {
                       ((AntennaReadPoint) readPoint).killFailureOccurred();
                    }
                    int errorCode = he.getReaderProtocolErrorCode();
                    switch(errorCode) {
                        case MessagingConstants.ERROR_MULTIPLE_TAGS:
                           throw new ReaderProtocolException("ERROR_MULTIPLE_TAGS", errorCode);
                        case MessagingConstants.ERROR_NO_TAG:
                           throw new ReaderProtocolException("ERROR_NO_TAG", errorCode);
                    }*/
                    throw new ReaderProtocolException("ERROR_UNKNOWN", MessagingConstants.ERROR_UNKNOWN);
                }

            }

        }

    } catch (Exception e) {
        throw new ReaderProtocolException("ERROR_UNKNOWN", MessagingConstants.ERROR_UNKNOWN);
    }

}

From source file:org.accada.reader.rprm.core.Source.java

/**
 * Writes the specified TagFieldValues to one or more tags. A list of
 * TagSelector objects can be used to select a set of tags, in the readers
 * field of view, for writing.//from w  ww  . j  av  a  2s  .  co  m
 * @param tagFieldValueList
 *           The date to write on the tag
 * @param passwords
 *           An optional list of one or more passwords (or lock code). The
 *          use of passwords is dependent upon the tag's RF protocol
 * @param tagSelectorList
 *           The tag selectors
 * @throws ReaderProtocolException
 *            "ERROR_UNKNOWN"
 */
public void write(TagFieldValue[] tagFieldValueList, final String[] passwords,
        final TagSelector[] tagSelectorList) throws ReaderProtocolException {

    Hashtable tagSelectors;
    if (tagSelectorList == null) {
        tagSelectors = this.tagSelectors;
    } else {
        tagSelectors = new Hashtable();
        for (int i = 0; i < tagSelectorList.length; i++) {
            tagSelectors.put(tagSelectorList[i].getName(), tagSelectorList[i]);
        }
    }

    Hashtable tagFieldValues = new Hashtable();
    for (int i = 0; i < tagFieldValueList.length; i++) {
        tagFieldValues.put(tagFieldValueList[i].getTagField().getName(), tagFieldValueList[i]);
    }

    // get all tags in range
    ReadReport report = rawReadIDs(null);

    // possible exceptions : TagMemoryServiceException, HardwareException
    try {

        // get relevant readers and their readpoints
        Vector closure = getReaderAndReadPoints();

        // get relevant tags out of the report
        Hashtable tags = getRelevantTags(report, tagSelectors, closure);

        // tags
        Enumeration tagIterator = tags.elements();
        TagType curTag;
        while (tagIterator.hasMoreElements()) {
            curTag = (TagType) tagIterator.nextElement();

            // closure
            Enumeration closureIterator = closure.elements();
            ReaderAndReadPoints curClosure;
            while (closureIterator.hasMoreElements()) {
                curClosure = (ReaderAndReadPoints) closureIterator.nextElement();

                HardwareAbstraction reader = curClosure.getReader();
                String[] readPointNames = curClosure.getAllReadPointsAsArray();
                for (int i = 0; i < readPointNames.length; i++) {
                    Enumeration tagFieldIterator = tagFieldValues.elements();
                    TagFieldValue curTagFieldValue;
                    while (tagFieldIterator.hasMoreElements()) {
                        curTagFieldValue = (TagFieldValue) tagFieldIterator.nextElement();
                        try {
                            // assemble byte array to write
                            String readPointName = readPointNames[i];
                            String id = curTag.getId();
                            int memoryBank = curTagFieldValue.getTagField().getMemoryBank();
                            int offset = curTagFieldValue.getTagField().getOffset();
                            int length = curTagFieldValue.getTagField().getLength();
                            byte[] data = HexUtil.hexToByteArray(curTagFieldValue.getValue());
                            int byteoffset = offset / 8;
                            int bytelength = ((offset % 8) + length + 7) / 8;
                            int shift = (8 - ((offset + length) % 8)) % 8;
                            byte first;
                            if ((offset % 8) == 0) {
                                first = 0x00;
                            } else {
                                first = reader
                                        .readBytes(readPointName, id, memoryBank, byteoffset, 1, passwords)
                                        .toByteArray()[0];
                            }
                            byte last;
                            if (shift == 0) {
                                last = 0x00;
                            } else if (bytelength == 1) {
                                last = first;
                            } else {
                                last = reader.readBytes(readPointName, id, memoryBank,
                                        (byteoffset + bytelength - 1), 1, passwords).toByteArray()[0];
                            }
                            byte[] bytes = HexUtil.bitarrayShiftAndFill(data, length, shift, first, last);
                            reader.writeBytes(readPointName, id, memoryBank, byteoffset,
                                    new UnsignedByteArray(bytes), passwords);
                            increaseAntennaReadPointWriteCount(readPointNames[i]);
                        } catch (HardwareException he) {
                            ReadPoint readPoint = (ReadPoint) readPoints.get(readPointNames[i]);
                            if (readPoint instanceof AntennaReadPoint) {
                                ((AntennaReadPoint) readPoint).writeFailureOccurred();
                            }
                        }
                    }
                }

            }

        }

    } catch (Exception e) {
        throw new ReaderProtocolException("ERROR_UNKNOWN", MessagingConstants.ERROR_UNKNOWN);
    }

}

From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java

/**
 * PROPFIND Method.//  w  ww. j  a v a2 s . c  o  m
 *
 * @param context Description of the Parameter
 * @throws javax.servlet.ServletException Description of the Exception
 * @throws java.io.IOException            Description of the Exception
 */
protected void doPropfind(ActionContext context) throws ServletException, IOException {

    String path = getRelativePath(context.getRequest());
    //fix for windows clients
    if (path.equals("/files")) {
        path = "";
    }

    if (path.endsWith("/")) {
        path = path.substring(0, path.length() - 1);
    }

    if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) {
        context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    // Properties which are to be displayed.
    Vector properties = null;
    // Propfind depth
    int depth = INFINITY;
    // Propfind type
    int type = FIND_ALL_PROP;

    String depthStr = context.getRequest().getHeader("Depth");
    if (depthStr == null) {
        depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            depth = 0;
        } else if (depthStr.equals("1")) {
            depth = 1;
        } else if (depthStr.equals("infinity")) {
            depth = INFINITY;
        }
    }

    /*
     *  Read the request xml and determine all the properties
     */

    /*
    Node propNode = null;
    DocumentBuilder documentBuilder = getDocumentBuilder();
    try {
      Document document = documentBuilder.parse
          (new InputSource(context.getRequest().getInputStream()));
      // Get the root element of the document
      Element rootElement = document.getDocumentElement();
      NodeList childList = rootElement.getChildNodes();
      for (int i = 0; i < childList.getLength(); i++) {
        Node currentNode = childList.item(i);
        switch (currentNode.getNodeType()) {
          case Node.TEXT_NODE:
    break;
          case Node.ELEMENT_NODE:
    if (currentNode.getNodeName().endsWith("prop")) {
      type = FIND_BY_PROPERTY;
      propNode = currentNode;
    }
    if (currentNode.getNodeName().endsWith("propname")) {
      type = FIND_PROPERTY_NAMES;
    }
    if (currentNode.getNodeName().endsWith("allprop")) {
      type = FIND_ALL_PROP;
    }
    break;
        }
      }
    } catch (Exception e) {
      // Most likely there was no content : we use the defaults.
      // TODO : Enhance that !
      e.printStackTrace(System.out);
    }
            
    if (type == FIND_BY_PROPERTY) {
      properties = new Vector();
      NodeList childList = propNode.getChildNodes();
      for (int i = 0; i < childList.getLength(); i++) {
        Node currentNode = childList.item(i);
        switch (currentNode.getNodeType()) {
          case Node.TEXT_NODE:
    break;
          case Node.ELEMENT_NODE:
    String nodeName = currentNode.getNodeName();
    String propertyName = null;
    if (nodeName.indexOf(':') != -1) {
      propertyName = nodeName.substring
          (nodeName.indexOf(':') + 1);
    } else {
      propertyName = nodeName;
    }
    // href is a live property which is handled differently
    properties.addElement(propertyName);
    break;
        }
      }
    }
    */
    // Properties have been determined
    // Retrieve the resources

    Connection db = null;
    boolean exists = true;
    boolean status = true;
    Object object = null;
    ModuleContext resources = null;
    StringBuffer xmlsb = new StringBuffer();
    try {
        db = this.getConnection(context);
        resources = getCFSResources(db, context);
        if (resources == null) {
            context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        object = resources.lookup(db, path);
    } catch (NamingException e) {
        //e.printStackTrace(System.out);
        exists = false;
        int slash = path.lastIndexOf('/');
        if (slash != -1) {
            String parentPath = path.substring(0, slash);
            Vector currentLockNullResources = (Vector) lockNullResources.get(parentPath);
            if (currentLockNullResources != null) {
                Enumeration lockNullResourcesList = currentLockNullResources.elements();
                while (lockNullResourcesList.hasMoreElements()) {
                    String lockNullPath = (String) lockNullResourcesList.nextElement();
                    if (lockNullPath.equals(path)) {
                        context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS);
                        context.getResponse().setContentType("text/xml; charset=UTF-8");
                        // Create multistatus object
                        XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter());
                        generatedXML.writeXMLHeader();
                        generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(),
                                XMLWriter.OPENING);
                        parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type,
                                properties);
                        generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
                        generatedXML.sendData();
                        //e.printStackTrace(System.out);
                        return;
                    }
                }
            }
        }
    } catch (SQLException e) {
        e.printStackTrace(System.out);
        context.getResponse().sendError(SQLERROR, e.getMessage());
        status = false;
    } finally {
        this.freeConnection(db, context);
    }

    if (!status) {
        return;
    }

    if (!exists) {
        context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, path);
        return;
    }

    context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS);
    context.getResponse().setContentType("text/xml; charset=UTF-8");
    // Create multistatus object
    ////System.out.println("Creating Multistatus Object");

    XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter());
    generatedXML.writeXMLHeader();
    generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    //System.out.println("Depth: " + depth);
    if (depth == 0) {
        parseProperties(context, resources, generatedXML, path, type, properties);
    } else {
        // The stack always contains the object of the current level
        Stack stack = new Stack();
        stack.push(path);
        // Stack of the objects one level below
        Stack stackBelow = new Stack();

        while ((!stack.isEmpty()) && (depth >= 0)) {
            String currentPath = (String) stack.pop();
            if (!currentPath.equals(path)) {
                parseProperties(context, resources, generatedXML, currentPath, type, properties);
            }
            try {
                db = this.getConnection(context);
                object = resources.lookup(db, currentPath);
            } catch (NamingException e) {
                continue;
            } catch (SQLException e) {
                //e.printStackTrace(System.out);
                context.getResponse().sendError(SQLERROR, e.getMessage());
                status = false;
            } finally {
                this.freeConnection(db, context);
            }

            if (!status) {
                return;
            }

            if ((object instanceof ModuleContext) && depth > 0) {
                // Get a list of all the resources at the current path and store them
                // in the stack
                try {
                    NamingEnumeration enum1 = resources.list(currentPath);
                    int count = 0;
                    while (enum1.hasMoreElements()) {
                        NameClassPair ncPair = (NameClassPair) enum1.nextElement();
                        String newPath = currentPath;
                        if (!(newPath.endsWith("/"))) {
                            newPath += "/";
                        }
                        newPath += ncPair.getName();
                        stackBelow.push(newPath);
                        count++;
                    }
                    if (currentPath.equals(path) && count == 0) {
                        // This directory does not have any files or folders.
                        parseProperties(context, resources, generatedXML, properties);
                    }
                } catch (NamingException e) {
                    //e.printStackTrace(System.out);
                    context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
                    return;
                }

                // Displaying the lock-null resources present in that collection
                String lockPath = currentPath;
                if (lockPath.endsWith("/")) {
                    lockPath = lockPath.substring(0, lockPath.length() - 1);
                }
                Vector currentLockNullResources = (Vector) lockNullResources.get(lockPath);
                if (currentLockNullResources != null) {
                    Enumeration lockNullResourcesList = currentLockNullResources.elements();
                    while (lockNullResourcesList.hasMoreElements()) {
                        String lockNullPath = (String) lockNullResourcesList.nextElement();
                        System.out.println("Lock null path: " + lockNullPath);
                        parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type,
                                properties);
                    }
                }
            }
            if (stack.isEmpty()) {
                depth--;
                stack = stackBelow;
                stackBelow = new Stack();
            }
            xmlsb.append(generatedXML.toString());
            //System.out.println("xml : " + generatedXML.toString());
            generatedXML.sendData();
        }
    }

    generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
    xmlsb.append(generatedXML.toString());
    generatedXML.sendData();
    //System.out.println("xml: " + xmlsb.toString());
}

From source file:uk.co.maxant.j2me.core.ServerCaller.java

License:asdf

private void handleCookies(HttpConnection connection) throws IOException {
    long now = System.currentTimeMillis() / 1000; //seconds since epoch
    Vector newCookies = new Vector();
    int i = 0;//ww w  .j a va2 s. c o  m
    while (true) {
        String name = connection.getHeaderFieldKey(i);
        if (name == null || i > 1000 /*safety net*/) {
            break;
        } else if (name.toLowerCase().startsWith("set-cookie")) {
            //handle the cookie!
            String val = connection.getHeaderField(i);
            //c2=val2; Domain=domain; Max-Age=0; Path=path; Secure
            StringTokenizer st = new StringTokenizer(val, ";");
            while (st.hasMoreTokens()) {
                Cookie c = new Cookie();
                String token = st.nextToken().trim();
                if (token.toLowerCase().startsWith("domain")) {
                    int idx = token.indexOf('=');
                    if (idx >= 0) {
                        c.domain = token.substring(idx + 1);
                    }
                } else if (token.toLowerCase().startsWith("max-age")) {
                    int idx = token.indexOf('=');
                    if (idx >= 0) {
                        try {
                            c.maxAge = new Long(Long.parseLong(token.substring(idx + 1)));
                        } catch (NumberFormatException e) {
                            //oh well, lets ignore it
                        }
                    }
                } else if (token.toLowerCase().startsWith("path")) {
                    int idx = token.indexOf('=');
                    if (idx >= 0) {
                        try {
                            c.path = token.substring(idx + 1);
                        } catch (NumberFormatException e) {
                            //oh well, lets ignore it
                        }
                    }
                } else if (token.toLowerCase().startsWith("secure")) {
                    c.secure = true;
                } else {
                    //must be the cookie itself
                    int idx = token.indexOf('=');
                    if (idx >= 0) {
                        c.name = token.substring(0, idx);
                        c.value = token.substring(idx + 1);
                        newCookies.addElement(c);
                    }
                }
            }
        }

        i++;
    }

    //ok got them all, now reconcile:
    //update our list by removing expired ones, and adding new ones and updating existing ones!
    Vector toRemove = new Vector();
    Enumeration existing = getCookies().elements();
    while (existing.hasMoreElements()) {
        Cookie cExist = (Cookie) existing.nextElement();
        boolean matched = false;
        Enumeration newOnes = newCookies.elements();
        while (newOnes.hasMoreElements()) {
            Cookie cNew = (Cookie) newOnes.nextElement();
            if (cExist.name.equals(cNew.name)) {
                //matching...
                matched = true;
                if (cNew.maxAge != null && cNew.maxAge.longValue() < now) {
                    //old, remove it
                    toRemove.addElement(cExist);
                } else {
                    //update it
                    cExist.domain = cNew.domain;
                    cExist.maxAge = cNew.maxAge;
                    cExist.path = cNew.path;
                    cExist.value = cNew.value;
                }
                break;
            }
        }
        if (!matched) {
            //just check it aint exipred
            if (cExist.maxAge != null && cExist.maxAge.longValue() < now) {
                toRemove.addElement(cExist);
            }
        }
    }

    Enumeration rs = toRemove.elements();
    while (rs.hasMoreElements()) {
        Cookie remove = (Cookie) rs.nextElement();
        getCookies().removeElement(remove);
    }

    //finally add all which are not already in there
    Enumeration newOnes = newCookies.elements();
    while (newOnes.hasMoreElements()) {
        Cookie cNew = (Cookie) newOnes.nextElement();
        existing = getCookies().elements();
        boolean found = false;
        while (existing.hasMoreElements()) {
            Cookie cExist = (Cookie) existing.nextElement();
            if (cExist.name.equals(cNew.name)) {
                found = true;
                break;
            }
        }
        if (!found) {
            if (cNew.maxAge == null || cNew.maxAge.longValue() > now) {
                //its not expired, and its not in the list, so add it!
                getCookies().addElement(cNew);
            }
        }
    }
}

From source file:org.openflexo.foundation.wkf.FlexoProcess.java

/**
 * Return all OperationNode contained in this process that are associated with a WOComponent
 * /*from  ww w  .j a  va2  s .  co m*/
 * @return a Vector of OperationNode
 */
public Vector<OperationNode> getAllOperationNodesWithComponent() {
    Vector<OperationNode> retval = new Vector<OperationNode>();
    Vector<OperationNode> v = getAllEmbeddedOperationNodes();
    Enumeration<OperationNode> en = v.elements();
    while (en.hasMoreElements()) {
        OperationNode node = en.nextElement();
        if (node.hasWOComponent()) {
            retval.add(node);
        }
    }
    return retval;
}

From source file:org.openflexo.foundation.wkf.FlexoProcess.java

@Override
public final void delete() {
    if (isImported()) {
        isImported = true;// This is important, because it allows to do some
    }//from   w w  w  . ja va  2s .  co m
    // tests on this deleted object
    if (logger.isLoggable(Level.FINE)) {
        logger.fine("delete: FlexoProcess " + getName());
    }
    for (FlexoProcess p : new Vector<FlexoProcess>(getSubProcesses())) {
        p.delete();
    }
    Vector<SubProcessNode> allBoundSubProcessNodes = new Vector<SubProcessNode>(getSubProcessNodes());
    for (Enumeration<SubProcessNode> e = allBoundSubProcessNodes.elements(); e.hasMoreElements();) {
        SubProcessNode subProcessNode = e.nextElement();
        subProcessNode.setSubProcess(null);
        if (logger.isLoggable(Level.INFO)) {
            logger.info("Set subprocess to null for " + subProcessNode.getName());
        }
    }
    /*
     * FlexoProcessNode processNode = getProcessNode(); if (processNode !=
     * null) { processNode.delete(); processNode = null; }
     */
    if (_petriGraph != null) {
        _petriGraph.delete();
    }
    FlexoProcess parentProcess = getParentProcess();
    if (getFlexoResource() != null) {
        getFlexoResource().delete();
    }
    if (getProcessDMEntity() != null) {
        getProcessDMEntity().delete();
    }
    if (getProcessNode() != null) {
        getProcessNode().delete();
    } else {
        if (logger.isLoggable(Level.WARNING)) {
            logger.warning("Process " + getName() + " has no process node associated!");
        }
    }
    FlexoProcessImageBuilder.deleteSnapshot(this);
    super.delete();
    if (nameForNodeMap != null) {
        nameForNodeMap.clear();
    }
    nameForNodeMap = null;
    setChanged();
    notifyObservers(new ProcessRemoved(this, parentProcess));
    deleteObservers();
}

From source file:net.sourceforge.floggy.persistence.Weaver.java

/**
 * DOCUMENT ME!//from w w  w. j a v a 2  s .  com
*
* @throws CannotCompileException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
* @throws NotFoundException DOCUMENT ME!
*/
protected void addPersistableMetadataManagerClass()
        throws CannotCompileException, IOException, NotFoundException {
    alreadyProcessedMetadatas.addAll(configuration.getPersistableMetadatas());

    Set metadatas = alreadyProcessedMetadatas;
    StringBuffer buffer = new StringBuffer();

    buffer.append("public static void init() throws Exception {\n");
    buffer.append("rmsBasedMetadatas = new java.util.Hashtable();\n");
    buffer.append("classBasedMetadatas = new java.util.Hashtable();\n");
    buffer.append("java.util.Hashtable persistableImplementations = null;\n");
    buffer.append("java.util.Vector indexMetadatas = null;\n");
    buffer.append("java.util.Vector fields = null;\n");

    for (Iterator iterator = metadatas.iterator(); iterator.hasNext();) {
        PersistableMetadata metadata = (PersistableMetadata) iterator.next();
        boolean isAbstract = metadata.isAbstract();
        String className = metadata.getClassName();
        String superClassName = metadata.getSuperClassName();
        String[] fieldNames = metadata.getFieldNames();
        int[] fieldTypes = metadata.getFieldTypes();
        Hashtable persistableImplementations = metadata.getPersistableImplementations();
        String recordStoreName = metadata.getRecordStoreName();
        int persistableStrategy = metadata.getPersistableStrategy();
        Vector indexMetadatas = metadata.getIndexMetadatas();
        String[] descendents = metadata.getDescendents();

        StringBuffer fieldNamesBuffer = new StringBuffer("new String[");
        StringBuffer fieldTypesBuffer = new StringBuffer("new int[");
        boolean addHeader = true;

        for (int i = 0; i < fieldNames.length; i++) {
            if (addHeader) {
                fieldNamesBuffer.append("]{");
                fieldTypesBuffer.append("]{");
                addHeader = false;
            }

            fieldNamesBuffer.append("\"");
            fieldNamesBuffer.append(fieldNames[i]);
            fieldNamesBuffer.append("\",");

            fieldTypesBuffer.append(fieldTypes[i]);
            fieldTypesBuffer.append(",");
        }

        if (addHeader) {
            fieldNamesBuffer.append("0]");
            fieldTypesBuffer.append("0]");
        } else {
            fieldNamesBuffer.deleteCharAt(fieldNamesBuffer.length() - 1);
            fieldNamesBuffer.append("}");
            fieldTypesBuffer.deleteCharAt(fieldTypesBuffer.length() - 1);
            fieldTypesBuffer.append("}");
        }

        if ((persistableImplementations != null) && !persistableImplementations.isEmpty()) {
            buffer.append("persistableImplementations = new java.util.Hashtable();\n");

            Enumeration enumeration = persistableImplementations.keys();

            while (enumeration.hasMoreElements()) {
                String fieldName = (String) enumeration.nextElement();
                String classNameOfField = (String) persistableImplementations.get(fieldName);
                buffer.append("persistableImplementations.put(\"");
                buffer.append(fieldName);
                buffer.append("\", \"");
                buffer.append(classNameOfField);
                buffer.append("\");\n");
            }
        } else {
            buffer.append("persistableImplementations = null;\n");
        }

        if ((indexMetadatas != null) && !indexMetadatas.isEmpty()) {
            buffer.append("indexMetadatas = new java.util.Vector();\n");

            Enumeration enumeration = indexMetadatas.elements();

            while (enumeration.hasMoreElements()) {
                IndexMetadata indexMetadata = (IndexMetadata) enumeration.nextElement();

                buffer.append("fields = new java.util.Vector();\n");

                Vector fields = indexMetadata.getFields();

                for (int j = 0; j < fields.size(); j++) {
                    buffer.append("fields.addElement(\"");
                    buffer.append(fields.elementAt(j));
                    buffer.append("\");\n");
                }

                buffer.append(
                        "indexMetadatas.addElement(new net.sourceforge.floggy.persistence.impl.IndexMetadata(\"");
                buffer.append(indexMetadata.getRecordStoreName());
                buffer.append("\", \"");
                buffer.append(indexMetadata.getName());
                buffer.append("\", fields));\n");
            }
        } else {
            buffer.append("indexMetadatas = null;\n");
        }

        StringBuffer descendentsBuffer = new StringBuffer("new String[");
        addHeader = true;

        if (descendents != null) {
            for (int i = 0; i < descendents.length; i++) {
                if (addHeader) {
                    descendentsBuffer.append("]{");
                    addHeader = false;
                }

                descendentsBuffer.append("\"");
                descendentsBuffer.append(descendents[i]);
                descendentsBuffer.append("\",");
            }
        }

        if (addHeader) {
            descendentsBuffer.append("0]");
        } else {
            descendentsBuffer.deleteCharAt(descendentsBuffer.length() - 1);
            descendentsBuffer.append("}");
        }

        buffer.append("classBasedMetadatas.put(\"" + className
                + "\", new net.sourceforge.floggy.persistence.impl.PersistableMetadata(" + isAbstract + ", \""
                + className + "\", "
                + ((superClassName != null) ? ("\"" + superClassName + "\", ") : ("null, "))
                + fieldNamesBuffer.toString() + ", " + fieldTypesBuffer.toString()
                + ", persistableImplementations, indexMetadatas, " + "\"" + recordStoreName + "\", "
                + persistableStrategy + ", " + descendentsBuffer.toString() + "));\n");
    }

    buffer.append("load();\n");
    buffer.append("}\n");

    CtClass ctClass = this.classpathPool
            .get("net.sourceforge.floggy.persistence.impl.PersistableMetadataManager");
    CtMethod[] methods = ctClass.getMethods();

    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getName().equals("init")) {
            ctClass.removeMethod(methods[i]);
        }
    }

    ctClass.addMethod(CtNewMethod.make(buffer.toString(), ctClass));
    embeddedClassesOutputPool.addClass(ctClass);
}

From source file:com.zeroio.webdav.WebdavServlet.java

/**
 * PROPFIND Method./*from  w w w.  j a  v a 2 s  .  co  m*/
 *
 * @param context Description of the Parameter
 * @throws ServletException Description of the Exception
 * @throws IOException      Description of the Exception
 */
protected void doPropfind(ActionContext context) throws ServletException, IOException {

    String path = getRelativePath(context.getRequest());

    //fix for windows clients
    if (path.equals("/files")) {
        path = "";
    }

    if (path.endsWith("/")) {
        path = path.substring(0, path.length() - 1);
    }

    if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) {
        context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    if (path.indexOf("/.") > -1 || path.indexOf(".DS_Store") > -1) {
        //Fix for MACOSX finder. Do not allow requests for files starting with a period
        return;
    }
    //System.out.println("METHOD PROPFIND....PATH: " + path);
    // Properties which are to be displayed.
    Vector properties = null;
    // Propfind depth by default 1 for performance reasons
    int depth = 1;
    // Propfind type
    int type = FIND_ALL_PROP;

    String depthStr = context.getRequest().getHeader("Depth");
    if (depthStr == null) {
        depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            depth = 0;
        } else if (depthStr.equals("1")) {
            depth = 1;
        } else if (depthStr.equals("infinity")) {
            depth = INFINITY;
        }
    }

    /*
     *  Read the request xml and determine all the properties
     */
    Node propNode = null;
    DocumentBuilder documentBuilder = getDocumentBuilder();
    try {
        Document document = documentBuilder.parse(new InputSource(context.getRequest().getInputStream()));
        // Get the root element of the document
        Element rootElement = document.getDocumentElement();
        NodeList childList = rootElement.getChildNodes();
        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                if (currentNode.getNodeName().endsWith("prop")) {
                    type = FIND_BY_PROPERTY;
                    propNode = currentNode;
                }
                if (currentNode.getNodeName().endsWith("propname")) {
                    type = FIND_PROPERTY_NAMES;
                }
                if (currentNode.getNodeName().endsWith("allprop")) {
                    type = FIND_ALL_PROP;
                }
                break;
            }
        }
    } catch (Exception e) {
        // Most likely there was no content : we use the defaults.
        // TODO : Enhance that !
        //e.printStackTrace(System.out);
    }

    if (type == FIND_BY_PROPERTY) {
        properties = new Vector();
        if (!properties.contains("creationdate")) {
            //If the request did not contain creationdate property then add this to requested properties
            //to make the information available for clients
            properties.addElement("creationdate");
        }
        NodeList childList = propNode.getChildNodes();
        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                String nodeName = currentNode.getNodeName();
                String propertyName = null;
                if (nodeName.indexOf(':') != -1) {
                    propertyName = nodeName.substring(nodeName.indexOf(':') + 1);
                } else {
                    propertyName = nodeName;
                }
                // href is a live property which is handled differently
                properties.addElement(propertyName);
                break;
            }
        }
    }

    // Properties have been determined
    // Retrieve the resources

    Connection db = null;
    boolean exists = true;
    boolean status = true;
    Object current = null;
    Object child = null;
    ModuleContext resources = null;
    SystemStatus thisSystem = null;
    StringBuffer xmlsb = new StringBuffer();
    try {
        db = this.getConnection(context);
        resources = getCFSResources(db, context);
        if (resources == null) {
            context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        thisSystem = this.getSystemStatus(context);
        current = resources.lookup(thisSystem, db, path);
        if (current instanceof ModuleContext) {
            //System.out.println( ((ModuleContext) current).toString());
        }
    } catch (NamingException e) {
        //e.printStackTrace(System.out);
        exists = false;
        int slash = path.lastIndexOf('/');
        if (slash != -1) {
            String parentPath = path.substring(0, slash);
            Vector currentLockNullResources = (Vector) lockNullResources.get(parentPath);
            if (currentLockNullResources != null) {
                Enumeration lockNullResourcesList = currentLockNullResources.elements();
                while (lockNullResourcesList.hasMoreElements()) {
                    String lockNullPath = (String) lockNullResourcesList.nextElement();
                    if (lockNullPath.equals(path)) {
                        context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS);
                        context.getResponse().setContentType("text/xml; charset=UTF-8");
                        // Create multistatus object
                        XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter());
                        generatedXML.writeXMLHeader();
                        generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(),
                                XMLWriter.OPENING);
                        parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type,
                                properties);
                        generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
                        generatedXML.sendData();
                        //e.printStackTrace(System.out);
                        return;
                    }
                }
            }
        }
    } catch (SQLException e) {
        e.printStackTrace(System.out);
        context.getResponse().sendError(CFS_SQLERROR, e.getMessage());
        status = false;
    } finally {
        this.freeConnection(db, context);
    }

    if (!status) {
        return;
    }

    if (!exists) {
        context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, path);
        return;
    }

    context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS);
    context.getResponse().setContentType("text/xml; charset=UTF-8");
    // Create multistatus object
    ////System.out.println("Creating Multistatus Object");

    XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter());
    generatedXML.writeXMLHeader();
    generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    //System.out.println("Depth: " + depth);
    if (depth == 0) {
        parseProperties(context, resources, generatedXML, path, type, properties);
    } else {
        // The stack always contains the object of the current level
        Stack stack = new Stack();
        stack.push(path);
        // Stack of the objects one level below
        Stack stackBelow = new Stack();

        while ((!stack.isEmpty()) && (depth >= 0)) {
            String currentPath = (String) stack.pop();
            try {
                if (!currentPath.equals(path)) {
                    //object at url currentPath not yet looked up. so perform lookup at url currentPath
                    child = resources.lookup(currentPath);
                    parseProperties(context, resources, generatedXML, currentPath, type, properties);
                }
            } catch (NamingException e) {
                e.printStackTrace(System.out);
                continue;
            }

            if (!status) {
                return;
            }

            if ((current instanceof ModuleContext) && depth > 0) {
                // Get a list of all the resources at the current path and store them
                // in the stack
                try {
                    NamingEnumeration enum1 = ((ModuleContext) current).list("");
                    int count = 0;
                    while (enum1.hasMoreElements()) {
                        NameClassPair ncPair = (NameClassPair) enum1.nextElement();
                        String newPath = currentPath;
                        if (!(newPath.endsWith("/"))) {
                            newPath += "/";
                        }
                        newPath += ncPair.getName();
                        //System.out.println("STACKING CHILD: " + newPath);
                        stackBelow.push(newPath);
                        count++;
                    }
                    if (currentPath.equals(path) && count == 0) {
                        // This directory does not have any files or folders.
                        //System.out.println("DIRECTORY HAS NO FILES OR FOLDERS...");
                        parseProperties(context, resources, generatedXML, properties);
                    }
                } catch (NamingException e) {
                    //e.printStackTrace(System.out);
                    context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
                    return;
                }

                // Displaying the lock-null resources present in that collection
                String lockPath = currentPath;
                if (lockPath.endsWith("/")) {
                    lockPath = lockPath.substring(0, lockPath.length() - 1);
                }
                Vector currentLockNullResources = (Vector) lockNullResources.get(lockPath);
                if (currentLockNullResources != null) {
                    Enumeration lockNullResourcesList = currentLockNullResources.elements();
                    while (lockNullResourcesList.hasMoreElements()) {
                        String lockNullPath = (String) lockNullResourcesList.nextElement();
                        System.out.println("Lock null path: " + lockNullPath);
                        parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type,
                                properties);
                    }
                }
            }
            if (stack.isEmpty()) {
                depth--;
                stack = stackBelow;
                stackBelow = new Stack();
            }
            xmlsb.append(generatedXML.toString());
            //System.out.println("xml : " + generatedXML.toString());
            generatedXML.sendData();
        }
    }

    Iterator locks = lockNullResources.keySet().iterator();
    while (locks.hasNext()) {
        String lockpath = (String) locks.next();
        //System.out.println("LOCK PATH: " + lockpath);
    }

    generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
    xmlsb.append(generatedXML.toString());
    generatedXML.sendData();
    //System.out.println("xml: " + xmlsb.toString());
}

From source file:org.apache.catalina.loader.WebappClassLoader.java

/**
 * Return an enumeration of <code>URLs</code> representing all of the
 * resources with the given name.  If no resources with this name are
 * found, return an empty enumeration./*from  ww w .j av a 2s.c  o m*/
 *
 * @param name Name of the resources to be found
 *
 * @exception IOException if an input/output error occurs
 */
public Enumeration findResources(String name) throws IOException {

    if (log.isDebugEnabled())
        log.debug("    findResources(" + name + ")");

    Vector result = new Vector();

    int jarFilesLength = jarFiles.length;
    int repositoriesLength = repositories.length;

    int i;

    // Looking at the repositories
    for (i = 0; i < repositoriesLength; i++) {
        try {
            String fullPath = repositories[i] + name;
            resources.lookup(fullPath);
            // Note : Not getting an exception here means the resource was
            // found
            try {
                result.addElement(getURI(new File(files[i], name)));
            } catch (MalformedURLException e) {
                // Ignore
            }
        } catch (NamingException e) {
        }
    }

    // Looking at the JAR files
    synchronized (jarFiles) {
        openJARs();
        for (i = 0; i < jarFilesLength; i++) {
            JarEntry jarEntry = jarFiles[i].getJarEntry(name);
            if (jarEntry != null) {
                try {
                    String jarFakeUrl = getURI(jarRealFiles[i]).toString();
                    jarFakeUrl = "jar:" + jarFakeUrl + "!/" + name;
                    result.addElement(new URL(jarFakeUrl));
                } catch (MalformedURLException e) {
                    // Ignore
                }
            }
        }
    }

    // Adding the results of a call to the superclass
    if (hasExternalRepositories) {

        Enumeration otherResourcePaths = super.findResources(name);

        while (otherResourcePaths.hasMoreElements()) {
            result.addElement(otherResourcePaths.nextElement());
        }

    }

    return result.elements();

}