org.apache.tomcat.Jar Java Examples

The following examples show how to use org.apache.tomcat.Jar. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JarFactory.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
public static Jar newInstance(URL url) throws IOException {
    String urlString = url.toString();
    if (urlString.startsWith("jar:file:")) {
        if (urlString.endsWith("!/")) {
            return new JarFileUrlJar(url, true);
        } else {
            return new JarFileUrlNestedJar(url);
        }
    } else if (urlString.startsWith("war:file:")) {
        URL jarUrl = UriUtil.warToJar(url);
        return new JarFileUrlNestedJar(jarUrl);
    } else if (urlString.startsWith("file:")) {
        return new JarFileUrlJar(url, false);
    } else {
        return new UrlJar(url);
    }
}
 
Example #2
Source File: FatJarScanner.java    From oxygen with Apache License 2.0 6 votes vote down vote up
private void processFile(JarScanType scanType, JarScannerCallback callback, URL url,
    String webappPath, boolean isWebapp, Deque<URL> classPathUrlsToProcess) throws IOException {
  try {
    File f = new File(url.toURI());
    if (f.isFile()) {
      // Treat this file as a JAR
      try (Jar jar = JarFactory.newInstance(UriUtil.buildJarUrl(f))) {
        processManifest(jar, isWebapp, classPathUrlsToProcess);
        callback.scan(jar, webappPath, isWebapp);
      }
    } else if (f.isDirectory()) {
      if (scanType == JarScanType.PLUGGABILITY) {
        callback.scan(f, webappPath, isWebapp);
      } else {
        if (new File(f.getAbsoluteFile(), TomcatConf.META_INF).isDirectory()) {
          callback.scan(f, webappPath, isWebapp);
        }
      }
    }
  } catch (URISyntaxException e) {
    throw new IOException(e);
  }
}
 
Example #3
Source File: TldResourcePath.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
public Jar openJar() throws IOException {
    if (entryName == null) {
        return null;
    } else {
        // Bug 62976
        // Jar files containing tags are typically opened during initial
        // compilation and then closed when compilation is complete. The
        // reference counting wrapper is used because, when background
        // compilation is enabled, the Jar will need to be accessed (to
        // check for modifications) after it has been closed at the end
        // of the compilation stage.
        // Using a reference counted Jar enables the Jar to be re-opened,
        // used and then closed again rather than triggering an ISE.
        return new ReferenceCountedJar(url);
    }
}
 
Example #4
Source File: FatJarScanner.java    From oxygen with Apache License 2.0 6 votes vote down vote up
/**
 * Scan a URL for JARs with the optional extensions to look at all files and all directories.
 */
private void process(JarScanType scanType, JarScannerCallback callback, URL url,
    String webappPath, boolean isWebapp, Deque<URL> classPathUrlsToProcess) throws IOException {

  if (log.isTraceEnabled()) {
    log.trace(SM.getString("jarScan.jarUrlStart", url));
  }

  if (Urls.URL_PROTOCOL_JAR.equals(url.getProtocol()) || url.getPath()
      .endsWith(TomcatConf.JAR_EXT)) {
    try (Jar jar = JarFactory.newInstance(url)) {
      processManifest(jar, isWebapp, classPathUrlsToProcess);
      callback.scan(jar, webappPath, isWebapp);
    }
  } else if (Urls.URL_PROTOCOL_FILE.equals(url.getProtocol())) {
    processFile(scanType, callback, url, webappPath, isWebapp, classPathUrlsToProcess);
  }
}
 
Example #5
Source File: FatJarContextConfig.java    From oxygen with Apache License 2.0 6 votes vote down vote up
private void processJar(URL url) throws IOException {
  try (Jar jar = JarFactory.newInstance(url)) {
    jar.nextEntry();
    String entryName = jar.getEntryName();
    while (entryName != null) {
      if (entryName.startsWith(TomcatConf.META_INF_RESOURCES)) {
        context.getResources()
            .createWebResourceSet(WebResourceRoot.ResourceSetType.RESOURCE_JAR, Strings.SLASH,
                url, TomcatConf.META_INF_RESOURCES_PATH);
        break;
      }
      jar.nextEntry();
      entryName = jar.getEntryName();
    }
  }
}
 
