Search in sources :

Example 1 with CacheEntry

use of org.apache.naming.resources.CacheEntry in project Payara by payara.

the class DefaultServlet method serveResource.

/**
 * Serve the specified resource, optionally including the data content.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param content Should the content be included?
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 */
protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException {
    // Identify the requested resource path
    String path = getRelativePath(request);
    if (debug > 0) {
        if (content)
            log("DefaultServlet.serveResource:  Serving resource '" + path + "' headers and data");
        else
            log("DefaultServlet.serveResource:  Serving resource '" + path + "' headers only");
    }
    CacheEntry cacheEntry = null;
    ProxyDirContext proxyDirContext = resources;
    if (alternateDocBases == null || alternateDocBases.size() == 0) {
        cacheEntry = proxyDirContext.lookupCache(path);
    } else {
        AlternateDocBase match = AlternateDocBase.findMatch(path, alternateDocBases);
        if (match != null) {
            cacheEntry = ((ProxyDirContext) ContextsAdapterUtility.unwrap(match.getResources())).lookupCache(path);
        } else {
            // None of the url patterns for alternate docbases matched
            cacheEntry = proxyDirContext.lookupCache(path);
        }
    }
    if (!cacheEntry.exists) {
        // Check if we're included so we can return the appropriate
        // missing resource name in the error
        String requestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);
        /* IASRI 4878272 
            if (requestUri == null) {
                requestUri = request.getRequestURI();
            } else {
            */
        if (requestUri != null) {
            /*
                 * We're included, and the response.sendError() below is going
                 * to be ignored by the including resource (see SRV.8.3,
                 * "The Include Method").
                 * Therefore, the only way we can let the including resource
                 * know about the missing resource is by throwing an 
                 * exception
                */
            throw new FileNotFoundException(requestUri);
        }
        /* IASRI 4878272
            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                               requestUri);
            */
        // BEGIN IASRI 4878272
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        // END IASRI 4878272
        return;
    }
    // ends with "/" or "\", return NOT FOUND
    if (cacheEntry.context == null) {
        if (path.endsWith("/") || (path.endsWith("\\"))) {
            /* IASRI 4878272
                // Check if we're included so we can return the appropriate 
                // missing resource name in the error
                String requestUri = (String) request.getAttribute(
                    RequestDispatcher.INCLUDE_REQUEST_URI);
                if (requestUri == null) {
                    requestUri = request.getRequestURI();
                }
                 response.sendError(HttpServletResponse.SC_NOT_FOUND,
                                    requestUri);
                */
            // BEGIN IASRI 4878272
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            // END IASRI 4878272
            return;
        }
    }
    // satisfied.
    if (cacheEntry.context == null) {
        // Checking If headers
        boolean included = (request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH) != null);
        if (!included && !checkIfHeaders(request, response, cacheEntry.attributes)) {
            return;
        }
    }
    // Find content type.
    String contentType = cacheEntry.attributes.getMimeType();
    if (contentType == null && !cacheEntry.attributes.isMimeTypeInitialized()) {
        contentType = getServletContext().getMimeType(cacheEntry.name);
        cacheEntry.attributes.setMimeType(contentType);
    }
    ArrayList<Range> ranges = null;
    long contentLength = -1L;
    if (cacheEntry.context != null) {
        // suppress them
        if (!listings) {
            /* IASRI 4878272
                 response.sendError(HttpServletResponse.SC_NOT_FOUND,
                                    request.getRequestURI());
                */
            // BEGIN IASRI 4878272
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            // END IASRI 4878272
            return;
        }
        contentType = "text/html;charset=UTF-8";
    } else {
        if (useAcceptRanges) {
            // Accept ranges header
            response.setHeader("Accept-Ranges", "bytes");
        }
        // Parse range specifier
        ranges = parseRange(request, response, cacheEntry.attributes);
        // ETag header
        response.setHeader("ETag", cacheEntry.attributes.getETag());
        // Last-Modified header
        response.setHeader("Last-Modified", cacheEntry.attributes.getLastModifiedHttp());
        // Get content length
        contentLength = cacheEntry.attributes.getContentLength();
        // (silent) ISE when setting the output buffer size
        if (contentLength == 0L) {
            content = false;
        }
    }
    ServletOutputStream ostream = null;
    PrintWriter writer = null;
    if (content) {
        try {
            ostream = response.getOutputStream();
        } catch (IllegalStateException e) {
            // trying to serve a text file
            if ((contentType == null) || (contentType.startsWith("text")) || (contentType.startsWith("xml"))) {
                writer = response.getWriter();
            } else {
                throw e;
            }
        }
    }
    if ((cacheEntry.context != null) || (((ranges == null) || (ranges.isEmpty())) && (request.getHeader("Range") == null)) || (ranges == FULL)) {
        // Set the appropriate output headers
        if (contentType != null) {
            if (debug > 0)
                log("DefaultServlet.serveFile:  contentType='" + contentType + "'");
            response.setContentType(contentType);
        }
        if ((cacheEntry.resource != null) && (contentLength >= 0)) {
            if (debug > 0)
                log("DefaultServlet.serveFile:  contentLength=" + contentLength);
            if (contentLength < Integer.MAX_VALUE) {
                response.setContentLength((int) contentLength);
            } else {
                // Set the content-length as String to be able to use a long
                response.setHeader("content-length", "" + contentLength);
            }
        }
        InputStream renderResult = null;
        if (cacheEntry.context != null) {
            if (content) {
                // Serve the directory browser
                renderResult = render(request.getContextPath(), cacheEntry, proxyDirContext);
            }
        }
        // Copy the input stream to our output stream (if requested)
        if (content) {
            try {
                response.setBufferSize(output);
            } catch (IllegalStateException e) {
            // Silent catch
            }
            if (ostream != null) {
                if (!checkSendfile(request, response, cacheEntry, contentLength, null))
                    copy(cacheEntry, renderResult, ostream);
            } else {
                copy(cacheEntry, renderResult, writer);
            }
        }
    } else {
        if ((ranges == null) || (ranges.isEmpty()))
            return;
        if (maxHeaderRangeItems >= 0 && ranges.size() > maxHeaderRangeItems) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        // Partial content response.
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        if (ranges.size() == 1) {
            Range range = ranges.get(0);
            response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length);
            long length = range.end - range.start + 1;
            if (length < Integer.MAX_VALUE) {
                response.setContentLength((int) length);
            } else {
                // Set the content-length as String to be able to use a long
                response.setHeader("content-length", "" + length);
            }
            if (contentType != null) {
                if (debug > 0)
                    log("DefaultServlet.serveFile:  contentType='" + contentType + "'");
                response.setContentType(contentType);
            }
            if (content) {
                try {
                    response.setBufferSize(output);
                } catch (IllegalStateException e) {
                // Silent catch
                }
                if (ostream != null) {
                    if (!checkSendfile(request, response, cacheEntry, range.end - range.start + 1, range))
                        copy(cacheEntry, ostream, range);
                } else {
                    copy(cacheEntry, writer, range);
                }
            }
        } else {
            response.setContentType("multipart/byteranges; boundary=" + mimeSeparation);
            if (content) {
                try {
                    response.setBufferSize(output);
                } catch (IllegalStateException e) {
                // Silent catch
                }
                if (ostream != null) {
                    copy(cacheEntry, ostream, ranges.iterator(), contentType);
                } else {
                    copy(cacheEntry, writer, ranges.iterator(), contentType);
                }
            }
        }
    }
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) CacheEntry(org.apache.naming.resources.CacheEntry) AlternateDocBase(org.glassfish.grizzly.http.server.util.AlternateDocBase) ProxyDirContext(org.apache.naming.resources.ProxyDirContext) PrintWriter(java.io.PrintWriter)

