Search in sources :

Example 51 with NameClassPair

use of javax.naming.NameClassPair in project Payara by payara.

the class WebappClassLoader method modified.

/**
 * Have one or more classes or resources been modified so that a reload
 * is appropriate?
 */
@Override
public boolean modified() {
    if (logger.isLoggable(Level.FINER)) {
        logger.log(Level.FINER, "modified()");
    }
    // Checking for modified loaded resources
    int pathsLength = 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 lastModifiedDatesLength = lastModifiedDates.length;
    if (pathsLength > lastModifiedDatesLength) {
        pathsLength = lastModifiedDatesLength;
    }
    for (int i = 0; i < pathsLength; i++) {
        try {
            long lastModified = ((ResourceAttributes) resources.getAttributes(paths[i])).getLastModified();
            if (lastModified != lastModifiedDates[i]) {
                if (logger.isLoggable(Level.FINER)) {
                    logger.log(Level.FINER, "  Resource ''{0}'' was modified; Date is now: {1} Was: {2}", new Object[] { paths[i], new java.util.Date(lastModified), new java.util.Date(lastModifiedDates[i]) });
                }
                return true;
            }
        } catch (NamingException e) {
            logger.log(Level.SEVERE, LogFacade.MISSING_RESOURCE, paths[i]);
            return true;
        }
    }
    pathsLength = jarNames.size();
    // Check if JARs have been added or removed
    if (getJarPath() != null) {
        try {
            NamingEnumeration<Binding> enumeration = resources.listBindings(getJarPath());
            int i = 0;
            while (enumeration.hasMoreElements() && (i < pathsLength)) {
                NameClassPair ncPair = enumeration.nextElement();
                String name = ncPair.getName();
                // START OF IASRI 4657979
                if (!name.endsWith(".jar") && !name.endsWith(".zip")) {
                    // END OF IASRI 4657979
                    continue;
                }
                if (!name.equals(jarNames.get(i))) {
                    // Missing JAR
                    logger.log(Level.FINER, "    Additional JARs have been added : ''{0}''", name);
                    return true;
                }
                i++;
            }
            if (enumeration.hasMoreElements()) {
                while (enumeration.hasMoreElements()) {
                    NameClassPair ncPair = enumeration.nextElement();
                    String name = ncPair.getName();
                    // START OF IASRI 4657979
                    if (name.endsWith(".jar") || name.endsWith(".zip")) {
                        // END OF IASRI 4657979
                        // There was more JARs
                        logger.log(Level.FINER, "    Additional JARs have been added");
                        return true;
                    }
                }
            } else if (i < jarNames.size()) {
                // There was less JARs
                logger.log(Level.FINER, "    Additional JARs have been added");
                return true;
            }
        } catch (NamingException e) {
            if (logger.isLoggable(Level.FINER)) {
                logger.log(Level.FINER, "    Failed tracking modifications of ''{0}''", getJarPath());
            }
        } catch (ClassCastException e) {
            logger.log(Level.SEVERE, LogFacade.FAILED_TRACKING_MODIFICATIONS, new Object[] { getJarPath(), e.getMessage() });
        }
    }
    // No classes have been modified
    return false;
}
Also used : Binding(javax.naming.Binding) java.util(java.util) NameClassPair(javax.naming.NameClassPair) NamingException(javax.naming.NamingException) ResourceAttributes(org.apache.naming.resources.ResourceAttributes)

Example 52 with NameClassPair

use of javax.naming.NameClassPair in project Payara by payara.

the class DefaultServlet method renderHtml.