Example #6
Source File: TagLibraryInfoImpl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private TagFileInfo createTagFileInfo(TagFileXml tagFileXml, Jar jar) throws JasperException {

        String name = tagFileXml.getName();
        String path = tagFileXml.getPath();

        if (path == null) {
            // path is required
            err.jspError("jsp.error.tagfile.missingPath");
        } else if (!path.startsWith("/META-INF/tags") && !path.startsWith("/WEB-INF/tags")) {
            err.jspError("jsp.error.tagfile.illegalPath", path);
        }

        TagInfo tagInfo =
                TagFileProcessor.parseTagFileDirectives(parserController, name, path, jar, this);
        return new TagFileInfo(name, path, tagInfo);
    }
 
Example #7
Source File: JspServletWrapper.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
public JspServletWrapper(ServletContext servletContext,
                         Options options,
                         String tagFilePath,
                         TagInfo tagInfo,
                         JspRuntimeContext rctxt,
                         Jar tagJar) {

    this.isTagFile = true;
    this.config = null;        // not used
    this.options = options;
    this.jspUri = tagFilePath;
    this.tripCount = 0;
    unloadByCount = options.getMaxLoadedJsps() > 0 ? true : false;
    unloadByIdle = options.getJspIdleTimeout() > 0 ? true : false;
    unloadAllowed = unloadByCount || unloadByIdle ? true : false;
    ctxt = new JspCompilationContext(jspUri, tagInfo, options,
                                     servletContext, this, rctxt,
                                     tagJar);
}
 
Example #8
Source File: JspUtil.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
public static InputStream getInputStream(String fname, Jar jar,
        JspCompilationContext ctxt) throws IOException {

    InputStream in = null;

    if (jar != null) {
        String jarEntryName = fname.substring(1, fname.length());
        in = jar.getInputStream(jarEntryName);
    } else {
        in = ctxt.getResourceAsStream(fname);
    }

    if (in == null) {
        throw new FileNotFoundException(Localizer.getMessage(
                "jsp.error.file.not.found", fname));
    }

    return in;
}
 
Example #9
Source File: TestAbstractInputStreamJar.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testNestedJarGetInputStream() throws Exception {
    File f = new File("test/webresources/war-url-connection.war");
    StringBuilder sb = new StringBuilder("war:");
    sb.append(f.toURI().toURL());
    sb.append("*/WEB-INF/lib/test.jar");

    Jar jar = JarFactory.newInstance(new URL(sb.toString()));

    InputStream is1 = jar.getInputStream("META-INF/resources/index.html");
    ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
    IOTools.flow(is1, baos1);

    InputStream is2 = jar.getInputStream("META-INF/resources/index.html");
    ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
    IOTools.flow(is2, baos2);

    Assert.assertArrayEquals(baos1.toByteArray(), baos2.toByteArray());
}
 
Example #10
Source File: TagFileProcessor.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Parses the tag file, and collects information on the directives included
 * in it. The method is used to obtain the info on the tag file, when the
 * handler that it represents is referenced. The tag file is not compiled
 * here.
 *
 * @param pc
 *            the current ParserController used in this compilation
 * @param name
 *            the tag name as specified in the TLD
 * @param path
 *            the path for the tagfile
 * @param jar
 *            the Jar resource containing the tag file
 * @param tagLibInfo
 *            the TagLibraryInfo object associated with this TagInfo
 * @return a TagInfo object assembled from the directives in the tag file.
 *
 * @throws JasperException If an error occurs during parsing
 */
@SuppressWarnings("null") // page can't be null
public static TagInfo parseTagFileDirectives(ParserController pc,
        String name, String path, Jar jar, TagLibraryInfo tagLibInfo)
        throws JasperException {


    ErrorDispatcher err = pc.getCompiler().getErrorDispatcher();

    Node.Nodes page = null;
    try {
        page = pc.parseTagFileDirectives(path, jar);
    } catch (IOException e) {
        err.jspError("jsp.error.file.not.found", path);
    }

    TagFileDirectiveVisitor tagFileVisitor = new TagFileDirectiveVisitor(pc
            .getCompiler(), tagLibInfo, name, path);
    page.visit(tagFileVisitor);
    tagFileVisitor.postCheck();

    return tagFileVisitor.getTagInfo();
}
 
