Example usage for javax.naming NamingEnumeration hasMoreElements

List of usage examples for javax.naming NamingEnumeration hasMoreElements

Introduction

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

Prototype

boolean hasMoreElements();

Source Link

Document

Tests if this enumeration contains more elements.

Usage

From source file:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java

/**
 * {@inheritDoc}//from   w  w  w. ja  va2 s  .c o  m
 */
public Map<String, String> findByCommonNameStub(String stub, long maxCount) throws RepositoryException {
    Map<String, String> idNameMap = new LinkedHashMap<String, String>();
    String text = censorHumanoidSearchPhrase(stub);
    String filter = "(&(objectClass=" + getObjectClassName() + ")(cn=" + text + "*))";
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setCountLimit(maxCount);
    ctls.setReturningAttributes(new String[] { "cn", "uid" });

    try {
        NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls);
        while (resultEnum.hasMoreElements()) {
            SearchResult result = resultEnum.next();
            Attributes attrs = result.getAttributes();
            idNameMap.put((String) attrs.get("uid").get(), (String) attrs.get("cn").get());
        }
    } catch (NamingException e) {
        throw new RepositoryException(e);
    }
    return idNameMap;
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationUpdate(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    String entryNameAfter = entryName;
    if (paramValueMap != null) {
        String newEntryName = (String) paramValueMap.get("newEntryName");
        if (newEntryName != null && StringUtils.isNotEmpty(newEntryName)) {
            if (log.isDebugEnabled())
                log.debug("newEntryName=[" + newEntryName + "]");
            DirContext dirContext = null;
            try {
                dirContext = getDirContext(paramValueMap);
                dirContext.rename(entryName, newEntryName);
                entryNameAfter = newEntryName;
            } catch (NamingException e) {
                String msg;/*  ww w  . j  a v a  2 s  .  co m*/
                // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
                // Sun:
                //   [LDAP: error code 32 - No Such Object...
                if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                    msg = "Operation [" + getOperation() + "] failed - wrong entryName [" + entryName + "]";
                } else {
                    msg = "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]";
                }
                storeLdapException(e, prc);
                throw new SenderException(msg, e);
            } finally {
                closeDirContext(dirContext);
            }
        }
    }

    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Update attribute: " + a.getID());
            NamingEnumeration values;
            try {
                values = a.getAll();
            } catch (NamingException e1) {
                storeLdapException(e1, prc);
                throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1);
            }
            while (values.hasMoreElements()) {
                Attributes partialAttrs = new BasicAttributes();
                Attribute singleValuedAttribute;
                String id = a.getID();
                Object value = values.nextElement();
                if (log.isDebugEnabled()) {
                    if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) {
                        log.debug("Update value: ***");
                    } else {
                        log.debug("Update value: " + value);
                    }
                }
                if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) {
                    singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value));
                } else {
                    singleValuedAttribute = new BasicAttribute(id, value);
                }
                partialAttrs.put(singleValuedAttribute);
                DirContext dirContext = null;
                try {
                    dirContext = getDirContext(paramValueMap);
                    dirContext.modifyAttributes(entryNameAfter, DirContext.REPLACE_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    String msg;
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
                    // Sun:
                    //   [LDAP: error code 32 - No Such Object...
                    if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                        msg = "Operation [" + getOperation() + "] failed - wrong entryName [" + entryNameAfter
                                + "]";
                    } else {
                        msg = "Exception in operation [" + getOperation() + "] entryName [" + entryNameAfter
                                + "]";
                    }
                    //result = DEFAULT_RESULT_UPDATE_NOK;
                    storeLdapException(e, prc);
                    throw new SenderException(msg, e);
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            dirContext = getDirContext(paramValueMap);
            //dirContext.rename(newEntryName, oldEntryName);
            //result = DEFAULT_RESULT;
            dirContext.rename(entryName, entryName);
            return "<LdapResult>Deze functionaliteit is nog niet beschikbaar - naam niet veranderd.</LdapResult>";
        } catch (NamingException e) {
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   68 LDAP_ALREADY_EXISTS Indicates that the add operation attempted to add an entry that already exists, or that the modify operation attempted to rename an entry to the name of an entry that already exists.
            // Sun:
            //   [LDAP: error code 68 - Entry Already Exists]
            if (!e.getMessage().startsWith("[LDAP: error code 68 - ")) {
                storeLdapException(e, prc);
                throw new SenderException(e);
            }
            return DEFAULT_RESULT_CREATE_NOK;
        } finally {
            closeDirContext(dirContext);
        }
    }
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationCreate(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        String result = null;/* w ww .j  av  a 2 s .  c o m*/
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Create attribute: " + a.getID());
            NamingEnumeration values;
            try {
                values = a.getAll();
            } catch (NamingException e1) {
                storeLdapException(e1, prc);
                throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1);
            }
            while (values.hasMoreElements()) {
                Attributes partialAttrs = new BasicAttributes();
                Attribute singleValuedAttribute;
                String id = a.getID();
                Object value = values.nextElement();
                if (log.isDebugEnabled()) {
                    if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) {
                        log.debug("Create value: ***");
                    } else {
                        log.debug("Create value: " + value);
                    }
                }
                if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) {
                    singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value));
                } else {
                    singleValuedAttribute = new BasicAttribute(id, value);
                }
                partialAttrs.put(singleValuedAttribute);
                DirContext dirContext = null;
                try {
                    dirContext = getDirContext(paramValueMap);
                    dirContext.modifyAttributes(entryName, DirContext.ADD_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   20 LDAP_TYPE_OR_VALUE_EXISTS Indicates that the attribute value specified in a modify or add operation already exists as a value for that attribute.
                    // Sun:
                    //   [LDAP: error code 20 - Attribute Or Value Exists]
                    if (e.getMessage().startsWith("[LDAP: error code 20 - ")) {
                        if (log.isDebugEnabled())
                            log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                        result = DEFAULT_RESULT_CREATE_OK;
                    } else {
                        storeLdapException(e, prc);
                        throw new SenderException(
                                "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]",
                                e);
                    }
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        if (result != null) {
            return result;
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            if (unicodePwd) {
                Enumeration enumeration = attrs.getIDs();
                while (enumeration.hasMoreElements()) {
                    String id = (String) enumeration.nextElement();
                    if ("unicodePwd".equalsIgnoreCase(id)) {
                        Attribute attr = attrs.get(id);
                        for (int i = 0; i < attr.size(); i++) {
                            attr.set(i, encodeUnicodePwd(attr.get(i)));
                        }
                    }
                }
            }
            dirContext = getDirContext(paramValueMap);
            dirContext.bind(entryName, null, attrs);
            return DEFAULT_RESULT;
        } catch (NamingException e) {
            // if (log.isDebugEnabled()) log.debug("Exception in operation [" + getOperation()+ "] entryName ["+entryName+"]", e);
            if (log.isDebugEnabled())
                log.debug("Exception in operation [" + getOperation() + "] entryName [" + entryName + "]: "
                        + e.getMessage());
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   68 LDAP_ALREADY_EXISTS Indicates that the add operation attempted to add an entry that already exists, or that the modify operation attempted to rename an entry to the name of an entry that already exists.
            // Sun:
            //   [LDAP: error code 68 - Entry Already Exists]
            if (e.getMessage().startsWith("[LDAP: error code 68 - ")) {
                return DEFAULT_RESULT_CREATE_OK;
            } else {
                storeLdapException(e, prc);
                throw new SenderException(e);
            }
        } finally {
            closeDirContext(dirContext);
        }
    }

}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationDelete(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        String result = null;//from  w ww  .  j a  v  a 2  s  . c  o m
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Delete attribute: " + a.getID());
            NamingEnumeration values;
            try {
                values = a.getAll();
            } catch (NamingException e1) {
                storeLdapException(e1, prc);
                throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1);
            }
            while (values.hasMoreElements()) {
                Attributes partialAttrs = new BasicAttributes();
                Attribute singleValuedAttribute;
                String id = a.getID();
                Object value = values.nextElement();
                if (log.isDebugEnabled()) {
                    if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) {
                        log.debug("Delete value: ***");
                    } else {
                        log.debug("Delete value: " + value);
                    }
                }
                if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) {
                    singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value));
                } else {
                    singleValuedAttribute = new BasicAttribute(id, value);
                }
                partialAttrs.put(singleValuedAttribute);
                DirContext dirContext = null;
                try {
                    dirContext = getDirContext(paramValueMap);
                    dirContext.modifyAttributes(entryName, DirContext.REMOVE_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   16 LDAP_NO_SUCH_ATTRIBUTE Indicates that the attribute specified in the modify or compare operation does not exist in the entry.
                    //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
                    // Sun:
                    //   [LDAP: error code 16 - No Such Attribute...
                    //   [LDAP: error code 32 - No Such Object...
                    // AD:
                    //   [LDAP: error code 16 - 00002085: AtrErr: DSID-03151F03, #1...
                    if (e.getMessage().startsWith("[LDAP: error code 16 - ")
                            || e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                        if (log.isDebugEnabled())
                            log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                        result = DEFAULT_RESULT_DELETE;
                    } else {
                        storeLdapException(e, prc);
                        throw new SenderException(
                                "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]",
                                e);
                    }
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        if (result != null) {
            return result;
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            dirContext = getDirContext(paramValueMap);
            dirContext.unbind(entryName);
            return DEFAULT_RESULT;
        } catch (NamingException e) {
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
            // Sun:
            //   [LDAP: error code 32 - No Such Object...
            if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                if (log.isDebugEnabled())
                    log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                return DEFAULT_RESULT_DELETE;
            } else {
                storeLdapException(e, prc);
                throw new SenderException(
                        "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e);
            }
        } finally {
            closeDirContext(dirContext);
        }
    }
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

/**
 *Strips all the values from the attributes in <code>input</code>. This is performed to be able to delete 
 *the attributes without having to match the values. If values exist they must be exactly matched too in
 *order to delete the attribute./*from   ww  w. j  a va  2 s  . c o m*/
 */
protected Attributes removeValuesFromAttributes(Attributes input) {
    Attributes result = new BasicAttributes(true);
    // ignore attribute name case
    NamingEnumeration enumeration = input.getIDs();
    while (enumeration.hasMoreElements()) {
        String attrId = (String) enumeration.nextElement();
        result.put(new BasicAttribute(attrId));
    }
    return result;
}

From source file:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Does a subtree search for an element given a pattern. Only the first
 * element found is considered, and all references are searched in order
 * until either a match is found or no more references are left to search.
 * @param ldap/*  ww  w .  j  a va2 s.  c  o m*/
 *            A prepared LDAP context.
 * @param pattern
 *            The search pattern. Must not include the character '*' or the
 *            substring '\2a' to prevent possible LDAP exploits.
 * @return The element's relative DN, or <code>null</code> if none was
 *         found. <code>null</code> is also returned if the search pattern
 *         contains an illegal character or substring.
 * @throws BackendException
 *             If there was a problem accessing the backend. Typical causes
 *             include timeouts.
 */
private String ldapSearch(final InitialLdapContext ldap, final String pattern) throws BackendException {

    // Check pattern for illegal content.
    String[] illegals = { "*", "\\2a" };
    for (int i = 0; i < illegals.length; i++) {
        if (pattern.indexOf(illegals[i]) > -1)
            return null;
    }

    // The context provider URL, for later logging.
    String url = "unknown backend";

    // Start counting the (milli)seconds and prepare for timeouts.
    long searchStart = System.currentTimeMillis();
    JNDISearchInterruptor interruptTask = new JNDISearchInterruptor(ldap, mySessionTicket);
    NamingEnumeration results;
    try {

        // Remember the URL, for later logging.
        url = (String) ldap.getEnvironment().get(Context.PROVIDER_URL);
        interruptTask.setURL(url);

        // Start timeout interruptor and perform the search.
        Timer interruptTimer = new Timer();
        interruptTimer.schedule(interruptTask, (1000 * myTimeout));
        results = ldap.search("", pattern, new SearchControls(SearchControls.SUBTREE_SCOPE, 0, 1000 * myTimeout,
                new String[] {}, false, false));
        interruptTimer.cancel();
        if (!results.hasMore())
            return null;

    } catch (TimeLimitExceededException e) {

        // The search timed out.
        log.logWarn("Search on " + url + " for " + pattern + " timed out after ~"
                + (System.currentTimeMillis() - searchStart) + "ms", mySessionTicket);
        return null;

    } catch (SizeLimitExceededException e) {

        // The search returned too many results.
        log.logWarn("Search on " + url + " for " + pattern + " returned too many results", mySessionTicket);
        return null;

    } catch (NameNotFoundException e) {

        // Element not found. Possibly non-existing reference.
        log.logDebug("Could not find " + pattern + " on " + url, mySessionTicket); // Necessary?
        return null;

    } catch (AuthenticationException e) {

        // Search failed authentication; check non-anonymous search config.
        try {
            final String searchUser = (String) ldap.getEnvironment().get(Context.SECURITY_PRINCIPAL);
            final String errorMessage;
            if ((searchUser == null) || searchUser.equals(""))
                errorMessage = "Anonymous search failed authentication on " + url;
            else
                errorMessage = "Could not authenticate search user " + searchUser + " on " + url;
            log.logDebug(errorMessage, mySessionTicket);
            throw new BackendException(errorMessage, e);
        } catch (NamingException f) {

            // Should not happen!
            log.logCritical("Unable to read LDAP environment", mySessionTicket, f);
            throw new BackendException("Unable to read LDAP environment", f);

        }

    } catch (NamingException e) {

        // Did we interrupt the search ourselves?
        if (interruptTask.finished()) {
            final long elapsed = System.currentTimeMillis() - searchStart;
            log.logWarn("Search on " + url + " for " + pattern + " timed out after ~" + elapsed + "ms",
                    mySessionTicket);
            throw new BackendException("Search on " + url + " for " + pattern + " timed out after ~" + elapsed
                    + "ms; connection terminated");
        }

        // All other exceptions.
        log.logWarn("Search on " + url + " for " + pattern + " failed", mySessionTicket, e);
        return null;

    }

    // We just found at least one element. Did we get an ambigious result?
    SearchResult entry = null;
    try {
        entry = (SearchResult) results.next();
        String buffer = new String();
        while (results.hasMoreElements())
            buffer = buffer + ", " + ((SearchResult) results.next()).getName();
        if (!buffer.equals(""))
            log.logWarn("Search on " + url + " for " + pattern + " gave ambiguous result: [" + entry.getName()
                    + buffer + "]", mySessionTicket);
        // TODO: Throw BackendException, or a subclass, or just (as now)
        // pick the first and hope for the best?
        buffer = null;
    } catch (NamingException e) {
        throw new BackendException("Unable to read search results", e);
    }
    return entry.getName(); // Relative DN (to the reference).

}

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

/**
 * Have one or more classes or resources been modified so that a reload
 * is appropriate?//ww  w.j a v  a 2 s  .co  m
 */
public boolean modified() {

    if (log.isDebugEnabled())
        log.debug("modified()");

    // Checking for modified loaded resources
    int length = paths.length;

    // A rare race condition can occur in the updates of the two arrays
    // It's totally ok if the latest class added is not checked (it will
    // be checked the next time
    int length2 = lastModifiedDates.length;
    if (length > length2)
        length = length2;

    for (int i = 0; i < length; i++) {
        try {
            long lastModified = ((ResourceAttributes) resources.getAttributes(paths[i])).getLastModified();
            if (lastModified != lastModifiedDates[i]) {
                if (log.isDebugEnabled())
                    log.debug("  Resource '" + paths[i] + "' was modified; Date is now: "
                            + new java.util.Date(lastModified) + " Was: "
                            + new java.util.Date(lastModifiedDates[i]));
                return (true);
            }
        } catch (NamingException e) {
            log.error("    Resource '" + paths[i] + "' is missing");
            return (true);
        }
    }

    length = jarNames.length;

    // Check if JARs have been added or removed
    if (getJarPath() != null) {

        try {
            NamingEnumeration enum_ = resources.listBindings(getJarPath());
            int i = 0;
            while (enum_.hasMoreElements() && (i < length)) {
                NameClassPair ncPair = (NameClassPair) enum_.nextElement();
                String name = ncPair.getName();
                // Ignore non JARs present in the lib folder
                if (!name.endsWith(".jar"))
                    continue;
                if (!name.equals(jarNames[i])) {
                    // Missing JAR
                    log.info("    Additional JARs have been added : '" + name + "'");
                    return (true);
                }
                i++;
            }
            if (enum_.hasMoreElements()) {
                while (enum_.hasMoreElements()) {
                    NameClassPair ncPair = (NameClassPair) enum_.nextElement();
                    String name = ncPair.getName();
                    // Additional non-JAR files are allowed
                    if (name.endsWith(".jar")) {
                        // There was more JARs
                        log.info("    Additional JARs have been added");
                        return (true);
                    }
                }
            } else if (i < jarNames.length) {
                // There was less JARs
                log.info("    Additional JARs have been added");
                return (true);
            }
        } catch (NamingException e) {
            if (log.isDebugEnabled())
                log.debug("    Failed tracking modifications of '" + getJarPath() + "'");
        } catch (ClassCastException e) {
            log.error("    Failed tracking modifications of '" + getJarPath() + "' : " + e.getMessage());
        }

    }

    // No classes have been modified
    return (false);

}

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

/**
 * Return an InputStream to an HTML representation of the contents
 * of this directory.//from   ww  w  .j a  va 2  s.c om
 *
 * @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./*from   w w w. j a  v  a 2s. 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.catalina.startup.TldConfig.java

private void tldScanResourcePathsWebInf(DirContext resources, String rootPath, Set tldPaths)
        throws IOException {

    if (log.isTraceEnabled()) {
        log.trace("  Scanning TLDs in " + rootPath + " subdirectory");
    }/*from   w w w  .  j  a  v  a  2 s.c  om*/

    try {
        NamingEnumeration items = resources.list(rootPath);
        while (items.hasMoreElements()) {
            NameClassPair item = (NameClassPair) items.nextElement();
            String resourcePath = rootPath + "/" + item.getName();
            if (!resourcePath.endsWith(".tld") && (resourcePath.startsWith("/WEB-INF/classes")
                    || resourcePath.startsWith("/WEB-INF/lib"))) {
                continue;
            }
            if (resourcePath.endsWith(".tld")) {
                if (log.isTraceEnabled()) {
                    log.trace("   Adding path '" + resourcePath + "'");
                }
                tldPaths.add(resourcePath);
            } else {
                tldScanResourcePathsWebInf(resources, resourcePath, tldPaths);
            }
        }
    } catch (NamingException e) {
        ; // Silent catch: it's valid that no /WEB-INF directory exists
    }
}