Search in sources :

Example 1 with WebResource

use of org.apache.catalina.WebResource in project fess by codelibs.

the class FessWebResourceRoot method processWebInfLib.

@Override
protected void processWebInfLib() throws LifecycleException {
    super.processWebInfLib();
    final WebResource[] possibleJars = listResources("/WEB-INF/plugin", false);
    for (final WebResource possibleJar : possibleJars) {
        if (possibleJar.isFile() && possibleJar.getName().endsWith(".jar")) {
            try (final JarFile jarFile = new JarFile(possibleJar.getCanonicalPath())) {
                final Manifest manifest = jarFile.getManifest();
                if (manifest != null && manifest.getEntries() != null) {
                    final Attributes attributes = manifest.getMainAttributes();
                    if (attributes != null && (attributes.get("Fess-WebAppJar") != null || attributes.getValue("Fess-WebAppJar") != null)) {
                        createWebResourceSet(ResourceSetType.CLASSES_JAR, "/WEB-INF/classes", possibleJar.getURL(), "/");
                    }
                }
            } catch (final Exception e) {
                logger.log(Level.WARNING, "Failed to read " + possibleJar, e);
            }
        }
    }
}
Also used : Attributes(java.util.jar.Attributes) WebResource(org.apache.catalina.WebResource) JarFile(java.util.jar.JarFile) Manifest(java.util.jar.Manifest) LifecycleException(org.apache.catalina.LifecycleException)

Example 2 with WebResource

use of org.apache.catalina.WebResource in project tomee by apache.

the class DefaultServlet method renderXml.

/**
 * Return an InputStream to an XML representation of the contents this
 * directory.
 *
 * @param request     The HttpServletRequest being served
 * @param contextPath Context path to which our internal paths are relative
 * @param resource    The associated resource
 * @param xsltSource  The XSL stylesheet
 * @param encoding    The encoding to use to process the readme (if any)
 *
 * @return the XML data
 *
 * @throws IOException an IO error occurred
 * @throws ServletException rendering error
 */
protected InputStream renderXml(HttpServletRequest request, String contextPath, WebResource resource, Source xsltSource, String encoding) 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(resource.getName());
    sb.append("' ");
    sb.append(" hasParent='").append(!resource.getName().equals("/"));
    sb.append("'>");
    sb.append("<entries>");
    String[] entries = resources.list(resource.getWebappPath());
    // rewriteUrl(contextPath) is expensive. cache result for later reuse
    String rewrittenContextPath = rewriteUrl(contextPath);
    String directoryWebappPath = resource.getWebappPath();
    for (String entry : entries) {
        if (entry.equalsIgnoreCase("WEB-INF") || entry.equalsIgnoreCase("META-INF") || entry.equalsIgnoreCase(localXsltFile))
            continue;
        if ((directoryWebappPath + entry).equals(contextXsltFile))
            continue;
        WebResource childResource = resources.getResource(directoryWebappPath + entry);
        if (!childResource.exists()) {
            continue;
        }
        sb.append("<entry");
        sb.append(" type='").append(childResource.isDirectory() ? "dir" : "file").append('\'');
        sb.append(" urlPath='").append(rewrittenContextPath).append(rewriteUrl(directoryWebappPath + entry)).append(childResource.isDirectory() ? "/" : "").append('\'');
        if (childResource.isFile()) {
            sb.append(" size='").append(renderSize(childResource.getContentLength())).append('\'');
        }
        sb.append(" date='").append(childResource.getLastModifiedHttp()).append('\'');
        sb.append('>');
        sb.append(Escape.htmlElementContent(entry));
        if (childResource.isDirectory())
            sb.append('/');
        sb.append("</entry>");
    }
    sb.append("</entries>");
    String readme = getReadme(resource, encoding);
    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, StandardCharsets.UTF_8);
        StreamResult out = new StreamResult(osWriter);
        transformer.transform(xmlSource, out);
        osWriter.flush();
        return new ByteArrayInputStream(stream.toByteArray());
    } catch (TransformerException e) {
        throw new ServletException(sm.getString("defaultServlet.xslError"), e);
    } finally {
        if (Globals.IS_SECURITY_ENABLED) {
            PrivilegedSetTccl pa = new PrivilegedSetTccl(original);
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(original);
        }
    }
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) WebResource(org.apache.catalina.WebResource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) 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) ByteArrayInputStream(java.io.ByteArrayInputStream) PrivilegedGetTccl(org.apache.tomcat.util.security.PrivilegedGetTccl) StringReader(java.io.StringReader) OutputStreamWriter(java.io.OutputStreamWriter) TransformerException(javax.xml.transform.TransformerException) PrivilegedSetTccl(org.apache.tomcat.util.security.PrivilegedSetTccl)

Example 3 with WebResource

use of org.apache.catalina.WebResource in project tomee by apache.

the class DefaultServlet method getReadme.

/**
 * Get the readme file as a string.
 * @param directory The directory to search
 * @param encoding The readme encoding
 * @return the readme for the specified directory
 */
protected String getReadme(WebResource directory, String encoding) {
    if (readmeFile != null) {
        WebResource resource = resources.getResource(directory.getWebappPath() + readmeFile);
        if (resource.isFile()) {
            StringWriter buffer = new StringWriter();
            InputStreamReader reader = null;
            try (InputStream is = resource.getInputStream()) {
                if (encoding != null) {
                    reader = new InputStreamReader(is, encoding);
                } else {
                    reader = new InputStreamReader(is);
                }
                copyRange(reader, new PrintWriter(buffer));
            } catch (IOException e) {
                log(sm.getString("defaultServlet.readerCloseFailed"), e);
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                    }
                }
            }
            return buffer.toString();
        } else {
            if (debug > 10)
                log("readme '" + readmeFile + "' not found");
            return null;
        }
    }
    return null;
}
Also used : StringWriter(java.io.StringWriter) InputStreamReader(java.io.InputStreamReader) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) WebResource(org.apache.catalina.WebResource) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter)