Example #11
Source File: Parser.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * The main entry for Parser
 *
 * @param pc  The ParseController, use for getting other objects in compiler
 *            and for parsing included pages
 * @param reader To read the page
 * @param parent The parent node to this page, null for top level page
 * @param isTagFile Is the page being parsed a tag file?
 * @param directivesOnly Should only directives be parsed?
 * @param jar JAR, if any, that this page was loaded from
 * @param pageEnc The encoding of the source
 * @param jspConfigPageEnc The encoding for the page
 * @param isDefaultPageEncoding Is the page encoding the default?
 * @param isBomPresent Is a BOM present in the source
 * @return list of nodes representing the parsed page
 *
 * @throws JasperException If an error occurs during parsing
 */
public static Node.Nodes parse(ParserController pc, JspReader reader,
        Node parent, boolean isTagFile, boolean directivesOnly,
        Jar jar, String pageEnc, String jspConfigPageEnc,
        boolean isDefaultPageEncoding, boolean isBomPresent)
        throws JasperException {

    Parser parser = new Parser(pc, reader, isTagFile, directivesOnly, jar);

    Node.Root root = new Node.Root(reader.mark(), parent, false);
    root.setPageEncoding(pageEnc);
    root.setJspConfigPageEncoding(jspConfigPageEnc);
    root.setIsDefaultPageEncoding(isDefaultPageEncoding);
    root.setIsBomPresent(isBomPresent);

    // For the Top level page, add include-prelude and include-coda
    PageInfo pageInfo = pc.getCompiler().getPageInfo();
    if (parent == null && !isTagFile) {
        parser.addInclude(root, pageInfo.getIncludePrelude());
    }
    if (directivesOnly) {
        parser.parseFileDirectives(root);
    } else {
        while (reader.hasMoreInput()) {
            parser.parseElements(root);
        }
    }
    if (parent == null && !isTagFile) {
        parser.addInclude(root, pageInfo.getIncludeCoda());
    }

    Node.Nodes page = new Node.Nodes(root);
    return page;
}
 
Example #12
Source File: OWBJarScanner.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Override
public void scan(final JarScanType jarScanType, final ServletContext servletContext, final JarScannerCallback callback) {
    switch (jarScanType) {
        case PLUGGABILITY:
            CdiArchive.class.cast(WebScannerService.class.cast(WebBeansContext.getInstance().getScannerService()).getFinder().getArchive())
                    .classesByUrl().keySet().stream()
                    .filter(u -> !"jar:file://!/".equals(u)) // not a fake in memory url
                    .forEach(u -> {
                        try {
                            final URL url = new URL(u);
                            final File asFile = Files.toFile(url);
                            if (!asFile.exists()) {
                                return;
                            }
                            if (filter != null && !filter.check(jarScanType, asFile.getName())) {
                                return;
                            }

                            if (asFile.getName().endsWith(Constants.JAR_EXT)) {
                                try (final Jar jar = JarFactory.newInstance(asFile.toURI().toURL())) {
                                    callback.scan(jar, u, true);
                                }
                            } else if (asFile.isDirectory()) {
                                callback.scan(asFile, asFile.getAbsolutePath(), true);
                            }
                        } catch (final MalformedURLException e) {
                            // skip
                        } catch (final IOException ioe) {
                            throw new IllegalArgumentException(ioe);
                        }
                    });
            return;

        case TLD:
        default:
    }
}
 
Example #13
Source File: TldCache.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private long[] getLastModified(TldResourcePath tldResourcePath) {
    long[] result = new long[2];
    result[0] = -1;
    result[1] = -1;
    try {
        String webappPath = tldResourcePath.getWebappPath();
        if (webappPath != null) {
            // webappPath will be null for JARs containing TLDs that are on
            // the class path but not part of the web application
            URL url = servletContext.getResource(tldResourcePath.getWebappPath());
            URLConnection conn = url.openConnection();
            result[0] = conn.getLastModified();
            if ("file".equals(url.getProtocol())) {
                // Reading the last modified time opens an input stream so we
                // need to make sure it is closed again otherwise the TLD file
                // will be locked until GC runs.
                conn.getInputStream().close();
            }
        }
        try (Jar jar = tldResourcePath.openJar()) {
            if (jar != null) {
                result[1] = jar.getLastModified(tldResourcePath.getEntryName());
            }
        }
    } catch (IOException e) {
        // Ignore (shouldn't happen)
    }
    return result;
}
 