private InputStream renderHtml(String contextPath, CacheEntry cacheEntry, ProxyDirContext proxyDirContext) throws IOException, ServletException {
    String name = cacheEntry.name;
    /*
        // 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);
    StringBuilder sb = new StringBuilder();
    // rewriteUrl(contextPath) is expensive. cache result for later reuse
    String rewrittenContextPath = rewriteUrl(contextPath);
    String dirTitle = MessageFormat.format(rb.getString(LogFacade.DIR_TITLE_INFO), name);
    // Render the page header
    sb.append("<html>\r\n");
    sb.append("<head>\r\n");
    sb.append("<title>");
    sb.append(dirTitle);
    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(dirTitle);
    // 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);
        String dirParent = MessageFormat.format(rb.getString(LogFacade.DIR_PARENT_INFO), parent);
        sb.append(" - <a href=\"");
        sb.append(rewrittenContextPath);
        if (parent.equals(""))
            parent = "/";
        sb.append(rewriteUrl(parent));
        if (!parent.endsWith("/"))
            sb.append("/");
        sb.append("\">");
        sb.append("<b>");
        sb.append(dirParent);
        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(rb.getString(LogFacade.DIR_FILENAME_INFO));
    sb.append("</strong></font></td>\r\n");
    sb.append("<td align=\"center\"><font size=\"+1\"><strong>");
    sb.append(rb.getString(LogFacade.DIR_SIZE_INFO));
    sb.append("</strong></font></td>\r\n");
    sb.append("<td align=\"right\"><font size=\"+1\"><strong>");
    sb.append(rb.getString(LogFacade.DIR_LAST_MODIFIED_INFO));
    sb.append("</strong></font></td>\r\n");
    sb.append("</tr>");
    try {
        // Render the directory entries within this directory
        Enumeration<NameClassPair> enumeration = proxyDirContext.list(cacheEntry.name);
        if (sortedBy.equals(SortedBy.LAST_MODIFIED)) {
            ArrayList<NameClassPair> list = Collections.list(enumeration);
            Comparator<NameClassPair> c = new LastModifiedComparator(proxyDirContext, cacheEntry.name);
            Collections.sort(list, c);
            enumeration = Collections.enumeration(list);
        } else if (sortedBy.equals(SortedBy.SIZE)) {
            ArrayList<NameClassPair> list = Collections.list(enumeration);
            Comparator<NameClassPair> c = new SizeComparator(proxyDirContext, cacheEntry.name);
            Collections.sort(list, c);
            enumeration = Collections.enumeration(list);
        }
        boolean shade = false;
        while (enumeration.hasMoreElements()) {
            NameClassPair ncPair = enumeration.nextElement();
            String resourceName = ncPair.getName();
            String trimmed = resourceName;
            if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF"))
                continue;
            CacheEntry childCacheEntry = proxyDirContext.lookupCache(cacheEntry.name + resourceName);
            if (!childCacheEntry.exists) {
                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(rewrittenContextPath);
            resourceName = rewriteUrl(name + resourceName);
            sb.append(resourceName);
            if (childCacheEntry.context != null)
                sb.append("/");
            sb.append("\"><tt>");
            sb.append(HtmlEntityEncoder.encodeXSS(trimmed));
            if (childCacheEntry.context != null)
                sb.append("/");
            sb.append("</tt></a></td>\r\n");
            sb.append("<td align=\"right\"><tt>");
            if (childCacheEntry.context != null)
                sb.append("&nbsp;");
            else
                sb.append(renderSize(childCacheEntry.attributes.getContentLength()));
            sb.append("</tt></td>\r\n");
            sb.append("<td align=\"right\"><tt>");
            sb.append(childCacheEntry.attributes.getLastModifiedHttp());
            sb.append("</tt></td>\r\n");
            sb.append("</tr>\r\n");
        }
    } catch (NamingException e) {
        // Something went wrong
        throw new ServletException("Error accessing resource", e);
    }
    // Render the page footer
    sb.append("</table>\r\n");
    sb.append("<HR size=\"1\" noshade=\"noshade\">");
    String readme = getReadme(cacheEntry.context);
    if (readme != null) {
        sb.append(readme);
        sb.append("<HR size=\"1\" noshade=\"noshade\">");
    }
    String serverInfo = ServerInfo.getPublicServerInfo();
    if (serverInfo != null && !serverInfo.isEmpty()) {
        sb.append("<h3>").append(serverInfo).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()));
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) CacheEntry(org.apache.naming.resources.CacheEntry) ServletException(javax.servlet.ServletException) NamingException(javax.naming.NamingException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) IOException(java.io.IOException) UnavailableException(javax.servlet.UnavailableException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ServletException(javax.servlet.ServletException) ByteArrayInputStream(java.io.ByteArrayInputStream) NameClassPair(javax.naming.NameClassPair) OutputStreamWriter(java.io.OutputStreamWriter) NamingException(javax.naming.NamingException) PrintWriter(java.io.PrintWriter)

Example 53 with NameClassPair

use of javax.naming.NameClassPair in project Payara by payara.

the class DefaultServlet method renderXml.

private InputStream renderXml(String contextPath, CacheEntry cacheEntry, Source xsltSource, ProxyDirContext proxyDirContext) throws IOException, ServletException {
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\"?>");
    sb.append("<listing ");
    sb.append(" contextPath='");
    sb.append(contextPath);
    sb.append("'");
    sb.append(" directory='");
    sb.append(cacheEntry.name);
    sb.append("' ");
    sb.append(" hasParent='").append(!cacheEntry.name.equals("/"));
    sb.append("'>");
    sb.append("<entries>");
    try {
        // Render the directory entries within this directory
        Enumeration<NameClassPair> enumeration = proxyDirContext.list(cacheEntry.name);
        if (sortedBy.equals(SortedBy.LAST_MODIFIED)) {
            ArrayList<NameClassPair> list = Collections.list(enumeration);
            Comparator<NameClassPair> c = new LastModifiedComparator(proxyDirContext, cacheEntry.name);
            Collections.sort(list, c);
            enumeration = Collections.enumeration(list);
        } else if (sortedBy.equals(SortedBy.SIZE)) {
            ArrayList<NameClassPair> list = Collections.list(enumeration);
            Comparator<NameClassPair> c = new SizeComparator(proxyDirContext, cacheEntry.name);
            Collections.sort(list, c);
            enumeration = Collections.enumeration(list);
        }
        // rewriteUrl(contextPath) is expensive. cache result for later reuse
        String rewrittenContextPath = rewriteUrl(contextPath);
        while (enumeration.hasMoreElements()) {
            NameClassPair ncPair = enumeration.nextElement();
            String resourceName = ncPair.getName();
            String trimmed = resourceName;
            if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF") || trimmed.equalsIgnoreCase(localXsltFile))
                continue;
            if ((cacheEntry.name + trimmed).equals(contextXsltFile))
                continue;
            CacheEntry childCacheEntry = proxyDirContext.lookupCache(cacheEntry.name + resourceName);
            if (!childCacheEntry.exists) {
                continue;
            }
            sb.append("<entry");
            sb.append(" type='").append((childCacheEntry.context != null) ? "dir" : "file").append("'");
            sb.append(" urlPath='").append(rewrittenContextPath).append(rewriteUrl(cacheEntry.name + resourceName)).append((childCacheEntry.context != null) ? "/" : "").append("'");
            if (childCacheEntry.resource != null) {
                sb.append(" size='").append(renderSize(childCacheEntry.attributes.getContentLength())).append("'");
            }
            sb.append(" date='").append(childCacheEntry.attributes.getLastModifiedHttp()).append("'");
            sb.append(">");
            sb.append(HtmlEntityEncoder.encodeXSS(trimmed));
            if (childCacheEntry.context != null)
                sb.append("/");
            sb.append("</entry>");
        }
    } catch (NamingException e) {
        // Something went wrong
        throw new ServletException("Error accessing resource", e);
    }
    sb.append("</entries>");
    String readme = getReadme(cacheEntry.context);
    if (readme != null) {
        sb.append("<readme><![CDATA[");
        sb.append(readme);
        sb.append("]]></readme>");
    }
    sb.append("</listing>");
    // Prevent possible memory leak. Ensure Transformer and
    // TransformerFactory are not loaded from the web application.
    ClassLoader original;
    if (Globals.IS_SECURITY_ENABLED) {
        PrivilegedGetTccl pa = new PrivilegedGetTccl();
        original = AccessController.doPrivileged(pa);
    } else {
        original = Thread.currentThread().getContextClassLoader();
    }
    try {
        if (Globals.IS_SECURITY_ENABLED) {
            PrivilegedSetTccl pa = new PrivilegedSetTccl(DefaultServlet.class.getClassLoader());
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(DefaultServlet.class.getClassLoader());
        }
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Source xmlSource = new StreamSource(new StringReader(sb.toString()));
        Transformer transformer = tFactory.newTransformer(xsltSource);
        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, cacheEntry);
    } finally {
        if (Globals.IS_SECURITY_ENABLED) {
            PrivilegedSetTccl pa = new PrivilegedSetTccl(original);
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(original);
        }
    }
}
Also used : Transformer(javax.xml.transform.Transformer) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) ServletException(javax.servlet.ServletException) StringReader(java.io.StringReader) NamingException(javax.naming.NamingException) PrivilegedSetTccl(org.apache.tomcat.util.security.PrivilegedSetTccl) TransformerFactory(javax.xml.transform.TransformerFactory) StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CacheEntry(org.apache.naming.resources.CacheEntry) ServletException(javax.servlet.ServletException) NamingException(javax.naming.NamingException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) IOException(java.io.IOException) UnavailableException(javax.servlet.UnavailableException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ByteArrayInputStream(java.io.ByteArrayInputStream) NameClassPair(javax.naming.NameClassPair) PrivilegedGetTccl(org.apache.tomcat.util.security.PrivilegedGetTccl) OutputStreamWriter(java.io.OutputStreamWriter)

Example 54 with NameClassPair

use of javax.naming.NameClassPair in project Payara by payara.

the class DirContextURLConnection method list.

// --------------------------------------------------------- Public Methods
/**
 * List children of this collection. The names given are relative to this
 * URI's path. The full uri of the children is then : path + "/" + name.
 */
public Enumeration<String> list() throws IOException {
    if (!connected) {
        connect();
    }
    if ((resource == null) && (collection == null)) {
        throw new FileNotFoundException((getURL() == null) ? "null" : getURL().toString());
    }
    Vector<String> result = new Vector<String>();
    if (collection != null) {
        try {
            NamingEnumeration<NameClassPair> enumeration = context.list(getURL().getFile());
            while (enumeration.hasMoreElements()) {
                NameClassPair ncp = enumeration.nextElement();
                result.addElement(URLEncoder.encode(ncp.getName(), "UTF-8"));
            }
        } catch (NamingException e) {
            // Unexpected exception
            throw new FileNotFoundException((getURL() == null) ? "null" : getURL().toString());
        }
    }
    return result.elements();
}
Also used : NameClassPair(javax.naming.NameClassPair) FileNotFoundException(java.io.FileNotFoundException) NamingException(javax.naming.NamingException) Vector(java.util.Vector)

Example 55 with NameClassPair

use of javax.naming.NameClassPair in project wildfly by wildfly.

the class JndiViewOperation method addEntries.

private void addEntries(final ModelNode current, final Context context) throws NamingException {
    final NamingEnumeration<NameClassPair> entries = context.list("");
    while (entries.hasMore()) {
        final NameClassPair pair = entries.next();
        final ModelNode node = current.get(pair.getName());
        node.get("class-name").set(pair.getClassName());
        try {
            final Object value;
            if (context instanceof NamingContext) {
                value = ((NamingContext) context).lookup(pair.getName(), false);
            } else {
                value = context.lookup(pair.getName());
            }
            if (value instanceof Context) {
                addEntries(node.get("children"), Context.class.cast(value));
            } else if (value instanceof Reference) {
            // node.get("value").set(value.toString());
            } else {
                String jndiViewValue = JndiViewManagedReferenceFactory.DEFAULT_JNDI_VIEW_INSTANCE_VALUE;
                if (value instanceof JndiViewManagedReferenceFactory) {
                    try {
                        jndiViewValue = JndiViewManagedReferenceFactory.class.cast(value).getJndiViewInstanceValue();
                    } catch (Throwable e) {
                        // just log, don't stop the operation
                        NamingLogger.ROOT_LOGGER.failedToLookupJndiViewValue(pair.getName(), e);
                    }
                } else if (!(value instanceof ManagedReferenceFactory)) {
                    jndiViewValue = String.valueOf(value);
                }
                node.get("value").set(jndiViewValue);
            }
        } catch (NamingException e) {
            // just log, don't stop the operation
            NamingLogger.ROOT_LOGGER.failedToLookupJndiViewValue(pair.getName(), e);
        }
    }
}
Also used : OperationContext(org.jboss.as.controller.OperationContext) NamingContext(org.jboss.as.naming.NamingContext) Context(javax.naming.Context) NameClassPair(javax.naming.NameClassPair) Reference(javax.naming.Reference) ManagedReferenceFactory(org.jboss.as.naming.ManagedReferenceFactory) JndiViewManagedReferenceFactory(org.jboss.as.naming.JndiViewManagedReferenceFactory) NamingException(javax.naming.NamingException) ModelNode(org.jboss.dmr.ModelNode) NamingContext(org.jboss.as.naming.NamingContext) JndiViewManagedReferenceFactory(org.jboss.as.naming.JndiViewManagedReferenceFactory)

Aggregations

NameClassPair (javax.naming.NameClassPair)60 NamingException (javax.naming.NamingException)28 DirContext (javax.naming.directory.DirContext)19 Test (org.junit.Test)17 HashSet (java.util.HashSet)13 Context (javax.naming.Context)11 InitialContext (javax.naming.InitialContext)10 Hashtable (java.util.Hashtable)9 NamingEnumeration (javax.naming.NamingEnumeration)8 InitialDirContext (javax.naming.directory.InitialDirContext)8 IOException (java.io.IOException)7 FileNotFoundException (java.io.FileNotFoundException)5 HashMap (java.util.HashMap)5 Vector (java.util.Vector)5 Resource (org.apache.naming.resources.Resource)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 OutputStreamWriter (java.io.OutputStreamWriter)4 CompositeName (javax.naming.CompositeName)4 File (java.io.File)3