Example 4 with WebResource

use of org.apache.catalina.WebResource in project tomee by apache.

the class DefaultServlet method executePartialPut.

/**
 * Handle a partial PUT.  New content specified in request is appended to
 * existing content in oldRevisionContent (if present). This code does
 * not support simultaneous partial updates to the same resource.
 * @param req The Servlet request
 * @param range The range that will be written
 * @param path The path
 * @return the associated file object
 * @throws IOException an IO error occurred
 */
protected File executePartialPut(HttpServletRequest req, Range range, String path) throws IOException {
    // Append data specified in ranges to existing content for this
    // resource - create a temp. file on the local filesystem to
    // perform this operation
    File tempDir = (File) getServletContext().getAttribute(ServletContext.TEMPDIR);
    // Convert all '/' characters to '.' in resourcePath
    String convertedResourcePath = path.replace('/', '.');
    File contentFile = new File(tempDir, convertedResourcePath);
    if (contentFile.createNewFile()) {
        // Clean up contentFile when Tomcat is terminated
        contentFile.deleteOnExit();
    }
    try (RandomAccessFile randAccessContentFile = new RandomAccessFile(contentFile, "rw")) {
        WebResource oldResource = resources.getResource(path);
        // Copy data in oldRevisionContent to contentFile
        if (oldResource.isFile()) {
            try (BufferedInputStream bufOldRevStream = new BufferedInputStream(oldResource.getInputStream(), BUFFER_SIZE)) {
                int numBytesRead;
                byte[] copyBuffer = new byte[BUFFER_SIZE];
                while ((numBytesRead = bufOldRevStream.read(copyBuffer)) != -1) {
                    randAccessContentFile.write(copyBuffer, 0, numBytesRead);
                }
            }
        }
        randAccessContentFile.setLength(range.length);
        // Append data in request input stream to contentFile
        randAccessContentFile.seek(range.start);
        int numBytesRead;
        byte[] transferBuffer = new byte[BUFFER_SIZE];
        try (BufferedInputStream requestBufInStream = new BufferedInputStream(req.getInputStream(), BUFFER_SIZE)) {
            while ((numBytesRead = requestBufInStream.read(transferBuffer)) != -1) {
                randAccessContentFile.write(transferBuffer, 0, numBytesRead);
            }
        }
    }
    return contentFile;
}
Also used : RandomAccessFile(java.io.RandomAccessFile) BufferedInputStream(java.io.BufferedInputStream) WebResource(org.apache.catalina.WebResource) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 5 with WebResource

use of org.apache.catalina.WebResource in project tomcat by apache.

the class CachedResource method validateResource.

protected boolean validateResource(boolean useClassLoaderResources) {
    // resource.
    if (usesClassLoaderResources != useClassLoaderResources) {
        return false;
    }
    long now = System.currentTimeMillis();
    if (webResource == null) {
        synchronized (this) {
            if (webResource == null) {
                webResource = root.getResourceInternal(webAppPath, useClassLoaderResources);
                getLastModified();
                getContentLength();
                nextCheck = ttl + now;
                // use the fact that we know if it exists at this point
                if (webResource instanceof EmptyResource) {
                    cachedExists = Boolean.FALSE;
                } else {
                    cachedExists = Boolean.TRUE;
                }
                return true;
            }
        }
    }
    if (now < nextCheck) {
        return true;
    }
    // Assume resources inside WARs will not change
    if (!root.isPackedWarFile()) {
        WebResource webResourceInternal = root.getResourceInternal(webAppPath, useClassLoaderResources);
        if (!webResource.exists() && webResourceInternal.exists()) {
            return false;
        }
        // removed etc.
        if (webResource.getLastModified() != getLastModified() || webResource.getContentLength() != getContentLength()) {
            return false;
        }
        // Has a resource been inserted / removed in a different resource set
        if (webResource.getLastModified() != webResourceInternal.getLastModified() || webResource.getContentLength() != webResourceInternal.getContentLength()) {
            return false;
        }
    }
    nextCheck = ttl + now;
    return true;
}
Also used : WebResource(org.apache.catalina.WebResource)

Aggregations

WebResource (org.apache.catalina.WebResource)65 ByteArrayInputStream (java.io.ByteArrayInputStream)17 Test (org.junit.Test)17 File (java.io.File)15 InputStream (java.io.InputStream)15 BufferedInputStream (java.io.BufferedInputStream)11 IOException (java.io.IOException)10 FileInputStream (java.io.FileInputStream)9 OutputStreamWriter (java.io.OutputStreamWriter)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 PrintWriter (java.io.PrintWriter)7 RandomAccessFile (java.io.RandomAccessFile)7 URL (java.net.URL)7 InputSource (org.xml.sax.InputSource)7 StreamSource (javax.xml.transform.stream.StreamSource)5 Manifest (java.util.jar.Manifest)4 StringReader (java.io.StringReader)3 StringWriter (java.io.StringWriter)3 Source (javax.xml.transform.Source)3 Transformer (javax.xml.transform.Transformer)3