Example #14
Source File: TagFileProcessor.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void visit(Node.CustomTag n) throws JasperException {
    TagFileInfo tagFileInfo = n.getTagFileInfo();
    if (tagFileInfo != null) {
        String tagFilePath = tagFileInfo.getPath();
        if (tagFilePath.startsWith("/META-INF/")) {
            // For tags in JARs, add the TLD and the tag as a dependency
            TldResourcePath tldResourcePath =
                compiler.getCompilationContext().getTldResourcePath(
                    tagFileInfo.getTagInfo().getTagLibrary().getURI());

            try (Jar jar = tldResourcePath.openJar()) {

                if (jar != null) {
                    // Add TLD
                    pageInfo.addDependant(jar.getURL(tldResourcePath.getEntryName()),
                                          Long.valueOf(jar.getLastModified(tldResourcePath.getEntryName())));
                    // Add Tag
                    pageInfo.addDependant(jar.getURL(tagFilePath.substring(1)),
                                          Long.valueOf(jar.getLastModified(tagFilePath.substring(1))));
                } else {
                    pageInfo.addDependant(tagFilePath,
                                          compiler.getCompilationContext().getLastModified(tagFilePath));
                }
            } catch (IOException ioe) {
                throw new JasperException(ioe);
            }
        } else {
            pageInfo.addDependant(tagFilePath,
                    compiler.getCompilationContext().getLastModified(tagFilePath));
        }
        Class<?> c = loadTagFile(compiler, tagFilePath, n.getTagInfo(),
                pageInfo);
        n.setTagHandlerClass(c);
    }
    visitBody(n);
}
 
Example #15
Source File: TesterPerformance.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testClassParserPerformance() throws IOException {
    File libDir = new File(JAR_LOCATION);
    String[] libs = libDir.list();

    Assert.assertNotNull(libs);

    Set<URL> jarURLs = new HashSet<>();

    for (String lib : libs) {
        if (!lib.toLowerCase(Locale.ENGLISH).endsWith(".jar")) {
            continue;
        }
        jarURLs.add(new URL("jar:" + new File (libDir, lib).toURI().toURL().toExternalForm() + "!/"));
    }

    long duration = 0;

    for (URL jarURL : jarURLs) {
        try (Jar jar = JarFactory.newInstance(jarURL)) {
            jar.nextEntry();
            String jarEntryName = jar.getEntryName();
            while (jarEntryName != null) {
                if (jarEntryName.endsWith(".class")) {
                    InputStream is = jar.getEntryInputStream();
                    long start = System.nanoTime();
                    ClassParser cp = new ClassParser(is);
                    cp.parse();
                    duration += System.nanoTime() - start;
                }
                jar.nextEntry();
                jarEntryName = jar.getEntryName();
            }
        }
    }

    System.out.println("ClassParser performance test took: " + duration + " ns");
}
 
Example #16
Source File: TestTldScanner.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private static void scan(TldScanner.TldScannerCallback callback, File webapp, String path)
        throws Exception {
    String fullPath = new File(webapp, path).toURI().toString();
    URL jarUrl = new URL("jar:" + fullPath + "!/");
    try (Jar jar = JarFactory.newInstance(jarUrl)) {
        callback.scan(jar, path, true);
    }
}
 
Example #17
Source File: ContextConfig.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Scan JARs that contain web-fragment.xml files that will be used to
 * configure this application to see if they also contain static resources.
 * If static resources are found, add them to the context. Resources are
 * added in web-fragment.xml priority order.
 * @param fragments The set of fragments that will be scanned for
 *  static resources
 */
protected void processResourceJARs(Set<WebXml> fragments) {
    for (WebXml fragment : fragments) {
        URL url = fragment.getURL();
        try {
            if ("jar".equals(url.getProtocol()) || url.toString().endsWith(".jar")) {
                try (Jar jar = JarFactory.newInstance(url)) {
                    jar.nextEntry();
                    String entryName = jar.getEntryName();
                    while (entryName != null) {
                        if (entryName.startsWith("META-INF/resources/")) {
                            context.getResources().createWebResourceSet(
                                    WebResourceRoot.ResourceSetType.RESOURCE_JAR,
                                    "/", url, "/META-INF/resources");
                            break;
                        }
                        jar.nextEntry();
                        entryName = jar.getEntryName();
                    }
                }
            } else if ("file".equals(url.getProtocol())) {
                File file = new File(url.toURI());
                File resources = new File(file, "META-INF/resources/");
                if (resources.isDirectory()) {
                    context.getResources().createWebResourceSet(
                            WebResourceRoot.ResourceSetType.RESOURCE_JAR,
                            "/", resources.getAbsolutePath(), null, "/");
                }
            }
        } catch (IOException ioe) {
            log.error(sm.getString("contextConfig.resourceJarFail", url,
                    context.getName()));
        } catch (URISyntaxException e) {
            log.error(sm.getString("contextConfig.resourceJarFail", url,
                context.getName()));
        }
    }
}
 
