Example usage for javax.naming NamingEnumeration nextElement

List of usage examples for javax.naming NamingEnumeration nextElement

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration nextElement.

Prototype

E nextElement();

Source Link

Document

Returns the next element of this enumeration if this enumeration object has at least one more element to provide.

Usage

From source file:org.lsc.jndi.JndiServices.java

private SearchResult doGetEntry(final String base, final String filter, final SearchControls sc,
        final int scope) throws NamingException {
    //sanity checks
    String searchBase = base == null ? "" : base;
    String searchFilter = filter == null ? DEFAULT_FILTER : filter;

    NamingEnumeration<SearchResult> ne = null;
    try {//from   w w  w . j  a v  a  2s.com
        sc.setSearchScope(scope);
        String rewrittenBase = null;
        if (contextDn != null && searchBase.toLowerCase().endsWith(contextDn.toString().toLowerCase())) {
            if (!searchBase.equalsIgnoreCase(contextDn.toString())) {
                rewrittenBase = searchBase.substring(0,
                        searchBase.toLowerCase().lastIndexOf(contextDn.toString().toLowerCase()) - 1);
            } else {
                rewrittenBase = "";
            }
        } else {
            rewrittenBase = searchBase;
        }
        ne = ctx.search(rewrittenBase, searchFilter, sc);

    } catch (NamingException nex) {
        LOGGER.error("Error while looking for {} in {}: {}", new Object[] { searchFilter, searchBase, nex });
        throw nex;
    }

    SearchResult sr = null;
    if (ne.hasMoreElements()) {
        sr = (SearchResult) ne.nextElement();
        if (ne.hasMoreElements()) {
            LOGGER.error("Too many entries returned (base: \"{}\", filter: \"{}\")", searchBase, searchFilter);
            throw new SizeLimitExceededException("Too many entries returned (base: \"" + searchBase
                    + "\", filter: \"" + searchFilter + "\")");
        } else {
            return sr;
        }
    } else {
        // try hasMore method to throw exceptions if there are any and we didn't get our entry
        ne.hasMore();
    }
    return sr;
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Return an InputStream to an HTML representation of the contents
 * of this directory.//from   www  .j  a  v  a  2  s.  com
 *
 * @param contextPath     Context path to which our internal paths are
 *                        relative
 * @param resourceInfo    Description of the Parameter
 * @param xsltInputStream Description of the Parameter
 * @return Description of the Return Value
 */
protected InputStream renderXml(String contextPath, ResourceInfo resourceInfo, InputStream xsltInputStream) {

    StringBuffer sb = new StringBuffer();

    sb.append("<?xml version=\"1.0\"?>");
    sb.append("<listing ");
    sb.append(" contextPath='");
    sb.append(contextPath);
    sb.append("'");
    sb.append(" directory='");
    sb.append(resourceInfo.path);
    sb.append("' ");
    sb.append(" hasParent='").append(!resourceInfo.path.equals("/"));
    sb.append("'>");

    sb.append("<entries>");

    try {

        // Render the directory entries within this directory
        DirContext directory = resourceInfo.directory;
        NamingEnumeration enum1 = resourceInfo.resources.list(resourceInfo.path);
        while (enum1.hasMoreElements()) {

            NameClassPair ncPair = (NameClassPair) enum1.nextElement();
            String resourceName = ncPair.getName();
            ResourceInfo childResourceInfo = new ResourceInfo(resourceName, directory);

            String trimmed = resourceName;
            if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF")
                    || trimmed.equalsIgnoreCase(localXsltFile)) {
                continue;
            }

            sb.append("<entry");
            sb.append(" type='").append(childResourceInfo.collection ? "dir" : "file").append("'");
            sb.append(" urlPath='").append(rewriteUrl(contextPath))
                    .append(rewriteUrl(resourceInfo.path + resourceName))
                    .append(childResourceInfo.collection ? "/" : "").append("'");
            if (!childResourceInfo.collection) {
                sb.append(" size='").append(renderSize(childResourceInfo.length)).append("'");
            }
            sb.append(" date='").append(childResourceInfo.httpDate).append("'");

            sb.append(">");
            sb.append(trimmed);
            if (childResourceInfo.collection) {
                sb.append("/");
            }
            sb.append("</entry>");

        }

    } catch (NamingException e) {
        // Something went wrong
        e.printStackTrace();
    }

    sb.append("</entries>");

    String readme = getReadme(resourceInfo.directory);

    if (readme != null) {
        sb.append("<readme><![CDATA[");
        sb.append(readme);
        sb.append("]]></readme>");
    }

    sb.append("</listing>");

    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Source xmlSource = new StreamSource(new StringReader(sb.toString()));
        Source xslSource = new StreamSource(xsltInputStream);
        Transformer transformer = tFactory.newTransformer(xslSource);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8");
        StreamResult out = new StreamResult(osWriter);
        transformer.transform(xmlSource, out);
        osWriter.flush();
        return (new ByteArrayInputStream(stream.toByteArray()));
    } catch (Exception e) {
        log("directory transform failure: " + e.getMessage());
        return renderHtml(contextPath, resourceInfo);
    }
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Return an InputStream to an HTML representation of the contents
 * of this directory.//  w  ww .  j  a v  a  2  s. c om
 *
 * @param contextPath  Context path to which our internal paths are
 *                     relative
 * @param resourceInfo Description of the Parameter
 * @return Description of the Return Value
 */
