Search in sources :

Example 6 with JasperException

use of org.apache.sling.scripting.jsp.jasper.JasperException in project sling by apache.

the class ParserController method doParse.

/**
     * 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 isTagFile true if file to be parsed is tag file, and false if it
     * is a regular JSP page
     * @param directivesOnly true if the file to be parsed is a tag file and
     * we are only interested in the directives needed for constructing a
     * TagFileInfo.
     * @param jarFile 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, URL jarFileUrl) throws FileNotFoundException, JasperException, IOException {
    Node.Nodes parsedPage = null;
    isEncodingSpecifiedInProlog = false;
    isBomPresent = false;
    isDefaultPageEncoding = false;
    JarFile jarFile = getJarFile(jarFileUrl);
    String absFileName = resolveFileName(inFileName);
    String jspConfigPageEnc = getJspConfigPageEncoding(absFileName);
    // Figure out what type of JSP document and encoding type we are
    // dealing with
    determineSyntaxAndEncoding(absFileName, jarFile, jspConfigPageEnc);
    if (parent != null) {
        // Included resource, add to dependent list
        compiler.getPageInfo().addDependant(absFileName);
    }
    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, jarFile, parent, isTagFile, directiveOnly, sourceEnc, jspConfigPageEnc, isEncodingSpecifiedInProlog, isBomPresent);
    } else {
        // Standard syntax
        InputStreamReader inStreamReader = null;
        try {
            inStreamReader = JspUtil.getReader(absFileName, sourceEnc, jarFile, ctxt, err, skip);
            JspReader jspReader = new JspReader(ctxt, absFileName, sourceEnc, inStreamReader, err);
            parsedPage = Parser.parse(this, jspReader, parent, isTagFile, directiveOnly, jarFileUrl, sourceEnc, jspConfigPageEnc, isDefaultPageEncoding, isBomPresent);
        } finally {
            if (inStreamReader != null) {
                try {
                    inStreamReader.close();
                } catch (Exception any) {
                }
            }
        }
    }
    if (jarFile != null) {
        try {
            jarFile.close();
        } catch (Throwable t) {
        }
    }
    baseDirStack.pop();
    return parsedPage;
}
Also used : InputStreamReader(java.io.InputStreamReader) JarFile(java.util.jar.JarFile) IOException(java.io.IOException) JasperException(org.apache.sling.scripting.jsp.jasper.JasperException) FileNotFoundException(java.io.FileNotFoundException)

Example 7 with JasperException

use of org.apache.sling.scripting.jsp.jasper.JasperException in project sling by apache.

the class ParserController method determineSyntaxAndEncoding.

/**
     * Determines the syntax (standard or XML) and page encoding properties
     * for the given file, and stores them in the 'isXml' and 'sourceEnc'
     * instance variables, respectively.
     */