Example #18
Source File: FragmentJarScannerCallback.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void scan(Jar jar, String webappPath, boolean isWebapp) throws IOException {

    InputStream is = null;
    WebXml fragment = new WebXml();
    fragment.setWebappJar(isWebapp);
    fragment.setDelegate(delegate);

    try {
        // Only web application JARs are checked for web-fragment.xml
        // files.
        // web-fragment.xml files don't need to be parsed if they are never
        // going to be used.
        if (isWebapp && parseRequired) {
            is = jar.getInputStream(FRAGMENT_LOCATION);
        }

        if (is == null) {
            // If there is no web.xml, normal JAR no impact on
            // distributable
            fragment.setDistributable(true);
        } else {
            String fragmentUrl = jar.getURL(FRAGMENT_LOCATION);
            InputSource source = new InputSource(fragmentUrl);
            source.setByteStream(is);
            if (!webXmlParser.parseWebXml(source, fragment, true)) {
                ok = false;
            }
        }
    } finally {
        addFragment(fragment, jar.getJarFileURL());
    }
}
 
Example #19
Source File: TldScanner.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void scan(Jar jar, String webappPath, boolean isWebapp) throws IOException {
    boolean found = false;
    URL jarFileUrl = jar.getJarFileURL();
    jar.nextEntry();
    for (String entryName = jar.getEntryName();
        entryName != null;
        jar.nextEntry(), entryName = jar.getEntryName()) {
        if (!(entryName.startsWith("META-INF/") &&
                entryName.endsWith(TLD_EXT))) {
            continue;
        }
        found = true;
        TldResourcePath tldResourcePath =
                new TldResourcePath(jarFileUrl, webappPath, entryName);
        try {
            parseTld(tldResourcePath);
        } catch (SAXException e) {
            throw new IOException(e);
        }
    }
    if (found) {
        if (log.isDebugEnabled()) {
            log.debug(Localizer.getMessage("jsp.tldCache.tldInJar", jarFileUrl.toString()));
        }
    } else {
        foundJarWithoutTld = true;
        if (log.isDebugEnabled()) {
            log.debug(Localizer.getMessage(
                    "jsp.tldCache.noTldInJar", jarFileUrl.toString()));
        }
    }
}
 
Example #20
Source File: JspCServletContext.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Return a URL object of a resource that is mapped to the
 * specified context-relative path.
 *
 * @param path Context-relative path of the desired resource
 *
 * @exception MalformedURLException if the resource path is
 *  not properly formed
 */
@Override
public URL getResource(String path) throws MalformedURLException {

    if (!path.startsWith("/")) {
        throw new MalformedURLException("Path '" + path + "' does not start with '/'");
    }

    // Strip leading '/'
    path = path.substring(1);

    URL url = new URL(myResourceBaseURL, path);
    try (InputStream is = url.openStream()) {
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        url = null;
    }

    // During initialisation, getResource() is called before resourceJARs is
    // initialised
    if (url == null && resourceJARs != null) {
        String jarPath = "META-INF/resources/" + path;
        for (URL jarUrl : resourceJARs) {
            try (Jar jar = JarFactory.newInstance(jarUrl)) {
                if (jar.exists(jarPath)) {
                    return new URL(jar.getURL(jarPath));
                }
            } catch (IOException ioe) {
                // Ignore
            }
        }
    }
    return url;
}
 
Example #21
Source File: Parser.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * The constructor
 */
private Parser(ParserController pc, JspReader reader, boolean isTagFile,
        boolean directivesOnly, Jar jar) {
    this.parserController = pc;
    this.ctxt = pc.getJspCompilationContext();
    this.pageInfo = pc.getCompiler().getPageInfo();
    this.err = pc.getCompiler().getErrorDispatcher();
    this.reader = reader;
    this.scriptlessCount = 0;
    this.isTagFile = isTagFile;
    this.directivesOnly = directivesOnly;
    this.jar = jar;
    start = reader.mark();
}
 
