Search in sources :

Example 16 with Resource

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

the class DefaultServlet method getReadme.

/**
 * Get the readme file as a string.
 */
protected String getReadme(DirContext directory) throws IOException {
    if (readmeFile != null) {
        try {
            Object obj = directory.lookup(readmeFile);
            if ((obj != null) && (obj instanceof Resource)) {
                StringWriter buffer = new StringWriter();
                InputStream is = null;
                Reader reader = null;
                try {
                    is = ((Resource) obj).streamContent();
                    if (fileEncoding != null) {
                        reader = new InputStreamReader(is, fileEncoding);
                    } else {
                        reader = new InputStreamReader(is);
                    }
                    copyRange(reader, new PrintWriter(buffer));
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            log("Could not close reader", e);
                        }
                    }
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            log("Could not close is", e);
                        }
                    }
                }
                return buffer.toString();
            }
        } catch (NamingException e) {
            if (debug > 10) {
                log("readme '" + readmeFile + "' not found", e);
            }
            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) Resource(org.apache.naming.resources.Resource) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) StringReader(java.io.StringReader) NamingException(javax.naming.NamingException) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter)

Example 17 with Resource

use of org.apache.naming.resources.Resource in project tomcat70 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.
 */
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();
    }
    RandomAccessFile randAccessContentFile = null;
    try {
        randAccessContentFile = new RandomAccessFile(contentFile, "rw");
        Resource oldResource = null;
        try {
            Object obj = resources.lookup(path);
            if (obj instanceof Resource)
                oldResource = (Resource) obj;
        } catch (NamingException e) {
        // Ignore
        }
        // Copy data in oldRevisionContent to contentFile
        if (oldResource != null) {
            BufferedInputStream bufOldRevStream = null;
            try {
                bufOldRevStream = new BufferedInputStream(oldResource.streamContent(), BUFFER_SIZE);
                int numBytesRead;
                byte[] copyBuffer = new byte[BUFFER_SIZE];
                while ((numBytesRead = bufOldRevStream.read(copyBuffer)) != -1) {
                    randAccessContentFile.write(copyBuffer, 0, numBytesRead);
                }
            } finally {
                if (bufOldRevStream != null) {
                    try {
                        bufOldRevStream.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
        randAccessContentFile.setLength(range.length);
        // Append data in request input stream to contentFile
        randAccessContentFile.seek(range.start);
        int numBytesRead;
        byte[] transferBuffer = new byte[BUFFER_SIZE];
        BufferedInputStream requestBufInStream = null;
        try {
            requestBufInStream = new BufferedInputStream(req.getInputStream(), BUFFER_SIZE);
            while ((numBytesRead = requestBufInStream.read(transferBuffer)) != -1) {
                randAccessContentFile.write(transferBuffer, 0, numBytesRead);
            }
        } finally {
            if (requestBufInStream != null) {
                try {
                    requestBufInStream.close();
                } catch (IOException e) {
                }
            }
        }
    } finally {
        if (randAccessContentFile != null) {
            try {
                randAccessContentFile.close();
            } catch (IOException e) {
            }
        }
    }
    return contentFile;
}
Also used : RandomAccessFile(java.io.RandomAccessFile) BufferedInputStream(java.io.BufferedInputStream) Resource(org.apache.naming.resources.Resource) NamingException(javax.naming.NamingException) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 18 with Resource

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

the class StandardContext method getResourceAsStream.

/**
 * Return the requested resource as an <code>InputStream</code>.  The
 * path must be specified according to the rules described under
 * <code>getResource</code>.  If no such resource can be identified,
 * return <code>null</code>.
 */
@Override
public InputStream getResourceAsStream(String path) {
    if (path == null || !path.startsWith("/")) {
        return (null);
    }
    path = RequestUtil.normalize(path);
    if (path == null) {
        return (null);
    }
    DirContext resources = null;
    if (alternateDocBases == null || alternateDocBases.isEmpty()) {
        resources = getResources();
    } else {
        AlternateDocBase match = AlternateDocBase.findMatch(path, alternateDocBases);
        if (match != null) {
            resources = ContextsAdapterUtility.unwrap(match.getResources());
        } else {
            // None of the url patterns for alternate doc bases matched
            resources = getResources();
        }
    }
    if (resources != null) {
        try {
            Object resource = resources.lookup(path);
            if (resource instanceof Resource) {
                return (((Resource) resource).streamContent());
            }
        } catch (Exception e) {
        // do nothing
        }
    }
    return (null);
}
Also used : AlternateDocBase(org.glassfish.grizzly.http.server.util.AlternateDocBase) ContextResource(org.apache.catalina.deploy.ContextResource) Resource(org.apache.naming.resources.Resource) WARDirContext(org.apache.naming.resources.WARDirContext) BaseDirContext(org.apache.naming.resources.BaseDirContext) ProxyDirContext(org.apache.naming.resources.ProxyDirContext) DirContext(javax.naming.directory.DirContext) WebDirContext(org.apache.naming.resources.WebDirContext) FileDirContext(org.apache.naming.resources.FileDirContext) LifecycleException(org.apache.catalina.LifecycleException) MalformedObjectNameException(javax.management.MalformedObjectNameException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) NamingException(javax.naming.NamingException) MBeanRegistrationException(javax.management.MBeanRegistrationException) MalformedURLException(java.net.MalformedURLException)

Example 19 with Resource

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

the class WebappLoader method setRepositories.

/**
 * Configure the repositories for our class loader, based on the
 * associated Context.
 */
private void setRepositories() throws IOException {
    if (!(container instanceof Context))
        return;
    ServletContext servletContext = ((Context) container).getServletContext();
    if (servletContext == null)
        return;
    // Loading the work directory
    File workDir = (File) servletContext.getAttribute(ServletContext.TEMPDIR);
    if (workDir == null) {
        if (log.isLoggable(Level.INFO)) {
            log.log(Level.INFO, LogFacade.NO_WORK_DIR_INFO, servletContext);
        }
    }
    if (log.isLoggable(Level.FINEST) && workDir != null)
        log.log(Level.FINEST, "Deploying class repositories to work directory{0}", workDir.getAbsolutePath());
    DirContext resources = container.getResources();
    // Setting up the class repository (/WEB-INF/classes), if it exists
    String classesPath = "/WEB-INF/classes";
    DirContext classes = null;
    try {
        Object object = resources.lookup(classesPath);
        if (object instanceof DirContext) {
            classes = (DirContext) object;
        }
    } catch (NamingException e) {
    // Silent catch: it's valid that no /WEB-INF/classes collection
    // exists
    }
    if (classes != null) {
        File classRepository = null;
        String absoluteClassesPath = servletContext.getRealPath(classesPath);
        if (absoluteClassesPath != null) {
            classRepository = new File(absoluteClassesPath);
        } else {
            classRepository = new File(workDir, classesPath);
            if (!classRepository.mkdirs() && !classRepository.isDirectory()) {
                throw new IOException(rb.getString(LogFacade.FAILED_CREATE_DEST_DIR));
            }
            if (!copyDir(classes, classRepository)) {
                throw new IOException(rb.getString(LogFacade.FAILED_COPY_RESOURCE));
            }
        }
        if (log.isLoggable(Level.FINEST))
            log.log(Level.FINEST, "Deploy class files {0} to {1}", new Object[] { classesPath, classRepository.getAbsolutePath() });
    }
    // Setting up the JAR repository (/WEB-INF/lib), if it exists
    String libPath = "/WEB-INF/lib";
    classLoader.setJarPath(libPath);
    DirContext libDir = null;
    // Looking up directory /WEB-INF/lib in the context
    try {
        Object object = resources.lookup(libPath);
        if (object instanceof DirContext)
            libDir = (DirContext) object;
    } catch (NamingException e) {
    // Silent catch: it's valid that no /WEB-INF/lib collection
    // exists
    }
    if (libDir != null) {
        boolean copyJars = false;
        String absoluteLibPath = servletContext.getRealPath(libPath);
        File destDir = null;
        if (absoluteLibPath != null) {
            destDir = new File(absoluteLibPath);
        } else {
            copyJars = true;
            destDir = new File(workDir, libPath);
            if (!destDir.mkdirs() && !destDir.isDirectory()) {
                log.log(Level.SEVERE, LogFacade.FAILED_CREATE_WORK_DIR_EXCEPTION, destDir.getAbsolutePath());
            }
        }
        if (!copyJars) {
            return;
        }
        // Looking up directory /WEB-INF/lib in the context
        try {
            NamingEnumeration<Binding> enumeration = resources.listBindings(libPath);
            while (enumeration.hasMoreElements()) {
                Binding binding = enumeration.nextElement();
                String filename = libPath + "/" + binding.getName();
                // START OF IASRI 4657979
                if (!filename.endsWith(".jar") && !filename.endsWith(".zip"))
                    // END OF IASRI 4657979
                    continue;
                // START PWC 1.1 6314481
                if (binding.getName() != null && binding.getName().startsWith(".") && ignoreHiddenJarFiles) {
                    continue;
                }
                // END PWC 1.1 6314481
                File destFile = new File(destDir, binding.getName());
                if (log.isLoggable(Level.FINEST)) {
                    log.log(Level.FINEST, "Deploy JAR {0} to {1}", new Object[] { filename, destFile.getAbsolutePath() });
                }
                Object obj = binding.getObject();
                if (!(obj instanceof Resource))
                    continue;
                Resource jarResource = (Resource) obj;
                try (FileOutputStream fos = new FileOutputStream(destFile)) {
                    if (!copy(jarResource.streamContent(), fos)) {
                        continue;
                    }
                }
            }
        } catch (NamingException e) {
        // Silent catch: it's valid that no /WEB-INF/lib directory
        // exists
        } catch (IOException e) {
            log("Unable to configure repositories", e);
        }
    }
}
Also used : DirContext(javax.naming.directory.DirContext) ServletContext(javax.servlet.ServletContext) StandardContext(org.apache.catalina.core.StandardContext) Binding(javax.naming.Binding) Resource(org.apache.naming.resources.Resource) DirContext(javax.naming.directory.DirContext) ServletContext(javax.servlet.ServletContext) NamingException(javax.naming.NamingException)

Example 20 with Resource

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

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.
 */
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
        FileUtils.deleteOnExit(contentFile);
    }
    Resource oldResource = null;
    try {
        Object obj = resources.lookup(path);
        if (obj instanceof Resource)
            oldResource = (Resource) obj;
    } catch (NamingException e) {
    // Ignore
    }
    try (RandomAccessFile randAccessContentFile = new RandomAccessFile(contentFile, "rw")) {
        // Copy data in oldRevisionContent to contentFile
        if (oldResource != null) {
            try (BufferedInputStream bufOldRevStream = new BufferedInputStream(oldResource.streamContent(), 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) Resource(org.apache.naming.resources.Resource) NamingException(javax.naming.NamingException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Aggregations

Resource (org.apache.naming.resources.Resource)21 NamingException (javax.naming.NamingException)19 InputStream (java.io.InputStream)10 File (java.io.File)9 IOException (java.io.IOException)9 BufferedInputStream (java.io.BufferedInputStream)8 FileInputStream (java.io.FileInputStream)8 DirContext (javax.naming.directory.DirContext)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 RandomAccessFile (java.io.RandomAccessFile)6 NameClassPair (javax.naming.NameClassPair)5 MalformedURLException (java.net.MalformedURLException)4 FileOutputStream (java.io.FileOutputStream)3 JarFile (java.util.jar.JarFile)3 Binding (javax.naming.Binding)3 LifecycleException (org.apache.catalina.LifecycleException)3 ResourceAttributes (org.apache.naming.resources.ResourceAttributes)3 InputStreamReader (java.io.InputStreamReader)2 PrintWriter (java.io.PrintWriter)2 StringWriter (java.io.StringWriter)2