protected InputStream renderHtml(String contextPath, ResourceInfo resourceInfo) {

    String name = resourceInfo.path;

    // Number of characters to trim from the beginnings of filenames
    int trim = name.length();
    if (!name.endsWith("/")) {
        trim += 1;
    }
    if (name.equals("/")) {
        trim = 1;
    }

    // Prepare a writer to a buffered area
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    OutputStreamWriter osWriter = null;
    try {
        osWriter = new OutputStreamWriter(stream, "UTF8");
    } catch (Exception e) {
        // Should never happen
        osWriter = new OutputStreamWriter(stream);
    }
    PrintWriter writer = new PrintWriter(osWriter);

    StringBuffer sb = new StringBuffer();

    // Render the page header
    sb.append("<html>\r\n");
    sb.append("<head>\r\n");
    sb.append("<title>");
    sb.append(sm.getString("directory.title", name));
    sb.append("</title>\r\n");
    sb.append("<STYLE><!--");
    sb.append(org.apache.catalina.util.TomcatCSS.TOMCAT_CSS);
    sb.append("--></STYLE> ");
    sb.append("</head>\r\n");
    sb.append("<body>");
    sb.append("<h1>");
    sb.append(sm.getString("directory.title", name));

    // Render the link to our parent (if required)
    String parentDirectory = name;
    if (parentDirectory.endsWith("/")) {
        parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1);
    }
    int slash = parentDirectory.lastIndexOf('/');
    if (slash >= 0) {
        String parent = name.substring(0, slash);
        sb.append(" - <a href=\"");
        sb.append(rewriteUrl(contextPath));
        if (parent.equals("")) {
            parent = "/";
        }
        sb.append(rewriteUrl(parent));
        if (!parent.endsWith("/")) {
            sb.append("/");
        }
        sb.append("\">");
        sb.append("<b>");
        sb.append(sm.getString("directory.parent", parent));
        sb.append("</b>");
        sb.append("</a>");
    }

    sb.append("</h1>");
    sb.append("<HR size=\"1\" noshade=\"noshade\">");

    sb.append("<table width=\"100%\" cellspacing=\"0\"" + " cellpadding=\"5\" align=\"center\">\r\n");

    // Render the column headings
    sb.append("<tr>\r\n");
    sb.append("<td align=\"left\"><font size=\"+1\"><strong>");
    sb.append(sm.getString("directory.filename"));
    sb.append("</strong></font></td>\r\n");
    sb.append("<td align=\"center\"><font size=\"+1\"><strong>");
    sb.append(sm.getString("directory.size"));
    sb.append("</strong></font></td>\r\n");
    sb.append("<td align=\"right\"><font size=\"+1\"><strong>");
    sb.append(sm.getString("directory.lastModified"));
    sb.append("</strong></font></td>\r\n");
    sb.append("</tr>");

    try {

        // Render the directory entries within this directory
        DirContext directory = resourceInfo.directory;
        NamingEnumeration enum1 = resourceInfo.resources.list(resourceInfo.path);
        boolean shade = false;
        while (enum1.hasMoreElements()) {

            NameClassPair ncPair = (NameClassPair) enum1.nextElement();
            String resourceName = ncPair.getName();
            ResourceInfo childResourceInfo = new ResourceInfo(resourceName, directory);

            String trimmed = resourceName;
            if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF")) {
                continue;
            }

            sb.append("<tr");
            if (shade) {
                sb.append(" bgcolor=\"#eeeeee\"");
            }
            sb.append(">\r\n");
            shade = !shade;

            sb.append("<td align=\"left\">&nbsp;&nbsp;\r\n");
            sb.append("<a href=\"");
            sb.append(rewriteUrl(contextPath));
            resourceName = rewriteUrl(name + resourceName);
            sb.append(resourceName);
            if (childResourceInfo.collection) {
                sb.append("/");
            }
            sb.append("\"><tt>");
            sb.append(trimmed);
            if (childResourceInfo.collection) {
                sb.append("/");
            }
            sb.append("</tt></a></td>\r\n");

            sb.append("<td align=\"right\"><tt>");
            if (childResourceInfo.collection) {
                sb.append("&nbsp;");
            } else {
                sb.append(renderSize(childResourceInfo.length));
            }
            sb.append("</tt></td>\r\n");

            sb.append("<td align=\"right\"><tt>");
            sb.append(childResourceInfo.httpDate);
            sb.append("</tt></td>\r\n");

            sb.append("</tr>\r\n");
        }

    } catch (NamingException e) {
        // Something went wrong
        e.printStackTrace();
    }

    // Render the page footer
    sb.append("</table>\r\n");

    sb.append("<HR size=\"1\" noshade=\"noshade\">");

    String readme = getReadme(resourceInfo.directory);
    if (readme != null) {
        sb.append(readme);
        sb.append("<HR size=\"1\" noshade=\"noshade\">");
    }

    sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>");
    sb.append("</body>\r\n");
    sb.append("</html>\r\n");

    // Return an input stream to the underlying bytes
    writer.write(sb.toString());
    writer.flush();
    return (new ByteArrayInputStream(stream.toByteArray()));
}