Example #22
Source File: JspCompilationContext.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private JspCompilationContext(String jspUri, TagInfo tagInfo,
        Options options, ServletContext context, JspServletWrapper jsw,
        JspRuntimeContext rctxt, Jar tagJar, boolean isTagFile) {

    this.jspUri = canonicalURI(jspUri);
    this.options = options;
    this.jsw = jsw;
    this.context = context;

    String baseURI = jspUri.substring(0, jspUri.lastIndexOf('/') + 1);
    // hack fix for resolveRelativeURI
    if (baseURI.isEmpty()) {
        baseURI = "/";
    } else if (baseURI.charAt(0) != '/') {
        // strip the base slash since it will be combined with the
        // uriBase to generate a file
        baseURI = "/" + baseURI;
    }
    if (baseURI.charAt(baseURI.length() - 1) != '/') {
        baseURI += '/';
    }
    this.baseURI = baseURI;

    this.rctxt = rctxt;
    this.basePackageName = Constants.JSP_PACKAGE_NAME;

    this.tagInfo = tagInfo;
    this.tagJar = tagJar;
    this.isTagFile = isTagFile;
}
 
Example #23
Source File: JavacErrorDetail.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Constructor.
 *
 * @param javaFileName The name of the Java file in which the
 * compilation error occurred
 * @param javaLineNum The compilation error line number
 * @param jspFileName The name of the JSP file from which the Java source
 * file was generated
 * @param jspBeginLineNum The start line number of the JSP element
 * responsible for the compilation error
 * @param errMsg The compilation error message
 * @param ctxt The compilation context
 */
public JavacErrorDetail(String javaFileName,
        int javaLineNum,
        String jspFileName,
        int jspBeginLineNum,
        StringBuilder errMsg,
        JspCompilationContext ctxt) {

    this.javaFileName = javaFileName;
    this.javaLineNum = javaLineNum;
    this.errMsg = errMsg;
    this.jspFileName = jspFileName;
    // Note: this.jspBeginLineNum is set at the end of this method as it may
    //       be modified (corrected) during the execution of this method

    if (jspBeginLineNum > 0 && ctxt != null) {
        InputStream is = null;
        try {
            Jar tagJar = ctxt.getTagFileJar();
            if (tagJar != null) {
                // Strip leading '/'
                String entryName = jspFileName.substring(1);
                is = tagJar.getInputStream(entryName);
                this.jspFileName = tagJar.getURL(entryName);
            } else {
                is = ctxt.getResourceAsStream(jspFileName);
            }
            // Read both files in, so we can inspect them
            String[] jspLines = readFile(is);

            try (FileInputStream fis = new FileInputStream(ctxt.getServletJavaFileName())) {
                String[] javaLines = readFile(fis);

                if (jspLines.length < jspBeginLineNum) {
                    // Avoid ArrayIndexOutOfBoundsException
                    // Probably bug 48498 but could be some other cause
                    jspExtract = Localizer.getMessage("jsp.error.bug48498");
                    return;
                }

                // If the line contains the opening of a multi-line scriptlet
                // block, then the JSP line number we got back is probably
                // faulty.  Scan forward to match the java line...
                if (jspLines[jspBeginLineNum-1].lastIndexOf("<%") >
                    jspLines[jspBeginLineNum-1].lastIndexOf("%>")) {
                    String javaLine = javaLines[javaLineNum-1].trim();

                    for (int i=jspBeginLineNum-1; i<jspLines.length; i++) {
                        if (jspLines[i].indexOf(javaLine) != -1) {
                            // Update jsp line number
                            jspBeginLineNum = i+1;
                            break;
                        }
                    }
                }

                // copy out a fragment of JSP to display to the user
                StringBuilder fragment = new StringBuilder(1024);
                int startIndex = Math.max(0, jspBeginLineNum-1-3);
                int endIndex = Math.min(
                        jspLines.length-1, jspBeginLineNum-1+3);

                for (int i=startIndex;i<=endIndex; ++i) {
                    fragment.append(i+1);
                    fragment.append(": ");
                    fragment.append(jspLines[i]);
                    fragment.append(System.lineSeparator());
                }
                jspExtract = fragment.toString();
            }
        } catch (IOException ioe) {
            // Can't read files - ignore
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ignore) {
                    // Ignore
                }
            }
        }
    }
    this.jspBeginLineNum = jspBeginLineNum;
}
 