Example 2 with CacheEntry

use of org.apache.naming.resources.CacheEntry in project tomcat70 by apache.

the class DefaultServlet method renderHtml.

/**
 * Return an InputStream to an HTML representation of the contents
 * of this directory.
 *
 * @param contextPath Context path to which our internal paths are
 *  relative
 */
protected InputStream renderHtml(String contextPath, CacheEntry cacheEntry) throws IOException, ServletException {
    String name = cacheEntry.name;
    // Prepare a writer to a buffered area
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8");
    PrintWriter writer = new PrintWriter(osWriter);
    StringBuilder sb = new StringBuilder();
    // rewriteUrl(contextPath) is expensive. cache result for later reuse
    String rewrittenContextPath = rewriteUrl(contextPath);
    // 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(rewrittenContextPath);
        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
        NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name);
        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 = resources.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(RequestUtil.filter(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\">");
    }
    if (showServerInfo) {
        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()));
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) CacheEntry(org.apache.naming.resources.CacheEntry) 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 3 with CacheEntry

use of org.apache.naming.resources.CacheEntry 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 4 with CacheEntry

use of org.apache.naming.resources.CacheEntry 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 5 with CacheEntry

use of org.apache.naming.resources.CacheEntry in project Payara by payara.

the class WebdavStatus method parseProperties.