From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java

private void execute() throws Exception {
    // Connecting to server and retreiving entries
    NamingEnumeration entries = connectToServerAndGetEntries();

    // Creating destination file
    File destionationFile = new File(ldifFileName);

    // Deleting the destination file if it already exists
    if (destionationFile.exists()) {
        destionationFile.delete();//from   w  ww . jav a 2  s .co m
    }

    // Creating the writer to generate the LDIF file
    FileWriter fw = new FileWriter(ldifFileName, true);

    BufferedWriter writer = new BufferedWriter(fw);
    OtcLdifComposerImpl composer = new OtcLdifComposerImpl();
    MultiValueMap map = new MultiValueMap();
    //      MultiMap map = new MultiMap() {
    //         // FIXME Stop forking commons-collections.
    //         private final MultiValueMap map = new MultiValueMap();
    //
    //         public Object remove(Object arg0, Object arg1) {
    //            return map.remove(arg0, arg1);
    //         }
    //
    //         public int size() {
    //            return map.size();
    //         }
    //
    //         public Object get(Object arg0) {
    //            return map.get(arg0);
    //         }
    //
    //         public boolean containsValue(Object arg0) {
    //            return map.containsValue(arg0);
    //         }
    //
    //         public Object put(Object arg0, Object arg1) {
    //            return map.put(arg0, arg1);
    //         }
    //
    //         public Object remove(Object arg0) {
    //            return map.remove(arg0);
    //         }
    //
    //         public Collection values() {
    //            return map.values();
    //         }
    //
    //         public boolean isEmpty() {
    //            return map.isEmpty();
    //         }
    //
    //         public boolean containsKey(Object key) {
    //            return map.containsKey(key);
    //         }
    //
    //         public void putAll(Map arg0) {
    //            map.putAll(arg0);
    //         }
    //
    //         public void clear() {
    //            map.clear();
    //         }
    //
    //         public Set keySet() {
    //            return map.keySet();
    //         }
    //
    //         public Set entrySet() {
    //            return map.entrySet();
    //         }
    //      };

    int entriesCounter = 1;
    long t0 = System.currentTimeMillis();

    while (entries.hasMoreElements()) {
        SearchResult sr = (SearchResult) entries.nextElement();
        Attributes attributes = sr.getAttributes();
        NamingEnumeration attributesEnumeration = attributes.getAll();

        map.clear();

        while (attributesEnumeration.hasMoreElements()) {
            Attribute attr = (Attribute) attributesEnumeration.nextElement();
            NamingEnumeration e2 = null;

            e2 = attr.getAll();

            while (e2.hasMoreElements()) {
                Object value = e2.nextElement();
                map.put(attr.getID(), value);
            }
        }

        // Writing entry in the file
        writer.write("dn: " + sr.getNameInNamespace() + "\n");
        writer.write(composer.compose(map) + "\n");

        notifyEntryWrittenListener(sr.getNameInNamespace());
        entriesCounter++;

        if (entriesCounter % 10 == 0) {
            notifyOutputListener(new Character('.'));
        }

        if (entriesCounter % 500 == 0) {
            notifyOutputListener("" + entriesCounter);
        }
    }

    writer.flush();
    writer.close();
    fw.close();

    long t1 = System.currentTimeMillis();

    notifyOutputListener("Done!");
    notifyOutputListener(entriesCounter + " entries exported in " + ((t1 - t0) / 1000) + " seconds");
}

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

