Search in sources :

Example 6 with Resource

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

the class ExtensionValidator method validateApplication.

// --------------------------------------------------------- Public Methods
/**
 * Runtime validation of a Web Applicaiton.
 *
 * This method uses JNDI to look up the resources located under a
 * <code>DirContext</code>. It locates Web Application MANIFEST.MF
 * file in the /META-INF/ directory of the application and all
 * MANIFEST.MF files in each JAR file located in the WEB-INF/lib
 * directory and creates an <code>ArrayList</code> of
 * <code>ManifestResorce<code> objects. These objects are then passed
 * to the validateManifestResources method for validation.
 *
 * @param dirContext The JNDI root of the Web Application
 * @param context The context from which the Logger and path to the
 *                application
 *
 * @return true if all required extensions satisfied
 */
public static synchronized boolean validateApplication(DirContext dirContext, StandardContext context) throws IOException {
    String appName = context.getPath();
    ArrayList<ManifestResource> appManifestResources = new ArrayList<ManifestResource>();
    ManifestResource appManifestResource = null;
    // therefore is not valid
    if (dirContext == null)
        return false;
    // Find the Manifest for the Web Applicaiton
    InputStream inputStream = null;
    try {
        NamingEnumeration wne = dirContext.listBindings("/META-INF/");
        Binding binding = (Binding) wne.nextElement();
        if (binding.getName().toUpperCase(Locale.ENGLISH).equals("MANIFEST.MF")) {
            Resource resource = (Resource) dirContext.lookup("/META-INF/" + binding.getName());
            inputStream = resource.streamContent();
            Manifest manifest = new Manifest(inputStream);
            inputStream.close();
            inputStream = null;
            // Can we do it like this?
            String resourceName = "Web Application Manifest";
            ManifestResource mre = new ManifestResource(resourceName, manifest, ManifestResource.WAR);
            appManifestResources.add(mre);
        }
    } catch (NamingException nex) {
    // Application does not contain a MANIFEST.MF file
    } catch (NoSuchElementException nse) {
    // Application does not contain a MANIFEST.MF file
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Throwable t) {
            // Ignore
            }
        }
    }
    // Locate the Manifests for all bundled JARs
    NamingEnumeration ne = null;
    try {
        ne = dirContext.listBindings("WEB-INF/lib/");
        while ((ne != null) && ne.hasMoreElements()) {
            Binding binding = (Binding) ne.nextElement();
            if (!binding.getName().toLowerCase(Locale.ENGLISH).endsWith(".jar")) {
                continue;
            }
            Object obj = dirContext.lookup("/WEB-INF/lib/" + binding.getName());
            if (!(obj instanceof Resource)) {
                // Probably a directory named xxx.jar - ignore it
                continue;
            }
            Resource resource = (Resource) obj;
            Manifest jmanifest = getManifest(resource.streamContent());
            if (jmanifest != null) {
                ManifestResource mre = new ManifestResource(binding.getName(), jmanifest, ManifestResource.APPLICATION);
                appManifestResources.add(mre);
            }
        }
    } catch (NamingException nex) {
    // Jump out of the check for this application because it
    // has no resources
    }
    return validateManifestResources(appName, appManifestResources);
}
Also used : Binding(javax.naming.Binding) FileInputStream(java.io.FileInputStream) JarInputStream(java.util.jar.JarInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Resource(org.apache.naming.resources.Resource) NamingEnumeration(javax.naming.NamingEnumeration) Manifest(java.util.jar.Manifest) NamingException(javax.naming.NamingException) NoSuchElementException(java.util.NoSuchElementException)

Example 7 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 8 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" + 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 " + classesPath + " to " + 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 " + filename + " to " + 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 9 with Resource

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

the class DefaultServlet method findXsltInputStream.

/**
 * Return a Source for the xsl template (if possible)
 */
protected Source findXsltInputStream(DirContext directory) throws IOException, ServletException {
    if (localXsltFile != null) {
        try {
            Object obj = directory.lookup(localXsltFile);
            if (obj != null && obj instanceof Resource) {
                InputStream is = ((Resource) obj).streamContent();
                if (is != null) {
                    if (Globals.IS_SECURITY_ENABLED) {
                        return secureXslt(is);
                    } else {
                        return new StreamSource(is);
                    }
                }
            }
        } catch (Throwable e) {
            ;
            /* Should only be IOException or NamingException
                    * can be ignored
                    */
            if (debug > 10)
                log("localXsltFile '" + localXsltFile + "' not found", e);
            return null;
        }
    }
    if (contextXsltFile != null) {
        InputStream is = getServletContext().getResourceAsStream(contextXsltFile);
        if (is != null) {
            if (Globals.IS_SECURITY_ENABLED) {
                return secureXslt(is);
            } else {
                return new StreamSource(is);
            }
        }
        if (debug > 10)
            log("contextXsltFile '" + contextXsltFile + "' not found");
    }
    /*  Open and read in file in one fell swoop to reduce chance
         *  chance of leaving handle open.
         */
    if (globalXsltFile != null) {
        File f = validateGlobalXsltFile();
        if (f != null) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(f);
                long len = f.length();
                byte[] b = new byte[(int) len];
                /* danger! */
                if (len != fis.read(b)) {
                    throw new IOException(MessageFormat.format(rb.getString(LogFacade.READ_FILE_EXCEPTION), f.getAbsolutePath()));
                }
                return new StreamSource(new ByteArrayInputStream(b));
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException ioe) {
                        if (debug > 10) {
                            log(ioe.getMessage(), ioe);
                        }
                    }
                }
            }
        }
    }
    return null;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) Resource(org.apache.naming.resources.Resource) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 10 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
        contentFile.deleteOnExit();
    }
    Resource oldResource = null;
    try {
        Object obj = resources.lookup(path);
        if (obj instanceof Resource)
            oldResource = (Resource) obj;
    } catch (NamingException e) {
    // Ignore
    }
    RandomAccessFile randAccessContentFile = new RandomAccessFile(contentFile, "rw");
    try {
        // 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) {
                    bufOldRevStream.close();
                }
            }
        }
        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) {
                requestBufInStream.close();
            }
        }
    } finally {
        randAccessContentFile.close();
    }
    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)10 NamingException (javax.naming.NamingException)8 BufferedInputStream (java.io.BufferedInputStream)4 FileInputStream (java.io.FileInputStream)4 InputStream (java.io.InputStream)4 DirContext (javax.naming.directory.DirContext)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 File (java.io.File)3 RandomAccessFile (java.io.RandomAccessFile)3 IOException (java.io.IOException)2 Binding (javax.naming.Binding)2 NameClassPair (javax.naming.NameClassPair)2 InputStreamReader (java.io.InputStreamReader)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 MalformedURLException (java.net.MalformedURLException)1 ArrayList (java.util.ArrayList)1 NoSuchElementException (java.util.NoSuchElementException)1 JarInputStream (java.util.jar.JarInputStream)1 Manifest (java.util.jar.Manifest)1