private void determineSyntaxAndEncoding(String absFileName, JarFile jarFile, String jspConfigPageEnc) throws JasperException, IOException {
    isXml = false;
    /*
         * 'true' if the syntax (XML or standard) of the file is given
         * from external information: either via a JSP configuration element,
         * the ".jspx" suffix, or the enclosing file (for included resources)
         */
    boolean isExternal = false;
    /*
         * Indicates whether we need to revert from temporary usage of
         * "ISO-8859-1" back to "UTF-8"
         */
    boolean revert = false;
    JspConfig jspConfig = ctxt.getOptions().getJspConfig();
    JspConfig.JspProperty jspProperty = jspConfig.findJspProperty(absFileName);
    if (jspProperty.isXml() != null) {
        // If <is-xml> is specified in a <jsp-property-group>, it is used.
        isXml = JspUtil.booleanValue(jspProperty.isXml());
        isExternal = true;
    } else if (absFileName.endsWith(".jspx") || absFileName.endsWith(".tagx")) {
        isXml = true;
        isExternal = true;
    }
    if (isExternal && !isXml) {
        // JSP (standard) syntax. Use encoding specified in jsp-config
        // if provided.
        sourceEnc = jspConfigPageEnc;
        if (sourceEnc != null) {
            return;
        }
        // We don't know the encoding, so use BOM to determine it
        sourceEnc = "ISO-8859-1";
    } else {
        // XML syntax or unknown, (auto)detect encoding ...
        Object[] ret = XMLEncodingDetector.getEncoding(absFileName, jarFile, ctxt, err);
        sourceEnc = (String) ret[0];
        if (((Boolean) ret[1]).booleanValue()) {
            isEncodingSpecifiedInProlog = true;
        }
        if (((Boolean) ret[2]).booleanValue()) {
            isBomPresent = true;
        }
        skip = ((Integer) ret[3]).intValue();
        if (!isXml && sourceEnc.equals("UTF-8")) {
            /*
                 * We don't know if we're dealing with XML or standard syntax.
                 * Therefore, we need to check to see if the page contains
                 * a <jsp:root> element.
                 *
                 * We need to be careful, because the page may be encoded in
                 * ISO-8859-1 (or something entirely different), and may
                 * contain byte sequences that will cause a UTF-8 converter to
                 * throw exceptions. 
                 *
                 * It is safe to use a source encoding of ISO-8859-1 in this
                 * case, as there are no invalid byte sequences in ISO-8859-1,
                 * and the byte/character sequences we're looking for (i.e.,
                 * <jsp:root>) are identical in either encoding (both UTF-8
                 * and ISO-8859-1 are extensions of ASCII).
                 */
            sourceEnc = "ISO-8859-1";
            revert = true;
        }
    }
    if (isXml) {
        // ".jspx" suffix), so we're done.
        return;
    }
    /*
         * At this point, 'isExternal' or 'isXml' is FALSE.
         * Search for jsp:root action, in order to determine if we're dealing 
         * with XML or standard syntax (unless we already know what we're 
         * dealing with, i.e., when 'isExternal' is TRUE and 'isXml' is FALSE).
         * No check for XML prolog, since nothing prevents a page from
         * outputting XML and still using JSP syntax (in this case, the 
         * XML prolog is treated as template text).
         */
    JspReader jspReader = null;
    try {
        jspReader = new JspReader(ctxt, absFileName, sourceEnc, jarFile, err);
    } catch (FileNotFoundException ex) {
        throw new JasperException(ex);
    }
    jspReader.setSingleFile(true);
    Mark startMark = jspReader.mark();
    if (!isExternal) {
        jspReader.reset(startMark);
        if (hasJspRoot(jspReader)) {
            if (revert) {
                sourceEnc = "UTF-8";
            }
            isXml = true;
            return;
        } else {
            if (revert && isBomPresent) {
                sourceEnc = "UTF-8";
            }
            isXml = false;
        }
    }
    /*
         * At this point, we know we're dealing with JSP syntax.
         * If an XML prolog is provided, it's treated as template text.
         * Determine the page encoding from the page directive, unless it's
         * specified via JSP config.
         */
    if (!isBomPresent) {
        sourceEnc = jspConfigPageEnc;
        if (sourceEnc == null) {
            sourceEnc = getPageEncodingForJspSyntax(jspReader, startMark);
            if (sourceEnc == null) {
                // Default to "ISO-8859-1" per JSP spec
                sourceEnc = "ISO-8859-1";
                isDefaultPageEncoding = true;
            }
        }
    }
}
Also used : JasperException(org.apache.sling.scripting.jsp.jasper.JasperException) FileNotFoundException(java.io.FileNotFoundException)

Example 8 with JasperException

use of org.apache.sling.scripting.jsp.jasper.JasperException in project sling by apache.

the class SmapUtil method generateSmap.

//*********************************************************************
// Public entry points
/**
     * Generates an appropriate SMAP representing the current compilation
     * context.  (JSR-045.)
     *
     * @param ctxt Current compilation context
     * @param pageNodes The current JSP page
     * @return a SMAP for the page
     */
public static String[] generateSmap(JspCompilationContext ctxt, Node.Nodes pageNodes) throws IOException {
    // Scan the nodes for presence of Jasper generated inner classes
    PreScanVisitor psVisitor = new PreScanVisitor();
    try {
        pageNodes.visit(psVisitor);
    } catch (JasperException ex) {
    }
    HashMap map = psVisitor.getMap();
    // set up our SMAP generator
    SmapGenerator g = new SmapGenerator();
    /** Disable reading of input SMAP because:
            1. There is a bug here: getRealPath() is null if .jsp is in a jar
        	Bugzilla 14660.
            2. Mappings from other sources into .jsp files are not supported.
            TODO: fix 1. if 2. is not true.
        // determine if we have an input SMAP
        String smapPath = inputSmapPath(ctxt.getRealPath(ctxt.getJspFile()));
            File inputSmap = new File(smapPath);
            if (inputSmap.exists()) {
                byte[] embeddedSmap = null;
            byte[] subSmap = SDEInstaller.readWhole(inputSmap);
            String subSmapString = new String(subSmap, SMAP_ENCODING);
            g.addSmap(subSmapString, "JSP");
        }
         **/
    // now, assemble info about our own stratum (JSP) using JspLineMap
    SmapStratum s = new SmapStratum("JSP");
    g.setOutputFileName(unqualify(ctxt.getServletJavaFileName()));
    // Map out Node.Nodes
    evaluateNodes(pageNodes, s, map, ctxt.getOptions().getMappedFile());
    s.optimizeLineSection();
    g.addStratum(s, true);
    dumpSmap(g, ctxt.getClassFileName(), ctxt);
    String classFileName = ctxt.getClassFileName();
    int innerClassCount = map.size();
    String[] smapInfo = new String[2 + innerClassCount * 2];
    smapInfo[0] = classFileName;
    smapInfo[1] = g.getString();
    int count = 2;
    Iterator iter = map.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        String innerClass = (String) entry.getKey();
        s = (SmapStratum) entry.getValue();
        s.optimizeLineSection();
        g = new SmapGenerator();
        g.setOutputFileName(unqualify(ctxt.getServletJavaFileName()));
        g.addStratum(s, true);
        String innerClassFileName = classFileName.substring(0, classFileName.indexOf(".class")) + '$' + innerClass + ".class";
        dumpSmap(g, innerClassFileName, ctxt);
        smapInfo[count] = innerClassFileName;
        smapInfo[count + 1] = g.getString();
        count += 2;
    }
    return smapInfo;
}
Also used : JasperException(org.apache.sling.scripting.jsp.jasper.JasperException) HashMap(java.util.HashMap) Iterator(java.util.Iterator) Map(java.util.Map) HashMap(java.util.HashMap)