/**
 * Copy a collection./*from www  . j a  v a 2 s .  com*/
 *
 * @param resources Resources implementation to be used
 * @param errorList Hashtable containing the list of errors which occurred
 *                  during the copy operation
 * @param source    Path of the resource to be copied
 * @param dest      Destination path
 * @return Description of the Return Value
 */
private boolean copyResource(DirContext resources, Hashtable errorList, String source, String dest) {

    if (debug > 1) {
        System.out.println("Copy: " + source + " To: " + dest);
    }

    Object object = null;
    try {
        object = resources.lookup(source);
    } catch (NamingException e) {
    }

    if (object instanceof DirContext) {

        try {
            resources.createSubcontext(dest);
        } catch (NamingException e) {
            errorList.put(dest, new Integer(WebdavStatus.SC_CONFLICT));
            return false;
        }

        try {
            NamingEnumeration enum1 = resources.list(source);
            while (enum1.hasMoreElements()) {
                NameClassPair ncPair = (NameClassPair) enum1.nextElement();
                String childDest = dest;
                if (!childDest.equals("/")) {
                    childDest += "/";
                }
                childDest += ncPair.getName();
                String childSrc = source;
                if (!childSrc.equals("/")) {
                    childSrc += "/";
                }
                childSrc += ncPair.getName();
                copyResource(resources, errorList, childSrc, childDest);
            }
        } catch (NamingException e) {
            errorList.put(dest, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
            return false;
        }

    } else {

        if (object instanceof Resource) {
            try {
                resources.bind(dest, object);
            } catch (NamingException e) {
                errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
                return false;
            }
        } else {
            errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
            return false;
        }

    }

    return true;
}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java

@Override
public User importUser(long ldapServerId, long companyId, String emailAddress, String screenName)
        throws Exception {

    LdapContext ldapContext = null;

    NamingEnumeration<SearchResult> enu = null;

    try {/*  ww w.ja va 2s.  c o  m*/
        LDAPServerConfiguration ldapServerConfiguration = _ldapServerConfigurationProvider
                .getConfiguration(companyId, ldapServerId);

        String baseDN = ldapServerConfiguration.baseDN();

        ldapContext = _portalLDAP.getContext(ldapServerId, companyId);

        if (ldapContext == null) {
            _log.error("Unable to bind to the LDAP server");

            return null;
        }

        String filter = ldapServerConfiguration.authSearchFilter();

        if (_log.isDebugEnabled()) {
            _log.debug("Search filter before transformation " + filter);
        }

        filter = StringUtil.replace(filter, new String[] { "@company_id@", "@email_address@", "@screen_name@" },
                new String[] { String.valueOf(companyId), emailAddress, screenName });

        LDAPUtil.validateFilter(filter);

        if (_log.isDebugEnabled()) {
            _log.debug("Search filter after transformation " + filter);
        }

        Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId);

        String userMappingsScreenName = GetterUtil.getString(userMappings.getProperty("screenName"));

        userMappingsScreenName = StringUtil.toLowerCase(userMappingsScreenName);

        SearchControls searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0,
                new String[] { userMappingsScreenName }, false, false);

        enu = ldapContext.search(baseDN, filter, searchControls);

        if (enu.hasMoreElements()) {
            if (_log.isDebugEnabled()) {
                _log.debug("Search filter returned at least one result");
            }

            Binding binding = enu.nextElement();

            Attributes attributes = _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext,
                    binding.getNameInNamespace());

            return importUser(ldapServerId, companyId, ldapContext, attributes, null);
        } else {
            return null;
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn("Problem accessing LDAP server " + e.getMessage());
        }

        if (_log.isDebugEnabled()) {
            _log.debug(e, e);
        }

        throw new SystemException("Problem accessing LDAP server " + e.getMessage());
    } finally {
        if (enu != null) {
            enu.close();
        }

        if (ldapContext != null) {
            ldapContext.close();
        }
    }
}

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