Example #24
Source File: StandardJarScanner.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void processManifest(Jar jar, boolean isWebapp,
        Deque<URL> classPathUrlsToProcess) throws IOException {

    // Not processed for web application JARs nor if the caller did not
    // provide a Deque of URLs to append to.
    if (isWebapp || classPathUrlsToProcess == null) {
        return;
    }

    Manifest manifest = jar.getManifest();
    if (manifest != null) {
        Attributes attributes = manifest.getMainAttributes();
        String classPathAttribute = attributes.getValue("Class-Path");
        if (classPathAttribute == null) {
            return;
        }
        String[] classPathEntries = classPathAttribute.split(" ");
        for (String classPathEntry : classPathEntries) {
            classPathEntry = classPathEntry.trim();
            if (classPathEntry.length() == 0) {
                continue;
            }
            URL jarURL = jar.getJarFileURL();
            URL classPathEntryURL;
            try {
                URI jarURI = jarURL.toURI();
                /*
                 * Note: Resolving the relative URLs from the manifest has the
                 *       potential to introduce security concerns. However, since
                 *       only JARs provided by the container and NOT those provided
                 *       by web applications are processed, there should be no
                 *       issues.
                 *       If this feature is ever extended to include JARs provided
                 *       by web applications, checks should be added to ensure that
                 *       any relative URL does not step outside the web application.
                 */
                URI classPathEntryURI = jarURI.resolve(classPathEntry);
                classPathEntryURL = classPathEntryURI.toURL();
            } catch (Exception e) {
                if (log.isDebugEnabled()) {
                    log.debug(sm.getString("jarScan.invalidUri", jarURL), e);
                }
                continue;
            }
            classPathUrlsToProcess.add(classPathEntryURL);
        }
    }
}
 
Example #25
Source File: FatJarScanner.java    From oxygen with Apache License 2.0 4 votes vote down vote up
private void processManifest(Jar jar, boolean isWebapp, Deque<URL> classPathUrlsToProcess)
    throws IOException {

  // Not processed for web application JARs nor if the caller did not provide a Deque of URLs to append to.
  if (isWebapp || classPathUrlsToProcess == null) {
    return;
  }

  Manifest manifest = jar.getManifest();
  if (manifest == null) {
    return;
  }
  Attributes attributes = manifest.getMainAttributes();
  String classPathAttribute = attributes.getValue("Class-Path");
  if (classPathAttribute == null) {
    return;
  }
  String[] classPathEntries = classPathAttribute.split(" ");
  for (String classPathEntry : classPathEntries) {
    classPathEntry = classPathEntry.trim();
    if (classPathEntry.length() == 0) {
      continue;
    }
    URL jarURL = jar.getJarFileURL();
    try {
      /*
       * Note: Resolving the relative URLs from the manifest has the
       *       potential to introduce security concerns. However, since
       *       only JARs provided by the container and NOT those provided
       *       by web applications are processed, there should be no
       *       issues.
       *       If this feature is ever extended to include JARs provided
       *       by web applications, checks should be added to ensure that
       *       any relative URL does not step outside the web application.
       */
      URI classPathEntryUri = jar.getJarFileURL().toURI().resolve(classPathEntry);
      classPathUrlsToProcess.add(classPathEntryUri.toURL());
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.debug(SM.getString("jarScan.invalidUri", jarURL), e);
      }
    }
  }
}
 
Example #26
Source File: JspCServletContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Return the set of resource paths for the "directory" at the
 * specified context path.
 *
 * @param path Context-relative base path
 */
@Override
public Set<String> getResourcePaths(String path) {

    Set<String> thePaths = new HashSet<>();
    if (!path.endsWith("/")) {
        path += "/";
    }
    String basePath = getRealPath(path);
    if (basePath != null) {
        File theBaseDir = new File(basePath);
        if (theBaseDir.isDirectory()) {
            String theFiles[] = theBaseDir.list();
            if (theFiles != null) {
                for (int i = 0; i < theFiles.length; i++) {
                    File testFile = new File(basePath + File.separator + theFiles[i]);
                    if (testFile.isFile()) {
                        thePaths.add(path + theFiles[i]);
                    } else if (testFile.isDirectory()) {
                        thePaths.add(path + theFiles[i] + "/");
                    }
                }
            }
        }
    }

    // During initialisation, getResourcePaths() is called before
    // resourceJARs is initialised
    if (resourceJARs != null) {
        String jarPath = "META-INF/resources" + path;
        for (URL jarUrl : resourceJARs) {
            try (Jar jar = JarFactory.newInstance(jarUrl)) {
                jar.nextEntry();
                for (String entryName = jar.getEntryName();
                        entryName != null;
                        jar.nextEntry(), entryName = jar.getEntryName()) {
                    if (entryName.startsWith(jarPath) &&
                            entryName.length() > jarPath.length()) {
                        // Let the Set implementation handle duplicates
                        int sep = entryName.indexOf("/", jarPath.length());
                        if (sep < 0) {
                            // This is a file - strip leading "META-INF/resources"
                            thePaths.add(entryName.substring(18));
                        } else {
                            // This is a directory - strip leading "META-INF/resources"
                            thePaths.add(entryName.substring(18, sep + 1));
                        }
                    }
                }
            } catch (IOException e) {
                log(e.getMessage(), e);
            }
        }
    }

    return thePaths;
}
 