Example 9 with JasperException

use of org.apache.sling.scripting.jsp.jasper.JasperException in project sling by apache.

the class TagLibraryInfoImpl method generateTLDLocation.

/*
     * @param uri The uri of the TLD @param ctxt The compilation context
     *
     * @return String array whose first element denotes the path to the TLD. If
     * the path to the TLD points to a jar file, then the second element denotes
     * the name of the TLD entry in the jar file, which is hardcoded to
     * META-INF/taglib.tld.
     */
private String[] generateTLDLocation(String uri, JspCompilationContext ctxt) throws JasperException {
    int uriType = TldLocationsCache.uriType(uri);
    if (uriType == TldLocationsCache.ABS_URI) {
        err.jspError("jsp.error.taglibDirective.absUriCannotBeResolved", uri);
    } else if (uriType == TldLocationsCache.NOROOT_REL_URI) {
        uri = ctxt.resolveRelativeUri(uri);
    }
    String[] location = new String[2];
    location[0] = uri;
    if (location[0].endsWith("jar")) {
        URL url = null;
        try {
            url = ctxt.getResource(location[0]);
        } catch (Exception ex) {
            err.jspError("jsp.error.tld.unable_to_get_jar", location[0], ex.toString());
        }
        if (url == null) {
            err.jspError("jsp.error.tld.missing_jar", location[0]);
        }
        location[0] = url.toString();
        location[1] = "META-INF/taglib.tld";
    }
    return location;
}
Also used : URL(java.net.URL) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) JasperException(org.apache.sling.scripting.jsp.jasper.JasperException)

Example 10 with JasperException

use of org.apache.sling.scripting.jsp.jasper.JasperException in project sling by apache.

the class JspReader method pushFile.

/**
     * Push a file (and its associated Stream) on the file stack.  THe
     * current position in the current file is remembered.
     */
private void pushFile(String file, String encoding, InputStreamReader reader) throws JasperException, FileNotFoundException {
    // Register the file
    String longName = file;
    int fileid = registerSourceFile(longName);
    if (fileid == -1) {
        // Bugzilla 37407: http://issues.apache.org/bugzilla/show_bug.cgi?id=37407
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception any) {
                if (log.isDebugEnabled()) {
                    log.debug("Exception closing reader: ", any);
                }
            }
        }
        err.jspError("jsp.error.file.already.registered", file);
    }
    currFileId = fileid;
    try {
        CharArrayWriter caw = new CharArrayWriter();
        char[] buf = new char[1024];
        for (int i = 0; (i = reader.read(buf)) != -1; ) caw.write(buf, 0, i);
        caw.close();
        if (current == null) {
            current = new Mark(this, caw.toCharArray(), fileid, getFile(fileid), master, encoding);
        } else {
            current.pushStream(caw.toCharArray(), fileid, getFile(fileid), longName, encoding);
        }
    } catch (Throwable ex) {
        log.error("Exception parsing file ", ex);
        // Pop state being constructed:
        popFile();
        err.jspError("jsp.error.file.cannot.read", file);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception any) {
                if (log.isDebugEnabled()) {
                    log.debug("Exception closing reader: ", any);
                }
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) JasperException(org.apache.sling.scripting.jsp.jasper.JasperException) CharArrayWriter(java.io.CharArrayWriter)

Aggregations

JasperException (org.apache.sling.scripting.jsp.jasper.JasperException)42 IOException (java.io.IOException)31 ServletException (javax.servlet.ServletException)19 PrivilegedActionException (java.security.PrivilegedActionException)17 Method (java.lang.reflect.Method)14 FileNotFoundException (java.io.FileNotFoundException)9 MalformedURLException (java.net.MalformedURLException)6 Iterator (java.util.Iterator)6 InputStream (java.io.InputStream)5 JarFile (java.util.jar.JarFile)5 TagInfo (javax.servlet.jsp.tagext.TagInfo)4 TreeNode (org.apache.sling.scripting.jsp.jasper.xmlparser.TreeNode)4 DependencyResolutionRequiredException (org.apache.maven.artifact.DependencyResolutionRequiredException)3 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)3 SAXException (org.xml.sax.SAXException)3 File (java.io.File)2 InputStreamReader (java.io.InputStreamReader)2 URL (java.net.URL)2 Enumeration (java.util.Enumeration)2 HashMap (java.util.HashMap)2