/**
 * PROPFIND Method.//from  w w  w.  ja  v  a  2  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:com.zeroio.webdav.WebdavServlet.java

/**
 * Copy a collection./*from www. j  a  va 2s  .co  m*/
 *
 * @param resources  Resources implementation to be used
 * @param errorList  Hashtable containing the list of errors
 *                   which occurred during the copy operation
 * @param source     Path of the resource to be copied
 * @param dest       Destination path
 * @param thisSystem Description of the Parameter
 * @param db         Description of the Parameter
 * @return Description of the Return Value
 * @throws SQLException          Description of the Exception
 * @throws FileNotFoundException Description of the Exception
 */
private boolean copyResource(ActionContext context, SystemStatus thisSystem, Connection db,
        ModuleContext resources, Hashtable errorList, String source, String dest)
        throws SQLException, FileNotFoundException {

    if (debug > 1) {
        System.out.println("Copy: " + source + " To: " + dest);
    }

    Object object = null;
    try {
        object = resources.lookup(thisSystem, db, source);
    } catch (NamingException e) {
        e.printStackTrace(System.out);
    }

    if (object instanceof ModuleContext) {
        try {
            resources.createSubcontext(thisSystem, db, dest);
        } catch (NamingException e) {
            e.printStackTrace(System.out);
            errorList.put(dest, new Integer(WebdavStatus.SC_CONFLICT));
            return false;
        }

        try {
            //System.out.println("Listing resources at path: " + source);
            //System.out.println("OBJECT: " + object);
            object = resources.lookup(thisSystem, db, source);
            NamingEnumeration enum1 = resources.list(source);
            while (enum1.hasMoreElements()) {
                //System.out.println("COPYING CHILD CONTEXT.........................");
                NameClassPair ncPair = (NameClassPair) enum1.nextElement();
                String childDest = dest;
                if (!childDest.equals("/")) {
                    childDest += "/";
                }
                childDest += ncPair.getName();
                String childSrc = source;
                if (!childSrc.equals("/")) {
                    childSrc += "/";
                }
                childSrc += ncPair.getName();
                copyResource(context, thisSystem, db, resources, errorList, childSrc, childDest);
            }
        } catch (NamingException e) {
            e.printStackTrace(System.out);
            errorList.put(dest, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
            return false;
        }

    } else {

        if (object instanceof Resource) {
            try {
                Object resource = resources.copyResource(thisSystem, db, dest, object);
                if (resource != null) {
                    processInsertHook(context, resource);
                }
            } catch (NamingException e) {
                errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
                return false;
            } catch (IOException io) {
                errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
                return false;
            }
        } else {
            errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
            return false;
        }
    }
    return true;
}

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

/**
 * PROPFIND Method.//from   ww w.  j av a 2s.com
 *
 * @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());
}