alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *  Copyright 1999-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.apache.jasper.compiler;

import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.jasper.Constants;
import org.apache.jasper.JasperException;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/** 
 * This class has all the utility method(s).
 * Ideally should move all the bean containers here.
 *
 * @author Mandar Raje.
 * @author Rajiv Mordani.
 */
public class JspUtil {

    private static final String OPEN_EXPR  = "<%=";
    private static final String CLOSE_EXPR = "%>";

    public static char[] removeQuotes(char []chars) {
	CharArrayWriter caw = new CharArrayWriter();
	try {
	for (int i = 0; i < chars.length; i++) {
	    if (chars[i] == '%' && chars[i+1] == '\\' &&
		chars[i+2] == '\\' && chars[i+3] == '>') {
		caw.write('%');
		caw.write('>');
		i = i + 3;
	    }
	    else caw.write(chars[i]);
	}
	} catch( Exception ex ) {}
	return caw.toCharArray();
    }

    // Checks if the token is a runtime expression.
    public static boolean isExpression (String token) {
	
	if (token.startsWith(OPEN_EXPR) && token.endsWith(CLOSE_EXPR)) {
	    return true;
	}

	return false;
    }

    // Returns the "expression" part -- takin <%= and %> out.
    public static String getExpr (String expression) {
	String returnString;
	int length = expression.length();
	
	if (expression.startsWith(OPEN_EXPR) && expression.endsWith(CLOSE_EXPR)) {
	    returnString = expression.substring (OPEN_EXPR.length(), length - CLOSE_EXPR.length());
	} else {
	    returnString = "";
	}

	return returnString;
    }

    // Parses the XML document contained in the InputStream.
    public static Document parseXMLDoc(InputStream in, String dtdResource, 
    					  String dtdId) throws JasperException 
    {
	return parseXMLDocJaxp(in, dtdResource, dtdId );
    }

    // Parses the XML document contained in the InputStream.
    public static Document parseXMLDocJaxp(InputStream in, String dtdResource, 
					   String dtdId)
	throws JasperException
    {
	try {
	    Document tld;
	    DocumentBuilderFactory docFactory = DocumentBuilderFactory.
		newInstance();
	    docFactory.setValidating(true);
	    docFactory.setNamespaceAware(true);
	    DocumentBuilder builder = docFactory.newDocumentBuilder();
	    
	    /***
	     * These lines make sure that we have an internal catalog entry for
	     * the taglib.dtdfile; this is so that jasper can run standalone 
	     * without running out to the net to pick up the taglib.dtd file.
	     */
	    MyEntityResolver resolver =
		new MyEntityResolver(dtdId, dtdResource);
	    builder.setEntityResolver(resolver);
	    tld = builder.parse(in);
	    return tld;
	} catch( ParserConfigurationException ex ) {
	    ex.printStackTrace();
            throw new JasperException(Constants.
				      getString("jsp.error.parse.error.in.TLD",
						new Object[] {
						    ex.getMessage()
						}));
	    
	} catch ( SAXException sx ) {
            throw new JasperException(Constants.
				      getString("jsp.error.parse.error.in.TLD",
						new Object[] {
						    sx.getMessage()
						}));
        } catch (IOException io) {
            throw new JasperException(Constants.
				      getString("jsp.error.unable.to.open.TLD",
						new Object[] {
						    io.getMessage() }));
	}
    }

    public static void checkAttributes (String typeOfTag, Hashtable attrs,
    					ValidAttribute[] validAttributes, Mark start)
					throws JasperException
    {
	boolean valid = true;
	Hashtable temp = (Hashtable)attrs.clone ();

	/**
	 * First check to see if all the mandatory attributes are present.
	 * If so only then proceed to see if the other attributes are valid
	 * for the particular tag.
	 */
	String missingAttribute = null;

	for (int i = 0; i < validAttributes.length; i++) {
	        
	    if (validAttributes[i].mandatory) {
	        if (temp.get (validAttributes[i].name) != null) {
	            temp.remove (validAttributes[i].name);
		    valid = true;
		} else {
		    valid = false;
		    missingAttribute = validAttributes[i].name;
		    break;
		}
	    }
	}

	/**
	 * If mandatory attribute is missing then the exception is thrown.
	 */
	if (!valid)
	    throw new ParseException(start, Constants.getString(
			"jsp.error.mandatory.attribute", 
                                 new Object[] { typeOfTag, missingAttribute}));

	/**
	 * Check to see if there are any more attributes for the specified
	 * tag.
	 */
	if (temp.size() == 0)
	    return;

	/**
	 * Now check to see if the rest of the attributes are valid too.
	 */
   	Enumeration enum = temp.keys ();
	String attribute = null;

	while (enum.hasMoreElements ()) {
	    valid = false;
	    attribute = (String) enum.nextElement ();
	    for (int i = 0; i < validAttributes.length; i++) {
	        if (attribute.equals(validAttributes[i].name)) {
		    valid = true;
		    break;
		}
	    }
	    if (!valid)
	        throw new ParseException(start, Constants.getString(
			"jsp.error.invalid.attribute", 
                                 new Object[] { typeOfTag, attribute }));
	}
    }
    
    public static String escapeQueryString(String unescString) {
	if ( unescString == null )
	    return null;
	
	String escString    = "";
	String shellSpChars = "\\\"";
	
	for(int index=0; index') {
                sb.append(">");
            } else if (c == '\'') {
                sb.append("'");
            } else if (c == '&') {
                sb.append("&");
            } else if (c == '"') {
                sb.append(""e;");
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static class ValidAttribute {
   	String name;
	boolean mandatory;

	public ValidAttribute (String name, boolean mandatory) {
	    this.name = name;
	    this.mandatory = mandatory;
	}

	public ValidAttribute (String name) {
	    this (name, false);
	}
    }
}

class MyEntityResolver implements EntityResolver {

    String dtdId;
    String dtdResource;
    
    public MyEntityResolver(String id, String resource) {
	this.dtdId = id;
	this.dtdResource = resource;
    }
    
    public InputSource resolveEntity(String publicId, String systemId)
	throws SAXException, IOException
    {
	//System.out.println ("publicId = " + publicId);
	//System.out.println ("systemId is " + systemId);
	//System.out.println ("resource is " + dtdResource);
	if (publicId.equals(dtdId)) {
	    InputStream input =
		this.getClass().getResourceAsStream(dtdResource);
	    InputSource isrc =
		new InputSource(input);
	    return isrc;
	}
	else {
	    //System.out.println ("returning null though dtdURL is " + dtdURL);
	    return null;
	}
    }
}




... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.