Example #27
Source File: JspCompilationContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
public JspCompilationContext(String tagfile, TagInfo tagInfo,
        Options options, ServletContext context, JspServletWrapper jsw,
        JspRuntimeContext rctxt, Jar tagJar) {
    this(tagfile, tagInfo, options, context, jsw, rctxt, tagJar, true);
}
 
Example #28
Source File: TestStandardJarScanner.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public void scan(Jar jar, String webappPath,
        boolean isWebapp) throws IOException {
    callbacks.add(jar.getJarFileURL().toString() + "::" + webappPath + "::" + isWebapp);
}
 
Example #29
Source File: JspCompilationContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
public void setTagFileJar(Jar tagJar) {
    this.tagJar = tagJar;
}
 
Example #30
Source File: ParserController.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Parses the JSP page or tag file with the given path name.
 *
 * @param inFileName The name of the JSP page or tag file to be parsed.
 * @param parent The parent node (non-null when processing an include
 * directive)
 * @param jar  The JAR file from which to read the JSP page or tag file,
 * or null if the JSP page or tag file is to be read from the filesystem
 */
private Node.Nodes doParse(String inFileName, Node parent, Jar jar)
        throws FileNotFoundException, JasperException, IOException {

    Node.Nodes parsedPage = null;
    isEncodingSpecifiedInProlog = false;
    isBomPresent = false;
    isDefaultPageEncoding = false;

    String absFileName = resolveFileName(inFileName);
    String jspConfigPageEnc = getJspConfigPageEncoding(absFileName);

    // Figure out what type of JSP document and encoding type we are
    // dealing with
    determineSyntaxAndEncoding(absFileName, jar, jspConfigPageEnc);

    if (parent != null) {
        // Included resource, add to dependent list
        if (jar == null) {
            compiler.getPageInfo().addDependant(absFileName,
                    ctxt.getLastModified(absFileName));
        } else {
            String entry = absFileName.substring(1);
            compiler.getPageInfo().addDependant(jar.getURL(entry),
                    Long.valueOf(jar.getLastModified(entry)));

        }
    }

    if ((isXml && isEncodingSpecifiedInProlog) || isBomPresent) {
        /*
         * Make sure the encoding explicitly specified in the XML
         * prolog (if any) matches that in the JSP config element
         * (if any), treating "UTF-16", "UTF-16BE", and "UTF-16LE" as
         * identical.
         */
        if (jspConfigPageEnc != null && !jspConfigPageEnc.equals(sourceEnc)
                && (!jspConfigPageEnc.startsWith("UTF-16")
                        || !sourceEnc.startsWith("UTF-16"))) {
            err.jspError("jsp.error.prolog_config_encoding_mismatch",
                    sourceEnc, jspConfigPageEnc);
        }
    }

    // Dispatch to the appropriate parser
    if (isXml) {
        // JSP document (XML syntax)
        // InputStream for jspx page is created and properly closed in
        // JspDocumentParser.
        parsedPage = JspDocumentParser.parse(this, absFileName, jar, parent,
                isTagFile, directiveOnly, sourceEnc, jspConfigPageEnc,
                isEncodingSpecifiedInProlog, isBomPresent);
    } else {
        // Standard syntax
        try (InputStreamReader inStreamReader = JspUtil.getReader(
                absFileName, sourceEnc, jar, ctxt, err, skip);) {
            JspReader jspReader = new JspReader(ctxt, absFileName,
                    inStreamReader, err);
            parsedPage = Parser.parse(this, jspReader, parent, isTagFile,
                    directiveOnly, jar, sourceEnc, jspConfigPageEnc,
                    isDefaultPageEncoding, isBomPresent);
        }
    }

    baseDirStack.pop();

    return parsedPage;
}