/**
 * Propfind helper method.
 *
 * @param req The servlet request
 * @param generatedXML XML response to the Propfind request
 * @param path Path of the current resource
 * @param type Propfind type
 * @param propertiesVector If the propfind type is find properties by
 * name, then this Vector contains those properties
 */
private void parseProperties(HttpServletRequest req, XMLWriter generatedXML, String path, int type, Vector<String> propertiesVector) {
    // (the "toUpperCase()" avoids problems on Windows systems)
    if (path.toUpperCase(Locale.ENGLISH).startsWith("/WEB-INF") || path.toUpperCase(Locale.ENGLISH).startsWith("/META-INF"))
        return;
    CacheEntry cacheEntry = resources.lookupCache(path);
    generatedXML.writeElement(null, "response", XMLWriter.OPENING);
    String status = "HTTP/1.1 " + WebdavStatus.SC_OK + " " + WebdavStatus.getStatusText(WebdavStatus.SC_OK);
    // Generating href element
    generatedXML.writeElement(null, "href", XMLWriter.OPENING);
    String href = req.getContextPath() + req.getServletPath();
    if (href.endsWith("/") && path.startsWith("/"))
        href += path.substring(1);
    else
        href += path;
    if (cacheEntry.context != null && !href.endsWith("/"))
        href += "/";
    generatedXML.writeText(rewriteUrl(href));
    generatedXML.writeElement(null, "href", XMLWriter.CLOSING);
    String resourceName = path;
    int lastSlash = path.lastIndexOf('/');
    if (lastSlash != -1)
        resourceName = resourceName.substring(lastSlash + 1);
    switch(type) {
        case FIND_ALL_PROP:
            generatedXML.writeElement(null, "propstat", XMLWriter.OPENING);
            generatedXML.writeElement(null, "prop", XMLWriter.OPENING);
            generatedXML.writeProperty(null, "creationdate", getISOCreationDate(cacheEntry.attributes.getCreation()));
            generatedXML.writeElement(null, "displayname", XMLWriter.OPENING);
            generatedXML.writeData(resourceName);
            generatedXML.writeElement(null, "displayname", XMLWriter.CLOSING);
            if (cacheEntry.resource != null) {
                generatedXML.writeProperty(null, "getlastmodified", FastHttpDateFormat.formatDate(cacheEntry.attributes.getLastModified(), null));
                generatedXML.writeProperty(null, "getcontentlength", String.valueOf(cacheEntry.attributes.getContentLength()));
                String contentType = getServletContext().getMimeType(cacheEntry.name);
                if (contentType != null) {
                    generatedXML.writeProperty(null, "getcontenttype", contentType);
                }
                generatedXML.writeProperty(null, "getetag", cacheEntry.attributes.getETag());
                generatedXML.writeElement(null, "resourcetype", XMLWriter.NO_CONTENT);
            } else {
                generatedXML.writeElement(null, "resourcetype", XMLWriter.OPENING);
                generatedXML.writeElement(null, "collection", XMLWriter.NO_CONTENT);
                generatedXML.writeElement(null, "resourcetype", XMLWriter.CLOSING);
            }
            generatedXML.writeProperty(null, "source", "");
            String supportedLocks = "<lockentry>" + "<lockscope><exclusive/></lockscope>" + "<locktype><write/></locktype>" + "</lockentry>" + "<lockentry>" + "<lockscope><shared/></lockscope>" + "<locktype><write/></locktype>" + "</lockentry>";
            generatedXML.writeElement(null, "supportedlock", XMLWriter.OPENING);
            generatedXML.writeText(supportedLocks);
            generatedXML.writeElement(null, "supportedlock", XMLWriter.CLOSING);
            generateLockDiscovery(path, generatedXML);
            generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);
            generatedXML.writeElement(null, "status", XMLWriter.OPENING);
            generatedXML.writeText(status);
            generatedXML.writeElement(null, "status", XMLWriter.CLOSING);
            generatedXML.writeElement(null, "propstat", XMLWriter.CLOSING);
            break;
        case FIND_PROPERTY_NAMES:
            generatedXML.writeElement(null, "propstat", XMLWriter.OPENING);
            generatedXML.writeElement(null, "prop", XMLWriter.OPENING);
            generatedXML.writeElement(null, "creationdate", XMLWriter.NO_CONTENT);
            generatedXML.writeElement(null, "displayname", XMLWriter.NO_CONTENT);
            if (cacheEntry.resource != null) {
                generatedXML.writeElement(null, "getcontentlanguage", XMLWriter.NO_CONTENT);
                generatedXML.writeElement(null, "getcontentlength", XMLWriter.NO_CONTENT);
                generatedXML.writeElement(null, "getcontenttype", XMLWriter.NO_CONTENT);
                generatedXML.writeElement(null, "getetag", XMLWriter.NO_CONTENT);
                generatedXML.writeElement(null, "getlastmodified", XMLWriter.NO_CONTENT);
            }
            generatedXML.writeElement(null, "resourcetype", XMLWriter.NO_CONTENT);
            generatedXML.writeElement(null, "source", XMLWriter.NO_CONTENT);
            generatedXML.writeElement(null, "lockdiscovery", XMLWriter.NO_CONTENT);
            generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);
            generatedXML.writeElement(null, "status", XMLWriter.OPENING);
            generatedXML.writeText(status);
            generatedXML.writeElement(null, "status", XMLWriter.CLOSING);
            generatedXML.writeElement(null, "propstat", XMLWriter.CLOSING);
            break;
        case FIND_BY_PROPERTY:
            Vector<String> propertiesNotFound = new Vector<String>();
            // Parse the list of properties
            generatedXML.writeElement(null, "propstat", XMLWriter.OPENING);
            generatedXML.writeElement(null, "prop", XMLWriter.OPENING);
            Enumeration<String> properties = propertiesVector.elements();
            while (properties.hasMoreElements()) {
                String property = properties.nextElement();
                if ("creationdate".equals(property)) {
                    generatedXML.writeProperty(null, "creationdate", getISOCreationDate(cacheEntry.attributes.getCreation()));
                } else if ("displayname".equals(property)) {
                    generatedXML.writeElement(null, "displayname", XMLWriter.OPENING);
                    generatedXML.writeData(resourceName);
                    generatedXML.writeElement(null, "displayname", XMLWriter.CLOSING);
                } else if ("getcontentlanguage".equals(property)) {
                    if (cacheEntry.context != null) {
                        propertiesNotFound.addElement(property);
                    } else {
                        generatedXML.writeElement(null, "getcontentlanguage", XMLWriter.NO_CONTENT);
                    }
                } else if ("getcontentlength".equals(property)) {
                    if (cacheEntry.context != null) {
                        propertiesNotFound.addElement(property);
                    } else {
                        generatedXML.writeProperty(null, "getcontentlength", String.valueOf(cacheEntry.attributes.getContentLength()));
                    }
                } else if ("getcontenttype".equals(property)) {
                    if (cacheEntry.context != null) {
                        propertiesNotFound.addElement(property);
                    } else {
                        generatedXML.writeProperty(null, "getcontenttype", getServletContext().getMimeType(cacheEntry.name));
                    }
                } else if ("getetag".equals(property)) {
                    if (cacheEntry.context != null) {
                        propertiesNotFound.addElement(property);
                    } else {
                        generatedXML.writeProperty(null, "getetag", cacheEntry.attributes.getETag());
                    }
                } else if ("getlastmodified".equals(property)) {
                    if (cacheEntry.context != null) {
                        propertiesNotFound.addElement(property);
                    } else {
                        generatedXML.writeProperty(null, "getlastmodified", FastHttpDateFormat.formatDate(cacheEntry.attributes.getLastModified(), null));
                    }
                } else if ("resourcetype".equals(property)) {
                    if (cacheEntry.context != null) {
                        generatedXML.writeElement(null, "resourcetype", XMLWriter.OPENING);
                        generatedXML.writeElement(null, "collection", XMLWriter.NO_CONTENT);
                        generatedXML.writeElement(null, "resourcetype", XMLWriter.CLOSING);
                    } else {
                        generatedXML.writeElement(null, "resourcetype", XMLWriter.NO_CONTENT);
                    }
                } else if ("source".equals(property)) {
                    generatedXML.writeProperty(null, "source", "");
                } else if ("supportedlock".equals(property)) {
                    supportedLocks = "<lockentry>" + "<lockscope><exclusive/></lockscope>" + "<locktype><write/></locktype>" + "</lockentry>" + "<lockentry>" + "<lockscope><shared/></lockscope>" + "<locktype><write/></locktype>" + "</lockentry>";
                    generatedXML.writeElement(null, "supportedlock", XMLWriter.OPENING);
                    generatedXML.writeText(supportedLocks);
                    generatedXML.writeElement(null, "supportedlock", XMLWriter.CLOSING);
                } else if ("lockdiscovery".equals(property)) {
                    if (!generateLockDiscovery(path, generatedXML))
                        propertiesNotFound.addElement(property);
                } else {
                    propertiesNotFound.addElement(property);
                }
            }
            generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);
            generatedXML.writeElement(null, "status", XMLWriter.OPENING);
            generatedXML.writeText(status);
            generatedXML.writeElement(null, "status", XMLWriter.CLOSING);
            generatedXML.writeElement(null, "propstat", XMLWriter.CLOSING);
            Enumeration<String> propertiesNotFoundList = propertiesNotFound.elements();
            if (propertiesNotFoundList.hasMoreElements()) {
                status = "HTTP/1.1 " + WebdavStatus.SC_NOT_FOUND + " " + WebdavStatus.getStatusText(WebdavStatus.SC_NOT_FOUND);
                generatedXML.writeElement(null, "propstat", XMLWriter.OPENING);
                generatedXML.writeElement(null, "prop", XMLWriter.OPENING);
                while (propertiesNotFoundList.hasMoreElements()) {
                    generatedXML.writeElement(null, propertiesNotFoundList.nextElement(), XMLWriter.NO_CONTENT);
                }
                generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);
                generatedXML.writeElement(null, "status", XMLWriter.OPENING);
                generatedXML.writeText(status);
                generatedXML.writeElement(null, "status", XMLWriter.CLOSING);
                generatedXML.writeElement(null, "propstat", XMLWriter.CLOSING);
            }
            break;
        default:
            // not possible
            break;
    }
    generatedXML.writeElement(null, "response", XMLWriter.CLOSING);
}
Also used : CacheEntry(org.apache.naming.resources.CacheEntry) Vector(java.util.Vector)

Aggregations

CacheEntry (org.apache.naming.resources.CacheEntry)8 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 FileNotFoundException (java.io.FileNotFoundException)4 OutputStreamWriter (java.io.OutputStreamWriter)4 PrintWriter (java.io.PrintWriter)4 NameClassPair (javax.naming.NameClassPair)4 NamingException (javax.naming.NamingException)4 ServletException (javax.servlet.ServletException)4 BufferedInputStream (java.io.BufferedInputStream)2 FileInputStream (java.io.FileInputStream)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 StringReader (java.io.StringReader)2 Vector (java.util.Vector)2 ServletOutputStream (javax.servlet.ServletOutputStream)2 UnavailableException (javax.servlet.UnavailableException)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 Source (javax.xml.transform.Source)2 Transformer (javax.xml.transform.Transformer)2