. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions
-// are met:
-// 1. Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
-// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
-// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-// SUCH DAMAGE.
-//
-// Visit the ACME Labs Java page for up-to-date versions of this and other
-// fine Java utilities: http://www.acme.com/java/
-//
-// Base64 code borrowed from public domain supported by Robert Harder
-// Please visit http://iharder.net/base64
-// periodically to check for updates or to contribute improvements.
-//
-// All enhancements Copyright (C)1998-2010 by Dmitriy Rogatkin
-//
-// $Id: Utils.java,v 1.39 2013/08/10 02:47:26 cvs Exp $
-
-package Acme;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.io.Reader;
-import java.io.UnsupportedEncodingException;
-import java.io.Writer;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.StringTokenizer;
-
-/// Assorted static utility routines.
-//
-// Whenever I come up with a static routine that might be of general use,
-// I put it here. So far the class includes:
-//
-// - some string routines that were left out of java.lang.String
-//
- a general array-to-string routine
-//
- a fixed version of java.io.InputStream's byte-array read routine
-//
- a bunch of URL-hacking routines
-//
- some easy-to-use wrappers for Runtime.exec
-//
- a debugging routine to dump the current call stack
-//
- a URLDecoder to match java.net.URLEncoder
-//
-// and lots more.
-//
-// Fetch the software.
-// Fetch the entire Acme package.
-
-public class Utils {
- // / Returns a date string formatted in Unix ls style - if it's within
- // six months of now, Mmm dd hh:ss, else Mmm dd yyyy.
- static final SimpleDateFormat shortfmt = new SimpleDateFormat("MMM dd HH:mm");
-
- static final SimpleDateFormat longfmt = new SimpleDateFormat("MMM dd yyyy");
-
- public static final int COPY_BUF_SIZE = 4096 * 2;
-
- public final static String ISO_8859_1 = "ISO-8859-1";
-
- public static final Class[] EMPTY_CLASSES = {};
-
- public static final Object[] EMPTY_OBJECTS = {};
-
- public static final Enumeration EMPTY_ENUMERATION = new Enumeration() {
- public boolean hasMoreElements() {
- return false;
- }
-
- public Object nextElement() {
- return null;
- }
- };
-
- public static String lsDateStr(Date date) {
- if (Math.abs(System.currentTimeMillis() - date.getTime()) < 183L * 24L * 60L * 60L * 1000L)
- return shortfmt.format(date);
- else
- return longfmt.format(date);
- }
-
- public static Hashtable parseQueryString(String query, String encoding) {
- Hashtable result = new Hashtable();
- if (encoding == null)
- encoding = "UTF-8";
- StringTokenizer st = new StringTokenizer(query, "&");
- while (st.hasMoreTokens()) {
- String pair = st.nextToken();
- int ep = pair.indexOf('=');
- String key = ep > 0 ? pair.substring(0, ep) : pair;
- String value = ep > 0 ? pair.substring(ep + 1) : "";
- try {
- key = /* URLDecoder. */decode(key, encoding);
- if (value != null)
- value = /* URLDecoder. */decode(value, encoding);
- } catch (UnsupportedEncodingException uee) {
- }
- String[] values = (String[]) result.get(key);
- String[] newValues;
- if (values == null) {
- newValues = new String[1];
- newValues[0] = value;
- } else {
- newValues = new String[values.length + 1];
- System.arraycopy(values, 0, newValues, 0, values.length);
- newValues[values.length] = value;
- }
- result.put(key, newValues);
- }
- return result;
- }
-
- public static Map parsePostData(long len, InputStream is, String encoding, String[] cachedStream)
- throws IOException {
- // TODO: handle parsing data over 2 GB
- if (len > Integer.MAX_VALUE)
- throw new RuntimeException("Can't process POST data over " + Integer.MAX_VALUE + ", requested: " + len);
- byte[] buf = new byte[(int) len];
- int fp = 0;
- while (fp < len) {
- int c = is.read(buf, fp, buf.length - fp);
- if (c < 0)
- break;
- fp += c;
- }
- //System.err.println("====>"+new String( buf));
- if (cachedStream != null && cachedStream.length > 0)
- return parseQueryString(cachedStream[0] = new String(buf, 0, fp, ISO_8859_1), encoding);
- else
- return parseQueryString(new String(buf, 0, fp, ISO_8859_1), encoding);
- }
-
- /**
- * Decodes URL encoded string including newly introduced JavaScript encoding with %uxxxx chars
- *
- * @param s
- * encoded string
- * @param enc
- * source encoding
- * @return decoded string or original if no decoding required
- * @throws UnsupportedEncodingException
- */
- public static String decode(String s, String enc) throws UnsupportedEncodingException {
- if (enc == null || enc.length() == 0) {
- throw new UnsupportedEncodingException("decode: no source char encoding provided.");
- }
- if (s == null)
- return null;
- boolean decoded = false;
- int l = s.length();
- StringBuffer sb = new StringBuffer(l > 1024 ? l / 3 : l);
-
- int state = sText;
- int i = 0;
- int code = 0;
- char c;
- int pos = 0;
- int ofs = 0;
- byte[] buf = null;
- boolean processDig = false;
- while (i < l) {
- c = s.charAt(i);
- switch (c) {
- case '+':
- decoded = true;
- if (state == sText)
- sb.append(' ');
- else if (state == s2Dig) {
- sb.append(new String(buf, 0, pos + 1, enc));
- state = sText;
- sb.append(' ');
- } else
- new IllegalArgumentException("decode: unexpected + at pos: " + i + ", of : " + s);
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- ofs = '0';
- processDig = true;
- break;
- case 'a':
- case 'b':
- case 'c':
- case 'd':
- case 'e':
- case 'f':
- ofs = 'a' - 10;
- processDig = true;
- break;
- case 'A':
- case 'B':
- case 'C':
- case 'D':
- case 'E':
- case 'F':
- ofs = 'A' - 10;
- processDig = true;
- break;
- case '%':
- decoded = true;
- if (state == sText) {
- state = sEscape;
- if (buf == null)
- buf = new byte[(l - i) / 3];
- pos = 0;
- } else if (state == s2Dig) {
- state = sEscape;
- pos++;
- } else
- new IllegalArgumentException("decode: unexpected escape % at pos: " + i + ", of : " + s);
- break;
- case 'u':
- if (state == sEscape) {
- if (pos > 0) {
- sb.append(new String(buf, 0, pos, enc));
- pos = 0;
- }
- state = sU1;
- } else if (state == sText) {
- sb.append(c);
- } else if (state == s2Dig) {
- sb.append(new String(buf, 0, pos + 1, enc));
- state = sText;
- sb.append(c);
- } else
- new IllegalArgumentException("decode: unexpected char in hex at pos: " + i + ", of : " + s);
- break;
- default:
- if (state == sText)
- sb.append(c);
- else if (state == s2Dig) {
- sb.append(new String(buf, 0, pos + 1, enc));
- state = sText;
- sb.append(c);
- } else
- new IllegalArgumentException("decode: unexpected char in hex at pos: " + i + ", of : " + s);
-
- break;
- }
- i++;
- if (processDig) {
- if (state == sEscape) {
- code = c - ofs;
- state = s1Dig;
- } else if (state == s1Dig) {
- buf[pos] = (byte) (code * 16 + (c - ofs));
- state = s2Dig;
- } else if (state == s2Dig) { // escape finished
- sb.append(new String(buf, 0, pos + 1, enc));
- state = sText;
- sb.append(c);
- } else if (state == sU1) {
- code = c - ofs;
- state = sU2;
- } else if (state == sU2) {
- code = code * 16 + c - ofs;
- state = sU3;
- } else if (state == sU3) {
- code = code * 16 + c - ofs;
- state = sU4;
- } else if (state == sU4) {
- sb.append((char) (code * 16 + c - ofs));
- state = sText;
- } else
- sb.append(c);
- processDig = false;
- }
- }
- if (state == s2Dig)
- sb.append(new String(buf, 0, pos + 1, enc));
- return (decoded ? sb.toString() : s);
- }
-
- private static final int sText = 0;
-
- private static final int s1Dig = 1;
-
- private static final int s2Dig = 2;
-
- private static final int sEscape = 3;
-
- private static final int sU1 = 4;
-
- private static final int sU2 = 5;
-
- private static final int sU3 = 6;
-
- private static final int sU4 = 7;
-
- public static String htmlEncode(String s, boolean encodeWS) {
- if (s == null)
- return null;
- char[] ca = s.toCharArray();
- StringBuffer res = new StringBuffer(ca.length);
- int ls = 0;
- boolean blankMet = true;
- for (int i = 0; i < ca.length; i++) {
- switch (ca[i]) {
- case '<':
- res.append(ca, ls, i - ls);
- res.append("<");
- ls = i + 1;
- break;
- case '>':
- res.append(ca, ls, i - ls);
- res.append(">");
- ls = i + 1;
- break;
- case '"':
- res.append(ca, ls, i - ls);
- res.append(""");
- ls = i + 1;
- break;
- case '&':
- res.append(ca, ls, i - ls);
- res.append("&");
- ls = i + 1;
- break;
- case ' ':
- if (blankMet && encodeWS) {
- res.append(ca, ls, i - ls);
- res.append(" ");
- ls = i + 1;
- } else
- blankMet = true;
- break;
- case '\n':
- if (encodeWS) {
- res.append(ca, ls, i - ls);
- res.append("
");
- ls = i + 1;
- }
- break;
- case '\r':
- if (encodeWS) {
- res.append(ca, ls, i - ls);
- ls = i + 1;
- }
- break;
- default:
- if (ca[i] > 127) { // no unicode
- res.append(ca, ls, i - ls);
- res.append("").append((int)ca[i]).append(';');
- ls = i + 1;
- }
- blankMet = false;
- }
- }
- if (ls < ca.length)
- res.append(ca, ls, ca.length - ls);
- return res.toString();
- }
-
- public static float isGzipAccepted(String contentEncoding) {
- float result = 0f;
- if (contentEncoding != null) {
- int gzsl = "gzip;".length();
- int zp = contentEncoding.indexOf("gzip");
- if (zp >= 0) {
- if (contentEncoding.length() > (zp+gzsl) &&contentEncoding.charAt(zp + gzsl) == ';') {
- zp = contentEncoding.indexOf("q=", zp + gzsl);
- if (zp > 0) {
- int qe = contentEncoding.indexOf(",", zp);
- if (qe < 0)
- qe = contentEncoding.length();
- try {
- result = Float.parseFloat(contentEncoding.substring(zp + 2, qe));
- } catch (NumberFormatException e) {
- }
- }
- } else
- result = 1f;
- }
- }
- return result;
- }
-
- // / Checks whether a string matches a given wildcard pattern.
- // Only does ? and *, and multiple patterns separated by |.
- public static boolean match(String pattern, String string) {
- for (int p = 0;; ++p) {
- for (int s = 0;; ++p, ++s) {
- boolean sEnd = (s >= string.length());
- boolean pEnd = (p >= pattern.length() || pattern.charAt(p) == '|');
- if (sEnd && pEnd)
- return true;
- if (sEnd || pEnd)
- break;
- if (pattern.charAt(p) == '?')
- continue;
- if (pattern.charAt(p) == '*') {
- int i;
- ++p;
- for (i = string.length(); i >= s; --i)
- if (match(pattern.substring(p), string.substring(i))) // not quite right
- return true;
- break;
- }
- if (pattern.charAt(p) != string.charAt(s))
- break;
- }
- p = pattern.indexOf('|', p);
- if (p == -1)
- return false;
- }
- }
-
- // / Finds the maximum length of a string that matches a given wildcard
- // pattern. Only does ? and *, and multiple patterns separated by |.
- public static int matchSpan(String pattern, String string) {
- int result = 0;
- StringTokenizer st = new StringTokenizer(pattern, "|");
-
- while (st.hasMoreTokens()) {
- int len = matchSpan1(st.nextToken(), string);
- if (len > result)
- result = len;
- }
- return result;
- }
-
- static int matchSpan1(String pattern, String string) {
- int p = 0;
- for (; p < string.length() && p < pattern.length(); p++) {
- if (pattern.charAt(p) == string.charAt(p))
- continue;
- if (pattern.charAt(p) == '*')
- return p - 1;
- return 0;
- }
- return p < (pattern.length() - 1) ? -1 : p;
- }
-
- // / Turns a String into an array of Strings, by using StringTokenizer
- // to split it up at whitespace.
- public static String[] splitStr(String str) {
- StringTokenizer st = new StringTokenizer(str);
- int n = st.countTokens();
- String[] strs = new String[n];
- for (int i = 0; i < n; ++i)
- strs[i] = st.nextToken();
- return strs;
- }
-
- // / Turns a String into an array of Strings, by splitting it at
- // the specified character. This does not use StringTokenizer,
- // and therefore can handle empty fields.
- public static String[] splitStr(String str, char delim) {
- int n = 1;
- int index = -1;
- while (true) {
- index = str.indexOf(delim, index + 1);
- if (index == -1)
- break;
- ++n;
- }
- String[] strs = new String[n];
- index = -1;
- for (int i = 0; i < n - 1; ++i) {
- int nextIndex = str.indexOf(delim, index + 1);
- strs[i] = str.substring(index + 1, nextIndex);
- index = nextIndex;
- }
- strs[n - 1] = str.substring(index + 1);
- return strs;
- }
-
- public static String[] splitStr(String str, String quotes) {
- char[] ca = str.toCharArray();
- // List result = new ArrayList(10);
- String[] result = new String[0];
- boolean inArg = false;
- boolean quoted = false;
- int argStart = -1;
- for (int i = 0; i < ca.length; i++) {
- char c = ca[i];
- if (inArg) {
- if (quoted) {
- if (quotes.indexOf(c) >= 0) {
- result = copyOf(result, result.length + 1);
- result[result.length - 1] = new String(ca, argStart, i - argStart);
- argStart = -1;
- quoted = false;
- inArg = false;
- }
- } else {
- if (c == ' ') {
- result = copyOf(result, result.length + 1);
- result[result.length - 1] = new String(ca, argStart, i - argStart);
- argStart = -1;
- inArg = false;
- }
- }
- } else {
- if (c != ' ') {
- inArg = true;
- if (quotes.indexOf(c) >= 0) {
- quoted = true;
- argStart = i + 1;
- } else
- argStart = i;
- }
- }
- }
- if (argStart > 0) {
- result = copyOf(result, result.length + 1);
- result[result.length - 1] = new String(ca, argStart, ca.length - argStart);
- }
- // for(int i=0;i 0)
- pathElems.remove(pathElems.size() - 1);
- else
- lev--;
- // else exception ?
- } else if (el.equals(".") == false)
- if (lev >= 0)
- pathElems.add(el);
- else
- lev++;
- if (f) {
- s = i;
- break;
- }
- s = -1;
- }
- }
- }
- if (s > 0) {
- String el = new String(pa, s, n - s);
- if (el.equals("..")) {
- if (pathElems.size() > 0)
- pathElems.remove(pathElems.size() - 1);
- // else exception ?
- } else if (el.equals(".") == false)
- if (lev >= 0)
- pathElems.add(el);
- } else
- pathElems.add("");
- if (pathElems.size() == 0)
- return lev>=0?"":null;
- StringBuffer result = new StringBuffer(n);
- result.append(pathElems.get(0));
- n = pathElems.size();
- for (int i = 1; i < n; i++)
- result.append('/').append(pathElems.get(i));
- // System.err.println("Before "+path+" after "+result);
- return result.toString();
- }
-
- // / Copy the input to the output until EOF.
- public static long copyStream(InputStream in, OutputStream out, long maxLen) throws IOException {
- byte[] buf = new byte[COPY_BUF_SIZE];
- int len;
- long tot = 0;
- if (maxLen <= 0)
- while ((len = in.read(buf)) > 0) {
- out.write(buf, 0, len);
- tot += len;
- }
- else
- while ((len = in.read(buf)) > 0)
- if (len <= maxLen) {
- out.write(buf, 0, len);
- maxLen -= len;
- tot += len;
- } else {
- out.write(buf, 0, (int) maxLen);
- tot += maxLen;
- break;
- }
- return tot;
- }
-
- // / Copy the input to the output until EOF.
- public static void copyStream(Reader in, Writer out) throws IOException {
- char[] buf = new char[COPY_BUF_SIZE];
- int len;
- while ((len = in.read(buf)) != -1)
- out.write(buf, 0, len);
- }
-
- // / Copy the input to the output until EOF.
- public static void copyStream(Reader in, OutputStream out, String charSet) throws IOException {
- char[] buf = new char[4096];
- int len;
- if (charSet == null)
- while ((len = in.read(buf)) != -1) {
- out.write(new String(buf, 0, len).getBytes());
- }
- else
- while ((len = in.read(buf)) != -1)
- out.write(new String(buf, 0, len).getBytes(charSet));
- }
-
- protected final static char BASE64ARRAY[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
- 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
- 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
- '4', '5', '6', '7', '8', '9', '+', '/' };
-
- /**
- * base 64 encoding, string converted to bytes using specified encoding
- *
- * @param String
- * _s original string to encode
- * @param String
- * encoding, can be null, then iso-8859-1 used
- * @return String result of encoding as iso-8859-1 string
- * return null in case of invalid encoding or original string null
- * @exception no
- * exceptions
- */
- public final static String base64Encode(String _s, String _enc) {
- if (_s == null)
- return null;
- if (_enc == null)
- _enc = ISO_8859_1;
- try {
- return base64Encode(_s.getBytes(_enc));
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * base 64 encoding, array of bytes converted to bytes using specified encoding
- *
- * @param String
- * _s original string to encode
- * @param String
- * encoding, can be null, then iso-8859-1 used
- * @return String result of encoding as iso-8859-1 string
- *
- * @exception NullPointerException if input parameter is null
- */
- public final static String base64Encode(byte[] _bytes) {
- StringBuffer encodedBuffer = new StringBuffer((int) (_bytes.length * 1.5));
- int i = 0;
- int pad = 0;
- while (i < _bytes.length) {
- int b1 = (0xFF & _bytes[i++]);
- int b2;
- int b3;
- if (i >= _bytes.length) {
- b2 = 0;
- b3 = 0;
- pad = 2;
- } else {
- b2 = 0xFF & _bytes[i++];
- if (i >= _bytes.length) {
- b3 = 0;
- pad = 1;
- } else
- b3 = (0xFF & _bytes[i++]);
- }
- byte c1 = (byte) (b1 >> 2);
- byte c2 = (byte) (((b1 & 0x3) << 4) | (b2 >> 4));
- byte c3 = (byte) (((b2 & 0xf) << 2) | (b3 >> 6));
- byte c4 = (byte) (b3 & 0x3f);
- encodedBuffer.append(BASE64ARRAY[c1]).append(BASE64ARRAY[c2]);
- switch (pad) {
- case 0:
- encodedBuffer.append(BASE64ARRAY[c3]).append(BASE64ARRAY[c4]);
- break;
- case 1:
- encodedBuffer.append(BASE64ARRAY[c3]).append('=');
- break;
- case 2:
- encodedBuffer.append("==");
- break;
- }
- }
- return encodedBuffer.toString();
- }
-
- /**
- * Translates a Base64 value to either its 6-bit reconstruction value or a negative number indicating some other meaning.
- */
- protected final static byte[] DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
- -5, -5, // Whitespace: Tab and Linefeed
- -9, -9, // Decimal 11 - 12
- -5, // Whitespace: Carriage Return
- -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 -
- // 26
- -9, -9, -9, -9, -9, // Decimal 27 - 31
- -5, // Whitespace: Space
- -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
- 62, // Plus sign at decimal 43
- -9, -9, -9, // Decimal 44 - 46
- 63, // Slash at decimal 47
- 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
- -9, -9, -9, // Decimal 58 - 60
- -1, // Equals sign at decimal 61
- -9, -9, -9, // Decimal 62 - 64
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A'
- // through 'N'
- 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O'
- // through 'Z'
- -9, -9, -9, -9, -9, -9, // Decimal 91 - 96
- 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a'
- // through 'm'
- 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n'
- // through 'z'
- -9, -9, -9, -9 // Decimal 123 - 126
- };
-
- protected final static byte WHITE_SPACE_ENC = -5; // Indicates white space
-
- // in encoding
-
- protected final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign
-
- // in encoding
-
- /** The equals sign (=) as a byte. */
- protected final static byte EQUALS_SIGN = (byte) '=';
-
- /**
- * base 64 decoding
- *
- * @param encoded
- * string
- * @param encoding
- * used to get string bytes
- * @return result of encoding, or null if encoding invalid or string null, or string is invalid base 64 encoding
- */
- public final static String base64Decode(String _s, String _enc) {
- if (_s == null)
- return null;
- if (_enc == null)
- _enc = ISO_8859_1;
- try {
- return new String(decode64(_s), _enc);
- } catch (UnsupportedEncodingException uee) {
- }
- return null;
- }
-
- /**
- * Decodes four bytes from array source and writes the resulting bytes (up to three of them) to destination. The source and
- * destination arrays can be manipulated anywhere along their length by specifying srcOffset and destOffset. This method does not
- * check to make sure your arrays are large enough to accomodate srcOffset + 4 for the source array or destOffset + 3
- * for the destination array. This method returns the actual number of bytes that were converted from the Base64 encoding.
- *
- *
- * @param source
- * the array to convert
- * @param srcOffset
- * the index where conversion begins
- * @param destination
- * the array to hold the conversion
- * @param destOffset
- * the index where output will be put
- * @return the number of decoded bytes converted
- * @since 1.3
- */
- private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset) {
- // Example: Dk==
- if (source[srcOffset + 2] == EQUALS_SIGN) {
- // Two ways to do the same thing. Don't know which way I like best.
- // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6
- // )
- // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
- int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
- | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12);
-
- destination[destOffset] = (byte) (outBuff >>> 16);
- return 1;
- }
-
- // Example: DkL=
- else if (source[srcOffset + 3] == EQUALS_SIGN) {
- // Two ways to do the same thing. Don't know which way I like best.
- // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6
- // )
- // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
- // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
- int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
- | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
- | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6);
-
- destination[destOffset] = (byte) (outBuff >>> 16);
- destination[destOffset + 1] = (byte) (outBuff >>> 8);
- return 2;
- }
-
- // Example: DkLE
- else {
- try {
- // Two ways to do the same thing. Don't know which way I like
- // best.
- // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 )
- // >>> 6 )
- // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
- // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
- // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
- int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
- | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
- | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6)
- | ((DECODABET[source[srcOffset + 3]] & 0xFF));
-
- destination[destOffset] = (byte) (outBuff >> 16);
- destination[destOffset + 1] = (byte) (outBuff >> 8);
- destination[destOffset + 2] = (byte) (outBuff);
-
- return 3;
- } catch (Exception e) {
- System.out.println("" + source[srcOffset] + ": " + (DECODABET[source[srcOffset]]));
- System.out.println("" + source[srcOffset + 1] + ": " + (DECODABET[source[srcOffset + 1]]));
- System.out.println("" + source[srcOffset + 2] + ": " + (DECODABET[source[srcOffset + 2]]));
- System.out.println("" + source[srcOffset + 3] + ": " + (DECODABET[source[srcOffset + 3]]));
- return -1;
- } // e nd catch
- }
- } // end decodeToBytes
-
- /**
- * Very low-level access to decoding ASCII characters in the form of a byte array. Does not support automatically gunzipping or any other "fancy" features.
- *
- * @param source
- * The Base64 encoded data
- * @param off
- * The offset of where to begin decoding
- * @param len
- * The length of characters to decode
- * @return decoded data
- * @since 1.3
- */
- public static byte[] decode(byte[] source, int off, int len) {
- int len34 = len * 3 / 4;
- byte[] outBuff = new byte[len34]; // Upper limit on size of output
- int outBuffPosn = 0;
-
- byte[] b4 = new byte[4];
- int b4Posn = 0;
- int i = 0;
- byte sbiCrop = 0;
- byte sbiDecode = 0;
- for (i = off; i < off + len; i++) {
- sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits
- sbiDecode = DECODABET[sbiCrop];
-
- if (sbiDecode >= WHITE_SPACE_ENC) // Whitesp ace,Eq ualssi gnor be
- // tter
- {
- if (sbiDecode >= EQUALS_SIGN_ENC) {
- b4[b4Posn++] = sbiCrop;
- if (b4Posn > 3) {
- outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn);
- b4Posn = 0;
-
- // If that was the equals sign, break out of 'for' loop
- if (sbiCrop == EQUALS_SIGN)
- break;
- } // end if: quartet built
-
- } // end if: equals sign or better
-
- } // end if: white space, equals sign or better
- else {
- System.err.println("Bad Base64 input character at " + i + ": " + source[i] + "(decimal)");
- return null;
- } // end else:
- } // each input character
-
- byte[] out = new byte[outBuffPosn];
- System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
- return out;
- } // end decode
-
- /**
- * Decodes data from Base64 notation, automatically detecting gzip-compressed data and decompressing it.
- *
- * @param s
- * the string to decode
- * @return the decoded data
- * @since 1.4
- */
- public static byte[] decode64(String s) {
- byte[] bytes;
- try {
- bytes = s.getBytes(ISO_8859_1);
- } // end try
- catch (java.io.UnsupportedEncodingException uee) {
- bytes = s.getBytes();
- } // end catch
- //
-
- // Decode
- bytes = decode(bytes, 0, bytes.length);
-
- // Check to see if it's gzip-compressed
- // GZIP Magic Two-Byte Number: 0x8b1f (35615)
- if (bytes != null && bytes.length >= 4) {
-
- int head = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
- if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) {
- java.io.ByteArrayInputStream bais = null;
- java.util.zip.GZIPInputStream gzis = null;
- java.io.ByteArrayOutputStream baos = null;
- byte[] buffer = new byte[2048];
- int length = 0;
-
- try {
- baos = new java.io.ByteArrayOutputStream();
- bais = new java.io.ByteArrayInputStream(bytes);
- gzis = new java.util.zip.GZIPInputStream(bais);
-
- while ((length = gzis.read(buffer)) >= 0) {
- baos.write(buffer, 0, length);
- } // end while: reading input
-
- // No error? Get new bytes.
- bytes = baos.toByteArray();
-
- } // end try
- catch (java.io.IOException e) {
- // Just return originally-decoded bytes
- } // end catch
- finally {
- try {
- baos.close();
- } catch (Exception e) {
- }
- try {
- gzis.close();
- } catch (Exception e) {
- }
- try {
- bais.close();
- } catch (Exception e) {
- }
- } // end finally
-
- } // end if: gzipped
- } // end if: bytes.length >= 2
-
- return bytes;
- } // end decode
-
- /**
- * calculate local file based class path for class loader if possible (servlet classes must be located there)
- *
- * @param cl
- * class loader
- * @return class path in string
- */
- static public String calculateClassPath(ClassLoader cl) {
- // scan cl chain to find
- StringBuffer classPath = new StringBuffer();
- boolean jspFound = false, servletFound = false;
- while (cl != null) {
- if (cl instanceof URLClassLoader) {
- boolean addClasses = false;
- if (jspFound == false) {
- jspFound = ((URLClassLoader) cl).findResource("javax/servlet/jsp/JspPage.class") != null;
- addClasses |= jspFound;
- }
- if (servletFound == false) {
- servletFound = ((URLClassLoader) cl).findResource("javax/servlet/http/HttpServlet.class") != null;
- addClasses |= servletFound;
- }
- if (addClasses) {
- URL[] urls = ((URLClassLoader) cl).getURLs();
- for (int i = 0; i < urls.length; i++) {
- String classFile = toFile(urls[i]);
- if (classFile == null)
- continue;
- if (classPath.length() > 0)
- classPath.append(File.pathSeparatorChar).append(classFile);
- else
- classPath.append(classFile);
- }
- }
- if (jspFound && servletFound)
- return classPath.toString();
- }
- cl = cl.getParent();
- }
- return System.getProperty("java.class.path");
- }
-
- public static int parseInt(Object num, int def) {
- if (num instanceof Number)
- return ((Number)num).intValue();
- try {
- return Integer.parseInt(num.toString());
- } catch (Exception e) {
- return def;
- }
- }
-
- public static final String toFile(URL url) {
- if (url.getProtocol().indexOf("file") < 0)
- return null;
- String result = url.getPath();
- if (result.charAt(0) == '/' && File.separatorChar == '\\')
- result = result.substring(1);
- try {
- return decode(result, "UTF-8");
- } catch (UnsupportedEncodingException e) {
- return result;
- }
- }
-
- // public static final int firstOccurrence(String s, String occur) {
- //
- // }
-
- public static interface ThreadFactory {
- Thread create(Runnable runnable);
- }
-
- public static final class ThreadPool {
- static final int DEF_MAX_POOLED_THREAD = 20;
-
- static final String ID = "Acme.Utils.ThreadPool";
-
- public static final String MAXNOTHREAD = ID + ".maxpooledthreads";
-
- protected static int counter;
-
- protected ArrayList freeThreads;
-
- protected HashMap busyThreads;
-
- protected int maxThreads;
-
- protected ThreadFactory threadFactory;
-
- /**
- * Creates a thread pool not queued with max number of threads defined in properties or DEF_MAX_POOLED_THREAD = 20
- *
- * @param Properties
- * where property THREADSINPOOL gives max threads Note if THREADSINPOOL not integers, or negative then DEF_MAX_POOLED_THREAD used
- */
- public ThreadPool(Properties properties, ThreadFactory threadfactory) {
- maxThreads = parseInt(properties.getProperty(MAXNOTHREAD), DEF_MAX_POOLED_THREAD);
- if (maxThreads < 0)
- maxThreads = DEF_MAX_POOLED_THREAD;
- freeThreads = new ArrayList(maxThreads);
- busyThreads = new HashMap(maxThreads);
- this.threadFactory = threadfactory;
- }
-
- /**
- * Assigns a new value for max threads
- *
- * @param int
- * new value of max threads, can't be less than 2, but can be 0 If current number threads exceed the value, then extra thread will be
- * discarded gracefully
- */
- public void setMaxThreads(int newSize) {
- if (newSize > 2 || newSize == 0)
- maxThreads = newSize;
- }
-
- /**
- * Returns setting for max number of threads
- *
- * @return int setting for max number of threads, doesn't reflect actual number of threads though
- */
- public int getMaxThreads() {
- return maxThreads;
- }
-
- /**
- * Takes a new task for execution by a threads in pool will wait until free threads if number of threads reached max
- *
- * @param Runnable
- * task for execution
- */
- public void executeThread(Runnable runnable) {
- PooledThread pt = null;
- do {
- synchronized (freeThreads) {
- if (freeThreads.size() > 0)
- pt = (PooledThread) freeThreads.remove(0);
- }
- if (pt != null && pt.isAlive() == false)
- pt = null;
- if (pt == null)
- synchronized (busyThreads) {
- if (busyThreads.size() < maxThreads || maxThreads == 0)
- pt = new PooledThread();
- }
- if (pt == null)
- synchronized (freeThreads) {
- try {
- freeThreads.wait();
- } catch (InterruptedException ie) {
- }
- }
- } while (pt == null);
- pt.setName("-PooledThread: " + runnable);
- pt.setRunner(runnable);
- synchronized (busyThreads) {
- busyThreads.put(pt, pt);
- }
- }
-
- protected void finalize() throws Throwable {
- synchronized (freeThreads) {
- Iterator i = freeThreads.iterator();
- while (i.hasNext())
- ((PooledThread) i.next()).interrupt();
- }
- synchronized (busyThreads) {
- Iterator i = freeThreads.iterator();
- while (i.hasNext())
- ((PooledThread) i.next()).interrupt();
- }
- super.finalize();
- }
-
- public String toString() {
- if (freeThreads != null && busyThreads != null)
- return ID + ": free threads " + freeThreads.size() + " busy threads " + busyThreads.size();
- else
- return ID + ": not initialized yet. " + super.toString();
- }
-
- class PooledThread implements Runnable {
-
- Runnable runner;
-
- boolean quit;
-
- Thread delegateThread;
-
- String id = ID + "(" + (counter++) + ")";
-
- PooledThread() {
- if (threadFactory != null)
- delegateThread = threadFactory.create(this);
- else
- delegateThread = new Thread(this);
- setName("-PooledThread: CREATED");
- delegateThread.start();
- }
-
- public void setName(String name) {
- delegateThread.setName(id + name);
- }
-
- public boolean isAlive() {
- return delegateThread.isAlive();
- }
-
- synchronized public void run() {
- do {
- if (runner == null)
- try {
- this.wait();
- } catch (InterruptedException ie) {
-
- }
- if (runner != null) {
- try {
- runner.run();
- } catch (Throwable t) {
- if (t instanceof ThreadDeath)
- throw (ThreadDeath) t;
- t.printStackTrace();
- } finally {
- runner = null;
- }
-
- int activeThreads = 0;
- synchronized (busyThreads) {
- busyThreads.remove(this);
- activeThreads = busyThreads.size();
- }
- synchronized (freeThreads) {
- if (freeThreads.size() + activeThreads > maxThreads)
- break; // discard this thread
- freeThreads.add(this);
- delegateThread.setName(ID + "-PooledThread: FREE");
- freeThreads.notify();
- }
- }
- } while (!quit);
- }
-
- synchronized public void interrupt() {
- quit = true;
- delegateThread.interrupt();
- }
-
- synchronized void setRunner(Runnable runnable) {
- if (runner != null)
- throw new RuntimeException("Invalid worker thread state, current runner not null.");
- runner = runnable;
- this.notifyAll();
- }
- }
- }
-
- public static class DummyPrintStream extends PrintStream {
- public DummyPrintStream() {
- super(new OutputStream() {
- public void write(int i) {
- }
- });
- }
- }
-
- public static class SimpleBuffer {
- byte[] buffer;
-
- int fillPos;
-
- byte[] emptyBuffer;
-
- public SimpleBuffer() {
- fillPos = 0;
- setSize(COPY_BUF_SIZE);
- }
-
- public synchronized void setSize(int size) {
- if (size < 0)
- throw new IllegalArgumentException("Size can't be negative");
- if (fillPos <= 0)
- buffer = new byte[size];
- else
- throw new IllegalStateException("Can't resize buffer containing data");
- }
-
- public synchronized int getSize() {
- return buffer.length;
- }
-
- public synchronized byte[] put(byte[] data, int off, int len) {
- //System.err.println("put in buff:" + len+", fp:"+fillPos);
- if (buffer.length > fillPos + len) {
- System.arraycopy(data, off, buffer, fillPos, len);
- fillPos += len;
- return getEmptyBuffer();
- }
- byte[] result = new byte[Math.max(fillPos + len - buffer.length, buffer.length)];
- //System.err.println("fp:" + fillPos + ",bl:" + buffer.length + ",rl:" + result.length + ",l:" + len);
- // fill result
- int rfilled = 0;
- if (fillPos < result.length) {
- System.arraycopy(buffer, 0, result, 0, fillPos);
- rfilled = result.length - fillPos;
- System.arraycopy(data, off, result, fillPos, rfilled);
- fillPos = 0;
- //System.err.println("1rf:"+rfilled);
- } else {
- System.arraycopy(buffer, 0, result, 0, result.length);
- System.arraycopy(buffer, result.length, buffer, 0, fillPos - result.length);
- fillPos -= result.length;
- rfilled = 0;
- //System.err.println("qrf: 0");
- }
- if (rfilled < len) {
- System.arraycopy(data, off + rfilled, buffer, fillPos, len - rfilled);
- fillPos += len - rfilled;
- //System.err.println("added to buf:"+(len - rfilled));
- }
- return result;
- }
-
- public synchronized byte[] get() {
- //System.err.println("get fp: "+fillPos);
- if (fillPos <= 0) {
- return getEmptyBuffer();
- }
- byte[] result = new byte[fillPos];
- System.arraycopy(buffer, 0, result, 0, fillPos);
- fillPos = 0;
- return result;
- }
-
- public synchronized void reset() {
- //System.err.println("reset buf");
- fillPos = 0;
- }
-
- private synchronized byte[] getEmptyBuffer() {
- if (emptyBuffer == null)
- emptyBuffer = new byte[0];
- return emptyBuffer;
- }
- }
-
- public static void main(String[] args) {
- try {
- System.out.println(args[0]);
- System.out.println(canonicalizePath(args[0]));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-}
diff --git a/1.x/src/jasper/JspC.java b/1.x/src/jasper/JspC.java
deleted file mode 100644
index 43f2146..0000000
--- a/1.x/src/jasper/JspC.java
+++ /dev/null
@@ -1,1368 +0,0 @@
-/*
- * Copyright 1999,2004-2005 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;
-
-import java.io.BufferedReader;
-import java.io.CharArrayWriter;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.Writer;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.Stack;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.jasper.compiler.Compiler;
-import org.apache.jasper.compiler.JspConfig;
-import org.apache.jasper.compiler.JspRuntimeContext;
-import org.apache.jasper.compiler.Localizer;
-import org.apache.jasper.compiler.TagPluginManager;
-import org.apache.jasper.compiler.TldLocationsCache;
-import org.apache.jasper.servlet.JspCServletContext;
-
-
-/**
- * Shell for the jspc compiler. Handles all options associated with the
- * command line and creates compilation contexts which it then compiles
- * according to the specified options.
- *
- * This version can process files from a _single_ webapp at once, i.e.
- * a single docbase can be specified.
- *
- * It can be used as an Ant task using:
- *
- * <taskdef classname="org.apache.jasper.JspC" name="jasper2" >
- * <classpath>
- * <pathelement location="${java.home}/../lib/tools.jar"/>
- * <fileset dir="${ENV.CATALINA_HOME}/server/lib">
- * <include name="*.jar"/>
- * </fileset>
- * <fileset dir="${ENV.CATALINA_HOME}/common/lib">
- * <include name="*.jar"/>
- * </fileset>
- * <path refid="myjars"/>
- * </classpath>
- * </taskdef>
- *
- * <jasper2 verbose="0"
- * package="my.package"
- * uriroot="${webapps.dir}/${webapp.name}"
- * webXmlFragment="${build.dir}/generated_web.xml"
- * outputDir="${webapp.dir}/${webapp.name}/WEB-INF/src/my/package" />
- *
- *
- * @author Danno Ferrin
- * @author Pierre Delisle
- * @author Costin Manolache
- * @author Yoav Shapira
- */
-public class JspC implements Options {
-
- public static final String DEFAULT_IE_CLASS_ID =
- "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";
-
- // Logger
- private static Log log = LogFactory.getLog(JspC.class);
-
- private static final String SWITCH_VERBOSE = "-v";
- private static final String SWITCH_HELP = "-help";
- private static final String SWITCH_QUIET = "-q";
- private static final String SWITCH_OUTPUT_DIR = "-d";
- private static final String SWITCH_IE_CLASS_ID = "-ieplugin";
- private static final String SWITCH_PACKAGE_NAME = "-p";
- private static final String SWITCH_CACHE = "-cache";
- private static final String SWITCH_CLASS_NAME = "-c";
- private static final String SWITCH_FULL_STOP = "--";
- private static final String SWITCH_COMPILE = "-compile";
- private static final String SWITCH_SOURCE = "-source";
- private static final String SWITCH_TARGET = "-target";
- private static final String SWITCH_URI_BASE = "-uribase";
- private static final String SWITCH_URI_ROOT = "-uriroot";
- private static final String SWITCH_FILE_WEBAPP = "-webapp";
- private static final String SWITCH_WEBAPP_INC = "-webinc";
- private static final String SWITCH_WEBAPP_XML = "-webxml";
- private static final String SWITCH_MAPPED = "-mapped";
- private static final String SWITCH_XPOWERED_BY = "-xpoweredBy";
- private static final String SWITCH_TRIM_SPACES = "-trimSpaces";
- private static final String SWITCH_CLASSPATH = "-classpath";
- private static final String SWITCH_DIE = "-die";
- private static final String SWITCH_POOLING = "-poolingEnabled";
- private static final String SWITCH_ENCODING = "-javaEncoding";
- private static final String SWITCH_SMAP = "-smap";
- private static final String SWITCH_DUMP_SMAP = "-dumpsmap";
-
- private static final String SHOW_SUCCESS ="-s";
- private static final String LIST_ERRORS = "-l";
- private static final int NO_WEBXML = 0;
- private static final int INC_WEBXML = 10;
- private static final int ALL_WEBXML = 20;
- private static final int DEFAULT_DIE_LEVEL = 1;
- private static final int NO_DIE_LEVEL = 0;
-
- private static final String[] insertBefore =
- { "", "", "",
- "", "", "", "",
- "", "", "",
- "", "", "", "",
- "" };
-
- private static int die;
- private String classPath = null;
- private URLClassLoader loader = null;
- private boolean trimSpaces = false;
- private boolean genStringAsCharArray = false;
- private boolean xpoweredBy;
- private boolean mappedFile = false;
- private boolean poolingEnabled = true;
- private File scratchDir;
- private String ieClassId = DEFAULT_IE_CLASS_ID;
- private String targetPackage;
- private String targetClassName;
- private String uriBase;
- private String uriRoot;
- private int dieLevel;
- private boolean helpNeeded = false;
- private boolean compile = false;
- private boolean smapSuppressed = true;
- private boolean smapDumped = false;
- private boolean caching = true;
- private Map cache = new HashMap();
-
- private String compiler = null;
-
- private String compilerTargetVM = "1.4";
- private String compilerSourceVM = "1.4";
-
- private boolean classDebugInfo = true;
-
- /**
- * Throw an exception if there's a compilation error, or swallow it.
- * Default is true to preserve old behavior.
- */
- private boolean failOnError = true;
-
- /**
- * The file extensions to be handled as JSP files.
- * Default list is .jsp and .jspx.
- */
- private List extensions;
-
- /**
- * The pages.
- */
- private List pages = new Vector();
-
- /**
- * Needs better documentation, this data member does.
- * True by default.
- */
- private boolean errorOnUseBeanInvalidClassAttribute = true;
-
- /**
- * The java file encoding. Default
- * is UTF-8. Added per bugzilla 19622.
- */
- private String javaEncoding = "UTF-8";
-
- // Generation of web.xml fragments
- private String webxmlFile;
- private int webxmlLevel;
- private boolean addWebXmlMappings = false;
-
- private Writer mapout;
- private CharArrayWriter servletout;
- private CharArrayWriter mappingout;
-
- /**
- * The servlet context.
- */
- private JspCServletContext context;
-
- /**
- * The runtime context.
- * Maintain a dummy JspRuntimeContext for compiling tag files.
- */
- private JspRuntimeContext rctxt;
-
- /**
- * Cache for the TLD locations
- */
- private TldLocationsCache tldLocationsCache = null;
-
- private JspConfig jspConfig = null;
- private TagPluginManager tagPluginManager = null;
-
- private boolean verbose = false;
- private boolean listErrors = false;
- private boolean showSuccess = false;
- private int argPos;
- private boolean fullstop = false;
- private String args[];
-
- public static void main(String arg[]) {
- if (arg.length == 0) {
- System.out.println(Localizer.getMessage("jspc.usage"));
- } else {
- try {
- JspC jspc = new JspC();
- jspc.setArgs(arg);
- if (jspc.helpNeeded) {
- System.out.println(Localizer.getMessage("jspc.usage"));
- } else {
- jspc.execute();
- }
- } catch (JasperException je) {
- System.err.println(je);
- //System.err.println(je.getMessage());
- if (die != NO_DIE_LEVEL) {
- System.exit(die);
- }
- }
- }
- }
-
- public void setArgs(String[] arg) throws JasperException {
- args = arg;
- String tok;
-
- dieLevel = NO_DIE_LEVEL;
- die = dieLevel;
-
- while ((tok = nextArg()) != null) {
- if (tok.equals(SWITCH_VERBOSE)) {
- verbose = true;
- showSuccess = true;
- listErrors = true;
- } else if (tok.equals(SWITCH_OUTPUT_DIR)) {
- tok = nextArg();
- setOutputDir( tok );
- } else if (tok.equals(SWITCH_PACKAGE_NAME)) {
- targetPackage = nextArg();
- } else if (tok.equals(SWITCH_COMPILE)) {
- compile=true;
- } else if (tok.equals(SWITCH_CLASS_NAME)) {
- targetClassName = nextArg();
- } else if (tok.equals(SWITCH_URI_BASE)) {
- uriBase=nextArg();
- } else if (tok.equals(SWITCH_URI_ROOT)) {
- setUriroot( nextArg());
- } else if (tok.equals(SWITCH_FILE_WEBAPP)) {
- setUriroot( nextArg());
- } else if ( tok.equals( SHOW_SUCCESS ) ) {
- showSuccess = true;
- } else if ( tok.equals( LIST_ERRORS ) ) {
- listErrors = true;
- } else if (tok.equals(SWITCH_WEBAPP_INC)) {
- webxmlFile = nextArg();
- if (webxmlFile != null) {
- webxmlLevel = INC_WEBXML;
- }
- } else if (tok.equals(SWITCH_WEBAPP_XML)) {
- webxmlFile = nextArg();
- if (webxmlFile != null) {
- webxmlLevel = ALL_WEBXML;
- }
- } else if (tok.equals(SWITCH_MAPPED)) {
- mappedFile = true;
- } else if (tok.equals(SWITCH_XPOWERED_BY)) {
- xpoweredBy = true;
- } else if (tok.equals(SWITCH_TRIM_SPACES)) {
- setTrimSpaces(true);
- } else if (tok.equals(SWITCH_CACHE)) {
- tok = nextArg();
- if ("false".equals(tok)) {
- caching = false;
- } else {
- caching = true;
- }
- } else if (tok.equals(SWITCH_CLASSPATH)) {
- setClassPath(nextArg());
- } else if (tok.startsWith(SWITCH_DIE)) {
- try {
- dieLevel = Integer.parseInt(
- tok.substring(SWITCH_DIE.length()));
- } catch (NumberFormatException nfe) {
- dieLevel = DEFAULT_DIE_LEVEL;
- }
- die = dieLevel;
- } else if (tok.equals(SWITCH_HELP)) {
- helpNeeded = true;
- } else if (tok.equals(SWITCH_POOLING)) {
- tok = nextArg();
- if ("false".equals(tok)) {
- poolingEnabled = false;
- } else {
- poolingEnabled = true;
- }
- } else if (tok.equals(SWITCH_ENCODING)) {
- setJavaEncoding(nextArg());
- } else if (tok.equals(SWITCH_SOURCE)) {
- setCompilerSourceVM(nextArg());
- } else if (tok.equals(SWITCH_TARGET)) {
- setCompilerTargetVM(nextArg());
- } else if (tok.equals(SWITCH_SMAP)) {
- smapSuppressed = false;
- } else if (tok.equals(SWITCH_DUMP_SMAP)) {
- smapDumped = true;
- } else {
- if (tok.startsWith("-")) {
- throw new JasperException("Unrecognized option: " + tok +
- ". Use -help for help.");
- }
- if (!fullstop) {
- argPos--;
- }
- // Start treating the rest as JSP Pages
- break;
- }
- }
-
- // Add all extra arguments to the list of files
- while( true ) {
- String file = nextFile();
- if( file==null ) {
- break;
- }
- pages.add( file );
- }
- }
-
- public boolean getKeepGenerated() {
- // isn't this why we are running jspc?
- return true;
- }
-
- public boolean getTrimSpaces() {
- return trimSpaces;
- }
-
- public void setTrimSpaces(boolean ts) {
- this.trimSpaces = ts;
- }
-
- public boolean isPoolingEnabled() {
- return poolingEnabled;
- }
-
- public void setPoolingEnabled(boolean poolingEnabled) {
- this.poolingEnabled = poolingEnabled;
- }
-
- public boolean isXpoweredBy() {
- return xpoweredBy;
- }
-
- public void setXpoweredBy(boolean xpoweredBy) {
- this.xpoweredBy = xpoweredBy;
- }
-
- public boolean getErrorOnUseBeanInvalidClassAttribute() {
- return errorOnUseBeanInvalidClassAttribute;
- }
-
- public void setErrorOnUseBeanInvalidClassAttribute(boolean b) {
- errorOnUseBeanInvalidClassAttribute = b;
- }
-
- public int getTagPoolSize() {
- return Constants.MAX_POOL_SIZE;
- }
-
- /**
- * Are we supporting HTML mapped servlets?
- */
- public boolean getMappedFile() {
- return mappedFile;
- }
-
- // Off-line compiler, no need for security manager
- public Object getProtectionDomain() {
- return null;
- }
-
- public boolean getSendErrorToClient() {
- // implied send to System.err
- return true;
- }
-
- public void setClassDebugInfo( boolean b ) {
- classDebugInfo=b;
- }
-
- public boolean getClassDebugInfo() {
- // compile with debug info
- return classDebugInfo;
- }
-
- /**
- * @see Options#isCaching()
- */
- public boolean isCaching() {
- return caching;
- }
-
- /**
- * @see Options#isCaching()
- */
- public void setCaching(boolean caching) {
- this.caching = caching;
- }
-
- /**
- * @see Options#getCache()
- */
- public Map getCache() {
- return cache;
- }
-
- /**
- * Background compilation check intervals in seconds
- */
- public int getCheckInterval() {
- return 0;
- }
-
- /**
- * Modification test interval.
- */
- public int getModificationTestInterval() {
- return 0;
- }
-
- /**
- * Is Jasper being used in development mode?
- */
- public boolean getDevelopment() {
- return false;
- }
-
- /**
- * Is the generation of SMAP info for JSR45 debuggin suppressed?
- */
- public boolean isSmapSuppressed() {
- return smapSuppressed;
- }
-
- /**
- * Set smapSuppressed flag.
- */
- public void setSmapSuppressed(boolean smapSuppressed) {
- this.smapSuppressed = smapSuppressed;
- }
-
-
- /**
- * Should SMAP info for JSR45 debugging be dumped to a file?
- */
- public boolean isSmapDumped() {
- return smapDumped;
- }
-
- /**
- * Set smapSuppressed flag.
- */
- public void setSmapDumped(boolean smapDumped) {
- this.smapDumped = smapDumped;
- }
-
-
- /**
- * Determines whether text strings are to be generated as char arrays,
- * which improves performance in some cases.
- *
- * @param genStringAsCharArray true if text strings are to be generated as
- * char arrays, false otherwise
- */
- public void setGenStringAsCharArray(boolean genStringAsCharArray) {
- this.genStringAsCharArray = genStringAsCharArray;
- }
-
- /**
- * Indicates whether text strings are to be generated as char arrays.
- *
- * @return true if text strings are to be generated as char arrays, false
- * otherwise
- */
- public boolean genStringAsCharArray() {
- return genStringAsCharArray;
- }
-
- /**
- * Sets the class-id value to be sent to Internet Explorer when using
- * tags.
- *
- * @param ieClassId Class-id value
- */
- public void setIeClassId(String ieClassId) {
- this.ieClassId = ieClassId;
- }
-
- /**
- * Gets the class-id value that is sent to Internet Explorer when using
- * tags.
- *
- * @return Class-id value
- */
- public String getIeClassId() {
- return ieClassId;
- }
-
- public File getScratchDir() {
- return scratchDir;
- }
-
- public Class getJspCompilerPlugin() {
- // we don't compile, so this is meanlingless
- return null;
- }
-
- public String getJspCompilerPath() {
- // we don't compile, so this is meanlingless
- return null;
- }
-
- /**
- * Compiler to use.
- */
- public String getCompiler() {
- return compiler;
- }
-
- public void setCompiler(String c) {
- compiler=c;
- }
-
- /**
- * @see Options#getCompilerTargetVM
- */
- public String getCompilerTargetVM() {
- return compilerTargetVM;
- }
-
- public void setCompilerTargetVM(String vm) {
- compilerTargetVM = vm;
- }
-
- /**
- * @see Options#getCompilerSourceVM()
- */
- public String getCompilerSourceVM() {
- return compilerSourceVM;
- }
-
- /**
- * @see Options#getCompilerSourceVM()
- */
- public void setCompilerSourceVM(String vm) {
- compilerSourceVM = vm;
- }
-
- public TldLocationsCache getTldLocationsCache() {
- return tldLocationsCache;
- }
-
- /**
- * Returns the encoding to use for
- * java files. The default is UTF-8.
- *
- * @return String The encoding
- */
- public String getJavaEncoding() {
- return javaEncoding;
- }
-
- /**
- * Sets the encoding to use for
- * java files.
- *
- * @param encodingName The name, e.g. "UTF-8"
- */
- public void setJavaEncoding(String encodingName) {
- javaEncoding = encodingName;
- }
-
- public boolean getFork() {
- return false;
- }
-
- public String getClassPath() {
- if( classPath != null )
- return classPath;
- return System.getProperty("java.class.path");
- }
-
- public void setClassPath(String s) {
- classPath=s;
- }
-
- /**
- * Returns the list of file extensions
- * that are treated as JSP files.
- *
- * @return The list of extensions
- */
- public List getExtensions() {
- return extensions;
- }
-
- /**
- * Adds the given file extension to the
- * list of extensions handled as JSP files.
- *
- * @param extension The extension to add, e.g. "myjsp"
- */
- protected void addExtension(final String extension) {
- if(extension != null) {
- if(extensions == null) {
- extensions = new Vector();
- }
-
- extensions.add(extension);
- }
- }
-
- /**
- * Base dir for the webapp. Used to generate class names and resolve
- * includes
- */
- public void setUriroot( String s ) {
- if( s==null ) {
- uriRoot = s;
- return;
- }
- try {
- uriRoot = resolveFile(s).getCanonicalPath();
- } catch( Exception ex ) {
- uriRoot = s;
- }
- }
-
- /**
- * Parses comma-separated list of JSP files to be processed. If the argument
- * is null, nothing is done.
- *
- * Each file is interpreted relative to uriroot, unless it is absolute,
- * in which case it must start with uriroot.
- *
- * @param jspFiles Comma-separated list of JSP files to be processed
- */
- public void setJspFiles(final String jspFiles) {
- if(jspFiles == null) {
- return;
- }
-
- StringTokenizer tok = new StringTokenizer(jspFiles, ",");
- while (tok.hasMoreTokens()) {
- pages.add(tok.nextToken());
- }
- }
-
- /**
- * Sets the compile flag.
- *
- * @param b Flag value
- */
- public void setCompile( final boolean b ) {
- compile = b;
- }
-
- /**
- * Sets the verbosity level. The actual number doesn't
- * matter: if it's greater than zero, the verbose flag will
- * be true.
- *
- * @param level Positive means verbose
- */
- public void setVerbose( final int level ) {
- if (level > 0) {
- verbose = true;
- showSuccess = true;
- listErrors = true;
- }
- }
-
- public void setValidateXml( boolean b ) {
- org.apache.jasper.xmlparser.ParserUtils.validating=b;
- }
-
- public void setListErrors( boolean b ) {
- listErrors = b;
- }
-
- public void setOutputDir( String s ) {
- if( s!= null ) {
- scratchDir = resolveFile(s).getAbsoluteFile();
- } else {
- scratchDir=null;
- }
- }
-
- public void setPackage( String p ) {
- targetPackage=p;
- }
-
- /**
- * Class name of the generated file ( without package ).
- * Can only be used if a single file is converted.
- * XXX Do we need this feature ?
- */
- public void setClassName( String p ) {
- targetClassName=p;
- }
-
- /**
- * File where we generate a web.xml fragment with the class definitions.
- */
- public void setWebXmlFragment( String s ) {
- webxmlFile=resolveFile(s).getAbsolutePath();
- webxmlLevel=INC_WEBXML;
- }
-
- /**
- * File where we generate a complete web.xml with the class definitions.
- */
- public void setWebXml( String s ) {
- webxmlFile=resolveFile(s).getAbsolutePath();
- webxmlLevel=ALL_WEBXML;
- }
-
- public void setAddWebXmlMappings(boolean b) {
- addWebXmlMappings = b;
- }
-
- /**
- * Set the option that throws an exception in case of a compilation error.
- */
- public void setFailOnError(final boolean b) {
- failOnError = b;
- }
-
- public boolean getFailOnError() {
- return failOnError;
- }
-
- /**
- * Obtain JSP configuration informantion specified in web.xml.
- */
- public JspConfig getJspConfig() {
- return jspConfig;
- }
-
- public TagPluginManager getTagPluginManager() {
- return tagPluginManager;
- }
-
- public void generateWebMapping( String file, JspCompilationContext clctxt )
- throws IOException
- {
- String className = clctxt.getServletClassName();
- String packageName = clctxt.getServletPackageName();
-
- String thisServletName;
- if ("".equals(packageName)) {
- thisServletName = className;
- } else {
- thisServletName = packageName + '.' + className;
- }
-
- if (servletout != null) {
- servletout.write("\n \n ");
- servletout.write(thisServletName);
- servletout.write("\n ");
- servletout.write(thisServletName);
- servletout.write("\n \n");
- }
- if (mappingout != null) {
- mappingout.write("\n \n ");
- mappingout.write(thisServletName);
- mappingout.write("\n ");
- mappingout.write(file.replace('\\', '/'));
- mappingout.write("\n \n");
-
- }
- }
-
- /**
- * Include the generated web.xml inside the webapp's web.xml.
- */
- protected void mergeIntoWebXml() throws IOException {
-
- File webappBase = new File(uriRoot);
- File webXml = new File(webappBase, "WEB-INF/web.xml");
- File webXml2 = new File(webappBase, "WEB-INF/web2.xml");
- String insertStartMarker =
- Localizer.getMessage("jspc.webinc.insertStart");
- String insertEndMarker =
- Localizer.getMessage("jspc.webinc.insertEnd");
-
- BufferedReader reader = new BufferedReader(new FileReader(webXml));
- BufferedReader fragmentReader =
- new BufferedReader(new FileReader(webxmlFile));
- PrintWriter writer = new PrintWriter(new FileWriter(webXml2));
-
- // Insert the and declarations
- int pos = -1;
- String line = null;
- while (true) {
- line = reader.readLine();
- if (line == null) {
- break;
- }
- // Skip anything previously generated by JSPC
- if (line.indexOf(insertStartMarker) >= 0) {
- while (true) {
- line = reader.readLine();
- if (line == null) {
- return;
- }
- if (line.indexOf(insertEndMarker) >= 0) {
- line = reader.readLine();
- line = reader.readLine();
- if (line == null) {
- return;
- }
- break;
- }
- }
- }
- for (int i = 0; i < insertBefore.length; i++) {
- pos = line.indexOf(insertBefore[i]);
- if (pos >= 0)
- break;
- }
- if (pos >= 0) {
- writer.print(line.substring(0, pos));
- break;
- } else {
- writer.println(line);
- }
- }
-
- writer.println(insertStartMarker);
- while (true) {
- String line2 = fragmentReader.readLine();
- if (line2 == null) {
- writer.println();
- break;
- }
- writer.println(line2);
- }
- writer.println(insertEndMarker);
- writer.println();
-
- for (int i = 0; i < pos; i++) {
- writer.print(" ");
- }
- writer.println(line.substring(pos));
-
- while (true) {
- line = reader.readLine();
- if (line == null) {
- break;
- }
- writer.println(line);
- }
- writer.close();
-
- reader.close();
- fragmentReader.close();
-
- FileInputStream fis = new FileInputStream(webXml2);
- FileOutputStream fos = new FileOutputStream(webXml);
-
- byte buf[] = new byte[512];
- while (true) {
- int n = fis.read(buf);
- if (n < 0) {
- break;
- }
- fos.write(buf, 0, n);
- }
-
- fis.close();
- fos.close();
-
- webXml2.delete();
- (new File(webxmlFile)).delete();
-
- }
-
- private void processFile(String file)
- throws JasperException
- {
- ClassLoader originalClassLoader = null;
-
- try {
- // set up a scratch/output dir if none is provided
- if (scratchDir == null) {
- String temp = System.getProperty("java.io.tmpdir");
- if (temp == null) {
- temp = "";
- }
- scratchDir = new File(new File(temp).getAbsolutePath());
- }
-
- String jspUri=file.replace('\\','/');
- JspCompilationContext clctxt = new JspCompilationContext
- ( jspUri, false, this, context, null, rctxt );
-
- /* Override the defaults */
- if ((targetClassName != null) && (targetClassName.length() > 0)) {
- clctxt.setServletClassName(targetClassName);
- targetClassName = null;
- }
- if (targetPackage != null) {
- clctxt.setServletPackageName(targetPackage);
- }
-
- originalClassLoader = Thread.currentThread().getContextClassLoader();
- if( loader==null ) {
- initClassLoader( clctxt );
- }
- Thread.currentThread().setContextClassLoader(loader);
-
- clctxt.setClassLoader(loader);
- clctxt.setClassPath(classPath);
-
- Compiler clc = clctxt.createCompiler();
-
- // If compile is set, generate both .java and .class, if
- // .jsp file is newer than .class file;
- // Otherwise only generate .java, if .jsp file is newer than
- // the .java file
- if( clc.isOutDated(compile) ) {
- clc.compile(compile, true);
- }
-
- // Generate mapping
- generateWebMapping( file, clctxt );
- if ( showSuccess ) {
- log.info( "Built File: " + file );
- }
-
- } catch (JasperException je) {
- Throwable rootCause = je;
- while (rootCause instanceof JasperException
- && ((JasperException) rootCause).getRootCause() != null) {
- rootCause = ((JasperException) rootCause).getRootCause();
- }
- if (rootCause != je) {
- log.error(Localizer.getMessage("jspc.error.generalException",
- file),
- rootCause);
- }
-
- // Bugzilla 35114.
- if(getFailOnError()) {
- throw je;
- } else {
- log.error(je.getMessage());
- }
-
- } catch (Exception e) {
- if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist",
- e.getMessage()));
- }
- throw new JasperException(e);
- } finally {
- if(originalClassLoader != null) {
- Thread.currentThread().setContextClassLoader(originalClassLoader);
- }
- }
- }
-
- /**
- * Locate all jsp files in the webapp. Used if no explicit
- * jsps are specified.
- */
- public void scanFiles( File base ) throws JasperException {
- Stack dirs = new Stack();
- dirs.push(base);
-
- // Make sure default extensions are always included
- if ((getExtensions() == null) || (getExtensions().size() < 2)) {
- addExtension("jsp");
- addExtension("jspx");
- }
-
- while (!dirs.isEmpty()) {
- String s = dirs.pop().toString();
- File f = new File(s);
- if (f.exists() && f.isDirectory()) {
- String[] files = f.list();
- String ext;
- for (int i = 0; (files != null) && i < files.length; i++) {
- File f2 = new File(s, files[i]);
- if (f2.isDirectory()) {
- dirs.push(f2.getPath());
- } else {
- String path = f2.getPath();
- String uri = path.substring(uriRoot.length());
- ext = files[i].substring(files[i].lastIndexOf('.') +1);
- if (getExtensions().contains(ext) ||
- jspConfig.isJspPage(uri)) {
- pages.add(path);
- }
- }
- }
- }
- }
- }
-
- /**
- * Executes the compilation.
- *
- * @throws JasperException If an error occurs
- */
- public void execute() throws JasperException {
- if(log.isDebugEnabled()) {
- log.debug("execute() starting for " + pages.size() + " pages.");
- }
-
- try {
- if (uriRoot == null) {
- if( pages.size() == 0 ) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.missingTarget"));
- }
- String firstJsp = (String) pages.get( 0 );
- File firstJspF = new File( firstJsp );
- if (!firstJspF.exists()) {
- throw new JasperException(
- Localizer.getMessage("jspc.error.fileDoesNotExist",
- firstJsp));
- }
- locateUriRoot( firstJspF );
- }
-
- if (uriRoot == null) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.no_uriroot"));
- }
-
- if( context==null ) {
- initServletContext();
- }
-
- // No explicit pages, we'll process all .jsp in the webapp
- if (pages.size() == 0) {
- scanFiles( new File( uriRoot ));
- }
-
- File uriRootF = new File(uriRoot);
- if (!uriRootF.exists() || !uriRootF.isDirectory()) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.uriroot_not_dir"));
- }
-
- initWebXml();
-
- Iterator iter = pages.iterator();
- while (iter.hasNext()) {
- String nextjsp = iter.next().toString();
- File fjsp = new File(nextjsp);
- if (!fjsp.isAbsolute()) {
- fjsp = new File(uriRootF, nextjsp);
- }
- if (!fjsp.exists()) {
- if (log.isWarnEnabled()) {
- log.warn
- (Localizer.getMessage
- ("jspc.error.fileDoesNotExist", fjsp.toString()));
- }
- continue;
- }
- String s = fjsp.getAbsolutePath();
- if (s.startsWith(uriRoot)) {
- nextjsp = s.substring(uriRoot.length());
- }
- if (nextjsp.startsWith("." + File.separatorChar)) {
- nextjsp = nextjsp.substring(2);
- }
- processFile(nextjsp);
- }
-
- completeWebXml();
-
- if (addWebXmlMappings) {
- mergeIntoWebXml();
- }
-
- } catch (IOException ioe) {
- throw new JasperException(ioe);
-
- } catch (JasperException je) {
- Throwable rootCause = je;
- while (rootCause instanceof JasperException
- && ((JasperException) rootCause).getRootCause() != null) {
- rootCause = ((JasperException) rootCause).getRootCause();
- }
- if (rootCause != je) {
- rootCause.printStackTrace();
- }
- throw je;
- } finally {
- if (loader != null) {
- LogFactory.release(loader);
- }
- }
- }
-
- // ==================== Private utility methods ====================
-
- private String nextArg() {
- if ((argPos >= args.length)
- || (fullstop = SWITCH_FULL_STOP.equals(args[argPos]))) {
- return null;
- } else {
- return args[argPos++];
- }
- }
-
- private String nextFile() {
- if (fullstop) argPos++;
- if (argPos >= args.length) {
- return null;
- } else {
- return args[argPos++];
- }
- }
-
- private void initWebXml() {
- try {
- if (webxmlLevel >= INC_WEBXML) {
- File fmapings = new File(webxmlFile);
- mapout = new FileWriter(fmapings);
- servletout = new CharArrayWriter();
- mappingout = new CharArrayWriter();
- } else {
- mapout = null;
- servletout = null;
- mappingout = null;
- }
- if (webxmlLevel >= ALL_WEBXML) {
- mapout.write(Localizer.getMessage("jspc.webxml.header"));
- mapout.flush();
- } else if ((webxmlLevel>= INC_WEBXML) && !addWebXmlMappings) {
- mapout.write(Localizer.getMessage("jspc.webinc.header"));
- mapout.flush();
- }
- } catch (IOException ioe) {
- mapout = null;
- servletout = null;
- mappingout = null;
- }
- }
-
- private void completeWebXml() {
- if (mapout != null) {
- try {
- servletout.writeTo(mapout);
- mappingout.writeTo(mapout);
- if (webxmlLevel >= ALL_WEBXML) {
- mapout.write(Localizer.getMessage("jspc.webxml.footer"));
- } else if ((webxmlLevel >= INC_WEBXML) && !addWebXmlMappings) {
- mapout.write(Localizer.getMessage("jspc.webinc.footer"));
- }
- mapout.close();
- } catch (IOException ioe) {
- // noting to do if it fails since we are done with it
- }
- }
- }
-
- private void initServletContext() {
- try {
- context =new JspCServletContext
- (new PrintWriter(System.out),
- new URL("file:" + uriRoot.replace('\\','/') + '/'));
- tldLocationsCache = new TldLocationsCache(context, true);
- } catch (MalformedURLException me) {
- System.out.println("**" + me);
- }
- rctxt = new JspRuntimeContext(context, this);
- jspConfig = new JspConfig(context);
- tagPluginManager = new TagPluginManager(context);
- }
-
- /**
- * Initializes the classloader as/if needed for the given
- * compilation context.
- *
- * @param clctxt The compilation context
- * @throws IOException If an error occurs
- */
- private void initClassLoader(JspCompilationContext clctxt)
- throws IOException {
-
- classPath = getClassPath();
-
- ClassLoader jspcLoader = getClass().getClassLoader();
-
- // Turn the classPath into URLs
- ArrayList urls = new ArrayList();
- StringTokenizer tokenizer = new StringTokenizer(classPath,
- File.pathSeparator);
- while (tokenizer.hasMoreTokens()) {
- String path = tokenizer.nextToken();
- try {
- File libFile = new File(path);
- urls.add(libFile.toURL());
- } catch (IOException ioe) {
- // Failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak uot
- throw new RuntimeException(ioe.toString());
- }
- }
-
- File webappBase = new File(uriRoot);
- if (webappBase.exists()) {
- File classes = new File(webappBase, "/WEB-INF/classes");
- try {
- if (classes.exists()) {
- classPath = classPath + File.pathSeparator
- + classes.getCanonicalPath();
- urls.add(classes.getCanonicalFile().toURL());
- }
- } catch (IOException ioe) {
- // failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak out
- throw new RuntimeException(ioe.toString());
- }
- File lib = new File(webappBase, "/WEB-INF/lib");
- if (lib.exists() && lib.isDirectory()) {
- String[] libs = lib.list();
- for (int i = 0; i < libs.length; i++) {
- if( libs[i].length() <5 ) continue;
- String ext=libs[i].substring( libs[i].length() - 4 );
- if (! ".jar".equalsIgnoreCase(ext)) {
- if (".tld".equalsIgnoreCase(ext)) {
- log.warn("TLD files should not be placed in "
- + "/WEB-INF/lib");
- }
- continue;
- }
- try {
- File libFile = new File(lib, libs[i]);
- classPath = classPath + File.pathSeparator
- + libFile.getAbsolutePath();
- urls.add(libFile.getAbsoluteFile().toURL());
- } catch (IOException ioe) {
- // failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak out
- throw new RuntimeException(ioe.toString());
- }
- }
- }
- }
-
- // What is this ??
- urls.add(new File(clctxt.getRealPath("/")).getCanonicalFile().toURL());
-
- URL urlsA[]=new URL[urls.size()];
- urls.toArray(urlsA);
- loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());
-
- }
-
- /**
- * Find the WEB-INF dir by looking up in the directory tree.
- * This is used if no explicit docbase is set, but only files.
- * XXX Maybe we should require the docbase.
- */
- private void locateUriRoot( File f ) {
- String tUriBase = uriBase;
- if (tUriBase == null) {
- tUriBase = "/";
- }
- try {
- if (f.exists()) {
- f = new File(f.getAbsolutePath());
- while (f != null) {
- File g = new File(f, "WEB-INF");
- if (g.exists() && g.isDirectory()) {
- uriRoot = f.getCanonicalPath();
- uriBase = tUriBase;
- if (log.isInfoEnabled()) {
- log.info(Localizer.getMessage(
- "jspc.implicit.uriRoot",
- uriRoot));
- }
- break;
- }
- if (f.exists() && f.isDirectory()) {
- tUriBase = "/" + f.getName() + "/" + tUriBase;
- }
-
- String fParent = f.getParent();
- if (fParent == null) {
- break;
- } else {
- f = new File(fParent);
- }
-
- // If there is no acceptible candidate, uriRoot will
- // remain null to indicate to the CompilerContext to
- // use the current working/user dir.
- }
-
- if (uriRoot != null) {
- File froot = new File(uriRoot);
- uriRoot = froot.getCanonicalPath();
- }
- }
- } catch (IOException ioe) {
- // since this is an optional default and a null value
- // for uriRoot has a non-error meaning, we can just
- // pass straight through
- }
- }
-
- /**
- * Resolves the relative or absolute pathname correctly
- * in both Ant and command-line situations. If Ant launched
- * us, we should use the basedir of the current project
- * to resolve relative paths.
- *
- * See Bugzilla 35571.
- *
- * @param s The file
- * @return The file resolved
- */
- protected File resolveFile(final String s) {
- return new File(s);
- }
-}
diff --git a/1.x/src/jasper/JspCompilationContext.java b/1.x/src/jasper/JspCompilationContext.java
deleted file mode 100644
index 183b6cf..0000000
--- a/1.x/src/jasper/JspCompilationContext.java
+++ /dev/null
@@ -1,694 +0,0 @@
-/*
- * 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;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.Hashtable;
-import java.util.Set;
-
-import javax.servlet.ServletContext;
-import javax.servlet.jsp.tagext.TagInfo;
-
-import org.apache.jasper.compiler.Compiler;
-import org.apache.jasper.compiler.JspRuntimeContext;
-import org.apache.jasper.compiler.JspUtil;
-import org.apache.jasper.compiler.Localizer;
-import org.apache.jasper.compiler.ServletWriter;
-import org.apache.jasper.servlet.JasperLoader;
-import org.apache.jasper.servlet.JspServletWrapper;
-
-/**
- * A place holder for various things that are used through out the JSP
- * engine. This is a per-request/per-context data structure. Some of
- * the instance variables are set at different points.
- *
- * Most of the path-related stuff is here - mangling names, versions, dirs,
- * loading resources and dealing with uris.
- *
- * @author Anil K. Vijendran
- * @author Harish Prabandham
- * @author Pierre Delisle
- * @author Costin Manolache
- * @author Kin-man Chung
- */
-public class JspCompilationContext {
-
- protected org.apache.commons.logging.Log log =
- org.apache.commons.logging.LogFactory.getLog(JspCompilationContext.class);
-
- private Hashtable tagFileJarUrls;
- private boolean isPackagedTagFile;
-
- private String className;
- private String jspUri;
- private boolean isErrPage;
- private String basePackageName;
- private String derivedPackageName;
- private String servletJavaFileName;
- private String javaPath;
- private String classFileName;
- private String contentType;
- private ServletWriter writer;
- private Options options;
- private JspServletWrapper jsw;
- private Compiler jspCompiler;
- private String classPath;
-
- private String baseURI;
- private String baseOutputDir;
- private String outputDir;
- private ServletContext context;
- private URLClassLoader loader;
-
- private JspRuntimeContext rctxt;
-
- private int removed = 0;
-
- private URLClassLoader jspLoader;
- private URL baseUrl;
- private Class servletClass;
-
- private boolean isTagFile;
- private boolean protoTypeMode;
- private TagInfo tagInfo;
- private URL tagFileJarUrl;
-
- // jspURI _must_ be relative to the context
- public JspCompilationContext(String jspUri,
- boolean isErrPage,
- Options options,
- ServletContext context,
- JspServletWrapper jsw,
- JspRuntimeContext rctxt) {
-
- this.jspUri = canonicalURI(jspUri);
- this.isErrPage = isErrPage;
- this.options = options;
- this.jsw = jsw;
- this.context = context;
-
- this.baseURI = jspUri.substring(0, jspUri.lastIndexOf('/') + 1);
- // hack fix for resolveRelativeURI
- if (baseURI == null) {
- baseURI = "/";
- } else if (baseURI.charAt(0) != '/') {
- // strip the basde slash since it will be combined with the
- // uriBase to generate a file
- baseURI = "/" + baseURI;
- }
- if (baseURI.charAt(baseURI.length() - 1) != '/') {
- baseURI += '/';
- }
-
- this.rctxt = rctxt;
- this.tagFileJarUrls = new Hashtable();
- this.basePackageName = Constants.JSP_PACKAGE_NAME;
- }
-
- public JspCompilationContext(String tagfile,
- TagInfo tagInfo,
- Options options,
- ServletContext context,
- JspServletWrapper jsw,
- JspRuntimeContext rctxt,
- URL tagFileJarUrl) {
- this(tagfile, false, options, context, jsw, rctxt);
- this.isTagFile = true;
- this.tagInfo = tagInfo;
- this.tagFileJarUrl = tagFileJarUrl;
- if (tagFileJarUrl != null) {
- isPackagedTagFile = true;
- }
- }
-
- /* ==================== Methods to override ==================== */
-
- /** ---------- Class path and loader ---------- */
-
- /**
- * The classpath that is passed off to the Java compiler.
- */
- public String getClassPath() {
- if( classPath != null )
- return classPath;
- return rctxt.getClassPath();
- }
-
- /**
- * The classpath that is passed off to the Java compiler.
- */
- public void setClassPath(String classPath) {
- this.classPath = classPath;
- }
-
- /**
- * What class loader to use for loading classes while compiling
- * this JSP?
- */
- public ClassLoader getClassLoader() {
- if( loader != null )
- return loader;
- return rctxt.getParentClassLoader();
- }
-
- public void setClassLoader(URLClassLoader loader) {
- this.loader = loader;
- }
-
- public ClassLoader getJspLoader() {
- if( jspLoader == null ) {
- jspLoader = new JasperLoader
- (new URL[] {baseUrl},
- getClassLoader(),
- rctxt.getPermissionCollection(),
- rctxt.getCodeSource());
- }
- return jspLoader;
- }
-
- /** ---------- Input/Output ---------- */
-
- /**
- * The output directory to generate code into. The output directory
- * is make up of the scratch directory, which is provide in Options,
- * plus the directory derived from the package name.
- */
- public String getOutputDir() {
- if (outputDir == null) {
- createOutputDir();
- }
-
- return outputDir;
- }
-
- /**
- * Create a "Compiler" object based on some init param data. This
- * is not done yet. Right now we're just hardcoding the actual
- * compilers that are created.
- */
- public Compiler createCompiler() throws JasperException {
- if (jspCompiler != null ) {
- return jspCompiler;
- }
- jspCompiler = createCompiler("org.apache.jasper.compiler.BeeCompiler");
- if (jspCompiler == null) {
- throw new IllegalStateException(Localizer.getMessage("jsp.error.compiler"));
- }
- jspCompiler.init(this, jsw);
- return jspCompiler;
- }
-
- private Compiler createCompiler(String className) {
- Compiler compiler = null;
- try {
- compiler = (Compiler) Class.forName(className).newInstance();
- } catch (Throwable t) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage("jsp.error.compiler"), t);
- }
- }
- return compiler;
- }
-
- public Compiler getCompiler() {
- return jspCompiler;
- }
-
- /** ---------- Access resources in the webapp ---------- */
-
- /**
- * Get the full value of a URI relative to this compilations context
- * uses current file as the base.
- */
- public String resolveRelativeUri(String uri) {
- // sometimes we get uri's massaged from File(String), so check for
- // a root directory deperator char
- if (uri.startsWith("/") || uri.startsWith(File.separator)) {
- return uri;
- } else {
- return baseURI + uri;
- }
- }
-
- /**
- * Gets a resource as a stream, relative to the meanings of this
- * context's implementation.
- * @return a null if the resource cannot be found or represented
- * as an InputStream.
- */
- public java.io.InputStream getResourceAsStream(String res) {
- return context.getResourceAsStream(canonicalURI(res));
- }
-
-
- public URL getResource(String res) throws MalformedURLException {
- return context.getResource(canonicalURI(res));
- }
-
- public Set getResourcePaths(String path) {
- return context.getResourcePaths(canonicalURI(path));
- }
-
- /**
- * Gets the actual path of a URI relative to the context of
- * the compilation.
- */
- public String getRealPath(String path) {
- if (context != null) {
- return context.getRealPath(path);
- }
- return path;
- }
-
- /**
- * Returns the tag-file-name-to-JAR-file map of this compilation unit,
- * which maps tag file names to the JAR files in which the tag files are
- * packaged.
- *
- * The map is populated when parsing the tag-file elements of the TLDs
- * of any imported taglibs.
- */
- public Hashtable getTagFileJarUrls() {
- return this.tagFileJarUrls;
- }
-
- /**
- * Returns the JAR file in which the tag file for which this
- * JspCompilationContext was created is packaged, or null if this
- * JspCompilationContext does not correspond to a tag file, or if the
- * corresponding tag file is not packaged in a JAR.
- */
- public URL getTagFileJarUrl() {
- return this.tagFileJarUrl;
- }
-
- /* ==================== Common implementation ==================== */
-
- /**
- * Just the class name (does not include package name) of the
- * generated class.
- */
- public String getServletClassName() {
-
- if (className != null) {
- return className;
- }
-
- if (isTagFile) {
- className = tagInfo.getTagClassName();
- int lastIndex = className.lastIndexOf('.');
- if (lastIndex != -1) {
- className = className.substring(lastIndex + 1);
- }
- } else {
- int iSep = jspUri.lastIndexOf('/') + 1;
- className = JspUtil.makeJavaIdentifier(jspUri.substring(iSep));
- }
- return className;
- }
-
- public void setServletClassName(String className) {
- this.className = className;
- }
-
- /**
- * Path of the JSP URI. Note that this is not a file name. This is
- * the context rooted URI of the JSP file.
- */
- public String getJspFile() {
- return jspUri;
- }
-
- /**
- * Are we processing something that has been declared as an
- * errorpage?
- */
- public boolean isErrorPage() {
- return isErrPage;
- }
-
- public void setErrorPage(boolean isErrPage) {
- this.isErrPage = isErrPage;
- }
-
- public boolean isTagFile() {
- return isTagFile;
- }
-
- public TagInfo getTagInfo() {
- return tagInfo;
- }
-
- public void setTagInfo(TagInfo tagi) {
- tagInfo = tagi;
- }
-
- /**
- * True if we are compiling a tag file in prototype mode.
- * ie we only generate codes with class for the tag handler with empty
- * method bodies.
- */
- public boolean isPrototypeMode() {
- return protoTypeMode;
- }
-
- public void setPrototypeMode(boolean pm) {
- protoTypeMode = pm;
- }
-
- /**
- * Package name for the generated class is make up of the base package
- * name, which is user settable, and the derived package name. The
- * derived package name directly mirrors the file heirachy of the JSP page.
- */
- public String getServletPackageName() {
- if (isTagFile()) {
- String className = tagInfo.getTagClassName();
- int lastIndex = className.lastIndexOf('.');
- String pkgName = "";
- if (lastIndex != -1) {
- pkgName = className.substring(0, lastIndex);
- }
- return pkgName;
- } else {
- String dPackageName = getDerivedPackageName();
- if (dPackageName.length() == 0) {
- return basePackageName;
- }
- return basePackageName + '.' + getDerivedPackageName();
- }
- }
-
- private String getDerivedPackageName() {
- if (derivedPackageName == null) {
- int iSep = jspUri.lastIndexOf('/');
- derivedPackageName = (iSep > 0) ?
- JspUtil.makeJavaPackage(jspUri.substring(1,iSep)) : "";
- }
- return derivedPackageName;
- }
-
- /**
- * The package name into which the servlet class is generated.
- */
- public void setServletPackageName(String servletPackageName) {
- this.basePackageName = servletPackageName;
- }
-
- /**
- * Full path name of the Java file into which the servlet is being
- * generated.
- */
- public String getServletJavaFileName() {
-
- if (servletJavaFileName == null) {
- servletJavaFileName =
- getOutputDir() + getServletClassName() + ".java";
- } else {
- // Make sure output dir exists
- makeOutputDir();
- }
- return servletJavaFileName;
- }
-
- public void setServletJavaFileName(String servletJavaFileName) {
- this.servletJavaFileName = servletJavaFileName;
- }
-
- /**
- * Get hold of the Options object for this context.
- */
- public Options getOptions() {
- return options;
- }
-
- public ServletContext getServletContext() {
- return context;
- }
-
- public JspRuntimeContext getRuntimeContext() {
- return rctxt;
- }
-
- /**
- * Path of the Java file relative to the work directory.
- */
- public String getJavaPath() {
-
- if (javaPath != null) {
- return javaPath;
- }
-
- if (isTagFile()) {
- String tagName = tagInfo.getTagClassName();
- javaPath = tagName.replace('.', '/') + ".java";
- } else {
- javaPath = getServletPackageName().replace('.', '/') + '/' +
- getServletClassName() + ".java";
- }
- return javaPath;
- }
-
- public String getClassFileName() {
-
- if (classFileName == null) {
- classFileName = getOutputDir() + getServletClassName() + ".class";
- } else {
- // Make sure output dir exists
- makeOutputDir();
- }
- return classFileName;
- }
-
- /**
- * Get the content type of this JSP.
- *
- * Content type includes content type and encoding.
- */
- public String getContentType() {
- return contentType;
- }
-
- public void setContentType(String contentType) {
- this.contentType = contentType;
- }
-
- /**
- * Where is the servlet being generated?
- */
- public ServletWriter getWriter() {
- return writer;
- }
-
- public void setWriter(ServletWriter writer) {
- this.writer = writer;
- }
-
- /**
- * Gets the 'location' of the TLD associated with the given taglib 'uri'.
- *
- * @return An array of two Strings: The first element denotes the real
- * 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.
- * Returns null if the given uri is not associated with any tag library
- * 'exposed' in the web application.
- */
- public String[] getTldLocation(String uri) throws JasperException {
- String[] location =
- getOptions().getTldLocationsCache().getLocation(uri);
- return location;
- }
-
- /**
- * Are we keeping generated code around?
- */
- public boolean keepGenerated() {
- return getOptions().getKeepGenerated();
- }
-
- // ==================== Removal ====================
-
- public void incrementRemoved() {
- if (removed > 1) {
- jspCompiler.removeGeneratedFiles();
- if( rctxt != null )
- rctxt.removeWrapper(jspUri);
- }
- removed++;
- }
-
- public boolean isRemoved() {
- if (removed > 1 ) {
- return true;
- }
- return false;
- }
-
- // ==================== Compile and reload ====================
-
- public void compile() throws JasperException, FileNotFoundException {
- createCompiler();
- if (isPackagedTagFile || jspCompiler.isOutDated()) {
- try {
- jspLoader = null;
- jspCompiler.compile();
- jsw.setReload(true);
- jsw.setCompilationException(null);
- } catch (JasperException ex) {
- // Cache compilation exception
- jsw.setCompilationException(ex);
- throw ex;
- } catch (Exception ex) {
- ex.printStackTrace();
- JasperException je = new JasperException(
- Localizer.getMessage("jsp.error.unable.compile"),
- ex);
- // Cache compilation exception
- jsw.setCompilationException(je);
- throw je;
- }
- }
- }
-
- // ==================== Manipulating the class ====================
-
- public Class load()
- throws JasperException, FileNotFoundException
- {
- try {
- getJspLoader();
-
- String name;
- if (isTagFile()) {
- name = tagInfo.getTagClassName();
- } else {
- name = getServletPackageName() + "." + getServletClassName();
- }
- servletClass = jspLoader.loadClass(name);
- } catch (ClassNotFoundException cex) {
- throw new JasperException(Localizer.getMessage("jsp.error.unable.load"),
- cex);
- } catch (Exception ex) {
- throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"),
- ex);
- }
- removed = 0;
- return servletClass;
- }
-
- // ==================== Private methods ====================
-
- static Object outputDirLock = new Object();
-
- private void makeOutputDir() {
- synchronized(outputDirLock) {
- File outDirFile = new File(outputDir);
- outDirFile.mkdirs();
- }
- }
-
- private void createOutputDir() {
- String path = null;
- if (isTagFile()) {
- String tagName = tagInfo.getTagClassName();
- path = tagName.replace('.', '/');
- path = path.substring(0, path.lastIndexOf('/'));
- } else {
- path = getServletPackageName().replace('.', '/');
- }
-
- try {
- // Append servlet or tag handler path to scratch dir
- baseUrl = options.getScratchDir().toURL();
- String outUrlString = baseUrl.toString() + '/' + path;
- URL outUrl = new URL(outUrlString);
- outputDir = outUrl.getFile() + File.separator;
- makeOutputDir();
- } catch (Exception e) {
- throw new IllegalStateException("No output directory: " +
- e.getMessage());
- }
- }
-
- private static final boolean isPathSeparator(char c) {
- return (c == '/' || c == '\\');
- }
-
- private static final String canonicalURI(String s) {
- if (s == null) return null;
- StringBuffer result = new StringBuffer();
- final int len = s.length();
- int pos = 0;
- while (pos < len) {
- char c = s.charAt(pos);
- if ( isPathSeparator(c) ) {
- /*
- * multiple path separators.
- * 'foo///bar' -> 'foo/bar'
- */
- while (pos+1 < len && isPathSeparator(s.charAt(pos+1))) {
- ++pos;
- }
-
- if (pos+1 < len && s.charAt(pos+1) == '.') {
- /*
- * a single dot at the end of the path - we are done.
- */
- if (pos+2 >= len) break;
-
- switch (s.charAt(pos+2)) {
- /*
- * self directory in path
- * foo/./bar -> foo/bar
- */
- case '/':
- case '\\':
- pos += 2;
- continue;
-
- /*
- * two dots in a path: go back one hierarchy.
- * foo/bar/../baz -> foo/baz
- */
- case '.':
- // only if we have exactly _two_ dots.
- if (pos+3 < len && isPathSeparator(s.charAt(pos+3))) {
- pos += 3;
- int separatorPos = result.length()-1;
- while (separatorPos >= 0 &&
- ! isPathSeparator(result
- .charAt(separatorPos))) {
- --separatorPos;
- }
- if (separatorPos >= 0)
- result.setLength(separatorPos);
- continue;
- }
- }
- }
- }
- result.append(c);
- ++pos;
- }
- return result.toString();
- }
-}
-
diff --git a/1.x/src/jasper/TldLocationsCache.java b/1.x/src/jasper/TldLocationsCache.java
deleted file mode 100644
index 5c7b30e..0000000
--- a/1.x/src/jasper/TldLocationsCache.java
+++ /dev/null
@@ -1,554 +0,0 @@
-/*
- * 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.InputStream;
-import java.io.IOException;
-import java.net.JarURLConnection;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.net.URLConnection;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-import org.xml.sax.InputSource;
-
-import javax.servlet.ServletContext;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.jasper.Constants;
-import org.apache.jasper.JasperException;
-import org.apache.jasper.xmlparser.ParserUtils;
-import org.apache.jasper.xmlparser.TreeNode;
-
-/**
- * A container for all tag libraries that are defined "globally"
- * for the web application.
- *
- * Tag Libraries can be defined globally in one of two ways:
- * 1. Via elements in web.xml:
- * the uri and location of the tag-library are specified in
- * the element.
- * 2. Via packaged jar files that contain .tld files
- * within the META-INF directory, or some subdirectory
- * of it. The taglib is 'global' if it has the
- * element defined.
- *
- * A mapping between the taglib URI and its associated TaglibraryInfoImpl
- * is maintained in this container.
- * Actually, that's what we'd like to do. However, because of the
- * way the classes TagLibraryInfo and TagInfo have been defined,
- * it is not currently possible to share an instance of TagLibraryInfo
- * across page invocations. A bug has been submitted to the spec lead.
- * In the mean time, all we do is save the 'location' where the
- * TLD associated with a taglib URI can be found.
- *
- * When a JSP page has a taglib directive, the mappings in this container
- * are first searched (see method getLocation()).
- * If a mapping is found, then the location of the TLD is returned.
- * If no mapping is found, then the uri specified
- * in the taglib directive is to be interpreted as the location for
- * the TLD of this tag library.
- *
- * @author Pierre Delisle
- * @author Jan Luehe
- */
-
-public class TldLocationsCache {
-
- // Logger
- private Log log = LogFactory.getLog(TldLocationsCache.class);
-
- /**
- * The types of URI one may specify for a tag library
- */
- public static final int ABS_URI = 0;
- public static final int ROOT_REL_URI = 1;
- public static final int NOROOT_REL_URI = 2;
-
- private static final String WEB_XML = "/WEB-INF/web.xml";
- private static final String FILE_PROTOCOL = "file:";
- private static final String JAR_FILE_SUFFIX = ".jar";
-
- // Names of JARs that are known not to contain any TLDs
- private static HashSet noTldJars;
-
- /**
- * The mapping of the 'global' tag library URI to the location (resource
- * path) of the TLD associated with that tag library. The location is
- * returned as a String array:
- * [0] The location
- * [1] If the location is a jar file, this is the location of the tld.
- */
- private Hashtable mappings;
-
- private boolean initialized;
- private ServletContext ctxt;
- private boolean redeployMode;
-
- //*********************************************************************
- // Constructor and Initilizations
-
- /*
- * Initializes the set of JARs that are known not to contain any TLDs
- */
- static {
- noTldJars = new HashSet();
- noTldJars.add("ant.jar");
- noTldJars.add("catalina.jar");
- noTldJars.add("catalina-ant.jar");
- noTldJars.add("catalina-cluster.jar");
- noTldJars.add("catalina-optional.jar");
- noTldJars.add("catalina-i18n-fr.jar");
- noTldJars.add("catalina-i18n-ja.jar");
- noTldJars.add("catalina-i18n-es.jar");
- noTldJars.add("commons-dbcp.jar");
- noTldJars.add("commons-modeler.jar");
- noTldJars.add("commons-logging-api.jar");
- noTldJars.add("commons-beanutils.jar");
- noTldJars.add("commons-fileupload-1.0.jar");
- noTldJars.add("commons-pool.jar");
- noTldJars.add("commons-digester.jar");
- noTldJars.add("commons-logging.jar");
- noTldJars.add("commons-collections.jar");
- noTldJars.add("commons-el.jar");
- noTldJars.add("jakarta-regexp-1.2.jar");
- noTldJars.add("jasper-compiler.jar");
- noTldJars.add("jasper-runtime.jar");
- noTldJars.add("jmx.jar");
- noTldJars.add("jmx-tools.jar");
- noTldJars.add("jsp-api.jar");
- noTldJars.add("jkshm.jar");
- noTldJars.add("jkconfig.jar");
- noTldJars.add("naming-common.jar");
- noTldJars.add("naming-resources.jar");
- noTldJars.add("naming-factory.jar");
- noTldJars.add("naming-java.jar");
- noTldJars.add("servlet-api.jar");
- noTldJars.add("servlets-default.jar");
- noTldJars.add("servlets-invoker.jar");
- noTldJars.add("servlets-common.jar");
- noTldJars.add("servlets-webdav.jar");
- noTldJars.add("tomcat-util.jar");
- noTldJars.add("tomcat-http11.jar");
- noTldJars.add("tomcat-jni.jar");
- noTldJars.add("tomcat-jk.jar");
- noTldJars.add("tomcat-jk2.jar");
- noTldJars.add("tomcat-coyote.jar");
- noTldJars.add("xercesImpl.jar");
- noTldJars.add("xmlParserAPIs.jar");
- noTldJars.add("xml-apis.jar");
- // JARs from J2SE runtime
- noTldJars.add("sunjce_provider.jar");
- noTldJars.add("ldapsec.jar");
- noTldJars.add("localedata.jar");
- noTldJars.add("dnsns.jar");
- }
-
- public TldLocationsCache(ServletContext ctxt) {
- this(ctxt, true);
- }
-
- /** Constructor.
- *
- * @param ctxt the servlet context of the web application in which Jasper
- * is running
- * @param redeployMode if true, then the compiler will allow redeploying
- * a tag library from the same jar, at the expense of slowing down the
- * server a bit. Note that this may only work on JDK 1.3.1_01a and later,
- * because of JDK bug 4211817 fixed in this release.
- * If redeployMode is false, a faster but less capable mode will be used.
- */
- public TldLocationsCache(ServletContext ctxt, boolean redeployMode) {
- this.ctxt = ctxt;
- this.redeployMode = redeployMode;
- mappings = new Hashtable();
- initialized = false;
- }
-
- /**
- * Sets the list of JARs that are known not to contain any TLDs.
- *
- * @param jarNames List of comma-separated names of JAR files that are
- * known not to contain any TLDs
- */
- public static void setNoTldJars(String jarNames) {
- if (jarNames != null) {
- noTldJars.clear();
- StringTokenizer tokenizer = new StringTokenizer(jarNames, ",");
- while (tokenizer.hasMoreElements()) {
- noTldJars.add(tokenizer.nextToken());
- }
- }
- }
-
- /**
- * Gets the 'location' of the TLD associated with the given taglib 'uri'.
- *
- * Returns null if the uri is not associated with any tag library 'exposed'
- * in the web application. A tag library is 'exposed' either explicitly in
- * web.xml or implicitly via the uri tag in the TLD of a taglib deployed
- * in a jar file (WEB-INF/lib).
- *
- * @param uri The taglib uri
- *
- * @return An array of two Strings: The first element denotes the real
- * 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.
- * Returns null if the uri is not associated with any tag library 'exposed'
- * in the web application.
- */
- public String[] getLocation(String uri) throws JasperException {
- if (!initialized) {
- init();
- }
- return (String[]) mappings.get(uri);
- }
-
- /**
- * Returns the type of a URI:
- * ABS_URI
- * ROOT_REL_URI
- * NOROOT_REL_URI
- */
- public static int uriType(String uri) {
- if (uri.indexOf(':') != -1) {
- return ABS_URI;
- } else if (uri.startsWith("/")) {
- return ROOT_REL_URI;
- } else {
- return NOROOT_REL_URI;
- }
- }
-
- private void init() throws JasperException {
- if (initialized) return;
- try {
- processWebDotXml();
- scanJars();
- processTldsInFileSystem("/WEB-INF/");
- initialized = true;
- } catch (Exception ex) {
- throw new JasperException(Localizer.getMessage(
- "jsp.error.internal.tldinit", ex.getMessage()), ex);
- }
- }
-
- /*
- * Populates taglib map described in web.xml.
- */
- private void processWebDotXml() throws Exception {
-
- InputStream is = null;
-
- try {
- // Acquire input stream to web application deployment descriptor
- String altDDName = (String)ctxt.getAttribute(
- Constants.ALT_DD_ATTR);
- URL uri = null;
- if (altDDName != null) {
- try {
- uri = new URL(FILE_PROTOCOL+altDDName.replace('\\', '/'));
- } catch (MalformedURLException e) {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage(
- "jsp.error.internal.filenotfound",
- altDDName));
- }
- }
- } else {
- uri = ctxt.getResource(WEB_XML);
- if (uri == null && log.isWarnEnabled()) {
- log.warn(Localizer.getMessage(
- "jsp.error.internal.filenotfound",
- WEB_XML));
- }
- }
-
- if (uri == null) {
- return;
- }
- is = uri.openStream();
- InputSource ip = new InputSource(is);
- ip.setSystemId(uri.toExternalForm());
-
- // Parse the web application deployment descriptor
- TreeNode webtld = null;
- // altDDName is the absolute path of the DD
- if (altDDName != null) {
- webtld = new ParserUtils().parseXMLDocument(altDDName, ip);
- } else {
- webtld = new ParserUtils().parseXMLDocument(WEB_XML, ip);
- }
-
- // Allow taglib to be an element of the root or jsp-config (JSP2.0)
- TreeNode jspConfig = webtld.findChild("jsp-config");
- if (jspConfig != null) {
- webtld = jspConfig;
- }
- Iterator taglibs = webtld.findChildren("taglib");
- while (taglibs.hasNext()) {
-
- // Parse the next element
- TreeNode taglib = (TreeNode) taglibs.next();
- String tagUri = null;
- String tagLoc = null;
- TreeNode child = taglib.findChild("taglib-uri");
- if (child != null)
- tagUri = child.getBody();
- child = taglib.findChild("taglib-location");
- if (child != null)
- tagLoc = child.getBody();
-
- // Save this location if appropriate
- if (tagLoc == null)
- continue;
- if (uriType(tagLoc) == NOROOT_REL_URI)
- tagLoc = "/WEB-INF/" + tagLoc;
- String tagLoc2 = null;
- if (tagLoc.endsWith(JAR_FILE_SUFFIX)) {
- tagLoc = ctxt.getResource(tagLoc).toString();
- tagLoc2 = "META-INF/taglib.tld";
- }
- mappings.put(tagUri, new String[] { tagLoc, tagLoc2 });
- }
- } finally {
- if (is != null) {
- try {
- is.close();
- } catch (Throwable t) {}
- }
- }
- }
-
- /**
- * Scans the given JarURLConnection for TLD files located in META-INF
- * (or a subdirectory of it), adding an implicit map entry to the taglib
- * map for any TLD that has a element.
- *
- * @param conn The JarURLConnection to the JAR file to scan
- * @param ignore true if any exceptions raised when processing the given
- * JAR should be ignored, false otherwise
- */
- private void scanJar(JarURLConnection conn, boolean ignore)
- throws JasperException {
-
- JarFile jarFile = null;
- String resourcePath = conn.getJarFileURL().toString();
- try {
- if (redeployMode) {
- conn.setUseCaches(false);
- }
- jarFile = conn.getJarFile();
- Enumeration entries = jarFile.entries();
- while (entries.hasMoreElements()) {
- JarEntry entry = (JarEntry) entries.nextElement();
- String name = entry.getName();
- if (!name.startsWith("META-INF/")) continue;
- if (!name.endsWith(".tld")) continue;
- InputStream stream = jarFile.getInputStream(entry);
- try {
- String uri = getUriFromTld(resourcePath, stream);
- // Add implicit map entry only if its uri is not already
- // present in the map
- if (uri != null && mappings.get(uri) == null) {
- mappings.put(uri, new String[]{ resourcePath, name });
- }
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (Throwable t) {
- // do nothing
- }
- }
- }
- }
- } catch (Exception ex) {
- if (!redeployMode) {
- // if not in redeploy mode, close the jar in case of an error
- if (jarFile != null) {
- try {
- jarFile.close();
- } catch (Throwable t) {
- // ignore
- }
- }
- }
- if (!ignore) {
- throw new JasperException(ex);
- }
- } finally {
- if (redeployMode) {
- // if in redeploy mode, always close the jar
- if (jarFile != null) {
- try {
- jarFile.close();
- } catch (Throwable t) {
- // ignore
- }
- }
- }
- }
- }
-
- /*
- * Searches the filesystem under /WEB-INF for any TLD files, and adds
- * an implicit map entry to the taglib map for any TLD that has a
- * element.
- */
- private void processTldsInFileSystem(String startPath)
- throws Exception {
-
- Set dirList = ctxt.getResourcePaths(startPath);
- if (dirList != null) {
- Iterator it = dirList.iterator();
- while (it.hasNext()) {
- String path = (String) it.next();
- if (path.endsWith("/")) {
- processTldsInFileSystem(path);
- }
- if (!path.endsWith(".tld")) {
- continue;
- }
- InputStream stream = ctxt.getResourceAsStream(path);
- String uri = null;
- try {
- uri = getUriFromTld(path, stream);
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (Throwable t) {
- // do nothing
- }
- }
- }
- // Add implicit map entry only if its uri is not already
- // present in the map
- if (uri != null && mappings.get(uri) == null) {
- mappings.put(uri, new String[] { path, null });
- }
- }
- }
- }
-
- /*
- * Returns the value of the uri element of the given TLD, or null if the
- * given TLD does not contain any such element.
- */
- private String getUriFromTld(String resourcePath, InputStream in)
- throws JasperException
- {
- // Parse the tag library descriptor at the specified resource path
- TreeNode tld = new ParserUtils().parseXMLDocument(resourcePath, in);
- TreeNode uri = tld.findChild("uri");
- if (uri != null) {
- String body = uri.getBody();
- if (body != null)
- return body;
- }
-
- return null;
- }
-
- /*
- * Scans all JARs accessible to the webapp's classloader and its
- * parent classloaders for TLDs.
- *
- * The list of JARs always includes the JARs under WEB-INF/lib, as well as
- * all shared JARs in the classloader delegation chain of the webapp's
- * classloader.
- *
- * Considering JARs in the classloader delegation chain constitutes a
- * Tomcat-specific extension to the TLD search
- * order defined in the JSP spec. It allows tag libraries packaged as JAR
- * files to be shared by web applications by simply dropping them in a
- * location that all web applications have access to (e.g.,
- * /common/lib).
- *
- * The set of shared JARs to be scanned for TLDs is narrowed down by
- * the noTldJars class variable, which contains the names of JARs
- * that are known not to contain any TLDs.
- */
- private void scanJars() throws Exception {
-
- ClassLoader webappLoader
- = Thread.currentThread().getContextClassLoader();
- ClassLoader loader = webappLoader;
-
- while (loader != null) {
- if (loader instanceof URLClassLoader) {
- URL[] urls = ((URLClassLoader) loader).getURLs();
- for (int i=0; ijarPath needs to be
- * scanned for TLDs.
- *
- * @param loader The current classloader in the parent chain
- * @param webappLoader The webapp classloader
- * @param jarPath The JAR file path
- *
- * @return TRUE if the JAR file identified by jarPath needs to be
- * scanned for TLDs, FALSE otherwise
- */
- private boolean needScanJar(ClassLoader loader, ClassLoader webappLoader,
- String jarPath) {
- if (loader == webappLoader) {
- // JARs under WEB-INF/lib must be scanned unconditionally according
- // to the spec.
- return true;
- } else {
- String jarName = jarPath;
- int slash = jarPath.lastIndexOf('/');
- if (slash >= 0) {
- jarName = jarPath.substring(slash + 1);
- }
- return (!noTldJars.contains(jarName));
- }
- }
-}
diff --git a/1.x/src/jasper/bee-jasper.xml b/1.x/src/jasper/bee-jasper.xml
deleted file mode 100644
index 5314734..0000000
--- a/1.x/src/jasper/bee-jasper.xml
+++ /dev/null
@@ -1,451 +0,0 @@
-
-
-
-
-
-
-
-
-
-
- ]>
-
-
-
- &env;
-
-
-
-
- /bin/javac
-
-
-
-
-
-
- /bin/javadoc
-
-
-
-
-
- ******** &project; Build Process ********
-********* Available targets: *************************************
-* compile - do Java compilation *
-* jar - build &build_file; file *
-* run - run application &main_class; *
-*******************************************************************
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- /&build_directory;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Compiling javax...
-
-
-
-
-
-
-
-
-
- >
-
-
-
- 0
-
-
- Error(s) at compilation of javax
-
-
-
-
-
-
-
-
- Exception at compilation of javax
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Compiling... &project;
-
-
-
-
-
-
-
-
-
- >
-
-
-
- 0
-
-
- Error(s) at compilation of &project;
-
-
-
-
-
-
-
-
- Exception at compilation of &project;
-
-
-
-
-
-
-
-
-
- &manifestf;
-
-
-
-
- true
-
-
-
- -d
-
- -sourcepath
-
- -classpath
-
- &domain;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- &source_directory;/javax/servlet/jsp/resources/jsp*.dtd
- &build_directory;/javax/servlet/jsp/resources
- &source_directory;/javax/servlet/jsp/resources/jsp*.xsd
- &build_directory;/javax/servlet/jsp/resources
- &source_directory;/javax/servlet/jsp/resources/web-jsp*.dtd
- &build_directory;/javax/servlet/jsp/resources
- &source_directory;/javax/servlet/jsp/resources/web-jsp*.xsd
- &build_directory;/javax/servlet/jsp/resources
-
- &source_directory;/javax/servlet/resources/j2ee*.dtd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/j2ee*.xsd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/javaee_*.xsd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/web-app*.dtd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/web-*.xsd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/datatypes.dtd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/xml.xsd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/XMLSchema.dtd
- &build_directory;/javax/servlet/resources
-
-
-
-
-
-
-
-
-
-
-
-
- Jarring...
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -cf
-
-
-
- -cmf
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- java
- org/apache/jasper/resources
-
-
-
-
-
-
- -C
- &source_directory;
-
-
-
-
-
-
-
-
-
-
-
- -C
- &source_directory;
-
-
-
-
-
-
-
-
-
-
-
- -C
- &source_directory;
-
-
-
-
-
-
-
-
-
-
-
-
- -C
- &source_directory;
-
-
-
-
-
-
-
-
-
-
-
- -C
- &source_directory;
-
-
-
-
-
-
-
-
-
- Exception at jarring
-
-
-
-
-
-
-
-
-
-
-
-
- y
-
-
-
-
-
-
-
-
- Cleaning...
-
-
-
-
-
-
-
-
-
-
- /&build_directory;/&build_file;
-
-
-
-
- /lib/tools.jar
-
-
-
-
- Running...
-
-
-
- -classpath
-
-
-
-
-
-
diff --git a/1.x/src/jasper/env.xml b/1.x/src/jasper/env.xml
deleted file mode 100644
index 270b948..0000000
--- a/1.x/src/jasper/env.xml
+++ /dev/null
@@ -1,48 +0,0 @@
-
-
-
-
- .
-
-
-
-
-
-
- /
-
-
-
-
-
-
-
-
- /jre
-
-
-
-
-
-
-
-
-
-
- maven:javax.servlet:javax.servlet-api:3.1.0
-
- 1.6
-
-
-
- \\jre
-
-
-
-
-
-
-
-
-
diff --git a/1.x/src/jasper6/JspC.java b/1.x/src/jasper6/JspC.java
deleted file mode 100644
index 2f6d632..0000000
--- a/1.x/src/jasper6/JspC.java
+++ /dev/null
@@ -1,1597 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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;
-
-import java.io.BufferedReader;
-import java.io.CharArrayWriter;
-import java.io.EOFException;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.io.Reader;
-import java.io.Writer;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.Stack;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
-import org.apache.jasper.compiler.Compiler;
-import org.apache.jasper.compiler.JspConfig;
-import org.apache.jasper.compiler.JspRuntimeContext;
-import org.apache.jasper.compiler.Localizer;
-import org.apache.jasper.compiler.TagPluginManager;
-import org.apache.jasper.compiler.TldLocationsCache;
-import org.apache.jasper.servlet.JspCServletContext;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-
-
-/**
- * Shell for the jspc compiler. Handles all options associated with the
- * command line and creates compilation contexts which it then compiles
- * according to the specified options.
- *
- * This version can process files from a _single_ webapp at once, i.e.
- * a single docbase can be specified.
- *
- * It can be used as an Ant task using:
- *
- * <taskdef classname="org.apache.jasper.JspC" name="jasper" >
- * <classpath>
- * <pathelement location="${java.home}/../lib/tools.jar"/>
- * <fileset dir="${ENV.CATALINA_HOME}/lib">
- * <include name="*.jar"/>
- * </fileset>
- * <path refid="myjars"/>
- * </classpath>
- * </taskdef>
- *
- * <jasper verbose="0"
- * package="my.package"
- * uriroot="${webapps.dir}/${webapp.name}"
- * webXmlFragment="${build.dir}/generated_web.xml"
- * outputDir="${webapp.dir}/${webapp.name}/WEB-INF/src/my/package" />
- *
- *
- * @author Danno Ferrin
- * @author Pierre Delisle
- * @author Costin Manolache
- * @author Yoav Shapira
- */
-public class JspC implements Options {
-
- public static final String DEFAULT_IE_CLASS_ID =
- "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";
-
- // Logger
- protected static Log log = LogFactory.getLog(JspC.class);
-
- protected static final String SWITCH_VERBOSE = "-v";
- protected static final String SWITCH_HELP = "-help";
- protected static final String SWITCH_OUTPUT_DIR = "-d";
- protected static final String SWITCH_PACKAGE_NAME = "-p";
- protected static final String SWITCH_CACHE = "-cache";
- protected static final String SWITCH_CLASS_NAME = "-c";
- protected static final String SWITCH_FULL_STOP = "--";
- protected static final String SWITCH_COMPILE = "-compile";
- protected static final String SWITCH_SOURCE = "-source";
- protected static final String SWITCH_TARGET = "-target";
- protected static final String SWITCH_URI_BASE = "-uribase";
- protected static final String SWITCH_URI_ROOT = "-uriroot";
- protected static final String SWITCH_FILE_WEBAPP = "-webapp";
- protected static final String SWITCH_WEBAPP_INC = "-webinc";
- protected static final String SWITCH_WEBAPP_XML = "-webxml";
- protected static final String SWITCH_WEBAPP_XML_ENCODING = "-webxmlencoding";
- protected static final String SWITCH_ADD_WEBAPP_XML_MAPPINGS = "-addwebxmlmappings";
- protected static final String SWITCH_MAPPED = "-mapped";
- protected static final String SWITCH_XPOWERED_BY = "-xpoweredBy";
- protected static final String SWITCH_TRIM_SPACES = "-trimSpaces";
- protected static final String SWITCH_CLASSPATH = "-classpath";
- protected static final String SWITCH_DIE = "-die";
- protected static final String SWITCH_POOLING = "-poolingEnabled";
- protected static final String SWITCH_ENCODING = "-javaEncoding";
- protected static final String SWITCH_SMAP = "-smap";
- protected static final String SWITCH_DUMP_SMAP = "-dumpsmap";
-
- protected static final String SHOW_SUCCESS ="-s";
- protected static final String LIST_ERRORS = "-l";
- protected static final int INC_WEBXML = 10;
- protected static final int ALL_WEBXML = 20;
- protected static final int DEFAULT_DIE_LEVEL = 1;
- protected static final int NO_DIE_LEVEL = 0;
-
- protected static final String[] insertBefore =
- { "", "", "",
- "", "", "", "",
- "", "", "",
- "", "", "", "",
- "" };
-
- protected static int die;
- protected String classPath = null;
- protected URLClassLoader loader = null;
- protected boolean trimSpaces = false;
- protected boolean genStringAsCharArray = false;
- protected boolean xpoweredBy;
- protected boolean mappedFile = false;
- protected boolean poolingEnabled = true;
- protected File scratchDir;
- protected String ieClassId = DEFAULT_IE_CLASS_ID;
- protected String targetPackage;
- protected String targetClassName;
- protected String uriBase;
- protected String uriRoot;
- protected int dieLevel;
- protected boolean helpNeeded = false;
- protected boolean compile = false;
- protected boolean smapSuppressed = true;
- protected boolean smapDumped = false;
- protected boolean caching = true;
- protected Map cache = new HashMap();
-
- protected String compiler = null;
-
- protected String compilerTargetVM = "1.5";
- protected String compilerSourceVM = "1.5";
-
- protected boolean classDebugInfo = true;
-
- /**
- * Throw an exception if there's a compilation error, or swallow it.
- * Default is true to preserve old behavior.
- */
- protected boolean failOnError = true;
-
- /**
- * The file extensions to be handled as JSP files.
- * Default list is .jsp and .jspx.
- */
- protected List extensions;
-
- /**
- * The pages.
- */
- protected List pages = new Vector();
-
- /**
- * Needs better documentation, this data member does.
- * True by default.
- */
- protected boolean errorOnUseBeanInvalidClassAttribute = true;
-
- /**
- * The java file encoding. Default
- * is UTF-8. Added per bugzilla 19622.
- */
- protected String javaEncoding = "UTF-8";
-
- // Generation of web.xml fragments
- protected String webxmlFile;
- protected int webxmlLevel;
- protected String webxmlEncoding;
- protected boolean addWebXmlMappings = false;
-
- protected Writer mapout;
- protected CharArrayWriter servletout;
- protected CharArrayWriter mappingout;
-
- /**
- * The servlet context.
- */
- protected JspCServletContext context;
-
- /**
- * The runtime context.
- * Maintain a dummy JspRuntimeContext for compiling tag files.
- */
- protected JspRuntimeContext rctxt;
-
- /**
- * Cache for the TLD locations
- */
- protected TldLocationsCache tldLocationsCache = null;
-
- protected JspConfig jspConfig = null;
- protected TagPluginManager tagPluginManager = null;
-
- protected boolean verbose = false;
- protected boolean listErrors = false;
- protected boolean showSuccess = false;
- protected int argPos;
- protected boolean fullstop = false;
- protected String args[];
-
- public static void main(String arg[]) {
- if (arg.length == 0) {
- System.out.println(Localizer.getMessage("jspc.usage"));
- } else {
- try {
- JspC jspc = new JspC();
- jspc.setArgs(arg);
- if (jspc.helpNeeded) {
- System.out.println(Localizer.getMessage("jspc.usage"));
- } else {
- jspc.execute();
- }
- } catch (JasperException je) {
- System.err.println(je);
- if (die != NO_DIE_LEVEL) {
- System.exit(die);
- }
- }
- }
- }
-
- /**
- * Apply command-line arguments.
- *
- * @param arg
- * The arguments
- */
- public void setArgs(String[] arg) throws JasperException {
- args = arg;
- String tok;
-
- dieLevel = NO_DIE_LEVEL;
- die = dieLevel;
-
- while ((tok = nextArg()) != null) {
- if (tok.equals(SWITCH_VERBOSE)) {
- verbose = true;
- showSuccess = true;
- listErrors = true;
- } else if (tok.equals(SWITCH_OUTPUT_DIR)) {
- tok = nextArg();
- setOutputDir( tok );
- } else if (tok.equals(SWITCH_PACKAGE_NAME)) {
- targetPackage = nextArg();
- } else if (tok.equals(SWITCH_COMPILE)) {
- compile=true;
- } else if (tok.equals(SWITCH_CLASS_NAME)) {
- targetClassName = nextArg();
- } else if (tok.equals(SWITCH_URI_BASE)) {
- uriBase=nextArg();
- } else if (tok.equals(SWITCH_URI_ROOT)) {
- setUriroot( nextArg());
- } else if (tok.equals(SWITCH_FILE_WEBAPP)) {
- setUriroot( nextArg());
- } else if ( tok.equals( SHOW_SUCCESS ) ) {
- showSuccess = true;
- } else if ( tok.equals( LIST_ERRORS ) ) {
- listErrors = true;
- } else if (tok.equals(SWITCH_WEBAPP_INC)) {
- webxmlFile = nextArg();
- if (webxmlFile != null) {
- webxmlLevel = INC_WEBXML;
- }
- } else if (tok.equals(SWITCH_WEBAPP_XML)) {
- webxmlFile = nextArg();
- if (webxmlFile != null) {
- webxmlLevel = ALL_WEBXML;
- }
- } else if (tok.equals(SWITCH_WEBAPP_XML_ENCODING)) {
- setWebXmlEncoding(nextArg());
- } else if (tok.equals(SWITCH_ADD_WEBAPP_XML_MAPPINGS)) {
- setAddWebXmlMappings(true);
- } else if (tok.equals(SWITCH_MAPPED)) {
- mappedFile = true;
- } else if (tok.equals(SWITCH_XPOWERED_BY)) {
- xpoweredBy = true;
- } else if (tok.equals(SWITCH_TRIM_SPACES)) {
- setTrimSpaces(true);
- } else if (tok.equals(SWITCH_CACHE)) {
- tok = nextArg();
- if ("false".equals(tok)) {
- caching = false;
- } else {
- caching = true;
- }
- } else if (tok.equals(SWITCH_CLASSPATH)) {
- setClassPath(nextArg());
- } else if (tok.startsWith(SWITCH_DIE)) {
- try {
- dieLevel = Integer.parseInt(
- tok.substring(SWITCH_DIE.length()));
- } catch (NumberFormatException nfe) {
- dieLevel = DEFAULT_DIE_LEVEL;
- }
- die = dieLevel;
- } else if (tok.equals(SWITCH_HELP)) {
- helpNeeded = true;
- } else if (tok.equals(SWITCH_POOLING)) {
- tok = nextArg();
- if ("false".equals(tok)) {
- poolingEnabled = false;
- } else {
- poolingEnabled = true;
- }
- } else if (tok.equals(SWITCH_ENCODING)) {
- setJavaEncoding(nextArg());
- } else if (tok.equals(SWITCH_SOURCE)) {
- setCompilerSourceVM(nextArg());
- } else if (tok.equals(SWITCH_TARGET)) {
- setCompilerTargetVM(nextArg());
- } else if (tok.equals(SWITCH_SMAP)) {
- smapSuppressed = false;
- } else if (tok.equals(SWITCH_DUMP_SMAP)) {
- smapDumped = true;
- } else {
- if (tok.startsWith("-")) {
- throw new JasperException("Unrecognized option: " + tok +
- ". Use -help for help.");
- }
- if (!fullstop) {
- argPos--;
- }
- // Start treating the rest as JSP Pages
- break;
- }
- }
-
- // Add all extra arguments to the list of files
- while( true ) {
- String file = nextFile();
- if( file==null ) {
- break;
- }
- pages.add( file );
- }
- }
-
- /**
- * In JspC this always returns true.
- * {@inheritDoc}
- */
- public boolean getKeepGenerated() {
- // isn't this why we are running jspc?
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean getTrimSpaces() {
- return trimSpaces;
- }
-
- /**
- * Sets the option to trim white spaces between directives or actions.
- */
- public void setTrimSpaces(boolean ts) {
- this.trimSpaces = ts;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isPoolingEnabled() {
- return poolingEnabled;
- }
-
- /**
- * Sets the option to enable the tag handler pooling.
- */
- public void setPoolingEnabled(boolean poolingEnabled) {
- this.poolingEnabled = poolingEnabled;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isXpoweredBy() {
- return xpoweredBy;
- }
-
- /**
- * Sets the option to enable generation of X-Powered-By response header.
- */
- public void setXpoweredBy(boolean xpoweredBy) {
- this.xpoweredBy = xpoweredBy;
- }
-
- /**
- * In JspC this always returns true.
- * {@inheritDoc}
- */
- public boolean getDisplaySourceFragment() {
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean getErrorOnUseBeanInvalidClassAttribute() {
- return errorOnUseBeanInvalidClassAttribute;
- }
-
- /**
- * Sets the option to issue a compilation error if the class attribute
- * specified in useBean action is invalid.
- */
- public void setErrorOnUseBeanInvalidClassAttribute(boolean b) {
- errorOnUseBeanInvalidClassAttribute = b;
- }
-
- /**
- * @deprecated Removed in Tomcat 7
- */
- @Deprecated
- public int getTagPoolSize() {
- return Constants.MAX_POOL_SIZE;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean getMappedFile() {
- return mappedFile;
- }
-
- /**
- * @deprecated Removed in Tomcat 7
- */
- @Deprecated
- public Object getProtectionDomain() {
- // Off-line compiler, no need for security manager
- return null;
- }
-
- /**
- * @deprecated
- */
- @Deprecated
- public boolean getSendErrorToClient() {
- return true;
- }
-
- /**
- * Sets the option to include debug information in compiled class.
- */
- public void setClassDebugInfo( boolean b ) {
- classDebugInfo=b;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean getClassDebugInfo() {
- // compile with debug info
- return classDebugInfo;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isCaching() {
- return caching;
- }
-
- /**
- * Sets the option to enable caching.
- *
- * @see Options#isCaching()
- */
- public void setCaching(boolean caching) {
- this.caching = caching;
- }
-
- /**
- * {@inheritDoc}
- */
- public Map getCache() {
- return cache;
- }
-
- /**
- * In JspC this always returns 0.
- * {@inheritDoc}
- */
- public int getCheckInterval() {
- return 0;
- }
-
- /**
- * In JspC this always returns 0.
- * {@inheritDoc}
- */
- public int getModificationTestInterval() {
- return 0;
- }
-
-
- /**
- * In JspC this always returns false.
- * {@inheritDoc}
- */
- public boolean getRecompileOnFail() {
- return false;
- }
-
-
- /**
- * In JspC this always returns false.
- * {@inheritDoc}
- */
- public boolean getDevelopment() {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isSmapSuppressed() {
- return smapSuppressed;
- }
-
- /**
- * Sets smapSuppressed flag.
- */
- public void setSmapSuppressed(boolean smapSuppressed) {
- this.smapSuppressed = smapSuppressed;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isSmapDumped() {
- return smapDumped;
- }
-
- /**
- * Sets smapDumped flag.
- *
- * @see Options#isSmapDumped()
- */
- public void setSmapDumped(boolean smapDumped) {
- this.smapDumped = smapDumped;
- }
-
-
- /**
- * Determines whether text strings are to be generated as char arrays,
- * which improves performance in some cases.
- *
- * @param genStringAsCharArray true if text strings are to be generated as
- * char arrays, false otherwise
- */
- public void setGenStringAsCharArray(boolean genStringAsCharArray) {
- this.genStringAsCharArray = genStringAsCharArray;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean genStringAsCharArray() {
- return genStringAsCharArray;
- }
-
- /**
- * Sets the class-id value to be sent to Internet Explorer when using
- * <jsp:plugin> tags.
- *
- * @param ieClassId
- * Class-id value
- */
- public void setIeClassId(String ieClassId) {
- this.ieClassId = ieClassId;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getIeClassId() {
- return ieClassId;
- }
-
- /**
- * {@inheritDoc}
- */
- public File getScratchDir() {
- return scratchDir;
- }
-
- /**
- * @deprecated Removed in Tomcat 7
- */
- @Deprecated
- public Class getJspCompilerPlugin() {
- // we don't compile, so this is meanlingless
- return null;
- }
-
- /**
- * @deprecated Removed in Tomcat 7
- */
- @Deprecated
- public String getJspCompilerPath() {
- // we don't compile, so this is meanlingless
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getCompiler() {
- return compiler;
- }
-
- /**
- * Sets the option to determine what compiler to use.
- *
- * @see Options#getCompiler()
- */
- public void setCompiler(String c) {
- compiler=c;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getCompilerClassName() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getCompilerTargetVM() {
- return compilerTargetVM;
- }
-
- /**
- * Sets the compiler target VM.
- *
- * @see Options#getCompilerTargetVM()
- */
- public void setCompilerTargetVM(String vm) {
- compilerTargetVM = vm;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getCompilerSourceVM() {
- return compilerSourceVM;
- }
-
- /**
- * Sets the compiler source VM.
- *
- * @see Options#getCompilerSourceVM()
- */
- public void setCompilerSourceVM(String vm) {
- compilerSourceVM = vm;
- }
-
- /**
- * {@inheritDoc}
- */
- public TldLocationsCache getTldLocationsCache() {
- return tldLocationsCache;
- }
-
- /**
- * Returns the encoding to use for
- * java files. The default is UTF-8.
- *
- * @return String The encoding
- */
- public String getJavaEncoding() {
- return javaEncoding;
- }
-
- /**
- * Sets the encoding to use for
- * java files.
- *
- * @param encodingName The name, e.g. "UTF-8"
- */
- public void setJavaEncoding(String encodingName) {
- javaEncoding = encodingName;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean getFork() {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getClassPath() {
- if( classPath != null )
- return classPath;
- return System.getProperty("java.class.path");
- }
-
- /**
- * Sets the classpath used while compiling the servlets generated from JSP
- * files
- */
- public void setClassPath(String s) {
- classPath=s;
- }
-
- /**
- * Returns the list of file extensions
- * that are treated as JSP files.
- *
- * @return The list of extensions
- */
- public List getExtensions() {
- return extensions;
- }
-
- /**
- * Adds the given file extension to the
- * list of extensions handled as JSP files.
- *
- * @param extension The extension to add, e.g. "myjsp"
- */
- protected void addExtension(final String extension) {
- if(extension != null) {
- if(extensions == null) {
- extensions = new Vector();
- }
-
- extensions.add(extension);
- }
- }
-
- /**
- * Base dir for the webapp. Used to generate class names and resolve
- * includes.
- */
- public void setUriroot( String s ) {
- if( s==null ) {
- uriRoot = s;
- return;
- }
- try {
- uriRoot = resolveFile(s).getCanonicalPath();
- } catch( Exception ex ) {
- uriRoot = s;
- }
- }
-
- /**
- * Parses comma-separated list of JSP files to be processed. If the argument
- * is null, nothing is done.
- *
- * Each file is interpreted relative to uriroot, unless it is absolute,
- * in which case it must start with uriroot.
- *
- * @param jspFiles Comma-separated list of JSP files to be processed
- */
- public void setJspFiles(final String jspFiles) {
- if(jspFiles == null) {
- return;
- }
-
- StringTokenizer tok = new StringTokenizer(jspFiles, ",");
- while (tok.hasMoreTokens()) {
- pages.add(tok.nextToken());
- }
- }
-
- /**
- * Sets the compile flag.
- *
- * @param b Flag value
- */
- public void setCompile( final boolean b ) {
- compile = b;
- }
-
- /**
- * Sets the verbosity level. The actual number doesn't
- * matter: if it's greater than zero, the verbose flag will
- * be true.
- *
- * @param level Positive means verbose
- */
- public void setVerbose( final int level ) {
- if (level > 0) {
- verbose = true;
- showSuccess = true;
- listErrors = true;
- }
- }
-
- public void setValidateXml( boolean b ) {
- org.apache.jasper.xmlparser.ParserUtils.validating=b;
- }
-
- public void setListErrors( boolean b ) {
- listErrors = b;
- }
-
- public void setOutputDir( String s ) {
- if( s!= null ) {
- scratchDir = resolveFile(s).getAbsoluteFile();
- } else {
- scratchDir=null;
- }
- }
-
- /**
- * Sets the package name to be used for the generated servlet classes.
- */
- public void setPackage( String p ) {
- targetPackage=p;
- }
-
- /**
- * Class name of the generated file ( without package ).
- * Can only be used if a single file is converted.
- * XXX Do we need this feature ?
- */
- public void setClassName( String p ) {
- targetClassName=p;
- }
-
- /**
- * File where we generate a web.xml fragment with the class definitions.
- */
- public void setWebXmlFragment( String s ) {
- webxmlFile=resolveFile(s).getAbsolutePath();
- webxmlLevel=INC_WEBXML;
- }
-
- /**
- * File where we generate a complete web.xml with the class definitions.
- */
- public void setWebXml( String s ) {
- webxmlFile=resolveFile(s).getAbsolutePath();
- webxmlLevel=ALL_WEBXML;
- }
-
- /**
- * Sets the encoding to be used to read and write web.xml files.
- *
- *
- * If not specified, defaults to the platform default encoding.
- *
- *
- * @param encoding
- * Encoding, e.g. "UTF-8".
- */
- public void setWebXmlEncoding(String encoding) {
- webxmlEncoding = encoding;
- }
-
- /**
- * Sets the option to merge generated web.xml fragment into the
- * WEB-INF/web.xml file of the web application that we were processing.
- *
- * @param b
- * true to merge the fragment into the existing
- * web.xml file of the processed web application
- * ({uriroot}/WEB-INF/web.xml), false to keep the
- * generated web.xml fragment
- */
- public void setAddWebXmlMappings(boolean b) {
- addWebXmlMappings = b;
- }
-
- /**
- * Sets the option that throws an exception in case of a compilation error.
- */
- public void setFailOnError(final boolean b) {
- failOnError = b;
- }
-
- /**
- * Returns true if an exception will be thrown in case of a compilation
- * error.
- */
- public boolean getFailOnError() {
- return failOnError;
- }
-
- /**
- * {@inheritDoc}
- */
- public JspConfig getJspConfig() {
- return jspConfig;
- }
-
- /**
- * {@inheritDoc}
- */
- public TagPluginManager getTagPluginManager() {
- return tagPluginManager;
- }
-
- /**
- * Adds servlet declaration and mapping for the JSP page servlet to the
- * generated web.xml fragment.
- *
- * @param file
- * Context-relative path to the JSP file, e.g.
- * /index.jsp
- * @param clctxt
- * Compilation context of the servlet
- */
- public void generateWebMapping( String file, JspCompilationContext clctxt )
- throws IOException
- {
- if (log.isDebugEnabled()) {
- log.debug("Generating web mapping for file " + file
- + " using compilation context " + clctxt);
- }
-
- String className = clctxt.getServletClassName();
- String packageName = clctxt.getServletPackageName();
-
- String thisServletName;
- if ("".equals(packageName)) {
- thisServletName = className;
- } else {
- thisServletName = packageName + '.' + className;
- }
-
- if (servletout != null) {
- servletout.write("\n \n ");
- servletout.write(thisServletName);
- servletout.write("\n ");
- servletout.write(thisServletName);
- servletout.write("\n \n");
- }
- if (mappingout != null) {
- mappingout.write("\n \n ");
- mappingout.write(thisServletName);
- mappingout.write("\n ");
- mappingout.write(file.replace('\\', '/'));
- mappingout.write("\n \n");
-
- }
- }
-
- /**
- * Include the generated web.xml inside the webapp's web.xml.
- */
- protected void mergeIntoWebXml() throws IOException {
-
- File webappBase = new File(uriRoot);
- File webXml = new File(webappBase, "WEB-INF/web.xml");
- File webXml2 = new File(webappBase, "WEB-INF/web2.xml");
- String insertStartMarker =
- Localizer.getMessage("jspc.webinc.insertStart");
- String insertEndMarker =
- Localizer.getMessage("jspc.webinc.insertEnd");
-
- BufferedReader reader = new BufferedReader(openWebxmlReader(webXml));
- BufferedReader fragmentReader = new BufferedReader(
- openWebxmlReader(new File(webxmlFile)));
- PrintWriter writer = new PrintWriter(openWebxmlWriter(webXml2));
-
- // Insert the and declarations
- boolean inserted = false;
- int current = reader.read();
- while (current > -1) {
- if (current == '<') {
- String element = getElement(reader);
- boolean found = false;
- if (!inserted) {
- for (String before : insertBefore) {
- if (element.equals(before)) {
- found = true;
- break;
- }
- }
- }
- if (found) {
- // Insert generated content here
- writer.println(insertStartMarker);
- while (true) {
- String line = fragmentReader.readLine();
- if (line == null) {
- writer.println();
- break;
- }
- writer.println(line);
- }
- writer.println(insertEndMarker);
- writer.println();
- writer.write(element);
- inserted = true;
- } else if (element.equals(insertStartMarker)) {
- // Skip the previous auto-generated content
- while (true) {
- current = reader.read();
- if (current < 0) {
- throw new EOFException();
- }
- if (current == '<') {
- element = getElement(reader);
- if (element.equals(insertEndMarker)) {
- break;
- }
- }
- }
- current = reader.read();
- while (current == '\n' || current == '\r') {
- current = reader.read();
- }
- continue;
- } else {
- writer.write(element);
- }
- } else {
- writer.write(current);
- }
- current = reader.read();
- }
- writer.close();
-
- reader.close();
- fragmentReader.close();
-
- FileInputStream fis = new FileInputStream(webXml2);
- FileOutputStream fos = new FileOutputStream(webXml);
-
- byte buf[] = new byte[512];
- while (true) {
- int n = fis.read(buf);
- if (n < 0) {
- break;
- }
- fos.write(buf, 0, n);
- }
-
- fis.close();
- fos.close();
-
- webXml2.delete();
- (new File(webxmlFile)).delete();
-
- }
-
-
- /*
- * Assumes valid xml
- */
- private String getElement(Reader reader) throws IOException {
- StringBuilder result = new StringBuilder();
- result.append('<');
-
- boolean done = false;
-
- while (!done) {
- int current = reader.read();
- while (current != '>') {
- if (current < 0) {
- throw new EOFException();
- }
- result.append((char) current);
- current = reader.read();
- }
- result.append((char) current);
-
- int len = result.length();
- if (len > 4 && result.substring(0, 4).equals("")) {
- done = true;
- }
- } else {
- done = true;
- }
- }
-
-
- return result.toString();
- }
-
-
- protected void processFile(String file)
- throws JasperException
- {
- if (log.isDebugEnabled()) {
- log.debug("Processing file: " + file);
- }
-
- ClassLoader originalClassLoader = null;
-
- try {
- // set up a scratch/output dir if none is provided
- if (scratchDir == null) {
- String temp = System.getProperty("java.io.tmpdir");
- if (temp == null) {
- temp = "";
- }
- scratchDir = new File(new File(temp).getAbsolutePath());
- }
-
- String jspUri=file.replace('\\','/');
- JspCompilationContext clctxt = new JspCompilationContext
- ( jspUri, false, this, context, null, rctxt );
-
- /* Override the defaults */
- if ((targetClassName != null) && (targetClassName.length() > 0)) {
- clctxt.setServletClassName(targetClassName);
- targetClassName = null;
- }
- if (targetPackage != null) {
- clctxt.setServletPackageName(targetPackage);
- }
-
- originalClassLoader = Thread.currentThread().getContextClassLoader();
- if( loader==null ) {
- initClassLoader( clctxt );
- }
- Thread.currentThread().setContextClassLoader(loader);
-
- clctxt.setClassLoader(loader);
- clctxt.setClassPath(classPath);
-
- Compiler clc = clctxt.createCompiler();
-
- // If compile is set, generate both .java and .class, if
- // .jsp file is newer than .class file;
- // Otherwise only generate .java, if .jsp file is newer than
- // the .java file
- if( clc.isOutDated(compile) ) {
- if (log.isDebugEnabled()) {
- log.debug(jspUri + " is out dated, compiling...");
- }
-
- clc.compile(compile, true);
- }
-
- // Generate mapping
- generateWebMapping( file, clctxt );
- if ( showSuccess ) {
- log.info( "Built File: " + file );
- }
-
- } catch (JasperException je) {
- Throwable rootCause = je;
- while (rootCause instanceof JasperException
- && ((JasperException) rootCause).getRootCause() != null) {
- rootCause = ((JasperException) rootCause).getRootCause();
- }
- if (rootCause != je) {
- log.error(Localizer.getMessage("jspc.error.generalException",
- file),
- rootCause);
- }
-
- // Bugzilla 35114.
- if(getFailOnError()) {
- throw je;
- } else {
- log.error(je.getMessage());
- }
-
- } catch (Exception e) {
- if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist",
- e.getMessage()));
- }
- throw new JasperException(e);
- } finally {
- if(originalClassLoader != null) {
- Thread.currentThread().setContextClassLoader(originalClassLoader);
- }
- }
- }
-
- /**
- * Locate all jsp files in the webapp. Used if no explicit
- * jsps are specified.
- */
- public void scanFiles( File base ) throws JasperException {
- Stack dirs = new Stack();
- dirs.push(base.toString());
-
- // Make sure default extensions are always included
- if ((getExtensions() == null) || (getExtensions().size() < 2)) {
- addExtension("jsp");
- addExtension("jspx");
- }
-
- while (!dirs.isEmpty()) {
- String s = dirs.pop();
- File f = new File(s);
- if (f.exists() && f.isDirectory()) {
- String[] files = f.list();
- String ext;
- for (int i = 0; (files != null) && i < files.length; i++) {
- File f2 = new File(s, files[i]);
- if (f2.isDirectory()) {
- dirs.push(f2.getPath());
- } else {
- String path = f2.getPath();
- String uri = path.substring(uriRoot.length());
- ext = files[i].substring(files[i].lastIndexOf('.') +1);
- if (getExtensions().contains(ext) ||
- jspConfig.isJspPage(uri)) {
- pages.add(path);
- }
- }
- }
- }
- }
- }
-
- /**
- * Executes the compilation.
- *
- * @throws JasperException If an error occurs
- */
- public void execute() throws JasperException {
- if(log.isDebugEnabled()) {
- log.debug("execute() starting for " + pages.size() + " pages.");
- }
-
- try {
- if (uriRoot == null) {
- if( pages.size() == 0 ) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.missingTarget"));
- }
- String firstJsp = (String) pages.get( 0 );
- File firstJspF = new File( firstJsp );
- if (!firstJspF.exists()) {
- throw new JasperException(
- Localizer.getMessage("jspc.error.fileDoesNotExist",
- firstJsp));
- }
- locateUriRoot( firstJspF );
- }
-
- if (uriRoot == null) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.no_uriroot"));
- }
-
- if( context==null ) {
- initServletContext();
- }
-
- // No explicit pages, we'll process all .jsp in the webapp
- if (pages.size() == 0) {
- scanFiles( new File( uriRoot ));
- }
-
- File uriRootF = new File(uriRoot);
- if (!uriRootF.exists() || !uriRootF.isDirectory()) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.uriroot_not_dir"));
- }
-
- initWebXml();
-
- Iterator iter = pages.iterator();
- while (iter.hasNext()) {
- String nextjsp = iter.next().toString();
- File fjsp = new File(nextjsp);
- if (!fjsp.isAbsolute()) {
- fjsp = new File(uriRootF, nextjsp);
- }
- if (!fjsp.exists()) {
- if (log.isWarnEnabled()) {
- log.warn
- (Localizer.getMessage
- ("jspc.error.fileDoesNotExist", fjsp.toString()));
- }
- continue;
- }
- String s = fjsp.getAbsolutePath();
- if (s.startsWith(uriRoot)) {
- nextjsp = s.substring(uriRoot.length());
- }
- if (nextjsp.startsWith("." + File.separatorChar)) {
- nextjsp = nextjsp.substring(2);
- }
- processFile(nextjsp);
- }
-
- completeWebXml();
-
- if (addWebXmlMappings) {
- mergeIntoWebXml();
- }
-
- } catch (IOException ioe) {
- throw new JasperException(ioe);
-
- } catch (JasperException je) {
- Throwable rootCause = je;
- while (rootCause instanceof JasperException
- && ((JasperException) rootCause).getRootCause() != null) {
- rootCause = ((JasperException) rootCause).getRootCause();
- }
- if (rootCause != je) {
- rootCause.printStackTrace();
- }
- throw je;
- } finally {
- if (loader != null) {
- LogFactory.release(loader);
- }
- }
- }
-
- // ==================== protected utility methods ====================
-
- protected String nextArg() {
- if ((argPos >= args.length)
- || (fullstop = SWITCH_FULL_STOP.equals(args[argPos]))) {
- return null;
- } else {
- return args[argPos++];
- }
- }
-
- protected String nextFile() {
- if (fullstop) argPos++;
- if (argPos >= args.length) {
- return null;
- } else {
- return args[argPos++];
- }
- }
-
- protected void initWebXml() {
- try {
- if (webxmlLevel >= INC_WEBXML) {
- mapout = openWebxmlWriter(new File(webxmlFile));
- servletout = new CharArrayWriter();
- mappingout = new CharArrayWriter();
- } else {
- mapout = null;
- servletout = null;
- mappingout = null;
- }
- if (webxmlLevel >= ALL_WEBXML) {
- mapout.write(Localizer.getMessage("jspc.webxml.header"));
- mapout.flush();
- } else if ((webxmlLevel>= INC_WEBXML) && !addWebXmlMappings) {
- mapout.write(Localizer.getMessage("jspc.webinc.header"));
- mapout.flush();
- }
- } catch (IOException ioe) {
- mapout = null;
- servletout = null;
- mappingout = null;
- }
- }
-
- protected void completeWebXml() {
- if (mapout != null) {
- try {
- servletout.writeTo(mapout);
- mappingout.writeTo(mapout);
- if (webxmlLevel >= ALL_WEBXML) {
- mapout.write(Localizer.getMessage("jspc.webxml.footer"));
- } else if ((webxmlLevel >= INC_WEBXML) && !addWebXmlMappings) {
- mapout.write(Localizer.getMessage("jspc.webinc.footer"));
- }
- mapout.close();
- } catch (IOException ioe) {
- // noting to do if it fails since we are done with it
- }
- }
- }
-
- protected void initServletContext() {
- try {
- context =new JspCServletContext
- (new PrintWriter(System.out),
- new URL("file:" + uriRoot.replace('\\','/') + '/'));
- tldLocationsCache = new TldLocationsCache(context, true);
- } catch (MalformedURLException me) {
- System.out.println("**" + me);
- }
- rctxt = new JspRuntimeContext(context, this);
- jspConfig = new JspConfig(context);
- tagPluginManager = new TagPluginManager(context);
- }
-
- /**
- * Initializes the classloader as/if needed for the given
- * compilation context.
- *
- * @param clctxt The compilation context
- * @throws IOException If an error occurs
- */
- protected void initClassLoader(JspCompilationContext clctxt)
- throws IOException {
-
- classPath = getClassPath();
-
- ClassLoader jspcLoader = getClass().getClassLoader();
-
- // TODO add 7Bee class loader
-
- // Turn the classPath into URLs
- ArrayList urls = new ArrayList();
- StringTokenizer tokenizer = new StringTokenizer(classPath,
- File.pathSeparator);
- while (tokenizer.hasMoreTokens()) {
- String path = tokenizer.nextToken();
- try {
- File libFile = new File(path);
- urls.add(libFile.toURL());
- } catch (IOException ioe) {
- // Failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak uot
- throw new RuntimeException(ioe.toString());
- }
- }
-
- File webappBase = new File(uriRoot);
- if (webappBase.exists()) {
- File classes = new File(webappBase, "/WEB-INF/classes");
- try {
- if (classes.exists()) {
- classPath = classPath + File.pathSeparator
- + classes.getCanonicalPath();
- urls.add(classes.getCanonicalFile().toURL());
- }
- } catch (IOException ioe) {
- // failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak out
- throw new RuntimeException(ioe.toString());
- }
- File lib = new File(webappBase, "/WEB-INF/lib");
- if (lib.exists() && lib.isDirectory()) {
- String[] libs = lib.list();
- for (int i = 0; i < libs.length; i++) {
- if( libs[i].length() <5 ) continue;
- String ext=libs[i].substring( libs[i].length() - 4 );
- if (! ".jar".equalsIgnoreCase(ext)) {
- if (".tld".equalsIgnoreCase(ext)) {
- log.warn("TLD files should not be placed in "
- + "/WEB-INF/lib");
- }
- continue;
- }
- try {
- File libFile = new File(lib, libs[i]);
- classPath = classPath + File.pathSeparator
- + libFile.getAbsolutePath();
- urls.add(libFile.getAbsoluteFile().toURL());
- } catch (IOException ioe) {
- // failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak out
- throw new RuntimeException(ioe.toString());
- }
- }
- }
- }
-
- // What is this ??
- urls.add(new File(clctxt.getRealPath("/")).getCanonicalFile().toURL());
-
- URL urlsA[]=new URL[urls.size()];
- urls.toArray(urlsA);
- loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());
-
- }
-
- /**
- * Find the WEB-INF dir by looking up in the directory tree.
- * This is used if no explicit docbase is set, but only files.
- * XXX Maybe we should require the docbase.
- */
- protected void locateUriRoot( File f ) {
- String tUriBase = uriBase;
- if (tUriBase == null) {
- tUriBase = "/";
- }
- try {
- if (f.exists()) {
- f = new File(f.getAbsolutePath());
- while (f != null) {
- File g = new File(f, "WEB-INF");
- if (g.exists() && g.isDirectory()) {
- uriRoot = f.getCanonicalPath();
- uriBase = tUriBase;
- if (log.isInfoEnabled()) {
- log.info(Localizer.getMessage(
- "jspc.implicit.uriRoot",
- uriRoot));
- }
- break;
- }
- if (f.exists() && f.isDirectory()) {
- tUriBase = "/" + f.getName() + "/" + tUriBase;
- }
-
- String fParent = f.getParent();
- if (fParent == null) {
- break;
- } else {
- f = new File(fParent);
- }
-
- // If there is no acceptible candidate, uriRoot will
- // remain null to indicate to the CompilerContext to
- // use the current working/user dir.
- }
-
- if (uriRoot != null) {
- File froot = new File(uriRoot);
- uriRoot = froot.getCanonicalPath();
- }
- }
- } catch (IOException ioe) {
- // since this is an optional default and a null value
- // for uriRoot has a non-error meaning, we can just
- // pass straight through
- }
- }
-
- /**
- * Resolves the relative or absolute pathname correctly
- * in both Ant and command-line situations. If Ant launched
- * us, we should use the basedir of the current project
- * to resolve relative paths.
- *
- * See Bugzilla 35571.
- *
- * @param s The file
- * @return The file resolved
- */
- protected File resolveFile(final String s) {
- return new File(s);
- }
-
- private Reader openWebxmlReader(File file) throws IOException {
- FileInputStream fis = new FileInputStream(file);
- try {
- return webxmlEncoding != null ? new InputStreamReader(fis,
- webxmlEncoding) : new InputStreamReader(fis);
- } catch (IOException ex) {
- fis.close();
- throw ex;
- }
- }
-
- private Writer openWebxmlWriter(File file) throws IOException {
- FileOutputStream fos = new FileOutputStream(file);
- try {
- return webxmlEncoding != null ? new OutputStreamWriter(fos,
- webxmlEncoding) : new OutputStreamWriter(fos);
- } catch (IOException ex) {
- fos.close();
- throw ex;
- }
- }
-}
diff --git a/1.x/src/jasper6/JspCompilationContext.java b/1.x/src/jasper6/JspCompilationContext.java
deleted file mode 100644
index 1d78239..0000000
--- a/1.x/src/jasper6/JspCompilationContext.java
+++ /dev/null
@@ -1,703 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import javax.servlet.ServletContext;
-import javax.servlet.jsp.tagext.TagInfo;
-
-import org.apache.jasper.compiler.Compiler;
-import org.apache.jasper.compiler.JspRuntimeContext;
-import org.apache.jasper.compiler.JspUtil;
-import org.apache.jasper.compiler.Localizer;
-import org.apache.jasper.compiler.ServletWriter;
-import org.apache.jasper.servlet.JasperLoader;
-import org.apache.jasper.servlet.JspServletWrapper;
-
-/**
- * A place holder for various things that are used through out the JSP
- * engine. This is a per-request/per-context data structure. Some of
- * the instance variables are set at different points.
- *
- * Most of the path-related stuff is here - mangling names, versions, dirs,
- * loading resources and dealing with uris.
- *
- * @author Anil K. Vijendran
- * @author Harish Prabandham
- * @author Pierre Delisle
- * @author Costin Manolache
- * @author Kin-man Chung
- */
-public class JspCompilationContext {
-
- protected org.apache.juli.logging.Log log =
- org.apache.juli.logging.LogFactory.getLog(JspCompilationContext.class);
-
- protected Map tagFileJarUrls;
- protected boolean isPackagedTagFile;
-
- protected String className;
- protected String jspUri;
- protected boolean isErrPage;
- protected String basePackageName;
- protected String derivedPackageName;
- protected String servletJavaFileName;
- protected String javaPath;
- protected String classFileName;
- protected String contentType;
- protected ServletWriter writer;
- protected Options options;
- protected JspServletWrapper jsw;
- protected Compiler jspCompiler;
- protected String classPath;
-
- protected String baseURI;
- protected String outputDir;
- protected ServletContext context;
- protected URLClassLoader loader;
-
- protected JspRuntimeContext rctxt;
-
- protected int removed = 0;
-
- protected URLClassLoader jspLoader;
- protected URL baseUrl;
- protected Class servletClass;
-
- protected boolean isTagFile;
- protected boolean protoTypeMode;
- protected TagInfo tagInfo;
- protected URL tagFileJarUrl;
-
- // jspURI _must_ be relative to the context
- public JspCompilationContext(String jspUri,
- boolean isErrPage,
- Options options,
- ServletContext context,
- JspServletWrapper jsw,
- JspRuntimeContext rctxt) {
-
- this.jspUri = canonicalURI(jspUri);
- this.isErrPage = isErrPage;
- this.options = options;
- this.jsw = jsw;
- this.context = context;
-
- this.baseURI = jspUri.substring(0, jspUri.lastIndexOf('/') + 1);
- // hack fix for resolveRelativeURI
- if (baseURI == null) {
- baseURI = "/";
- } else if (baseURI.charAt(0) != '/') {
- // strip the basde slash since it will be combined with the
- // uriBase to generate a file
- baseURI = "/" + baseURI;
- }
- if (baseURI.charAt(baseURI.length() - 1) != '/') {
- baseURI += '/';
- }
-
- this.rctxt = rctxt;
- this.tagFileJarUrls = new HashMap();
- this.basePackageName = Constants.JSP_PACKAGE_NAME;
- }
-
- public JspCompilationContext(String tagfile,
- TagInfo tagInfo,
- Options options,
- ServletContext context,
- JspServletWrapper jsw,
- JspRuntimeContext rctxt,
- URL tagFileJarUrl) {
- this(tagfile, false, options, context, jsw, rctxt);
- this.isTagFile = true;
- this.tagInfo = tagInfo;
- this.tagFileJarUrl = tagFileJarUrl;
- if (tagFileJarUrl != null) {
- isPackagedTagFile = true;
- }
- }
-
- /* ==================== Methods to override ==================== */
-
- /** ---------- Class path and loader ---------- */
-
- /**
- * The classpath that is passed off to the Java compiler.
- */
- public String getClassPath() {
- if( classPath != null )
- return classPath;
- return rctxt.getClassPath();
- }
-
- /**
- * The classpath that is passed off to the Java compiler.
- */
- public void setClassPath(String classPath) {
- this.classPath = classPath;
- }
-
- /**
- * What class loader to use for loading classes while compiling
- * this JSP?
- */
- public ClassLoader getClassLoader() {
- if( loader != null )
- return loader;
- return rctxt.getParentClassLoader();
- }
-
- public void setClassLoader(URLClassLoader loader) {
- this.loader = loader;
- }
-
- public ClassLoader getJspLoader() {
- if( jspLoader == null ) {
- jspLoader = new JasperLoader
- (new URL[] {baseUrl},
- getClassLoader(),
- rctxt.getPermissionCollection(),
- rctxt.getCodeSource());
- }
- return jspLoader;
- }
-
- /** ---------- Input/Output ---------- */
-
- /**
- * The output directory to generate code into. The output directory
- * is make up of the scratch directory, which is provide in Options,
- * plus the directory derived from the package name.
- */
- public String getOutputDir() {
- if (outputDir == null) {
- createOutputDir();
- }
-
- return outputDir;
- }
-
- /**
- * Create a "Compiler" object based on some init param data. This
- * is not done yet. Right now we're just hardcoding the actual
- * compilers that are created.
- */
- public Compiler createCompiler() throws JasperException {
- if (jspCompiler != null ) {
- return jspCompiler;
- }
- jspCompiler = createCompiler("org.apache.jasper.compiler.BeeCompiler");
- if (jspCompiler == null) {
- throw new IllegalStateException(Localizer.getMessage("jsp.error.compiler"));
- }
- jspCompiler.init(this, jsw);
- return jspCompiler;
- }
-
- protected Compiler createCompiler(String className) {
- Compiler compiler = null;
- try {
- compiler = (Compiler) Class.forName(className).newInstance();
- } catch (InstantiationException e) {
- log.warn(Localizer.getMessage("jsp.error.compiler"), e);
- } catch (IllegalAccessException e) {
- log.warn(Localizer.getMessage("jsp.error.compiler"), e);
- } catch (NoClassDefFoundError e) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage("jsp.error.compiler"), e);
- }
- } catch (ClassNotFoundException e) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage("jsp.error.compiler"), e);
- }
- }
- return compiler;
- }
-
- public Compiler getCompiler() {
- return jspCompiler;
- }
-
- /** ---------- Access resources in the webapp ---------- */
-
- /**
- * Get the full value of a URI relative to this compilations context
- * uses current file as the base.
- */
- public String resolveRelativeUri(String uri) {
- // sometimes we get uri's massaged from File(String), so check for
- // a root directory deperator char
- if (uri.startsWith("/") || uri.startsWith(File.separator)) {
- return uri;
- } else {
- return baseURI + uri;
- }
- }
-
- /**
- * Gets a resource as a stream, relative to the meanings of this
- * context's implementation.
- * @return a null if the resource cannot be found or represented
- * as an InputStream.
- */
- public java.io.InputStream getResourceAsStream(String res) {
- return context.getResourceAsStream(canonicalURI(res));
- }
-
-
- public URL getResource(String res) throws MalformedURLException {
- return context.getResource(canonicalURI(res));
- }
-
- public Set getResourcePaths(String path) {
- return context.getResourcePaths(canonicalURI(path));
- }
-
- /**
- * Gets the actual path of a URI relative to the context of
- * the compilation.
- */
- public String getRealPath(String path) {
- if (context != null) {
- return context.getRealPath(path);
- }
- return path;
- }
-
- /**
- * Returns the tag-file-name-to-JAR-file map of this compilation unit,
- * which maps tag file names to the JAR files in which the tag files are
- * packaged.
- *
- * The map is populated when parsing the tag-file elements of the TLDs
- * of any imported taglibs.
- */
- public URL getTagFileJarUrl(String tagFile) {
- return this.tagFileJarUrls.get(tagFile);
- }
-
- public void setTagFileJarUrl(String tagFile, URL tagFileURL) {
- this.tagFileJarUrls.put(tagFile, tagFileURL);
- }
-
- /**
- * Returns the JAR file in which the tag file for which this
- * JspCompilationContext was created is packaged, or null if this
- * JspCompilationContext does not correspond to a tag file, or if the
- * corresponding tag file is not packaged in a JAR.
- */
- public URL getTagFileJarUrl() {
- return this.tagFileJarUrl;
- }
-
- /* ==================== Common implementation ==================== */
-
- /**
- * Just the class name (does not include package name) of the
- * generated class.
- */
- public String getServletClassName() {
-
- if (className != null) {
- return className;
- }
-
- if (isTagFile) {
- className = tagInfo.getTagClassName();
- int lastIndex = className.lastIndexOf('.');
- if (lastIndex != -1) {
- className = className.substring(lastIndex + 1);
- }
- } else {
- int iSep = jspUri.lastIndexOf('/') + 1;
- className = JspUtil.makeJavaIdentifier(jspUri.substring(iSep));
- }
- return className;
- }
-
- public void setServletClassName(String className) {
- this.className = className;
- }
-
- /**
- * Path of the JSP URI. Note that this is not a file name. This is
- * the context rooted URI of the JSP file.
- */
- public String getJspFile() {
- return jspUri;
- }
-
- /**
- * Are we processing something that has been declared as an
- * errorpage?
- */
- public boolean isErrorPage() {
- return isErrPage;
- }
-
- public void setErrorPage(boolean isErrPage) {
- this.isErrPage = isErrPage;
- }
-
- public boolean isTagFile() {
- return isTagFile;
- }
-
- public TagInfo getTagInfo() {
- return tagInfo;
- }
-
- public void setTagInfo(TagInfo tagi) {
- tagInfo = tagi;
- }
-
- /**
- * True if we are compiling a tag file in prototype mode.
- * ie we only generate codes with class for the tag handler with empty
- * method bodies.
- */
- public boolean isPrototypeMode() {
- return protoTypeMode;
- }
-
- public void setPrototypeMode(boolean pm) {
- protoTypeMode = pm;
- }
-
- /**
- * Package name for the generated class is make up of the base package
- * name, which is user settable, and the derived package name. The
- * derived package name directly mirrors the file heirachy of the JSP page.
- */
- public String getServletPackageName() {
- if (isTagFile()) {
- String className = tagInfo.getTagClassName();
- int lastIndex = className.lastIndexOf('.');
- String pkgName = "";
- if (lastIndex != -1) {
- pkgName = className.substring(0, lastIndex);
- }
- return pkgName;
- } else {
- String dPackageName = getDerivedPackageName();
- if (dPackageName.length() == 0) {
- return basePackageName;
- }
- return basePackageName + '.' + getDerivedPackageName();
- }
- }
-
- protected String getDerivedPackageName() {
- if (derivedPackageName == null) {
- int iSep = jspUri.lastIndexOf('/');
- derivedPackageName = (iSep > 0) ?
- JspUtil.makeJavaPackage(jspUri.substring(1,iSep)) : "";
- }
- return derivedPackageName;
- }
-
- /**
- * The package name into which the servlet class is generated.
- */
- public void setServletPackageName(String servletPackageName) {
- this.basePackageName = servletPackageName;
- }
-
- /**
- * Full path name of the Java file into which the servlet is being
- * generated.
- */
- public String getServletJavaFileName() {
- if (servletJavaFileName == null) {
- servletJavaFileName = getOutputDir() + getServletClassName() + ".java";
- }
- return servletJavaFileName;
- }
-
- /**
- * Get hold of the Options object for this context.
- */
- public Options getOptions() {
- return options;
- }
-
- public ServletContext getServletContext() {
- return context;
- }
-
- public JspRuntimeContext getRuntimeContext() {
- return rctxt;
- }
-
- /**
- * Path of the Java file relative to the work directory.
- */
- public String getJavaPath() {
-
- if (javaPath != null) {
- return javaPath;
- }
-
- if (isTagFile()) {
- String tagName = tagInfo.getTagClassName();
- javaPath = tagName.replace('.', '/') + ".java";
- } else {
- javaPath = getServletPackageName().replace('.', '/') + '/' +
- getServletClassName() + ".java";
- }
- return javaPath;
- }
-
- public String getClassFileName() {
- if (classFileName == null) {
- classFileName = getOutputDir() + getServletClassName() + ".class";
- }
- return classFileName;
- }
-
- /**
- * Get the content type of this JSP.
- *
- * Content type includes content type and encoding.
- */
- public String getContentType() {
- return contentType;
- }
-
- public void setContentType(String contentType) {
- this.contentType = contentType;
- }
-
- /**
- * Where is the servlet being generated?
- */
- public ServletWriter getWriter() {
- return writer;
- }
-
- public void setWriter(ServletWriter writer) {
- this.writer = writer;
- }
-
- /**
- * Gets the 'location' of the TLD associated with the given taglib 'uri'.
- *
- * @return An array of two Strings: The first element denotes the real
- * 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.
- * Returns null if the given uri is not associated with any tag library
- * 'exposed' in the web application.
- */
- public String[] getTldLocation(String uri) throws JasperException {
- String[] location =
- getOptions().getTldLocationsCache().getLocation(uri);
- return location;
- }
-
- /**
- * Are we keeping generated code around?
- */
- public boolean keepGenerated() {
- return getOptions().getKeepGenerated();
- }
-
- // ==================== Removal ====================
-
- public void incrementRemoved() {
- if (removed == 0 && rctxt != null) {
- rctxt.removeWrapper(jspUri);
- }
- removed++;
- }
-
- public boolean isRemoved() {
- if (removed > 1 ) {
- return true;
- }
- return false;
- }
-
- // ==================== Compile and reload ====================
-
- public void compile() throws JasperException, FileNotFoundException {
- createCompiler();
- if (isPackagedTagFile || jspCompiler.isOutDated()) {
- try {
- jspCompiler.removeGeneratedFiles();
- jspLoader = null;
- jspCompiler.compile();
- jsw.setReload(true);
- jsw.setCompilationException(null);
- } catch (JasperException ex) {
- // Cache compilation exception
- jsw.setCompilationException(ex);
- throw ex;
- } catch (Exception ex) {
- JasperException je = new JasperException(
- Localizer.getMessage("jsp.error.unable.compile"),
- ex);
- // Cache compilation exception
- jsw.setCompilationException(je);
- throw je;
- }
- }
- }
-
- // ==================== Manipulating the class ====================
-
- public Class load()
- throws JasperException, FileNotFoundException
- {
- try {
- getJspLoader();
-
- String name;
- if (isTagFile()) {
- name = tagInfo.getTagClassName();
- } else {
- name = getServletPackageName() + "." + getServletClassName();
- }
- servletClass = jspLoader.loadClass(name);
- } catch (ClassNotFoundException cex) {
- throw new JasperException(Localizer.getMessage("jsp.error.unable.load"),
- cex);
- } catch (Exception ex) {
- throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"),
- ex);
- }
- removed = 0;
- return servletClass;
- }
-
- // ==================== protected methods ====================
-
- static Object outputDirLock = new Object();
-
- public void checkOutputDir() {
- if (outputDir != null) {
- if (!(new File(outputDir)).exists()) {
- makeOutputDir();
- }
- } else {
- createOutputDir();
- }
- }
-
- protected boolean makeOutputDir() {
- synchronized(outputDirLock) {
- File outDirFile = new File(outputDir);
- return (outDirFile.exists() || outDirFile.mkdirs());
- }
- }
-
- protected void createOutputDir() {
- String path = null;
- if (isTagFile()) {
- String tagName = tagInfo.getTagClassName();
- path = tagName.replace('.', '/');
- path = path.substring(0, path.lastIndexOf('/'));
- } else {
- path = getServletPackageName().replace('.', '/');
- }
-
- // Append servlet or tag handler path to scratch dir
- try {
- baseUrl = options.getScratchDir().toURL();
- String outUrlString = baseUrl.toString() + '/' + path;
- URL outUrl = new URL(outUrlString);
- outputDir = outUrl.getFile() + File.separator;
- if (!makeOutputDir()) {
- throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"));
- }
- } catch (MalformedURLException e) {
- throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e);
- }
- }
-
- protected static final boolean isPathSeparator(char c) {
- return (c == '/' || c == '\\');
- }
-
- protected static final String canonicalURI(String s) {
- if (s == null) return null;
- StringBuffer result = new StringBuffer();
- final int len = s.length();
- int pos = 0;
- while (pos < len) {
- char c = s.charAt(pos);
- if ( isPathSeparator(c) ) {
- /*
- * multiple path separators.
- * 'foo///bar' -> 'foo/bar'
- */
- while (pos+1 < len && isPathSeparator(s.charAt(pos+1))) {
- ++pos;
- }
-
- if (pos+1 < len && s.charAt(pos+1) == '.') {
- /*
- * a single dot at the end of the path - we are done.
- */
- if (pos+2 >= len) break;
-
- switch (s.charAt(pos+2)) {
- /*
- * self directory in path
- * foo/./bar -> foo/bar
- */
- case '/':
- case '\\':
- pos += 2;
- continue;
-
- /*
- * two dots in a path: go back one hierarchy.
- * foo/bar/../baz -> foo/baz
- */
- case '.':
- // only if we have exactly _two_ dots.
- if (pos+3 < len && isPathSeparator(s.charAt(pos+3))) {
- pos += 3;
- int separatorPos = result.length()-1;
- while (separatorPos >= 0 &&
- ! isPathSeparator(result
- .charAt(separatorPos))) {
- --separatorPos;
- }
- if (separatorPos >= 0)
- result.setLength(separatorPos);
- continue;
- }
- }
- }
- }
- result.append(c);
- ++pos;
- }
- return result.toString();
- }
-}
-
diff --git a/1.x/src/jasper6/bee-jasper.xml b/1.x/src/jasper6/bee-jasper.xml
deleted file mode 100644
index 86f0bbd..0000000
--- a/1.x/src/jasper6/bee-jasper.xml
+++ /dev/null
@@ -1,405 +0,0 @@
-
-
-
-
-
-
-
-
-
-
- ]>
-
-
-
- &env;
-
-
-
-
- /bin/javac
-
-
-
-
-
-
- /bin/javadoc
-
-
-
-
-
- ******** &project; Build Process ********
-********* Available targets: *************************************
-* compile - do Java compilation *
-* jar - build &build_file; file *
-* run - run application &main_class; *
-*******************************************************************
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- /&build_directory;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Compiling javax...
-
-
-
-
-
-
-
-
-
- >
-
-
-
- 0
-
-
- Error(s) at compilation of javax
-
-
-
-
-
-
-
-
- Exception at compilation of javax
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Compiling... &project;
-
-
-
-
-
-
-
-
-
- >
-
-
-
- 0
-
-
- Error(s) at compilation of &project;
-
-
-
-
-
-
-
-
- Exception at compilation of &project;
-
-
-
-
-
-
-
-
-
- &manifestf;
-
-
-
-
- true
-
-
-
- -d
-
- -sourcepath
-
- -classpath
-
- &domain;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- &source_directory;/javax/servlet/jsp/resources/jsp*.dtd
- &build_directory;/javax/servlet/jsp/resources
- &source_directory;/javax/servlet/jsp/resources/jsp*.xsd
- &build_directory;/javax/servlet/jsp/resources
- &source_directory;/javax/servlet/jsp/resources/web-jsp*.dtd
- &build_directory;/javax/servlet/jsp/resources
- &source_directory;/javax/servlet/jsp/resources/web-jsp*.xsd
- &build_directory;/javax/servlet/jsp/resources
-
- &source_directory;/javax/servlet/resources/j2ee*.dtd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/j2ee*.xsd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/web-app*.dtd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/web-app*.xsd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/datatypes.dtd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/xml.xsd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/XMLSchema.dtd
- &build_directory;/javax/servlet/resources
-
-
-
-
-
-
-
-
-
-
-
-
- Jarring...
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -cf
-
-
-
- -cmf
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- java
- org/apache/jasper/resources
-
-
-
-
-
-
- -C
- &source_directory;
-
-
-
-
-
-
-
-
-
-
-
- -C
- &source_directory;
-
-
-
-
-
-
-
-
-
-
-
- -C
- &source_directory;
-
-
-
-
-
-
-
- Exception at jarring
-
-
-
-
-
-
-
-
-
-
-
-
- y
-
-
-
-
-
-
-
-
- Cleaning...
-
-
-
-
-
-
-
-
-
-
- /&build_directory;/&build_file;
-
-
-
-
- /lib/tools.jar
-
-
-
-
- Running...
-
-
-
- -classpath
-
-
-
-
-
-
diff --git a/1.x/src/jasper6/env.xml b/1.x/src/jasper6/env.xml
deleted file mode 100644
index f3eef26..0000000
--- a/1.x/src/jasper6/env.xml
+++ /dev/null
@@ -1,49 +0,0 @@
-
-
-
-
- .
-
-
-
-
-
-
- /
-
-
-
-
-
-
-
-
- /jre
-
-
-
-
-
-
-
-
-
-
- /home/dmitriy/libs/javax.
-
- 1.5
-
-
-
- \\jre
-
-
-
-
-
-
-
- servlet.jar
-
-
diff --git a/1.x/src/jasper7-6x/EmbeddedServletOptions.java b/1.x/src/jasper7-6x/EmbeddedServletOptions.java
deleted file mode 100644
index f381c80..0000000
--- a/1.x/src/jasper7-6x/EmbeddedServletOptions.java
+++ /dev/null
@@ -1,758 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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;
-
-import java.io.File;
-import java.util.Enumeration;
-import java.util.Map;
-import java.util.Properties;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.jsp.tagext.TagLibraryInfo;
-
-import org.apache.jasper.compiler.JspConfig;
-import org.apache.jasper.compiler.Localizer;
-import org.apache.jasper.compiler.TagPluginManager;
-import org.apache.jasper.compiler.TldLocationsCache;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-
-/**
- * A class to hold all init parameters specific to the JSP engine.
- *
- * @author Anil K. Vijendran
- * @author Hans Bergsten
- * @author Pierre Delisle
- */
-public final class EmbeddedServletOptions implements Options {
-
- // Logger
- private final Log log = LogFactory.getLog(EmbeddedServletOptions.class);
-
- private Properties settings = new Properties();
-
- /**
- * Is Jasper being used in development mode?
- */
- private boolean development = true;
-
- /**
- * Should Ant fork its java compiles of JSP pages.
- */
- public boolean fork = true;
-
- /**
- * Do you want to keep the generated Java files around?
- */
- private boolean keepGenerated = true;
-
- /**
- * Should white spaces between directives or actions be trimmed?
- */
- private boolean trimSpaces = false;
-
- /**
- * Determines whether tag handler pooling is enabled.
- */
- private boolean isPoolingEnabled = true;
-
- /**
- * Do you want support for "mapped" files? This will generate
- * servlet that has a print statement per line of the JSP file.
- * This seems like a really nice feature to have for debugging.
- */
- private boolean mappedFile = true;
-
- /**
- * Do we want to include debugging information in the class file?
- */
- private boolean classDebugInfo = true;
-
- /**
- * Background compile thread check interval in seconds.
- */
- private int checkInterval = 0;
-
- /**
- * Is the generation of SMAP info for JSR45 debugging suppressed?
- */
- private boolean isSmapSuppressed = false;
-
- /**
- * Should SMAP info for JSR45 debugging be dumped to a file?
- */
- private boolean isSmapDumped = false;
-
- /**
- * Are Text strings to be generated as char arrays?
- */
- private boolean genStringAsCharArray = false;
-
- private boolean errorOnUseBeanInvalidClassAttribute = true;
-
- /**
- * I want to see my generated servlets. Which directory are they
- * in?
- */
- private File scratchDir;
-
- /**
- * Need to have this as is for versions 4 and 5 of IE. Can be set from
- * the initParams so if it changes in the future all that is needed is
- * to have a jsp initParam of type ieClassId=""
- */
- private String ieClassId = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";
-
- /**
- * What classpath should I use while compiling generated servlets?
- */
- private String classpath = null;
-
- /**
- * Compiler to use.
- */
- private String compiler = null;
-
- /**
- * Compiler target VM.
- */
- private String compilerTargetVM = "1.6";
-
- /**
- * The compiler source VM.
- */
- private String compilerSourceVM = "1.6";
-
- /**
- * The compiler class name.
- */
- private String compilerClassName = null;
-
- /**
- * Cache for the TLD locations
- */
- private TldLocationsCache tldLocationsCache = null;
-
- /**
- * Jsp config information
- */
- private JspConfig jspConfig = null;
-
- /**
- * TagPluginManager
- */
- private TagPluginManager tagPluginManager = null;
-
- /**
- * Java platform encoding to generate the JSP
- * page servlet.
- */
- private String javaEncoding = "UTF8";
-
- /**
- * Modification test interval.
- */
- private int modificationTestInterval = 4;
-
- /**
- * Is re-compilation attempted immediately after a failure?
- */
- private boolean recompileOnFail = false;
-
- /**
- * Is generation of X-Powered-By response header enabled/disabled?
- */
- private boolean xpoweredBy;
-
- /**
- * Should we include a source fragment in exception messages, which could be displayed
- * to the developer ?
- */
- private boolean displaySourceFragment = true;
-
-
- /**
- * The maximum number of loaded jsps per web-application. If there are more
- * jsps loaded, they will be unloaded.
- */
- private int maxLoadedJsps = -1;
-
- /**
- * The idle time in seconds after which a JSP is unloaded.
- * If unset or less or equal than 0, no jsps are unloaded.
- */
- private int jspIdleTimeout = -1;
-
- public String getProperty(String name ) {
- return settings.getProperty( name );
- }
-
- public void setProperty(String name, String value ) {
- if (name != null && value != null){
- settings.setProperty( name, value );
- }
- }
-
- /**
- * Are we keeping generated code around?
- */
- @Override
- public boolean getKeepGenerated() {
- return keepGenerated;
- }
-
- /**
- * Should white spaces between directives or actions be trimmed?
- */
- @Override
- public boolean getTrimSpaces() {
- return trimSpaces;
- }
-
- @Override
- public boolean isPoolingEnabled() {
- return isPoolingEnabled;
- }
-
- /**
- * Are we supporting HTML mapped servlets?
- */
- @Override
- public boolean getMappedFile() {
- return mappedFile;
- }
-
- /**
- * Should class files be compiled with debug information?
- */
- @Override
- public boolean getClassDebugInfo() {
- return classDebugInfo;
- }
-
- /**
- * Background JSP compile thread check interval
- */
- @Override
- public int getCheckInterval() {
- return checkInterval;
- }
-
- /**
- * Modification test interval.
- */
- @Override
- public int getModificationTestInterval() {
- return modificationTestInterval;
- }
-
- /**
- * Re-compile on failure.
- */
- @Override
- public boolean getRecompileOnFail() {
- return recompileOnFail;
- }
-
- /**
- * Is Jasper being used in development mode?
- */
- @Override
- public boolean getDevelopment() {
- return development;
- }
-
- /**
- * Is the generation of SMAP info for JSR45 debugging suppressed?
- */
- @Override
- public boolean isSmapSuppressed() {
- return isSmapSuppressed;
- }
-
- /**
- * Should SMAP info for JSR45 debugging be dumped to a file?
- */
- @Override
- public boolean isSmapDumped() {
- return isSmapDumped;
- }
-
- /**
- * Are Text strings to be generated as char arrays?
- */
- @Override
- public boolean genStringAsCharArray() {
- return this.genStringAsCharArray;
- }
-
- /**
- * Class ID for use in the plugin tag when the browser is IE.
- */
- @Override
- public String getIeClassId() {
- return ieClassId;
- }
-
- /**
- * What is my scratch dir?
- */
- @Override
- public File getScratchDir() {
- return scratchDir;
- }
-
- /**
- * What classpath should I use while compiling the servlets
- * generated from JSP files?
- */
- @Override
- public String getClassPath() {
- return classpath;
- }
-
- /**
- * Is generation of X-Powered-By response header enabled/disabled?
- */
- @Override
- public boolean isXpoweredBy() {
- return xpoweredBy;
- }
-
- /**
- * Compiler to use.
- */
- @Override
- public String getCompiler() {
- return compiler;
- }
-
- /**
- * @see Options#getCompilerTargetVM
- */
- @Override
- public String getCompilerTargetVM() {
- return compilerTargetVM;
- }
-
- /**
- * @see Options#getCompilerSourceVM
- */
- @Override
- public String getCompilerSourceVM() {
- return compilerSourceVM;
- }
-
- /**
- * Java compiler class to use.
- */
- @Override
- public String getCompilerClassName() {
- return compilerClassName;
- }
-
- @Override
- public boolean getErrorOnUseBeanInvalidClassAttribute() {
- return errorOnUseBeanInvalidClassAttribute;
- }
-
- public void setErrorOnUseBeanInvalidClassAttribute(boolean b) {
- errorOnUseBeanInvalidClassAttribute = b;
- }
-
- @Override
- public TldLocationsCache getTldLocationsCache() {
- return tldLocationsCache;
- }
-
- public void setTldLocationsCache( TldLocationsCache tldC ) {
- tldLocationsCache = tldC;
- }
-
- @Override
- public String getJavaEncoding() {
- return javaEncoding;
- }
-
- @Override
- public boolean getFork() {
- return fork;
- }
-
- @Override
- public JspConfig getJspConfig() {
- return jspConfig;
- }
-
- @Override
- public TagPluginManager getTagPluginManager() {
- return tagPluginManager;
- }
-
- @Override
- public boolean isCaching() {
- return false;
- }
-
- @Override
- public Map getCache() {
- return null;
- }
-
- /**
- * Should we include a source fragment in exception messages, which could be displayed
- * to the developer ?
- */
- @Override
- public boolean getDisplaySourceFragment() {
- return displaySourceFragment;
- }
-
- /**
- * Should jsps be unloaded if to many are loaded?
- * If set to a value greater than 0 eviction of jsps is started. Default: -1
- */
- @Override
- public int getMaxLoadedJsps() {
- return maxLoadedJsps;
- }
-
- /**
- * Should any jsps be unloaded when being idle for this time in seconds?
- * If set to a value greater than 0 eviction of jsps is started. Default: -1
- */
- @Override
- public int getJspIdleTimeout() {
- return jspIdleTimeout;
- }
-
- /**
- * Create an EmbeddedServletOptions object using data available from
- * ServletConfig and ServletContext.
- */
- public EmbeddedServletOptions(ServletConfig config,
- ServletContext context) {
-
- Enumeration enumeration=config.getInitParameterNames();
- while( enumeration.hasMoreElements() ) {
- String k=enumeration.nextElement();
- String v=config.getInitParameter( k );
- setProperty( k, v);
- }
-
- String keepgen = config.getInitParameter("keepgenerated");
- if (keepgen != null) {
- if (keepgen.equalsIgnoreCase("true")) {
- this.keepGenerated = true;
- } else if (keepgen.equalsIgnoreCase("false")) {
- this.keepGenerated = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.keepgen"));
- }
- }
- }
-
-
- String trimsp = config.getInitParameter("trimSpaces");
- if (trimsp != null) {
- if (trimsp.equalsIgnoreCase("true")) {
- trimSpaces = true;
- } else if (trimsp.equalsIgnoreCase("false")) {
- trimSpaces = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.trimspaces"));
- }
- }
- }
-
- this.isPoolingEnabled = true;
- String poolingEnabledParam
- = config.getInitParameter("enablePooling");
- if (poolingEnabledParam != null
- && !poolingEnabledParam.equalsIgnoreCase("true")) {
- if (poolingEnabledParam.equalsIgnoreCase("false")) {
- this.isPoolingEnabled = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.enablePooling"));
- }
- }
- }
-
- String mapFile = config.getInitParameter("mappedfile");
- if (mapFile != null) {
- if (mapFile.equalsIgnoreCase("true")) {
- this.mappedFile = true;
- } else if (mapFile.equalsIgnoreCase("false")) {
- this.mappedFile = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.mappedFile"));
- }
- }
- }
-
- String debugInfo = config.getInitParameter("classdebuginfo");
- if (debugInfo != null) {
- if (debugInfo.equalsIgnoreCase("true")) {
- this.classDebugInfo = true;
- } else if (debugInfo.equalsIgnoreCase("false")) {
- this.classDebugInfo = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.classDebugInfo"));
- }
- }
- }
-
- String checkInterval = config.getInitParameter("checkInterval");
- if (checkInterval != null) {
- try {
- this.checkInterval = Integer.parseInt(checkInterval);
- } catch(NumberFormatException ex) {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.checkInterval"));
- }
- }
- }
-
- String modificationTestInterval = config.getInitParameter("modificationTestInterval");
- if (modificationTestInterval != null) {
- try {
- this.modificationTestInterval = Integer.parseInt(modificationTestInterval);
- } catch(NumberFormatException ex) {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval"));
- }
- }
- }
-
- String recompileOnFail = config.getInitParameter("recompileOnFail");
- if (recompileOnFail != null) {
- if (recompileOnFail.equalsIgnoreCase("true")) {
- this.recompileOnFail = true;
- } else if (recompileOnFail.equalsIgnoreCase("false")) {
- this.recompileOnFail = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.recompileOnFail"));
- }
- }
- }
- String development = config.getInitParameter("development");
- if (development != null) {
- if (development.equalsIgnoreCase("true")) {
- this.development = true;
- } else if (development.equalsIgnoreCase("false")) {
- this.development = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.development"));
- }
- }
- }
-
- String suppressSmap = config.getInitParameter("suppressSmap");
- if (suppressSmap != null) {
- if (suppressSmap.equalsIgnoreCase("true")) {
- isSmapSuppressed = true;
- } else if (suppressSmap.equalsIgnoreCase("false")) {
- isSmapSuppressed = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.suppressSmap"));
- }
- }
- }
-
- String dumpSmap = config.getInitParameter("dumpSmap");
- if (dumpSmap != null) {
- if (dumpSmap.equalsIgnoreCase("true")) {
- isSmapDumped = true;
- } else if (dumpSmap.equalsIgnoreCase("false")) {
- isSmapDumped = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.dumpSmap"));
- }
- }
- }
-
- String genCharArray = config.getInitParameter("genStringAsCharArray");
- if (genCharArray != null) {
- if (genCharArray.equalsIgnoreCase("true")) {
- genStringAsCharArray = true;
- } else if (genCharArray.equalsIgnoreCase("false")) {
- genStringAsCharArray = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.genchararray"));
- }
- }
- }
-
- String errBeanClass =
- config.getInitParameter("errorOnUseBeanInvalidClassAttribute");
- if (errBeanClass != null) {
- if (errBeanClass.equalsIgnoreCase("true")) {
- errorOnUseBeanInvalidClassAttribute = true;
- } else if (errBeanClass.equalsIgnoreCase("false")) {
- errorOnUseBeanInvalidClassAttribute = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.errBean"));
- }
- }
- }
-
- String ieClassId = config.getInitParameter("ieClassId");
- if (ieClassId != null)
- this.ieClassId = ieClassId;
-
- String classpath = config.getInitParameter("classpath");
- if (classpath != null)
- this.classpath = classpath;
-
- /*
- * scratchdir
- */
- String dir = config.getInitParameter("scratchdir");
- if (dir != null) {
- scratchDir = new File(dir);
- } else {
- // First try the Servlet 2.2 javax.servlet.context.tempdir property
- scratchDir = (File) context.getAttribute(ServletContext.TEMPDIR);
- if (scratchDir == null) {
- // Not running in a Servlet 2.2 container.
- // Try to get the JDK 1.2 java.io.tmpdir property
- dir = System.getProperty("java.io.tmpdir");
- if (dir != null)
- scratchDir = new File(dir);
- }
- }
- if (this.scratchDir == null) {
- log.fatal(Localizer.getMessage("jsp.error.no.scratch.dir"));
- return;
- }
-
- if (!scratchDir.exists())
- scratchDir.mkdirs();
- if (!(scratchDir.exists() && scratchDir.canRead() &&
- scratchDir.canWrite() && scratchDir.isDirectory()))
- log.fatal(Localizer.getMessage("jsp.error.bad.scratch.dir",
- scratchDir.getAbsolutePath()));
-
- this.compiler = config.getInitParameter("compiler");
-
- String compilerTargetVM = config.getInitParameter("compilerTargetVM");
- if(compilerTargetVM != null) {
- this.compilerTargetVM = compilerTargetVM;
- }
-
- String compilerSourceVM = config.getInitParameter("compilerSourceVM");
- if(compilerSourceVM != null) {
- this.compilerSourceVM = compilerSourceVM;
- }
-
- String javaEncoding = config.getInitParameter("javaEncoding");
- if (javaEncoding != null) {
- this.javaEncoding = javaEncoding;
- }
-
- String compilerClassName = config.getInitParameter("compilerClassName");
- if (compilerClassName != null) {
- this.compilerClassName = compilerClassName;
- }
-
- String fork = config.getInitParameter("fork");
- if (fork != null) {
- if (fork.equalsIgnoreCase("true")) {
- this.fork = true;
- } else if (fork.equalsIgnoreCase("false")) {
- this.fork = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.fork"));
- }
- }
- }
-
- String xpoweredBy = config.getInitParameter("xpoweredBy");
- if (xpoweredBy != null) {
- if (xpoweredBy.equalsIgnoreCase("true")) {
- this.xpoweredBy = true;
- } else if (xpoweredBy.equalsIgnoreCase("false")) {
- this.xpoweredBy = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.xpoweredBy"));
- }
- }
- }
-
- String displaySourceFragment = config.getInitParameter("displaySourceFragment");
- if (displaySourceFragment != null) {
- if (displaySourceFragment.equalsIgnoreCase("true")) {
- this.displaySourceFragment = true;
- } else if (displaySourceFragment.equalsIgnoreCase("false")) {
- this.displaySourceFragment = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.displaySourceFragment"));
- }
- }
- }
-
- String maxLoadedJsps = config.getInitParameter("maxLoadedJsps");
- if (maxLoadedJsps != null) {
- try {
- this.maxLoadedJsps = Integer.parseInt(maxLoadedJsps);
- } catch(NumberFormatException ex) {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps));
- }
- }
- }
-
- String jspIdleTimeout = config.getInitParameter("jspIdleTimeout");
- if (jspIdleTimeout != null) {
- try {
- this.jspIdleTimeout = Integer.parseInt(jspIdleTimeout);
- } catch(NumberFormatException ex) {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout));
- }
- }
- }
-
- // Setup the global Tag Libraries location cache for this
- // web-application.
- tldLocationsCache = TldLocationsCache.getInstance(context);
-
- // Setup the jsp config info for this web app.
- jspConfig = new JspConfig(context);
-
- // Create a Tag plugin instance
- tagPluginManager = new TagPluginManager(context);
- }
-
-}
-
diff --git a/1.x/src/jasper7-6x/JspC.java b/1.x/src/jasper7-6x/JspC.java
deleted file mode 100644
index 3f520a7..0000000
--- a/1.x/src/jasper7-6x/JspC.java
+++ /dev/null
@@ -1,1640 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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;
-
-import java.io.BufferedReader;
-import java.io.CharArrayWriter;
-import java.io.EOFException;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.io.Reader;
-import java.io.Writer;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.Stack;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
-import javax.servlet.jsp.tagext.TagLibraryInfo;
-
-import org.apache.jasper.compiler.Compiler;
-import org.apache.jasper.compiler.JspConfig;
-import org.apache.jasper.compiler.JspRuntimeContext;
-import org.apache.jasper.compiler.Localizer;
-import org.apache.jasper.compiler.TagPluginManager;
-import org.apache.jasper.compiler.TldLocationsCache;
-import org.apache.jasper.servlet.JspCServletContext;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-
-/**
- * Shell for the jspc compiler. Handles all options associated with the
- * command line and creates compilation contexts which it then compiles
- * according to the specified options.
- *
- * This version can process files from a _single_ webapp at once, i.e.
- * a single docbase can be specified.
- *
- * It can be used as an Ant task using:
- *
- * <taskdef classname="org.apache.jasper.JspC" name="jasper" >
- * <classpath>
- * <pathelement location="${java.home}/../lib/tools.jar"/>
- * <fileset dir="${ENV.CATALINA_HOME}/lib">
- * <include name="*.jar"/>
- * </fileset>
- * <path refid="myjars"/>
- * </classpath>
- * </taskdef>
- *
- * <jasper verbose="0"
- * package="my.package"
- * uriroot="${webapps.dir}/${webapp.name}"
- * webXmlFragment="${build.dir}/generated_web.xml"
- * outputDir="${webapp.dir}/${webapp.name}/WEB-INF/src/my/package" />
- *
- *
- * @author Danno Ferrin
- * @author Pierre Delisle
- * @author Costin Manolache
- * @author Yoav Shapira
- */
-public class JspC implements Options {
-
- public static final String DEFAULT_IE_CLASS_ID =
- "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";
-
- // Logger
- private static final Log log = LogFactory.getLog(JspC.class);
-
- protected static final String SWITCH_VERBOSE = "-v";
- protected static final String SWITCH_HELP = "-help";
- protected static final String SWITCH_OUTPUT_DIR = "-d";
- protected static final String SWITCH_PACKAGE_NAME = "-p";
- protected static final String SWITCH_CACHE = "-cache";
- protected static final String SWITCH_CLASS_NAME = "-c";
- protected static final String SWITCH_FULL_STOP = "--";
- protected static final String SWITCH_COMPILE = "-compile";
- protected static final String SWITCH_SOURCE = "-source";
- protected static final String SWITCH_TARGET = "-target";
- protected static final String SWITCH_URI_BASE = "-uribase";
- protected static final String SWITCH_URI_ROOT = "-uriroot";
- protected static final String SWITCH_FILE_WEBAPP = "-webapp";
- protected static final String SWITCH_WEBAPP_INC = "-webinc";
- protected static final String SWITCH_WEBAPP_XML = "-webxml";
- protected static final String SWITCH_WEBAPP_XML_ENCODING = "-webxmlencoding";
- protected static final String SWITCH_ADD_WEBAPP_XML_MAPPINGS = "-addwebxmlmappings";
- protected static final String SWITCH_MAPPED = "-mapped";
- protected static final String SWITCH_XPOWERED_BY = "-xpoweredBy";
- protected static final String SWITCH_TRIM_SPACES = "-trimSpaces";
- protected static final String SWITCH_CLASSPATH = "-classpath";
- protected static final String SWITCH_DIE = "-die";
- protected static final String SWITCH_POOLING = "-poolingEnabled";
- protected static final String SWITCH_ENCODING = "-javaEncoding";
- protected static final String SWITCH_SMAP = "-smap";
- protected static final String SWITCH_DUMP_SMAP = "-dumpsmap";
- protected static final String SWITCH_VALIDATE_TLD = "-validateTld";
- protected static final String SWITCH_VALIDATE_XML = "-validateXml";
- protected static final String SWITCH_BLOCK_EXTERNAL = "-blockExternal";
- protected static final String SWITCH_NO_BLOCK_EXTERNAL = "-no-blockExternal";
- protected static final String SHOW_SUCCESS ="-s";
- protected static final String LIST_ERRORS = "-l";
- protected static final int INC_WEBXML = 10;
- protected static final int ALL_WEBXML = 20;
- protected static final int DEFAULT_DIE_LEVEL = 1;
- protected static final int NO_DIE_LEVEL = 0;
- protected static final Set insertBefore = new HashSet();
-
- static {
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- }
-
- protected String classPath = null;
- protected ClassLoader loader = null;
- protected boolean trimSpaces = false;
- protected boolean genStringAsCharArray = false;
- protected boolean validateTld;
- protected boolean validateXml;
- protected boolean blockExternal = true;
- protected boolean xpoweredBy;
- protected boolean mappedFile = false;
- protected boolean poolingEnabled = true;
- protected File scratchDir;
- protected String ieClassId = DEFAULT_IE_CLASS_ID;
- protected String targetPackage;
- protected String targetClassName;
- protected String uriBase;
- protected String uriRoot;
- protected int dieLevel;
- protected boolean helpNeeded = false;
- protected boolean compile = false;
- protected boolean smapSuppressed = true;
- protected boolean smapDumped = false;
- protected boolean caching = true;
- protected final Map cache =
- new HashMap();
-
- protected String compiler = null;
-
- protected String compilerTargetVM = "1.6";
- protected String compilerSourceVM = "1.6";
-
- protected boolean classDebugInfo = true;
-
- /**
- * Throw an exception if there's a compilation error, or swallow it.
- * Default is true to preserve old behavior.
- */
- protected boolean failOnError = true;
-
- /**
- * The file extensions to be handled as JSP files.
- * Default list is .jsp and .jspx.
- */
- protected List extensions;
-
- /**
- * The pages.
- */
- protected final List pages = new Vector();
-
- /**
- * Needs better documentation, this data member does.
- * True by default.
- */
- protected boolean errorOnUseBeanInvalidClassAttribute = true;
-
- /**
- * The java file encoding. Default
- * is UTF-8. Added per bugzilla 19622.
- */
- protected String javaEncoding = "UTF-8";
-
- // Generation of web.xml fragments
- protected String webxmlFile;
- protected int webxmlLevel;
- protected String webxmlEncoding;
- protected boolean addWebXmlMappings = false;
-
- protected Writer mapout;
- protected CharArrayWriter servletout;
- protected CharArrayWriter mappingout;
-
- /**
- * The servlet context.
- */
- protected JspCServletContext context;
-
- /**
- * The runtime context.
- * Maintain a dummy JspRuntimeContext for compiling tag files.
- */
- protected JspRuntimeContext rctxt;
-
- /**
- * Cache for the TLD locations
- */
- protected TldLocationsCache tldLocationsCache = null;
-
- protected JspConfig jspConfig = null;
- protected TagPluginManager tagPluginManager = null;
-
- protected boolean verbose = false;
- protected boolean listErrors = false;
- protected boolean showSuccess = false;
- protected int argPos;
- protected boolean fullstop = false;
- protected String args[];
-
- public static void main(String arg[]) {
- if (arg.length == 0) {
- System.out.println(Localizer.getMessage("jspc.usage"));
- } else {
- JspC jspc = new JspC();
- try {
- jspc.setArgs(arg);
- if (jspc.helpNeeded) {
- System.out.println(Localizer.getMessage("jspc.usage"));
- } else {
- jspc.execute();
- }
- } catch (JasperException je) {
- System.err.println(je);
- if (jspc.dieLevel != NO_DIE_LEVEL) {
- System.exit(jspc.dieLevel);
- }
- } catch (RuntimeException je) {
- System.err.println(je);
- if (jspc.dieLevel != NO_DIE_LEVEL) {
- System.exit(jspc.dieLevel);
- }
- }
- }
- }
-
- /**
- * Apply command-line arguments.
- *
- * @param arg
- * The arguments
- */
- public void setArgs(String[] arg) throws JasperException {
- args = arg;
- String tok;
-
- dieLevel = NO_DIE_LEVEL;
-
- while ((tok = nextArg()) != null) {
- if (tok.equals(SWITCH_VERBOSE)) {
- verbose = true;
- showSuccess = true;
- listErrors = true;
- } else if (tok.equals(SWITCH_OUTPUT_DIR)) {
- tok = nextArg();
- setOutputDir( tok );
- } else if (tok.equals(SWITCH_PACKAGE_NAME)) {
- targetPackage = nextArg();
- } else if (tok.equals(SWITCH_COMPILE)) {
- compile=true;
- } else if (tok.equals(SWITCH_CLASS_NAME)) {
- targetClassName = nextArg();
- } else if (tok.equals(SWITCH_URI_BASE)) {
- uriBase=nextArg();
- } else if (tok.equals(SWITCH_URI_ROOT)) {
- setUriroot( nextArg());
- } else if (tok.equals(SWITCH_FILE_WEBAPP)) {
- setUriroot( nextArg());
- } else if ( tok.equals( SHOW_SUCCESS ) ) {
- showSuccess = true;
- } else if ( tok.equals( LIST_ERRORS ) ) {
- listErrors = true;
- } else if (tok.equals(SWITCH_WEBAPP_INC)) {
- webxmlFile = nextArg();
- if (webxmlFile != null) {
- webxmlLevel = INC_WEBXML;
- }
- } else if (tok.equals(SWITCH_WEBAPP_XML)) {
- webxmlFile = nextArg();
- if (webxmlFile != null) {
- webxmlLevel = ALL_WEBXML;
- }
- } else if (tok.equals(SWITCH_WEBAPP_XML_ENCODING)) {
- setWebXmlEncoding(nextArg());
- } else if (tok.equals(SWITCH_ADD_WEBAPP_XML_MAPPINGS)) {
- setAddWebXmlMappings(true);
- } else if (tok.equals(SWITCH_MAPPED)) {
- mappedFile = true;
- } else if (tok.equals(SWITCH_XPOWERED_BY)) {
- xpoweredBy = true;
- } else if (tok.equals(SWITCH_TRIM_SPACES)) {
- setTrimSpaces(true);
- } else if (tok.equals(SWITCH_CACHE)) {
- tok = nextArg();
- if ("false".equals(tok)) {
- caching = false;
- } else {
- caching = true;
- }
- } else if (tok.equals(SWITCH_CLASSPATH)) {
- setClassPath(nextArg());
- } else if (tok.startsWith(SWITCH_DIE)) {
- try {
- dieLevel = Integer.parseInt(
- tok.substring(SWITCH_DIE.length()));
- } catch (NumberFormatException nfe) {
- dieLevel = DEFAULT_DIE_LEVEL;
- }
- } else if (tok.equals(SWITCH_HELP)) {
- helpNeeded = true;
- } else if (tok.equals(SWITCH_POOLING)) {
- tok = nextArg();
- if ("false".equals(tok)) {
- poolingEnabled = false;
- } else {
- poolingEnabled = true;
- }
- } else if (tok.equals(SWITCH_ENCODING)) {
- setJavaEncoding(nextArg());
- } else if (tok.equals(SWITCH_SOURCE)) {
- setCompilerSourceVM(nextArg());
- } else if (tok.equals(SWITCH_TARGET)) {
- setCompilerTargetVM(nextArg());
- } else if (tok.equals(SWITCH_SMAP)) {
- smapSuppressed = false;
- } else if (tok.equals(SWITCH_DUMP_SMAP)) {
- smapDumped = true;
- } else if (tok.equals(SWITCH_VALIDATE_TLD)) {
- setValidateTld(true);
- } else if (tok.equals(SWITCH_VALIDATE_XML)) {
- setValidateXml(true);
- } else if (tok.equals(SWITCH_BLOCK_EXTERNAL)) {
- setBlockExternal(true);
- } else if (tok.equals(SWITCH_NO_BLOCK_EXTERNAL)) {
- setBlockExternal(false);
- } else {
- if (tok.startsWith("-")) {
- throw new JasperException("Unrecognized option: " + tok +
- ". Use -help for help.");
- }
- if (!fullstop) {
- argPos--;
- }
- // Start treating the rest as JSP Pages
- break;
- }
- }
-
- // Add all extra arguments to the list of files
- while( true ) {
- String file = nextFile();
- if( file==null ) {
- break;
- }
- pages.add( file );
- }
- }
-
- /**
- * In JspC this always returns true.
- * {@inheritDoc}
- */
- @Override
- public boolean getKeepGenerated() {
- // isn't this why we are running jspc?
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getTrimSpaces() {
- return trimSpaces;
- }
-
- /**
- * Sets the option to trim white spaces between directives or actions.
- */
- public void setTrimSpaces(boolean ts) {
- this.trimSpaces = ts;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isPoolingEnabled() {
- return poolingEnabled;
- }
-
- /**
- * Sets the option to enable the tag handler pooling.
- */
- public void setPoolingEnabled(boolean poolingEnabled) {
- this.poolingEnabled = poolingEnabled;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isXpoweredBy() {
- return xpoweredBy;
- }
-
- /**
- * Sets the option to enable generation of X-Powered-By response header.
- */
- public void setXpoweredBy(boolean xpoweredBy) {
- this.xpoweredBy = xpoweredBy;
- }
-
- /**
- * In JspC this always returns true.
- * {@inheritDoc}
- */
- @Override
- public boolean getDisplaySourceFragment() {
- return true;
- }
-
- @Override
- public int getMaxLoadedJsps() {
- return -1;
- }
-
- @Override
- public int getJspIdleTimeout() {
- return -1;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getErrorOnUseBeanInvalidClassAttribute() {
- return errorOnUseBeanInvalidClassAttribute;
- }
-
- /**
- * Sets the option to issue a compilation error if the class attribute
- * specified in useBean action is invalid.
- */
- public void setErrorOnUseBeanInvalidClassAttribute(boolean b) {
- errorOnUseBeanInvalidClassAttribute = b;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getMappedFile() {
- return mappedFile;
- }
-
- public void setMappedFile(boolean b) {
- mappedFile = b;
- }
-
- /**
- * Sets the option to include debug information in compiled class.
- */
- public void setClassDebugInfo( boolean b ) {
- classDebugInfo=b;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getClassDebugInfo() {
- // compile with debug info
- return classDebugInfo;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isCaching() {
- return caching;
- }
-
- /**
- * Sets the option to enable caching.
- *
- * @see Options#isCaching()
- */
- public void setCaching(boolean caching) {
- this.caching = caching;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Map getCache() {
- return cache;
- }
-
- /**
- * In JspC this always returns 0.
- * {@inheritDoc}
- */
- @Override
- public int getCheckInterval() {
- return 0;
- }
-
- /**
- * In JspC this always returns 0.
- * {@inheritDoc}
- */
- @Override
- public int getModificationTestInterval() {
- return 0;
- }
-
-
- /**
- * In JspC this always returns false.
- * {@inheritDoc}
- */
- @Override
- public boolean getRecompileOnFail() {
- return false;
- }
-
-
- /**
- * In JspC this always returns false.
- * {@inheritDoc}
- */
- @Override
- public boolean getDevelopment() {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isSmapSuppressed() {
- return smapSuppressed;
- }
-
- /**
- * Sets smapSuppressed flag.
- */
- public void setSmapSuppressed(boolean smapSuppressed) {
- this.smapSuppressed = smapSuppressed;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isSmapDumped() {
- return smapDumped;
- }
-
- /**
- * Sets smapDumped flag.
- *
- * @see Options#isSmapDumped()
- */
- public void setSmapDumped(boolean smapDumped) {
- this.smapDumped = smapDumped;
- }
-
-
- /**
- * Determines whether text strings are to be generated as char arrays,
- * which improves performance in some cases.
- *
- * @param genStringAsCharArray true if text strings are to be generated as
- * char arrays, false otherwise
- */
- public void setGenStringAsCharArray(boolean genStringAsCharArray) {
- this.genStringAsCharArray = genStringAsCharArray;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean genStringAsCharArray() {
- return genStringAsCharArray;
- }
-
- /**
- * Sets the class-id value to be sent to Internet Explorer when using
- * <jsp:plugin> tags.
- *
- * @param ieClassId
- * Class-id value
- */
- public void setIeClassId(String ieClassId) {
- this.ieClassId = ieClassId;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getIeClassId() {
- return ieClassId;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public File getScratchDir() {
- return scratchDir;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getCompiler() {
- return compiler;
- }
-
- /**
- * Sets the option to determine what compiler to use.
- *
- * @see Options#getCompiler()
- */
- public void setCompiler(String c) {
- compiler=c;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getCompilerClassName() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getCompilerTargetVM() {
- return compilerTargetVM;
- }
-
- /**
- * Sets the compiler target VM.
- *
- * @see Options#getCompilerTargetVM()
- */
- public void setCompilerTargetVM(String vm) {
- compilerTargetVM = vm;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getCompilerSourceVM() {
- return compilerSourceVM;
- }
-
- /**
- * Sets the compiler source VM.
- *
- * @see Options#getCompilerSourceVM()
- */
- public void setCompilerSourceVM(String vm) {
- compilerSourceVM = vm;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public TldLocationsCache getTldLocationsCache() {
- return tldLocationsCache;
- }
-
- /**
- * Returns the encoding to use for
- * java files. The default is UTF-8.
- *
- * @return String The encoding
- */
- @Override
- public String getJavaEncoding() {
- return javaEncoding;
- }
-
- /**
- * Sets the encoding to use for
- * java files.
- *
- * @param encodingName The name, e.g. "UTF-8"
- */
- public void setJavaEncoding(String encodingName) {
- javaEncoding = encodingName;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getFork() {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getClassPath() {
- if( classPath != null )
- return classPath;
- return System.getProperty("java.class.path");
- }
-
- /**
- * Sets the classpath used while compiling the servlets generated from JSP
- * files
- */
- public void setClassPath(String s) {
- classPath=s;
- }
-
- /**
- * Returns the list of file extensions
- * that are treated as JSP files.
- *
- * @return The list of extensions
- */
- public List getExtensions() {
- return extensions;
- }
-
- /**
- * Adds the given file extension to the
- * list of extensions handled as JSP files.
- *
- * @param extension The extension to add, e.g. "myjsp"
- */
- protected void addExtension(final String extension) {
- if(extension != null) {
- if(extensions == null) {
- extensions = new Vector();
- }
-
- extensions.add(extension);
- }
- }
-
- /**
- * Base dir for the webapp. Used to generate class names and resolve
- * includes.
- */
- public void setUriroot( String s ) {
- if (s == null) {
- uriRoot = null;
- return;
- }
- try {
- uriRoot = resolveFile(s).getCanonicalPath();
- } catch( Exception ex ) {
- uriRoot = s;
- }
- }
-
- /**
- * Parses comma-separated list of JSP files to be processed. If the argument
- * is null, nothing is done.
- *
- * Each file is interpreted relative to uriroot, unless it is absolute,
- * in which case it must start with uriroot.
- *
- * @param jspFiles Comma-separated list of JSP files to be processed
- */
- public void setJspFiles(final String jspFiles) {
- if(jspFiles == null) {
- return;
- }
-
- StringTokenizer tok = new StringTokenizer(jspFiles, ",");
- while (tok.hasMoreTokens()) {
- pages.add(tok.nextToken());
- }
- }
-
- /**
- * Sets the compile flag.
- *
- * @param b Flag value
- */
- public void setCompile( final boolean b ) {
- compile = b;
- }
-
- /**
- * Sets the verbosity level. The actual number doesn't
- * matter: if it's greater than zero, the verbose flag will
- * be true.
- *
- * @param level Positive means verbose
- */
- public void setVerbose( final int level ) {
- if (level > 0) {
- verbose = true;
- showSuccess = true;
- listErrors = true;
- }
- }
-
- public void setValidateTld( boolean b ) {
- this.validateTld = b;
- }
-
- public boolean isValidateTld() {
- return validateTld;
- }
-
- public void setValidateXml( boolean b ) {
- this.validateXml = b;
- }
-
- public boolean isValidateXml() {
- return validateXml;
- }
-
- public void setBlockExternal( boolean b ) {
- this.blockExternal = b;
- }
-
- public boolean isBlockExternal() {
- return blockExternal;
- }
-
- public void setListErrors( boolean b ) {
- listErrors = b;
- }
-
- public void setOutputDir( String s ) {
- if( s!= null ) {
- scratchDir = resolveFile(s).getAbsoluteFile();
- } else {
- scratchDir=null;
- }
- }
-
- /**
- * Sets the package name to be used for the generated servlet classes.
- */
- public void setPackage( String p ) {
- targetPackage=p;
- }
-
- /**
- * Class name of the generated file ( without package ).
- * Can only be used if a single file is converted.
- * XXX Do we need this feature ?
- */
- public void setClassName( String p ) {
- targetClassName=p;
- }
-
- /**
- * File where we generate a web.xml fragment with the class definitions.
- */
- public void setWebXmlFragment( String s ) {
- webxmlFile=resolveFile(s).getAbsolutePath();
- webxmlLevel=INC_WEBXML;
- }
-
- /**
- * File where we generate a complete web.xml with the class definitions.
- */
- public void setWebXml( String s ) {
- webxmlFile=resolveFile(s).getAbsolutePath();
- webxmlLevel=ALL_WEBXML;
- }
-
- /**
- * Sets the encoding to be used to read and write web.xml files.
- *
- *
- * If not specified, defaults to the platform default encoding.
- *
- *
- * @param encoding
- * Encoding, e.g. "UTF-8".
- */
- public void setWebXmlEncoding(String encoding) {
- webxmlEncoding = encoding;
- }
-
- /**
- * Sets the option to merge generated web.xml fragment into the
- * WEB-INF/web.xml file of the web application that we were processing.
- *
- * @param b
- * true to merge the fragment into the existing
- * web.xml file of the processed web application
- * ({uriroot}/WEB-INF/web.xml), false to keep the
- * generated web.xml fragment
- */
- public void setAddWebXmlMappings(boolean b) {
- addWebXmlMappings = b;
- }
-
- /**
- * Sets the option that throws an exception in case of a compilation error.
- */
- public void setFailOnError(final boolean b) {
- failOnError = b;
- }
-
- /**
- * Returns true if an exception will be thrown in case of a compilation
- * error.
- */
- public boolean getFailOnError() {
- return failOnError;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public JspConfig getJspConfig() {
- return jspConfig;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public TagPluginManager getTagPluginManager() {
- return tagPluginManager;
- }
-
- /**
- * Adds servlet declaration and mapping for the JSP page servlet to the
- * generated web.xml fragment.
- *
- * @param file
- * Context-relative path to the JSP file, e.g.
- * /index.jsp
- * @param clctxt
- * Compilation context of the servlet
- */
- public void generateWebMapping( String file, JspCompilationContext clctxt )
- throws IOException
- {
- if (log.isDebugEnabled()) {
- log.debug("Generating web mapping for file " + file
- + " using compilation context " + clctxt);
- }
-
- String className = clctxt.getServletClassName();
- String packageName = clctxt.getServletPackageName();
-
- String thisServletName;
- if ("".equals(packageName)) {
- thisServletName = className;
- } else {
- thisServletName = packageName + '.' + className;
- }
-
- if (servletout != null) {
- servletout.write("\n \n ");
- servletout.write(thisServletName);
- servletout.write("\n ");
- servletout.write(thisServletName);
- servletout.write("\n \n");
- }
- if (mappingout != null) {
- mappingout.write("\n \n ");
- mappingout.write(thisServletName);
- mappingout.write("\n ");
- mappingout.write(file.replace('\\', '/'));
- mappingout.write("\n \n");
-
- }
- }
-
- /**
- * Include the generated web.xml inside the webapp's web.xml.
- */
- protected void mergeIntoWebXml() throws IOException {
-
- File webappBase = new File(uriRoot);
- File webXml = new File(webappBase, "WEB-INF/web.xml");
- File webXml2 = new File(webappBase, "WEB-INF/web2.xml");
- String insertStartMarker =
- Localizer.getMessage("jspc.webinc.insertStart");
- String insertEndMarker =
- Localizer.getMessage("jspc.webinc.insertEnd");
-
- BufferedReader reader = new BufferedReader(openWebxmlReader(webXml));
- BufferedReader fragmentReader = new BufferedReader(
- openWebxmlReader(new File(webxmlFile)));
- PrintWriter writer = new PrintWriter(openWebxmlWriter(webXml2));
-
- // Insert the and declarations
- boolean inserted = false;
- int current = reader.read();
- while (current > -1) {
- if (current == '<') {
- String element = getElement(reader);
- if (!inserted && insertBefore.contains(element)) {
- // Insert generated content here
- writer.println(insertStartMarker);
- while (true) {
- String line = fragmentReader.readLine();
- if (line == null) {
- writer.println();
- break;
- }
- writer.println(line);
- }
- writer.println(insertEndMarker);
- writer.println();
- writer.write(element);
- inserted = true;
- } else if (element.equals(insertStartMarker)) {
- // Skip the previous auto-generated content
- while (true) {
- current = reader.read();
- if (current < 0) {
- throw new EOFException();
- }
- if (current == '<') {
- element = getElement(reader);
- if (element.equals(insertEndMarker)) {
- break;
- }
- }
- }
- current = reader.read();
- while (current == '\n' || current == '\r') {
- current = reader.read();
- }
- continue;
- } else {
- writer.write(element);
- }
- } else {
- writer.write(current);
- }
- current = reader.read();
- }
- writer.close();
-
- reader.close();
- fragmentReader.close();
-
- FileInputStream fis = new FileInputStream(webXml2);
- FileOutputStream fos = new FileOutputStream(webXml);
-
- byte buf[] = new byte[512];
- while (true) {
- int n = fis.read(buf);
- if (n < 0) {
- break;
- }
- fos.write(buf, 0, n);
- }
-
- fis.close();
- fos.close();
-
- if(!webXml2.delete() && log.isDebugEnabled())
- log.debug(Localizer.getMessage("jspc.delete.fail",
- webXml2.toString()));
-
- if (!(new File(webxmlFile)).delete() && log.isDebugEnabled())
- log.debug(Localizer.getMessage("jspc.delete.fail", webxmlFile));
-
- }
-
- /*
- * Assumes valid xml
- */
- private String getElement(Reader reader) throws IOException {
- StringBuilder result = new StringBuilder();
- result.append('<');
-
- boolean done = false;
-
- while (!done) {
- int current = reader.read();
- while (current != '>') {
- if (current < 0) {
- throw new EOFException();
- }
- result.append((char) current);
- current = reader.read();
- }
- result.append((char) current);
-
- int len = result.length();
- if (len > 4 && result.substring(0, 4).equals("")) {
- done = true;
- }
- } else {
- done = true;
- }
- }
-
-
- return result.toString();
- }
-
- protected void processFile(String file)
- throws JasperException
- {
- if (log.isDebugEnabled()) {
- log.debug("Processing file: " + file);
- }
-
- ClassLoader originalClassLoader = null;
-
- try {
- // set up a scratch/output dir if none is provided
- if (scratchDir == null) {
- String temp = System.getProperty("java.io.tmpdir");
- if (temp == null) {
- temp = "";
- }
- scratchDir = new File(new File(temp).getAbsolutePath());
- }
-
- String jspUri=file.replace('\\','/');
- JspCompilationContext clctxt = new JspCompilationContext
- ( jspUri, this, context, null, rctxt );
-
- /* Override the defaults */
- if ((targetClassName != null) && (targetClassName.length() > 0)) {
- clctxt.setServletClassName(targetClassName);
- targetClassName = null;
- }
- if (targetPackage != null) {
- clctxt.setServletPackageName(targetPackage);
- }
-
- originalClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(loader);
-
- clctxt.setClassLoader(loader);
- clctxt.setClassPath(classPath);
-
- Compiler clc = clctxt.createCompiler();
-
- // If compile is set, generate both .java and .class, if
- // .jsp file is newer than .class file;
- // Otherwise only generate .java, if .jsp file is newer than
- // the .java file
- if( clc.isOutDated(compile) ) {
- if (log.isDebugEnabled()) {
- log.debug(jspUri + " is out dated, compiling...");
- }
-
- clc.compile(compile, true);
- }
-
- // Generate mapping
- generateWebMapping( file, clctxt );
- if ( showSuccess ) {
- log.info( "Built File: " + file );
- }
-
- } catch (JasperException je) {
- Throwable rootCause = je;
- while (rootCause instanceof JasperException
- && ((JasperException) rootCause).getRootCause() != null) {
- rootCause = ((JasperException) rootCause).getRootCause();
- }
- if (rootCause != je) {
- log.error(Localizer.getMessage("jspc.error.generalException",
- file),
- rootCause);
- }
-
- // Bugzilla 35114.
- if(getFailOnError()) {
- throw je;
- } else {
- log.error(je.getMessage());
- }
-
- } catch (Exception e) {
- if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist",
- e.getMessage()));
- }
- throw new JasperException(e);
- } finally {
- if(originalClassLoader != null) {
- Thread.currentThread().setContextClassLoader(originalClassLoader);
- }
- }
- }
-
- /**
- * Locate all jsp files in the webapp. Used if no explicit
- * jsps are specified.
- */
- public void scanFiles( File base ) throws JasperException {
- Stack dirs = new Stack();
- dirs.push(base.toString());
-
- // Make sure default extensions are always included
- if ((getExtensions() == null) || (getExtensions().size() < 2)) {
- addExtension("jsp");
- addExtension("jspx");
- }
-
- while (!dirs.isEmpty()) {
- String s = dirs.pop();
- File f = new File(s);
- if (f.exists() && f.isDirectory()) {
- String[] files = f.list();
- String ext;
- for (int i = 0; (files != null) && i < files.length; i++) {
- File f2 = new File(s, files[i]);
- if (f2.isDirectory()) {
- dirs.push(f2.getPath());
- } else {
- String path = f2.getPath();
- String uri = path.substring(uriRoot.length());
- ext = files[i].substring(files[i].lastIndexOf('.') +1);
- if (getExtensions().contains(ext) ||
- jspConfig.isJspPage(uri)) {
- pages.add(path);
- }
- }
- }
- }
- }
- }
-
- /**
- * Executes the compilation.
- */
- public void execute() {
- if(log.isDebugEnabled()) {
- log.debug("execute() starting for " + pages.size() + " pages.");
- }
-
- try {
- if (uriRoot == null) {
- if( pages.size() == 0 ) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.missingTarget"));
- }
- String firstJsp = pages.get( 0 );
- File firstJspF = new File( firstJsp );
- if (!firstJspF.exists()) {
- throw new JasperException(
- Localizer.getMessage("jspc.error.fileDoesNotExist",
- firstJsp));
- }
- locateUriRoot( firstJspF );
- }
-
- if (uriRoot == null) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.no_uriroot"));
- }
-
- File uriRootF = new File(uriRoot);
- if (!uriRootF.isDirectory()) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.uriroot_not_dir"));
- }
-
- if (loader == null) {
- loader = initClassLoader();
- }
- if (context == null) {
- initServletContext(loader);
- }
-
- // No explicit pages, we'll process all .jsp in the webapp
- if (pages.size() == 0) {
- scanFiles(uriRootF);
- }
-
- initWebXml();
-
- Iterator iter = pages.iterator();
- while (iter.hasNext()) {
- String nextjsp = iter.next().toString();
- File fjsp = new File(nextjsp);
- if (!fjsp.isAbsolute()) {
- fjsp = new File(uriRootF, nextjsp);
- }
- if (!fjsp.exists()) {
- if (log.isWarnEnabled()) {
- log.warn
- (Localizer.getMessage
- ("jspc.error.fileDoesNotExist", fjsp.toString()));
- }
- continue;
- }
- String s = fjsp.getAbsolutePath();
- if (s.startsWith(uriRoot)) {
- nextjsp = s.substring(uriRoot.length());
- }
- if (nextjsp.startsWith("." + File.separatorChar)) {
- nextjsp = nextjsp.substring(2);
- }
- processFile(nextjsp);
- }
-
- completeWebXml();
-
- if (addWebXmlMappings) {
- mergeIntoWebXml();
- }
-
- } catch (IOException ioe) {
- throw new RuntimeException(ioe); // TODO make it our own
-
- } catch (JasperException je) {
- Throwable rootCause = je;
- while (rootCause instanceof JasperException
- && ((JasperException) rootCause).getRootCause() != null) {
- rootCause = ((JasperException) rootCause).getRootCause();
- }
- if (rootCause != je) {
- rootCause.printStackTrace();
- }
- throw new RuntimeException(je); // TODO make it our own
- } finally {
- if (loader != null) {
- LogFactory.release(loader);
- }
- }
- }
-
- // ==================== protected utility methods ====================
-
- protected String nextArg() {
- if ((argPos >= args.length)
- || (fullstop = SWITCH_FULL_STOP.equals(args[argPos]))) {
- return null;
- } else {
- return args[argPos++];
- }
- }
-
- protected String nextFile() {
- if (fullstop) argPos++;
- if (argPos >= args.length) {
- return null;
- } else {
- return args[argPos++];
- }
- }
-
- protected void initWebXml() {
- try {
- if (webxmlLevel >= INC_WEBXML) {
- mapout = openWebxmlWriter(new File(webxmlFile));
- servletout = new CharArrayWriter();
- mappingout = new CharArrayWriter();
- } else {
- mapout = null;
- servletout = null;
- mappingout = null;
- }
- if (webxmlLevel >= ALL_WEBXML) {
- mapout.write(Localizer.getMessage("jspc.webxml.header"));
- mapout.flush();
- } else if ((webxmlLevel>= INC_WEBXML) && !addWebXmlMappings) {
- mapout.write(Localizer.getMessage("jspc.webinc.header"));
- mapout.flush();
- }
- } catch (IOException ioe) {
- mapout = null;
- servletout = null;
- mappingout = null;
- }
- }
-
- protected void completeWebXml() {
- if (mapout != null) {
- try {
- servletout.writeTo(mapout);
- mappingout.writeTo(mapout);
- if (webxmlLevel >= ALL_WEBXML) {
- mapout.write(Localizer.getMessage("jspc.webxml.footer"));
- } else if ((webxmlLevel >= INC_WEBXML) && !addWebXmlMappings) {
- mapout.write(Localizer.getMessage("jspc.webinc.footer"));
- }
- mapout.close();
- } catch (IOException ioe) {
- // noting to do if it fails since we are done with it
- }
- }
- }
-
- protected void initServletContext(ClassLoader classLoader)
- throws IOException, JasperException {
- // TODO: should we use the Ant Project's log?
- PrintWriter log = new PrintWriter(System.out);
- URL resourceBase = new File(uriRoot).getCanonicalFile().toURI().toURL();
- context = new JspCServletContext(log, resourceBase, classLoader);
- if (isValidateTld()) {
- context.setInitParameter(Constants.XML_VALIDATION_TLD_INIT_PARAM, "true");
- }
- if (isValidateXml()) {
- context.setInitParameter(Constants.XML_VALIDATION_INIT_PARAM, "true");
- }
- context.setInitParameter(Constants.XML_BLOCK_EXTERNAL_INIT_PARAM,
- String.valueOf(isBlockExternal()));
-
- tldLocationsCache = TldLocationsCache.getInstance(context);
- rctxt = new JspRuntimeContext(context, this);
- jspConfig = new JspConfig(context);
- tagPluginManager = new TagPluginManager(context);
- }
-
- /**
- * Initializes the classloader as/if needed for the given
- * compilation context.
- *
- * @throws IOException If an error occurs
- */
- protected ClassLoader initClassLoader() throws IOException {
-
- classPath = getClassPath();
-
- ClassLoader jspcLoader = getClass().getClassLoader();
- // TODO add check for 7Bee/TJWS class loader and extend CP as needed
-
- // Turn the classPath into URLs
- ArrayList urls = new ArrayList();
- StringTokenizer tokenizer = new StringTokenizer(classPath,
- File.pathSeparator);
- while (tokenizer.hasMoreTokens()) {
- String path = tokenizer.nextToken();
- try {
- File libFile = new File(path);
- urls.add(libFile.toURI().toURL());
- } catch (IOException ioe) {
- // Failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak uot
- throw new RuntimeException(ioe.toString());
- }
- }
-
- File webappBase = new File(uriRoot);
- if (webappBase.exists()) {
- File classes = new File(webappBase, "/WEB-INF/classes");
- try {
- if (classes.exists()) {
- classPath = classPath + File.pathSeparator
- + classes.getCanonicalPath();
- urls.add(classes.getCanonicalFile().toURI().toURL());
- }
- } catch (IOException ioe) {
- // failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak out
- throw new RuntimeException(ioe.toString());
- }
- File lib = new File(webappBase, "/WEB-INF/lib");
- if (lib.exists() && lib.isDirectory()) {
- String[] libs = lib.list();
- for (int i = 0; i < libs.length; i++) {
- if( libs[i].length() <5 ) continue;
- String ext=libs[i].substring( libs[i].length() - 4 );
- if (! ".jar".equalsIgnoreCase(ext)) {
- if (".tld".equalsIgnoreCase(ext)) {
- log.warn("TLD files should not be placed in "
- + "/WEB-INF/lib");
- }
- continue;
- }
- try {
- File libFile = new File(lib, libs[i]);
- classPath = classPath + File.pathSeparator
- + libFile.getAbsolutePath();
- urls.add(libFile.getAbsoluteFile().toURI().toURL());
- } catch (IOException ioe) {
- // failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak out
- throw new RuntimeException(ioe.toString());
- }
- }
- }
- }
-
- URL urlsA[]=new URL[urls.size()];
- urls.toArray(urlsA);
- loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());
- return loader;
- }
-
- /**
- * Find the WEB-INF dir by looking up in the directory tree.
- * This is used if no explicit docbase is set, but only files.
- * XXX Maybe we should require the docbase.
- */
- protected void locateUriRoot( File f ) {
- String tUriBase = uriBase;
- if (tUriBase == null) {
- tUriBase = "/";
- }
- try {
- if (f.exists()) {
- f = new File(f.getAbsolutePath());
- while (true) {
- File g = new File(f, "WEB-INF");
- if (g.exists() && g.isDirectory()) {
- uriRoot = f.getCanonicalPath();
- uriBase = tUriBase;
- if (log.isInfoEnabled()) {
- log.info(Localizer.getMessage(
- "jspc.implicit.uriRoot",
- uriRoot));
- }
- break;
- }
- if (f.exists() && f.isDirectory()) {
- tUriBase = "/" + f.getName() + "/" + tUriBase;
- }
-
- String fParent = f.getParent();
- if (fParent == null) {
- break;
- } else {
- f = new File(fParent);
- }
-
- // If there is no acceptable candidate, uriRoot will
- // remain null to indicate to the CompilerContext to
- // use the current working/user dir.
- }
-
- if (uriRoot != null) {
- File froot = new File(uriRoot);
- uriRoot = froot.getCanonicalPath();
- }
- }
- } catch (IOException ioe) {
- // since this is an optional default and a null value
- // for uriRoot has a non-error meaning, we can just
- // pass straight through
- }
- }
-
- /**
- * Resolves the relative or absolute pathname correctly
- * in both Ant and command-line situations. If Ant launched
- * us, we should use the basedir of the current project
- * to resolve relative paths.
- *
- * See Bugzilla 35571.
- *
- * @param s The file
- * @return The file resolved
- */
- protected File resolveFile(final String s) {
- // TODO consider some massaging of s as relative path to project home
- return new File(s);
- }
-
- private Reader openWebxmlReader(File file) throws IOException {
- FileInputStream fis = new FileInputStream(file);
- try {
- return webxmlEncoding != null ? new InputStreamReader(fis,
- webxmlEncoding) : new InputStreamReader(fis);
- } catch (IOException ex) {
- fis.close();
- throw ex;
- }
- }
-
- private Writer openWebxmlWriter(File file) throws IOException {
- FileOutputStream fos = new FileOutputStream(file);
- try {
- return webxmlEncoding != null ? new OutputStreamWriter(fos,
- webxmlEncoding) : new OutputStreamWriter(fos);
- } catch (IOException ex) {
- fos.close();
- throw ex;
- }
- }
-}
diff --git a/1.x/src/jasper7-6x/JspCServletContext.java b/1.x/src/jasper7-6x/JspCServletContext.java
deleted file mode 100644
index 282d73b..0000000
--- a/1.x/src/jasper7-6x/JspCServletContext.java
+++ /dev/null
@@ -1,664 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.servlet;
-
-
-import java.io.File;
-import java.io.InputStream;
-import java.io.PrintWriter;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.EnumSet;
-import java.util.Enumeration;
-import java.util.EventListener;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.Set;
-import java.util.Vector;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javax.servlet.Filter;
-import javax.servlet.FilterRegistration;
-import javax.servlet.FilterRegistration.Dynamic;
-import javax.servlet.RequestDispatcher;
-import javax.servlet.Servlet;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRegistration;
-import javax.servlet.SessionCookieConfig;
-import javax.servlet.SessionTrackingMode;
-import javax.servlet.descriptor.JspConfigDescriptor;
-
-import org.apache.jasper.JasperException;
-import org.apache.jasper.util.ExceptionUtils;
-
-
-/**
- * Simple ServletContext implementation without
- * HTTP-specific methods.
- *
- * @author Peter Rossbach (pr@webapp.de)
- */
-
-public class JspCServletContext implements ServletContext {
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * Servlet context attributes.
- */
- protected Hashtable myAttributes;
-
-
- /**
- * Servlet context initialization parameters.
- */
- private final ConcurrentHashMap myParameters;
-
-
- /**
- * The log writer we will write log messages to.
- */
- protected PrintWriter myLogWriter;
-
-
- /**
- * The base URL (document root) for this context.
- */
- protected URL myResourceBaseURL;
-
-
- /**
- * Web application class loader.
- */
- private final ClassLoader loader;
-
-
- // ----------------------------------------------------------- Constructors
-
- /**
- * Create a new instance of this ServletContext implementation.
- *
- * @param aLogWriter PrintWriter which is used for log() calls
- * @param aResourceBaseURL Resource base URL
- */
- public JspCServletContext(PrintWriter aLogWriter, URL aResourceBaseURL, ClassLoader classLoader)
- throws JasperException {
-
- myAttributes = new Hashtable();
- myParameters = new ConcurrentHashMap();
- myLogWriter = aLogWriter;
- myResourceBaseURL = aResourceBaseURL;
- this.loader = classLoader;
-
- }
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Return the specified context attribute, if any.
- *
- * @param name Name of the requested attribute
- */
- @Override
- public Object getAttribute(String name) {
-
- return (myAttributes.get(name));
-
- }
-
-
- /**
- * Return an enumeration of context attribute names.
- */
- @Override
- public Enumeration getAttributeNames() {
-
- return (myAttributes.keys());
-
- }
-
-
- /**
- * Return the servlet context for the specified path.
- *
- * @param uripath Server-relative path starting with '/'
- */
- @Override
- public ServletContext getContext(String uripath) {
-
- return (null);
-
- }
-
-
- /**
- * Return the context path.
- */
- @Override
- public String getContextPath() {
-
- return (null);
-
- }
-
-
- /**
- * Return the specified context initialization parameter.
- *
- * @param name Name of the requested parameter
- */
- @Override
- public String getInitParameter(String name) {
- return myParameters.get(name);
- }
-
-
- /**
- * Return an enumeration of the names of context initialization
- * parameters.
- */
- @Override
- public Enumeration getInitParameterNames() {
- return myParameters.keys();
- }
-
-
- /**
- * Return the Servlet API major version number.
- */
- @Override
- public int getMajorVersion() {
-
- return (3);
-
- }
-
-
- /**
- * Return the MIME type for the specified filename.
- *
- * @param file Filename whose MIME type is requested
- */
- @Override
- public String getMimeType(String file) {
-
- return (null);
-
- }
-
-
- /**
- * Return the Servlet API minor version number.
- */
- @Override
- public int getMinorVersion() {
-
- return (0);
-
- }
-
-
- /**
- * Return a request dispatcher for the specified servlet name.
- *
- * @param name Name of the requested servlet
- */
- @Override
- public RequestDispatcher getNamedDispatcher(String name) {
-
- return (null);
-
- }
-
-
- /**
- * Return the real path for the specified context-relative
- * virtual path.
- *
- * @param path The context-relative virtual path to resolve
- */
- @Override
- public String getRealPath(String path) {
-
- if (!myResourceBaseURL.getProtocol().equals("file"))
- return null;
- if (!path.startsWith("/"))
- return null;
- try {
- File f = new File(getResource(path).toURI());
- return f.getAbsolutePath();
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- return null;
- }
- }
-
-
- /**
- * Return a request dispatcher for the specified context-relative path.
- *
- * @param path Context-relative path for which to acquire a dispatcher
- */
- @Override
- public RequestDispatcher getRequestDispatcher(String path) {
-
- return (null);
-
- }
-
-
- /**
- * 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 '/'");
- URL url = new URL(myResourceBaseURL, path.substring(1));
- InputStream is = null;
- try {
- is = url.openStream();
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- url = null;
- } finally {
- if (is != null) {
- try {
- is.close();
- } catch (Throwable t2) {
- ExceptionUtils.handleThrowable(t2);
- }
- }
- }
- return url;
-
- }
-
-
- /**
- * Return an InputStream allowing access to the resource at the
- * specified context-relative path.
- *
- * @param path Context-relative path of the desired resource
- */
- @Override
- public InputStream getResourceAsStream(String path) {
-
- try {
- return (getResource(path).openStream());
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- return (null);
- }
-
- }
-
-
- /**
- * Return the set of resource paths for the "directory" at the
- * specified context path.
- *
- * @param path Context-relative base path
- */
- @Override
- public Set getResourcePaths(String path) {
-
- Set thePaths = new HashSet();
- if (!path.endsWith("/"))
- path += "/";
- String basePath = getRealPath(path);
- if (basePath == null)
- return (thePaths);
- File theBaseDir = new File(basePath);
- if (!theBaseDir.exists() || !theBaseDir.isDirectory())
- return (thePaths);
- String theFiles[] = theBaseDir.list();
- 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] + "/");
- }
- return (thePaths);
-
- }
-
-
- /**
- * Return descriptive information about this server.
- */
- @Override
- public String getServerInfo() {
-
- return ("JspCServletContext/1.0");
-
- }
-
-
- /**
- * Return a null reference for the specified servlet name.
- *
- * @param name Name of the requested servlet
- *
- * @deprecated This method has been deprecated with no replacement
- */
- @Override
- @Deprecated
- public Servlet getServlet(String name) throws ServletException {
-
- return (null);
-
- }
-
-
- /**
- * Return the name of this servlet context.
- */
- @Override
- public String getServletContextName() {
-
- return (getServerInfo());
-
- }
-
-
- /**
- * Return an empty enumeration of servlet names.
- *
- * @deprecated This method has been deprecated with no replacement
- */
- @Override
- @Deprecated
- public Enumeration getServletNames() {
-
- return (new Vector().elements());
-
- }
-
-
- /**
- * Return an empty enumeration of servlets.
- *
- * @deprecated This method has been deprecated with no replacement
- */
- @Override
- @Deprecated
- public Enumeration getServlets() {
-
- return (new Vector().elements());
-
- }
-
-
- /**
- * Log the specified message.
- *
- * @param message The message to be logged
- */
- @Override
- public void log(String message) {
-
- myLogWriter.println(message);
-
- }
-
-
- /**
- * Log the specified message and exception.
- *
- * @param exception The exception to be logged
- * @param message The message to be logged
- *
- * @deprecated Use log(String,Throwable) instead
- */
- @Override
- @Deprecated
- public void log(Exception exception, String message) {
-
- log(message, exception);
-
- }
-
-
- /**
- * Log the specified message and exception.
- *
- * @param message The message to be logged
- * @param exception The exception to be logged
- */
- @Override
- public void log(String message, Throwable exception) {
-
- myLogWriter.println(message);
- exception.printStackTrace(myLogWriter);
-
- }
-
-
- /**
- * Remove the specified context attribute.
- *
- * @param name Name of the attribute to remove
- */
- @Override
- public void removeAttribute(String name) {
-
- myAttributes.remove(name);
-
- }
-
-
- /**
- * Set or replace the specified context attribute.
- *
- * @param name Name of the context attribute to set
- * @param value Corresponding attribute value
- */
- @Override
- public void setAttribute(String name, Object value) {
-
- myAttributes.put(name, value);
-
- }
-
-
- @Override
- public FilterRegistration.Dynamic addFilter(String filterName,
- String className) {
- return null;
- }
-
-
- @Override
- public ServletRegistration.Dynamic addServlet(String servletName,
- String className) {
- return null;
- }
-
-
- @Override
- public Set getDefaultSessionTrackingModes() {
- return EnumSet.noneOf(SessionTrackingMode.class);
- }
-
-
- @Override
- public Set getEffectiveSessionTrackingModes() {
- return EnumSet.noneOf(SessionTrackingMode.class);
- }
-
-
- @Override
- public SessionCookieConfig getSessionCookieConfig() {
- return null;
- }
-
-
- @Override
- public void setSessionTrackingModes(
- Set sessionTrackingModes) {
- // Do nothing
- }
-
-
- @Override
- public Dynamic addFilter(String filterName, Filter filter) {
- return null;
- }
-
-
- @Override
- public Dynamic addFilter(String filterName,
- Class extends Filter> filterClass) {
- return null;
- }
-
-
- @Override
- public ServletRegistration.Dynamic addServlet(String servletName,
- Servlet servlet) {
- return null;
- }
-
-
- @Override
- public ServletRegistration.Dynamic addServlet(String servletName,
- Class extends Servlet> servletClass) {
- return null;
- }
-
-
- @Override
- public T createFilter(Class c)
- throws ServletException {
- return null;
- }
-
-
- @Override
- public T createServlet(Class c)
- throws ServletException {
- return null;
- }
-
-
- @Override
- public FilterRegistration getFilterRegistration(String filterName) {
- return null;
- }
-
-
- @Override
- public ServletRegistration getServletRegistration(String servletName) {
- return null;
- }
-
-
- @Override
- public boolean setInitParameter(String name, String value) {
- return myParameters.putIfAbsent(name, value) == null;
- }
-
-
- @Override
- public void addListener(Class extends EventListener> listenerClass) {
- // NOOP
- }
-
-
- @Override
- public void addListener(String className) {
- // NOOP
- }
-
-
- @Override
- public void addListener(T t) {
- // NOOP
- }
-
-
- @Override
- public T createListener(Class c)
- throws ServletException {
- return null;
- }
-
-
- @Override
- public void declareRoles(String... roleNames) {
- // NOOP
- }
-
-
- @Override
- public ClassLoader getClassLoader() {
- return loader;
- }
-
-
- @Override
- public int getEffectiveMajorVersion() {
- return 3;
- }
-
-
- @Override
- public int getEffectiveMinorVersion() {
- return 0;
- }
-
-
- @Override
- public Map getFilterRegistrations() {
- return null;
- }
-
-
- @Override
- public JspConfigDescriptor getJspConfigDescriptor() {
- return null;
- }
-
-
- @Override
- public Map getServletRegistrations() {
- return null;
- }
-
- //@Override
- public String getVirtualServerName() {
- throw new UnsupportedOperationException("TJWS will do it");
- }
-
-}
diff --git a/1.x/src/jasper7-6x/JspCompilationContext.java b/1.x/src/jasper7-6x/JspCompilationContext.java
deleted file mode 100644
index a4bfbe7..0000000
--- a/1.x/src/jasper7-6x/JspCompilationContext.java
+++ /dev/null
@@ -1,821 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.net.JarURLConnection;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.net.URLConnection;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import javax.servlet.ServletContext;
-import javax.servlet.jsp.tagext.TagInfo;
-
-import org.apache.jasper.compiler.Compiler;
-import org.apache.jasper.compiler.JarResource;
-import org.apache.jasper.compiler.JspRuntimeContext;
-import org.apache.jasper.compiler.JspUtil;
-import org.apache.jasper.compiler.Localizer;
-import org.apache.jasper.compiler.ServletWriter;
-import org.apache.jasper.compiler.TldLocation;
-import org.apache.jasper.servlet.JasperLoader;
-import org.apache.jasper.servlet.JspServletWrapper;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-
-/**
- * A place holder for various things that are used through out the JSP
- * engine. This is a per-request/per-context data structure. Some of
- * the instance variables are set at different points.
- *
- * Most of the path-related stuff is here - mangling names, versions, dirs,
- * loading resources and dealing with uris.
- *
- * @author Anil K. Vijendran
- * @author Harish Prabandham
- * @author Pierre Delisle
- * @author Costin Manolache
- * @author Kin-man Chung
- */
-public class JspCompilationContext {
-
- private final Log log = LogFactory.getLog(JspCompilationContext.class); // must not be static
-
- protected Map tagFileJarUrls;
-
- protected String className;
- protected String jspUri;
- protected String basePackageName;
- protected String derivedPackageName;
- protected String servletJavaFileName;
- protected String javaPath;
- protected String classFileName;
- protected ServletWriter writer;
- protected Options options;
- protected JspServletWrapper jsw;
- protected Compiler jspCompiler;
- protected String classPath;
-
- protected String baseURI;
- protected String outputDir;
- protected ServletContext context;
- protected ClassLoader loader;
-
- protected JspRuntimeContext rctxt;
-
- protected volatile int removed = 0;
-
- protected URLClassLoader jspLoader;
- protected URL baseUrl;
- protected Class> servletClass;
-
- protected boolean isTagFile;
- protected boolean protoTypeMode;
- protected TagInfo tagInfo;
- protected JarResource tagJarResource;
-
- // jspURI _must_ be relative to the context
- public JspCompilationContext(String jspUri,
- Options options,
- ServletContext context,
- JspServletWrapper jsw,
- JspRuntimeContext rctxt) {
-
- this.jspUri = canonicalURI(jspUri);
- this.options = options;
- this.jsw = jsw;
- this.context = context;
-
- this.baseURI = jspUri.substring(0, jspUri.lastIndexOf('/') + 1);
- // hack fix for resolveRelativeURI
- if (baseURI == null) {
- 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.rctxt = rctxt;
- this.tagFileJarUrls = new HashMap();
- this.basePackageName = Constants.JSP_PACKAGE_NAME;
- }
-
- public JspCompilationContext(String tagfile,
- TagInfo tagInfo,
- Options options,
- ServletContext context,
- JspServletWrapper jsw,
- JspRuntimeContext rctxt,
- JarResource tagJarResource) {
- this(tagfile, options, context, jsw, rctxt);
- this.isTagFile = true;
- this.tagInfo = tagInfo;
- this.tagJarResource = tagJarResource;
- }
-
- /* ==================== Methods to override ==================== */
-
- /** ---------- Class path and loader ---------- */
-
- /**
- * The classpath that is passed off to the Java compiler.
- */
- public String getClassPath() {
- if( classPath != null ) {
- return classPath;
- }
- return rctxt.getClassPath();
- }
-
- /**
- * The classpath that is passed off to the Java compiler.
- */
- public void setClassPath(String classPath) {
- this.classPath = classPath;
- }
-
- /**
- * What class loader to use for loading classes while compiling
- * this JSP?
- */
- public ClassLoader getClassLoader() {
- if( loader != null ) {
- return loader;
- }
- return rctxt.getParentClassLoader();
- }
-
- public void setClassLoader(ClassLoader loader) {
- this.loader = loader;
- }
-
- public ClassLoader getJspLoader() {
- if( jspLoader == null ) {
- jspLoader = new JasperLoader
- (new URL[] {baseUrl},
- getClassLoader(),
- rctxt.getPermissionCollection());
- }
- return jspLoader;
- }
-
- public void clearJspLoader() {
- jspLoader = null;
- }
-
- /** ---------- Input/Output ---------- */
-
- /**
- * The output directory to generate code into. The output directory
- * is make up of the scratch directory, which is provide in Options,
- * plus the directory derived from the package name.
- */
- public String getOutputDir() {
- if (outputDir == null) {
- createOutputDir();
- }
-
- return outputDir;
- }
-
- /**
- * Create a "Compiler" object based on some init param data. This
- * is not done yet. Right now we're just hardcoding the actual
- * compilers that are created.
- */
- public Compiler createCompiler() {
- if (jspCompiler != null ) {
- return jspCompiler;
- }
- jspCompiler = null;
- jspCompiler = createCompiler("org.apache.jasper.compiler.BeeCompiler");
- if (jspCompiler == null) {
- throw new IllegalStateException(Localizer.getMessage("jsp.error.compiler"));
- }
- jspCompiler.init(this, jsw);
- return jspCompiler;
- }
-
- protected Compiler createCompiler(String className) {
- Compiler compiler = null;
- try {
- compiler = (Compiler) Class.forName(className).newInstance();
- } catch (InstantiationException e) {
- log.warn(Localizer.getMessage("jsp.error.compiler"), e);
- } catch (IllegalAccessException e) {
- log.warn(Localizer.getMessage("jsp.error.compiler"), e);
- } catch (NoClassDefFoundError e) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage("jsp.error.compiler"), e);
- }
- } catch (ClassNotFoundException e) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage("jsp.error.compiler"), e);
- }
- }
- return compiler;
- }
-
- public Compiler getCompiler() {
- return jspCompiler;
- }
-
- /** ---------- Access resources in the webapp ---------- */
-
- /**
- * Get the full value of a URI relative to this compilations context
- * uses current file as the base.
- */
- public String resolveRelativeUri(String uri) {
- // sometimes we get uri's massaged from File(String), so check for
- // a root directory separator char
- if (uri.startsWith("/") || uri.startsWith(File.separator)) {
- return uri;
- } else {
- return baseURI + uri;
- }
- }
-
- /**
- * Gets a resource as a stream, relative to the meanings of this
- * context's implementation.
- * @return a null if the resource cannot be found or represented
- * as an InputStream.
- */
- public java.io.InputStream getResourceAsStream(String res) {
- return context.getResourceAsStream(canonicalURI(res));
- }
-
-
- public URL getResource(String res) throws MalformedURLException {
- URL result = null;
-
- if (res.startsWith("/META-INF/")) {
- // This is a tag file packaged in a jar that is being compiled
- JarResource jarResource = tagFileJarUrls.get(res);
- if (jarResource == null) {
- jarResource = tagJarResource;
- }
- if (jarResource != null) {
- result = jarResource.getEntry(res.substring(1));
- } else {
- // May not be in a JAR in some IDE environments
- result = context.getResource(canonicalURI(res));
- }
- } else if (res.startsWith("jar:jndi:")) {
- // This is a tag file packaged in a jar that is being checked
- // for a dependency
- result = new URL(res);
-
- } else {
- result = context.getResource(canonicalURI(res));
- }
- return result;
- }
-
-
- public Set getResourcePaths(String path) {
- return context.getResourcePaths(canonicalURI(path));
- }
-
- /**
- * Gets the actual path of a URI relative to the context of
- * the compilation.
- */
- public String getRealPath(String path) {
- if (context != null) {
- return context.getRealPath(path);
- }
- return path;
- }
-
- /**
- * Returns the tag-file-name-to-JAR-file map of this compilation unit,
- * which maps tag file names to the JAR files in which the tag files are
- * packaged.
- *
- * The map is populated when parsing the tag-file elements of the TLDs
- * of any imported taglibs.
- */
- public JarResource getTagFileJarResource(String tagFile) {
- return this.tagFileJarUrls.get(tagFile);
- }
-
- public void setTagFileJarResource(String tagFile, JarResource jarResource) {
- this.tagFileJarUrls.put(tagFile, jarResource);
- }
-
- /**
- * Returns the JAR file in which the tag file for which this
- * JspCompilationContext was created is packaged, or null if this
- * JspCompilationContext does not correspond to a tag file, or if the
- * corresponding tag file is not packaged in a JAR.
- */
- public JarResource getTagFileJarResource() {
- return this.tagJarResource;
- }
-
- /* ==================== Common implementation ==================== */
-
- /**
- * Just the class name (does not include package name) of the
- * generated class.
- */
- public String getServletClassName() {
-
- if (className != null) {
- return className;
- }
-
- if (isTagFile) {
- className = tagInfo.getTagClassName();
- int lastIndex = className.lastIndexOf('.');
- if (lastIndex != -1) {
- className = className.substring(lastIndex + 1);
- }
- } else {
- int iSep = jspUri.lastIndexOf('/') + 1;
- className = JspUtil.makeJavaIdentifier(jspUri.substring(iSep));
- }
- return className;
- }
-
- public void setServletClassName(String className) {
- this.className = className;
- }
-
- /**
- * Path of the JSP URI. Note that this is not a file name. This is
- * the context rooted URI of the JSP file.
- */
- public String getJspFile() {
- return jspUri;
- }
-
- /**
- * @deprecated Will be removed in Tomcat 8.0.x. Use
- * {@link #getLastModified(String)} instead.
- */
- @Deprecated
- public long getJspLastModified() {
- long result = -1;
- URLConnection uc = null;
- try {
- URL jspUrl = getResource(getJspFile());
- if (jspUrl == null) {
- incrementRemoved();
- return result;
- }
- uc = jspUrl.openConnection();
- if (uc instanceof JarURLConnection) {
- result = ((JarURLConnection) uc).getJarEntry().getTime();
- } else {
- result = uc.getLastModified();
- }
- } catch (IOException e) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage(
- "jsp.error.lastModified", getJspFile()), e);
- }
- result = -1;
- } finally {
- if (uc != null) {
- try {
- uc.getInputStream().close();
- } catch (IOException e) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage(
- "jsp.error.lastModified", getJspFile()), e);
- }
- result = -1;
- }
- }
- }
- return result;
- }
-
-
- public Long getLastModified(String resource) {
- long result = -1;
- if (resource.startsWith("file:/")) {
- File f;
- try {
- f = new File(new URI(resource));
- } catch (URISyntaxException e) {
- return Long.valueOf(-1);
- }
- return Long.valueOf(f.lastModified());
- }
-
- URLConnection uc = null;
- try {
- URL jspUrl = getResource(resource);
- if (jspUrl == null) {
- incrementRemoved();
- return Long.valueOf(result);
- }
- File resFile = new File(jspUrl.getFile()); // TJWS on Android
- if (resFile.exists()) {
- result = resFile.lastModified();
- //System.err.printf("Android for %s is %d%n", jspUrl, result);
- } else {
- uc = jspUrl.openConnection();
- if (uc instanceof JarURLConnection) {
- result = ((JarURLConnection) uc).getJarEntry().getTime();
- } else {
- result = uc.getLastModified();
- }
- }
- } catch (IOException e) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage(
- "jsp.error.lastModified", getJspFile()), e);
- }
- result = -1;
- } finally {
- if (uc != null) {
- try {
- uc.getInputStream().close();
- } catch (IOException e) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage(
- "jsp.error.lastModified", getJspFile()), e);
- }
- result = -1;
- }
- }
- }
- return Long.valueOf(result);
- }
-
- public boolean isTagFile() {
- return isTagFile;
- }
-
- public TagInfo getTagInfo() {
- return tagInfo;
- }
-
- public void setTagInfo(TagInfo tagi) {
- tagInfo = tagi;
- }
-
- /**
- * True if we are compiling a tag file in prototype mode.
- * ie we only generate codes with class for the tag handler with empty
- * method bodies.
- */
- public boolean isPrototypeMode() {
- return protoTypeMode;
- }
-
- public void setPrototypeMode(boolean pm) {
- protoTypeMode = pm;
- }
-
- /**
- * Package name for the generated class is make up of the base package
- * name, which is user settable, and the derived package name. The
- * derived package name directly mirrors the file hierarchy of the JSP page.
- */
- public String getServletPackageName() {
- if (isTagFile()) {
- String className = tagInfo.getTagClassName();
- int lastIndex = className.lastIndexOf('.');
- String pkgName = "";
- if (lastIndex != -1) {
- pkgName = className.substring(0, lastIndex);
- }
- return pkgName;
- } else {
- String dPackageName = getDerivedPackageName();
- if (dPackageName.length() == 0) {
- return basePackageName;
- }
- return basePackageName + '.' + getDerivedPackageName();
- }
- }
-
- protected String getDerivedPackageName() {
- if (derivedPackageName == null) {
- int iSep = jspUri.lastIndexOf('/');
- derivedPackageName = (iSep > 0) ?
- JspUtil.makeJavaPackage(jspUri.substring(1,iSep)) : "";
- }
- return derivedPackageName;
- }
-
- /**
- * The package name into which the servlet class is generated.
- */
- public void setServletPackageName(String servletPackageName) {
- this.basePackageName = servletPackageName;
- }
-
- /**
- * Full path name of the Java file into which the servlet is being
- * generated.
- */
- public String getServletJavaFileName() {
- if (servletJavaFileName == null) {
- servletJavaFileName = getOutputDir() + getServletClassName() + ".java";
- }
- return servletJavaFileName;
- }
-
- /**
- * Get hold of the Options object for this context.
- */
- public Options getOptions() {
- return options;
- }
-
- public ServletContext getServletContext() {
- return context;
- }
-
- public JspRuntimeContext getRuntimeContext() {
- return rctxt;
- }
-
- /**
- * Path of the Java file relative to the work directory.
- */
- public String getJavaPath() {
-
- if (javaPath != null) {
- return javaPath;
- }
-
- if (isTagFile()) {
- String tagName = tagInfo.getTagClassName();
- javaPath = tagName.replace('.', '/') + ".java";
- } else {
- javaPath = getServletPackageName().replace('.', '/') + '/' +
- getServletClassName() + ".java";
- }
- return javaPath;
- }
-
- public String getClassFileName() {
- if (classFileName == null) {
- classFileName = getOutputDir() + getServletClassName() + ".class";
- }
- return classFileName;
- }
-
- /**
- * Where is the servlet being generated?
- */
- public ServletWriter getWriter() {
- return writer;
- }
-
- public void setWriter(ServletWriter writer) {
- this.writer = writer;
- }
-
- /**
- * Gets the 'location' of the TLD associated with the given taglib 'uri'.
- *
- * @return An array of two Strings: The first element denotes the real
- * 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.
- * Returns null if the given uri is not associated with any tag library
- * 'exposed' in the web application.
- */
- public TldLocation getTldLocation(String uri) throws JasperException {
- TldLocation location =
- getOptions().getTldLocationsCache().getLocation(uri);
- return location;
- }
-
- /**
- * Are we keeping generated code around?
- */
- public boolean keepGenerated() {
- return getOptions().getKeepGenerated();
- }
-
- // ==================== Removal ====================
-
- public void incrementRemoved() {
- if (removed == 0 && rctxt != null) {
- rctxt.removeWrapper(jspUri);
- }
- removed++;
- }
-
- public boolean isRemoved() {
- if (removed > 0 ) {
- return true;
- }
- return false;
- }
-
- // ==================== Compile and reload ====================
-
- public void compile() throws JasperException, FileNotFoundException {
- createCompiler();
- if (jspCompiler.isOutDated()) {
- if (isRemoved()) {
- throw new FileNotFoundException(jspUri);
- }
- try {
- jspCompiler.removeGeneratedFiles();
- jspLoader = null;
- jspCompiler.compile();
- jsw.setReload(true);
- jsw.setCompilationException(null);
- } catch (JasperException ex) {
- // Cache compilation exception
- jsw.setCompilationException(ex);
- if (options.getDevelopment() && options.getRecompileOnFail()) {
- // Force a recompilation attempt on next access
- jsw.setLastModificationTest(-1);
- }
- throw ex;
- } catch (FileNotFoundException fnfe) {
- // Re-throw to let caller handle this - will result in a 404
- throw fnfe;
- } catch (Exception ex) {
- JasperException je = new JasperException(
- Localizer.getMessage("jsp.error.unable.compile"),
- ex);
- // Cache compilation exception
- jsw.setCompilationException(je);
- throw je;
- }
- }
- }
-
- // ==================== Manipulating the class ====================
-
- public Class> load() throws JasperException {
- try {
- getJspLoader();
-
- String name = getFQCN();
- servletClass = jspLoader.loadClass(name);
- } catch (ClassNotFoundException cex) {
- throw new JasperException(Localizer.getMessage("jsp.error.unable.load"),
- cex);
- } catch (Exception ex) {
- throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"),
- ex);
- }
- removed = 0;
- return servletClass;
- }
-
- public String getFQCN() {
- String name;
- if (isTagFile()) {
- name = tagInfo.getTagClassName();
- } else {
- name = getServletPackageName() + "." + getServletClassName();
- }
- return name;
- }
-
- // ==================== protected methods ====================
-
- static Object outputDirLock = new Object();
-
- public void checkOutputDir() {
- if (outputDir != null) {
- if (!(new File(outputDir)).exists()) {
- makeOutputDir();
- }
- } else {
- createOutputDir();
- }
- }
-
- protected boolean makeOutputDir() {
- synchronized(outputDirLock) {
- File outDirFile = new File(outputDir);
- return (outDirFile.mkdirs() || outDirFile.isDirectory());
- }
- }
-
- protected void createOutputDir() {
- String path = null;
- if (isTagFile()) {
- String tagName = tagInfo.getTagClassName();
- path = tagName.replace('.', File.separatorChar);
- path = path.substring(0, path.lastIndexOf(File.separatorChar));
- } else {
- path = getServletPackageName().replace('.',File.separatorChar);
- }
-
- // Append servlet or tag handler path to scratch dir
- try {
- File base = options.getScratchDir();
- baseUrl = base.toURI().toURL();
- outputDir = base.getAbsolutePath() + File.separator + path +
- File.separator;
- if (!makeOutputDir()) {
- throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"));
- }
- } catch (MalformedURLException e) {
- throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e);
- }
- }
-
- protected static final boolean isPathSeparator(char c) {
- return (c == '/' || c == '\\');
- }
-
- protected static final String canonicalURI(String s) {
- if (s == null) {
- return null;
- }
- StringBuilder result = new StringBuilder();
- final int len = s.length();
- int pos = 0;
- while (pos < len) {
- char c = s.charAt(pos);
- if ( isPathSeparator(c) ) {
- /*
- * multiple path separators.
- * 'foo///bar' -> 'foo/bar'
- */
- while (pos+1 < len && isPathSeparator(s.charAt(pos+1))) {
- ++pos;
- }
-
- if (pos+1 < len && s.charAt(pos+1) == '.') {
- /*
- * a single dot at the end of the path - we are done.
- */
- if (pos+2 >= len) {
- break;
- }
-
- switch (s.charAt(pos+2)) {
- /*
- * self directory in path
- * foo/./bar -> foo/bar
- */
- case '/':
- case '\\':
- pos += 2;
- continue;
-
- /*
- * two dots in a path: go back one hierarchy.
- * foo/bar/../baz -> foo/baz
- */
- case '.':
- // only if we have exactly _two_ dots.
- if (pos+3 < len && isPathSeparator(s.charAt(pos+3))) {
- pos += 3;
- int separatorPos = result.length()-1;
- while (separatorPos >= 0 &&
- ! isPathSeparator(result
- .charAt(separatorPos))) {
- --separatorPos;
- }
- if (separatorPos >= 0) {
- result.setLength(separatorPos);
- }
- continue;
- }
- }
- }
- }
- result.append(c);
- ++pos;
- }
- return result.toString();
- }
-}
-
diff --git a/1.x/src/jasper7-6x/SimpleInstanceManager.java b/1.x/src/jasper7-6x/SimpleInstanceManager.java
deleted file mode 100644
index e6f64ad..0000000
--- a/1.x/src/jasper7-6x/SimpleInstanceManager.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package org.apache.jasper.tjws;
-
-import java.lang.reflect.InvocationTargetException;
-import javax.naming.NamingException;
-import org.apache.tomcat.InstanceManager;
-
-public class SimpleInstanceManager implements InstanceManager {
-
- public Object newInstance(Class> clazz)
- throws IllegalAccessException, InvocationTargetException, NamingException,
- InstantiationException {
- return clazz.newInstance();
- }
-
-
- public Object newInstance(String className) throws IllegalAccessException,
- InvocationTargetException, NamingException, InstantiationException,
- ClassNotFoundException {
- return Class.forName(className).newInstance();
- }
-
- public Object newInstance(String fqcn, ClassLoader classLoader)
- throws IllegalAccessException, InvocationTargetException,
- NamingException, InstantiationException, ClassNotFoundException {
- //System.err.printf("Requested new instance as %s with loader %s and parent %s%n", fqcn, classLoader, classLoader.getParent());
- try {
- return Class.forName(fqcn, true, classLoader).newInstance();
- } catch (ClassNotFoundException cnfe) {
- //System.err.printf("Exceprion %s%n", cnfe);
- // trying parent loader for Android
- }
- return Class.forName(fqcn, true, classLoader.getParent()).newInstance();
- }
-
- public void newInstance(Object o) throws IllegalAccessException,
- InvocationTargetException, NamingException {
- //System.err.printf("New instance for object %s", o);
- }
-
- public void destroyInstance(Object o) throws IllegalAccessException,
- InvocationTargetException {
- //System.err.printf("Destroying object %s", o);
- }
-
-}
\ No newline at end of file
diff --git a/1.x/src/jasper7-6x/Util.java b/1.x/src/jasper7-6x/Util.java
deleted file mode 100644
index 742f0fb..0000000
--- a/1.x/src/jasper7-6x/Util.java
+++ /dev/null
@@ -1,353 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tagplugins.jstl;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.io.UnsupportedEncodingException;
-import java.util.Locale;
-
-import javax.servlet.ServletOutputStream;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpServletResponseWrapper;
-import javax.servlet.jsp.JspException;
-import javax.servlet.jsp.JspTagException;
-import javax.servlet.jsp.PageContext;
-
-import org.apache.jasper.Constants;
-
-/**
- * Util contains some often used consts, static methods and embedded class
- * to support the JSTL tag plugin.
- */
-
-public class Util {
-
- public static final String VALID_SCHEME_CHAR =
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+.-";
-
- public static final String DEFAULT_ENCODING =
- "ISO-8859-1";
-
- public static final int HIGHEST_SPECIAL = '>';
-
- private static char[][] specialCharactersRepresentation = new char[HIGHEST_SPECIAL + 1][];
-
- static {
- specialCharactersRepresentation['&'] = "&".toCharArray();
- specialCharactersRepresentation['<'] = "<".toCharArray();
- specialCharactersRepresentation['>'] = ">".toCharArray();
- specialCharactersRepresentation['"'] = """.toCharArray();
- specialCharactersRepresentation['\''] = "'".toCharArray();
- }
-
- /**
- * Converts the given string description of a scope to the corresponding
- * PageContext constant.
- *
- * The validity of the given scope has already been checked by the
- * appropriate TLV.
- *
- * @param scope String description of scope
- *
- * @return PageContext constant corresponding to given scope description
- *
- * taken from org.apache.taglibs.standard.tag.common.core.Util
- */
- public static int getScope(String scope){
- int ret = PageContext.PAGE_SCOPE;
-
- if("request".equalsIgnoreCase(scope)){
- ret = PageContext.REQUEST_SCOPE;
- }else if("session".equalsIgnoreCase(scope)){
- ret = PageContext.SESSION_SCOPE;
- }else if("application".equalsIgnoreCase(scope)){
- ret = PageContext.APPLICATION_SCOPE;
- }
-
- return ret;
- }
-
- /**
- * Returns true if our current URL is absolute,
- * false otherwise.
- * taken from org.apache.taglibs.standard.tag.common.core.ImportSupport
- */
- public static boolean isAbsoluteUrl(String url){
- if(url == null){
- return false;
- }
-
- int colonPos = url.indexOf(":");
- if(colonPos == -1){
- return false;
- }
-
- for(int i=0;iurl. The session ID
- * is encoded as a URL "path parameter" beginning with "jsessionid=".
- * We thus remove anything we find between ";jsessionid=" (inclusive)
- * and either EOS or a subsequent ';' (exclusive).
- *
- * taken from org.apache.taglibs.standard.tag.common.core.ImportSupport
- */
- public static String stripSession(String url) {
- StringBuilder u = new StringBuilder(url);
- int sessionStart;
- while ((sessionStart = u.toString().indexOf(";" + Constants.SESSION_PARAMETER_NAME + "=")) != -1) {
- int sessionEnd = u.toString().indexOf(";", sessionStart + 1);
- if (sessionEnd == -1)
- sessionEnd = u.toString().indexOf("?", sessionStart + 1);
- if (sessionEnd == -1) // still
- sessionEnd = u.length();
- u.delete(sessionStart, sessionEnd);
- }
- return u.toString();
- }
-
-
- /**
- * Performs the following substring replacements
- * (to facilitate output to XML/HTML pages):
- *
- * & -> &
- * < -> <
- * > -> >
- * " -> "
- * ' -> '
- *
- * See also OutSupport.writeEscapedXml().
- *
- * taken from org.apache.taglibs.standard.tag.common.core.Util
- */
- public static String escapeXml(String buffer) {
- String result = escapeXml(buffer.toCharArray(), buffer.length());
- if (result == null) {
- return buffer;
- } else {
- return result;
- }
- }
-
- @SuppressWarnings("null") // escapedBuffer cannot be null
- public static String escapeXml(char[] arrayBuffer, int length) {
- int start = 0;
- StringBuilder escapedBuffer = null;
-
- for (int i = 0; i < length; i++) {
- char c = arrayBuffer[i];
- if (c <= HIGHEST_SPECIAL) {
- char[] escaped = specialCharactersRepresentation[c];
- if (escaped != null) {
- // create StringBuilder to hold escaped xml string
- if (start == 0) {
- escapedBuffer = new StringBuilder(length + 5);
- }
- // add unescaped portion
- if (start < i) {
- escapedBuffer.append(arrayBuffer,start,i-start);
- }
- start = i + 1;
- // add escaped xml
- escapedBuffer.append(escaped);
- }
- }
- }
- // no xml escaping was necessary
- if (start == 0) {
- return null;
- }
- // add rest of unescaped portion
- if (start < length) {
- escapedBuffer.append(arrayBuffer,start,length-start);
- }
- return escapedBuffer.toString();
- }
-
- /** Utility methods
- * taken from org.apache.taglibs.standard.tag.common.core.UrlSupport
- */
- public static String resolveUrl(
- String url, String context, PageContext pageContext)
- throws JspException {
- // don't touch absolute URLs
- if (isAbsoluteUrl(url))
- return url;
-
- // normalize relative URLs against a context root
- HttpServletRequest request =
- (HttpServletRequest) pageContext.getRequest();
- if (context == null) {
- if (url.startsWith("/"))
- return (request.getContextPath() + url);
- else
- return url;
- } else {
- if (!context.startsWith("/") || !url.startsWith("/")) {
- throw new JspTagException(
- "In URL tags, when the \"context\" attribute is specified, values of both \"context\" and \"url\" must start with \"/\".");
- }
- if (context.equals("/")) {
- // Don't produce string starting with '//', many
- // browsers interpret this as host name, not as
- // path on same host.
- return url;
- } else {
- return (context + url);
- }
- }
- }
-
- /** Wraps responses to allow us to retrieve results as Strings.
- * mainly taken from org.apache.taglibs.standard.tag.common.core.importSupport
- */
- public static class ImportResponseWrapper extends HttpServletResponseWrapper{
-
- private StringWriter sw = new StringWriter();
- private ByteArrayOutputStream bos = new ByteArrayOutputStream();
- private ServletOutputStream sos = new ServletOutputStream() {
- @Override
- public void write(int b) throws IOException {
- bos.write(b);
- }
- // @Override
- public void setWriteListener(javax.servlet.WriteListener writeListener) {
- // TODO implement it, or borrow from Tomcat 8
- }
- // @Override
- public boolean isReady() {
- return true;
- }
-
- };
- private boolean isWriterUsed;
- private boolean isStreamUsed;
- private int status = 200;
- private String charEncoding;
-
- public ImportResponseWrapper(HttpServletResponse arg0) {
- super(arg0);
- // TODO Auto-generated constructor stub
- }
-
- @Override
- public PrintWriter getWriter() {
- if (isStreamUsed)
- throw new IllegalStateException("Unexpected internal error during <import>: " +
- "Target servlet called getWriter(), then getOutputStream()");
- isWriterUsed = true;
- return new PrintWriter(sw);
- }
-
- @Override
- public ServletOutputStream getOutputStream() {
- if (isWriterUsed)
- throw new IllegalStateException("Unexpected internal error during <import>: " +
- "Target servlet called getOutputStream(), then getWriter()");
- isStreamUsed = true;
- return sos;
- }
-
- /** Has no effect. */
- @Override
- public void setContentType(String x) {
- // ignore
- }
-
- /** Has no effect. */
- @Override
- public void setLocale(Locale x) {
- // ignore
- }
-
- @Override
- public void setStatus(int status) {
- this.status = status;
- }
-
- @Override
- public int getStatus() {
- return status;
- }
-
- public String getCharEncoding(){
- return this.charEncoding;
- }
-
- public void setCharEncoding(String ce){
- this.charEncoding = ce;
- }
-
- public String getString() throws UnsupportedEncodingException {
- if (isWriterUsed)
- return sw.toString();
- else if (isStreamUsed) {
- if (this.charEncoding != null && !this.charEncoding.equals(""))
- return bos.toString(charEncoding);
- else
- return bos.toString("ISO-8859-1");
- } else
- return ""; // target didn't write anything
- }
-
- }
-
-}
diff --git a/1.x/src/jasper7-6x/bee-jasper.xml b/1.x/src/jasper7-6x/bee-jasper.xml
deleted file mode 100644
index 5314734..0000000
--- a/1.x/src/jasper7-6x/bee-jasper.xml
+++ /dev/null
@@ -1,451 +0,0 @@
-
-
-
-
-
-
-
-
-
-
- ]>
-
-
-
- &env;
-
-
-
-
- /bin/javac
-
-
-
-
-
-
- /bin/javadoc
-
-
-
-
-
- ******** &project; Build Process ********
-********* Available targets: *************************************
-* compile - do Java compilation *
-* jar - build &build_file; file *
-* run - run application &main_class; *
-*******************************************************************
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- /&build_directory;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Compiling javax...
-
-
-
-
-
-
-
-
-
- >
-
-
-
- 0
-
-
- Error(s) at compilation of javax
-
-
-
-
-
-
-
-
- Exception at compilation of javax
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Compiling... &project;
-
-
-
-
-
-
-
-
-
- >
-
-
-
- 0
-
-
- Error(s) at compilation of &project;
-
-
-
-
-
-
-
-
- Exception at compilation of &project;
-
-
-
-
-
-
-
-
-
- &manifestf;
-
-
-
-
- true
-
-
-
- -d
-
- -sourcepath
-
- -classpath
-
- &domain;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- &source_directory;/javax/servlet/jsp/resources/jsp*.dtd
- &build_directory;/javax/servlet/jsp/resources
- &source_directory;/javax/servlet/jsp/resources/jsp*.xsd
- &build_directory;/javax/servlet/jsp/resources
- &source_directory;/javax/servlet/jsp/resources/web-jsp*.dtd
- &build_directory;/javax/servlet/jsp/resources
- &source_directory;/javax/servlet/jsp/resources/web-jsp*.xsd
- &build_directory;/javax/servlet/jsp/resources
-
- &source_directory;/javax/servlet/resources/j2ee*.dtd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/j2ee*.xsd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/javaee_*.xsd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/web-app*.dtd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/web-*.xsd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/datatypes.dtd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/xml.xsd
- &build_directory;/javax/servlet/resources
- &source_directory;/javax/servlet/resources/XMLSchema.dtd
- &build_directory;/javax/servlet/resources
-
-
-
-
-
-
-
-
-
-
-
-
- Jarring...
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -cf
-
-
-
- -cmf
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- java
- org/apache/jasper/resources
-
-
-
-
-
-
- -C
- &source_directory;
-
-
-
-
-
-
-
-
-
-
-
- -C
- &source_directory;
-
-
-
-
-
-
-
-
-
-
-
- -C
- &source_directory;
-
-
-
-
-
-
-
-
-
-
-
-
- -C
- &source_directory;
-
-
-
-
-
-
-
-
-
-
-
- -C
- &source_directory;
-
-
-
-
-
-
-
-
-
- Exception at jarring
-
-
-
-
-
-
-
-
-
-
-
-
- y
-
-
-
-
-
-
-
-
- Cleaning...
-
-
-
-
-
-
-
-
-
-
- /&build_directory;/&build_file;
-
-
-
-
- /lib/tools.jar
-
-
-
-
- Running...
-
-
-
- -classpath
-
-
-
-
-
-
diff --git a/1.x/src/jasper7-6x/env.xml b/1.x/src/jasper7-6x/env.xml
deleted file mode 100644
index 270b948..0000000
--- a/1.x/src/jasper7-6x/env.xml
+++ /dev/null
@@ -1,48 +0,0 @@
-
-
-
-
- .
-
-
-
-
-
-
- /
-
-
-
-
-
-
-
-
- /jre
-
-
-
-
-
-
-
-
-
-
- maven:javax.servlet:javax.servlet-api:3.1.0
-
- 1.6
-
-
-
- \\jre
-
-
-
-
-
-
-
-
-
diff --git a/1.x/src/jasper7-7x/EmbeddedServletOptions.java b/1.x/src/jasper7-7x/EmbeddedServletOptions.java
deleted file mode 100644
index fae23f3..0000000
--- a/1.x/src/jasper7-7x/EmbeddedServletOptions.java
+++ /dev/null
@@ -1,789 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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;
-
-import java.io.File;
-import java.util.Enumeration;
-import java.util.Map;
-import java.util.Properties;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.jsp.tagext.TagLibraryInfo;
-
-import org.apache.jasper.compiler.JspConfig;
-import org.apache.jasper.compiler.Localizer;
-import org.apache.jasper.compiler.TagPluginManager;
-import org.apache.jasper.compiler.TldLocationsCache;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-
-/**
- * A class to hold all init parameters specific to the JSP engine.
- *
- * @author Anil K. Vijendran
- * @author Hans Bergsten
- * @author Pierre Delisle
- */
-public final class EmbeddedServletOptions implements Options {
-
- // Logger
- private final Log log = LogFactory.getLog(EmbeddedServletOptions.class);
-
- private Properties settings = new Properties();
-
- /**
- * Is Jasper being used in development mode?
- */
- private boolean development = true;
-
- /**
- * Should Ant fork its java compiles of JSP pages.
- */
- public boolean fork = true;
-
- /**
- * Do you want to keep the generated Java files around?
- */
- private boolean keepGenerated = true;
-
- /**
- * Should white spaces between directives or actions be trimmed?
- */
- private boolean trimSpaces = false;
-
- /**
- * Determines whether tag handler pooling is enabled.
- */
- private boolean isPoolingEnabled = true;
-
- /**
- * Do you want support for "mapped" files? This will generate
- * servlet that has a print statement per line of the JSP file.
- * This seems like a really nice feature to have for debugging.
- */
- private boolean mappedFile = true;
-
- /**
- * Do we want to include debugging information in the class file?
- */
- private boolean classDebugInfo = true;
-
- /**
- * Background compile thread check interval in seconds.
- */
- private int checkInterval = 0;
-
- /**
- * Is the generation of SMAP info for JSR45 debugging suppressed?
- */
- private boolean isSmapSuppressed = false;
-
- /**
- * Should SMAP info for JSR45 debugging be dumped to a file?
- */
- private boolean isSmapDumped = false;
-
- /**
- * Are Text strings to be generated as char arrays?
- */
- private boolean genStringAsCharArray = false;
-
- private boolean errorOnUseBeanInvalidClassAttribute = true;
-
- /**
- * I want to see my generated servlets. Which directory are they
- * in?
- */
- private File scratchDir;
-
- /**
- * Need to have this as is for versions 4 and 5 of IE. Can be set from
- * the initParams so if it changes in the future all that is needed is
- * to have a jsp initParam of type ieClassId=""
- */
- private String ieClassId = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";
-
- /**
- * What classpath should I use while compiling generated servlets?
- */
- private String classpath = null;
-
- /**
- * Compiler to use.
- */
- private String compiler = null;
-
- /**
- * Compiler target VM.
- */
- private String compilerTargetVM = "1.6";
-
- /**
- * The compiler source VM.
- */
- private String compilerSourceVM = "1.6";
-
- /**
- * The compiler class name.
- */
- private String compilerClassName = null;
-
- /**
- * Cache for the TLD locations
- */
- private TldLocationsCache tldLocationsCache = null;
-
- /**
- * Jsp config information
- */
- private JspConfig jspConfig = null;
-
- /**
- * TagPluginManager
- */
- private TagPluginManager tagPluginManager = null;
-
- /**
- * Java platform encoding to generate the JSP
- * page servlet.
- */
- private String javaEncoding = "UTF8";
-
- /**
- * Modification test interval.
- */
- private int modificationTestInterval = 4;
-
- /**
- * Is re-compilation attempted immediately after a failure?
- */
- private boolean recompileOnFail = false;
-
- /**
- * Is generation of X-Powered-By response header enabled/disabled?
- */
- private boolean xpoweredBy;
-
- /**
- * Should we include a source fragment in exception messages, which could be displayed
- * to the developer ?
- */
- private boolean displaySourceFragment = true;
-
-
- /**
- * The maximum number of loaded jsps per web-application. If there are more
- * jsps loaded, they will be unloaded.
- */
- private int maxLoadedJsps = -1;
-
- /**
- * The idle time in seconds after which a JSP is unloaded.
- * If unset or less or equal than 0, no jsps are unloaded.
- */
- private int jspIdleTimeout = -1;
-
- /**
- * When EL is used in JSP attribute values, should the rules for quoting of
- * attributes described in JSP.1.6 be applied to the expression?
- */
- private boolean quoteAttributeEL = true;
-
- public String getProperty(String name ) {
- return settings.getProperty( name );
- }
-
- public void setProperty(String name, String value ) {
- if (name != null && value != null){
- settings.setProperty( name, value );
- }
- }
-
- public void setQuoteAttributeEL(boolean b) {
- this.quoteAttributeEL = b;
- }
-
- @Override
- public boolean getQuoteAttributeEL() {
- return quoteAttributeEL;
- }
-
- /**
- * Are we keeping generated code around?
- */
- @Override
- public boolean getKeepGenerated() {
- return keepGenerated;
- }
-
- /**
- * Should white spaces between directives or actions be trimmed?
- */
- @Override
- public boolean getTrimSpaces() {
- return trimSpaces;
- }
-
- @Override
- public boolean isPoolingEnabled() {
- return isPoolingEnabled;
- }
-
- /**
- * Are we supporting HTML mapped servlets?
- */
- @Override
- public boolean getMappedFile() {
- return mappedFile;
- }
-
- /**
- * Should class files be compiled with debug information?
- */
- @Override
- public boolean getClassDebugInfo() {
- return classDebugInfo;
- }
-
- /**
- * Background JSP compile thread check interval
- */
- @Override
- public int getCheckInterval() {
- return checkInterval;
- }
-
- /**
- * Modification test interval.
- */
- @Override
- public int getModificationTestInterval() {
- return modificationTestInterval;
- }
-
- /**
- * Re-compile on failure.
- */
- @Override
- public boolean getRecompileOnFail() {
- return recompileOnFail;
- }
-
- /**
- * Is Jasper being used in development mode?
- */
- @Override
- public boolean getDevelopment() {
- return development;
- }
-
- /**
- * Is the generation of SMAP info for JSR45 debugging suppressed?
- */
- @Override
- public boolean isSmapSuppressed() {
- return isSmapSuppressed;
- }
-
- /**
- * Should SMAP info for JSR45 debugging be dumped to a file?
- */
- @Override
- public boolean isSmapDumped() {
- return isSmapDumped;
- }
-
- /**
- * Are Text strings to be generated as char arrays?
- */
- @Override
- public boolean genStringAsCharArray() {
- return this.genStringAsCharArray;
- }
-
- /**
- * Class ID for use in the plugin tag when the browser is IE.
- */
- @Override
- public String getIeClassId() {
- return ieClassId;
- }
-
- /**
- * What is my scratch dir?
- */
- @Override
- public File getScratchDir() {
- return scratchDir;
- }
-
- /**
- * What classpath should I use while compiling the servlets
- * generated from JSP files?
- */
- @Override
- public String getClassPath() {
- return classpath;
- }
-
- /**
- * Is generation of X-Powered-By response header enabled/disabled?
- */
- @Override
- public boolean isXpoweredBy() {
- return xpoweredBy;
- }
-
- /**
- * Compiler to use.
- */
- @Override
- public String getCompiler() {
- return compiler;
- }
-
- /**
- * @see Options#getCompilerTargetVM
- */
- @Override
- public String getCompilerTargetVM() {
- return compilerTargetVM;
- }
-
- /**
- * @see Options#getCompilerSourceVM
- */
- @Override
- public String getCompilerSourceVM() {
- return compilerSourceVM;
- }
-
- /**
- * Java compiler class to use.
- */
- @Override
- public String getCompilerClassName() {
- return compilerClassName;
- }
-
- @Override
- public boolean getErrorOnUseBeanInvalidClassAttribute() {
- return errorOnUseBeanInvalidClassAttribute;
- }
-
- public void setErrorOnUseBeanInvalidClassAttribute(boolean b) {
- errorOnUseBeanInvalidClassAttribute = b;
- }
-
- @Override
- public TldLocationsCache getTldLocationsCache() {
- return tldLocationsCache;
- }
-
- public void setTldLocationsCache( TldLocationsCache tldC ) {
- tldLocationsCache = tldC;
- }
-
- @Override
- public String getJavaEncoding() {
- return javaEncoding;
- }
-
- @Override
- public boolean getFork() {
- return fork;
- }
-
- @Override
- public JspConfig getJspConfig() {
- return jspConfig;
- }
-
- @Override
- public TagPluginManager getTagPluginManager() {
- return tagPluginManager;
- }
-
- @Override
- public boolean isCaching() {
- return false;
- }
-
- @Override
- public Map getCache() {
- return null;
- }
-
- /**
- * Should we include a source fragment in exception messages, which could be displayed
- * to the developer ?
- */
- @Override
- public boolean getDisplaySourceFragment() {
- return displaySourceFragment;
- }
-
- /**
- * Should jsps be unloaded if to many are loaded?
- * If set to a value greater than 0 eviction of jsps is started. Default: -1
- */
- @Override
- public int getMaxLoadedJsps() {
- return maxLoadedJsps;
- }
-
- /**
- * Should any jsps be unloaded when being idle for this time in seconds?
- * If set to a value greater than 0 eviction of jsps is started. Default: -1
- */
- @Override
- public int getJspIdleTimeout() {
- return jspIdleTimeout;
- }
-
- /**
- * Create an EmbeddedServletOptions object using data available from
- * ServletConfig and ServletContext.
- */
- public EmbeddedServletOptions(ServletConfig config,
- ServletContext context) {
-
- Enumeration enumeration=config.getInitParameterNames();
- while( enumeration.hasMoreElements() ) {
- String k=enumeration.nextElement();
- String v=config.getInitParameter( k );
- setProperty( k, v);
- }
-
- String keepgen = config.getInitParameter("keepgenerated");
- if (keepgen != null) {
- if (keepgen.equalsIgnoreCase("true")) {
- this.keepGenerated = true;
- } else if (keepgen.equalsIgnoreCase("false")) {
- this.keepGenerated = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.keepgen"));
- }
- }
- }
-
-
- String trimsp = config.getInitParameter("trimSpaces");
- if (trimsp != null) {
- if (trimsp.equalsIgnoreCase("true")) {
- trimSpaces = true;
- } else if (trimsp.equalsIgnoreCase("false")) {
- trimSpaces = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.trimspaces"));
- }
- }
- }
-
- this.isPoolingEnabled = true;
- String poolingEnabledParam
- = config.getInitParameter("enablePooling");
- if (poolingEnabledParam != null
- && !poolingEnabledParam.equalsIgnoreCase("true")) {
- if (poolingEnabledParam.equalsIgnoreCase("false")) {
- this.isPoolingEnabled = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.enablePooling"));
- }
- }
- }
-
- String mapFile = config.getInitParameter("mappedfile");
- if (mapFile != null) {
- if (mapFile.equalsIgnoreCase("true")) {
- this.mappedFile = true;
- } else if (mapFile.equalsIgnoreCase("false")) {
- this.mappedFile = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.mappedFile"));
- }
- }
- }
-
- String debugInfo = config.getInitParameter("classdebuginfo");
- if (debugInfo != null) {
- if (debugInfo.equalsIgnoreCase("true")) {
- this.classDebugInfo = true;
- } else if (debugInfo.equalsIgnoreCase("false")) {
- this.classDebugInfo = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.classDebugInfo"));
- }
- }
- }
-
- String checkInterval = config.getInitParameter("checkInterval");
- if (checkInterval != null) {
- try {
- this.checkInterval = Integer.parseInt(checkInterval);
- } catch(NumberFormatException ex) {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.checkInterval"));
- }
- }
- }
-
- String modificationTestInterval = config.getInitParameter("modificationTestInterval");
- if (modificationTestInterval != null) {
- try {
- this.modificationTestInterval = Integer.parseInt(modificationTestInterval);
- } catch(NumberFormatException ex) {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval"));
- }
- }
- }
-
- String recompileOnFail = config.getInitParameter("recompileOnFail");
- if (recompileOnFail != null) {
- if (recompileOnFail.equalsIgnoreCase("true")) {
- this.recompileOnFail = true;
- } else if (recompileOnFail.equalsIgnoreCase("false")) {
- this.recompileOnFail = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.recompileOnFail"));
- }
- }
- }
- String development = config.getInitParameter("development");
- if (development != null) {
- if (development.equalsIgnoreCase("true")) {
- this.development = true;
- } else if (development.equalsIgnoreCase("false")) {
- this.development = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.development"));
- }
- }
- }
-
- String suppressSmap = config.getInitParameter("suppressSmap");
- if (suppressSmap != null) {
- if (suppressSmap.equalsIgnoreCase("true")) {
- isSmapSuppressed = true;
- } else if (suppressSmap.equalsIgnoreCase("false")) {
- isSmapSuppressed = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.suppressSmap"));
- }
- }
- }
-
- String dumpSmap = config.getInitParameter("dumpSmap");
- if (dumpSmap != null) {
- if (dumpSmap.equalsIgnoreCase("true")) {
- isSmapDumped = true;
- } else if (dumpSmap.equalsIgnoreCase("false")) {
- isSmapDumped = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.dumpSmap"));
- }
- }
- }
-
- String genCharArray = config.getInitParameter("genStringAsCharArray");
- if (genCharArray != null) {
- if (genCharArray.equalsIgnoreCase("true")) {
- genStringAsCharArray = true;
- } else if (genCharArray.equalsIgnoreCase("false")) {
- genStringAsCharArray = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.genchararray"));
- }
- }
- }
-
- String errBeanClass =
- config.getInitParameter("errorOnUseBeanInvalidClassAttribute");
- if (errBeanClass != null) {
- if (errBeanClass.equalsIgnoreCase("true")) {
- errorOnUseBeanInvalidClassAttribute = true;
- } else if (errBeanClass.equalsIgnoreCase("false")) {
- errorOnUseBeanInvalidClassAttribute = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.errBean"));
- }
- }
- }
-
- String ieClassId = config.getInitParameter("ieClassId");
- if (ieClassId != null)
- this.ieClassId = ieClassId;
-
- String classpath = config.getInitParameter("classpath");
- if (classpath != null)
- this.classpath = classpath;
-
- /*
- * scratchdir
- */
- String dir = config.getInitParameter("scratchdir");
- if (dir != null && Constants.IS_SECURITY_ENABLED) {
- log.info(Localizer.getMessage("jsp.info.ignoreSetting", "scratchdir", dir));
- dir = null;
- }
- if (dir != null) {
- scratchDir = new File(dir);
- } else {
- // First try the Servlet 2.2 javax.servlet.context.tempdir property
- scratchDir = (File) context.getAttribute(ServletContext.TEMPDIR);
- if (scratchDir == null) {
- // Not running in a Servlet 2.2 container.
- // Try to get the JDK 1.2 java.io.tmpdir property
- dir = System.getProperty("java.io.tmpdir");
- if (dir != null)
- scratchDir = new File(dir);
- }
- }
- if (this.scratchDir == null) {
- log.fatal(Localizer.getMessage("jsp.error.no.scratch.dir"));
- return;
- }
- if (!scratchDir.exists()) // for TJWS force creation of scratchdir
- scratchDir.mkdirs();
- if (!(scratchDir.exists() && scratchDir.canRead() &&
- scratchDir.canWrite() && scratchDir.isDirectory()))
- log.fatal(Localizer.getMessage("jsp.error.bad.scratch.dir",
- scratchDir.getAbsolutePath()));
-
- this.compiler = config.getInitParameter("compiler");
-
- String compilerTargetVM = config.getInitParameter("compilerTargetVM");
- if(compilerTargetVM != null) {
- this.compilerTargetVM = compilerTargetVM;
- }
-
- String compilerSourceVM = config.getInitParameter("compilerSourceVM");
- if(compilerSourceVM != null) {
- this.compilerSourceVM = compilerSourceVM;
- }
-
- String javaEncoding = config.getInitParameter("javaEncoding");
- if (javaEncoding != null) {
- this.javaEncoding = javaEncoding;
- }
-
- String compilerClassName = config.getInitParameter("compilerClassName");
- if (compilerClassName != null) {
- this.compilerClassName = compilerClassName;
- }
-
- String fork = config.getInitParameter("fork");
- if (fork != null) {
- if (fork.equalsIgnoreCase("true")) {
- this.fork = true;
- } else if (fork.equalsIgnoreCase("false")) {
- this.fork = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.fork"));
- }
- }
- }
-
- String xpoweredBy = config.getInitParameter("xpoweredBy");
- if (xpoweredBy != null) {
- if (xpoweredBy.equalsIgnoreCase("true")) {
- this.xpoweredBy = true;
- } else if (xpoweredBy.equalsIgnoreCase("false")) {
- this.xpoweredBy = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.xpoweredBy"));
- }
- }
- }
-
- String displaySourceFragment = config.getInitParameter("displaySourceFragment");
- if (displaySourceFragment != null) {
- if (displaySourceFragment.equalsIgnoreCase("true")) {
- this.displaySourceFragment = true;
- } else if (displaySourceFragment.equalsIgnoreCase("false")) {
- this.displaySourceFragment = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.displaySourceFragment"));
- }
- }
- }
-
- String maxLoadedJsps = config.getInitParameter("maxLoadedJsps");
- if (maxLoadedJsps != null) {
- try {
- this.maxLoadedJsps = Integer.parseInt(maxLoadedJsps);
- } catch(NumberFormatException ex) {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps));
- }
- }
- }
-
- String jspIdleTimeout = config.getInitParameter("jspIdleTimeout");
- if (jspIdleTimeout != null) {
- try {
- this.jspIdleTimeout = Integer.parseInt(jspIdleTimeout);
- } catch(NumberFormatException ex) {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout));
- }
- }
- }
-
- String quoteAttributeEL = config.getInitParameter("quoteAttributeEL");
- if (quoteAttributeEL != null) {
- if (quoteAttributeEL.equalsIgnoreCase("true")) {
- this.quoteAttributeEL = true;
- } else if (quoteAttributeEL.equalsIgnoreCase("false")) {
- this.quoteAttributeEL = false;
- } else {
- if (log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jsp.warning.quoteAttributeEL"));
- }
- }
- }
-
- // Setup the global Tag Libraries location cache for this
- // web-application.
- tldLocationsCache = TldLocationsCache.getInstance(context);
-
- // Setup the jsp config info for this web app.
- jspConfig = new JspConfig(context);
-
- // Create a Tag plugin instance
- tagPluginManager = new TagPluginManager(context);
- }
-
-}
-
diff --git a/1.x/src/jasper7-7x/JspC.java b/1.x/src/jasper7-7x/JspC.java
deleted file mode 100644
index 060de36..0000000
--- a/1.x/src/jasper7-7x/JspC.java
+++ /dev/null
@@ -1,1689 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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;
-
-import java.io.BufferedReader;
-import java.io.CharArrayWriter;
-import java.io.EOFException;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.io.Reader;
-import java.io.Writer;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.Stack;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
-import javax.servlet.jsp.tagext.TagLibraryInfo;
-
-import org.apache.jasper.compiler.Compiler;
-import org.apache.jasper.compiler.JspConfig;
-import org.apache.jasper.compiler.JspRuntimeContext;
-import org.apache.jasper.compiler.Localizer;
-import org.apache.jasper.compiler.TagPluginManager;
-import org.apache.jasper.compiler.TldLocationsCache;
-import org.apache.jasper.servlet.JspCServletContext;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-
-/**
- * Shell for the jspc compiler. Handles all options associated with the
- * command line and creates compilation contexts which it then compiles
- * according to the specified options.
- *
- * This version can process files from a _single_ webapp at once, i.e.
- * a single docbase can be specified.
- *
- * It can be used as an Ant task using:
- *
- * <taskdef classname="org.apache.jasper.JspC" name="jasper" >
- * <classpath>
- * <pathelement location="${java.home}/../lib/tools.jar"/>
- * <fileset dir="${ENV.CATALINA_HOME}/lib">
- * <include name="*.jar"/>
- * </fileset>
- * <path refid="myjars"/>
- * </classpath>
- * </taskdef>
- *
- * <jasper verbose="0"
- * package="my.package"
- * uriroot="${webapps.dir}/${webapp.name}"
- * webXmlFragment="${build.dir}/generated_web.xml"
- * outputDir="${webapp.dir}/${webapp.name}/WEB-INF/src/my/package" />
- *
- *
- * @author Danno Ferrin
- * @author Pierre Delisle
- * @author Costin Manolache
- * @author Yoav Shapira
- */
-public class JspC implements Options {
-
- public static final String DEFAULT_IE_CLASS_ID =
- "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";
-
- // Logger
- private static final Log log = LogFactory.getLog(JspC.class);
-
- protected static final String SWITCH_VERBOSE = "-v";
- protected static final String SWITCH_HELP = "-help";
- protected static final String SWITCH_OUTPUT_DIR = "-d";
- protected static final String SWITCH_PACKAGE_NAME = "-p";
- protected static final String SWITCH_CACHE = "-cache";
- protected static final String SWITCH_CLASS_NAME = "-c";
- protected static final String SWITCH_FULL_STOP = "--";
- protected static final String SWITCH_COMPILE = "-compile";
- protected static final String SWITCH_SOURCE = "-source";
- protected static final String SWITCH_TARGET = "-target";
- protected static final String SWITCH_URI_BASE = "-uribase";
- protected static final String SWITCH_URI_ROOT = "-uriroot";
- protected static final String SWITCH_FILE_WEBAPP = "-webapp";
- protected static final String SWITCH_WEBAPP_INC = "-webinc";
- protected static final String SWITCH_WEBAPP_XML = "-webxml";
- protected static final String SWITCH_WEBAPP_XML_ENCODING = "-webxmlencoding";
- protected static final String SWITCH_ADD_WEBAPP_XML_MAPPINGS = "-addwebxmlmappings";
- protected static final String SWITCH_MAPPED = "-mapped";
- protected static final String SWITCH_XPOWERED_BY = "-xpoweredBy";
- protected static final String SWITCH_TRIM_SPACES = "-trimSpaces";
- protected static final String SWITCH_CLASSPATH = "-classpath";
- protected static final String SWITCH_DIE = "-die";
- protected static final String SWITCH_POOLING = "-poolingEnabled";
- protected static final String SWITCH_ENCODING = "-javaEncoding";
- protected static final String SWITCH_SMAP = "-smap";
- protected static final String SWITCH_DUMP_SMAP = "-dumpsmap";
- protected static final String SWITCH_VALIDATE_TLD = "-validateTld";
- protected static final String SWITCH_VALIDATE_XML = "-validateXml";
- protected static final String SWITCH_BLOCK_EXTERNAL = "-blockExternal";
- protected static final String SWITCH_NO_BLOCK_EXTERNAL = "-no-blockExternal";
- protected static final String SWITCH_QUOTE_ATTRIBUTE_EL = "-quoteAttributeEL";
- protected static final String SWITCH_NO_QUOTE_ATTRIBUTE_EL = "-no-quoteAttributeEL";
- protected static final String SHOW_SUCCESS ="-s";
- protected static final String LIST_ERRORS = "-l";
- protected static final int INC_WEBXML = 10;
- protected static final int ALL_WEBXML = 20;
- protected static final int DEFAULT_DIE_LEVEL = 1;
- protected static final int NO_DIE_LEVEL = 0;
- protected static final Set insertBefore = new HashSet();
-
- static {
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- }
-
- protected String classPath = null;
- protected ClassLoader loader = null;
- protected boolean trimSpaces = false;
- protected boolean genStringAsCharArray = false;
- protected boolean validateTld;
- protected boolean validateXml;
- protected boolean blockExternal = true;
- protected boolean quoteAttributeEL = true;
- protected boolean xpoweredBy;
- protected boolean mappedFile = false;
- protected boolean poolingEnabled = true;
- protected File scratchDir;
- protected String ieClassId = DEFAULT_IE_CLASS_ID;
- protected String targetPackage;
- protected String targetClassName;
- protected String uriBase;
- protected String uriRoot;
- protected int dieLevel;
- protected boolean helpNeeded = false;
- protected boolean compile = false;
- protected boolean smapSuppressed = true;
- protected boolean smapDumped = false;
- protected boolean caching = true;
- protected final Map cache =
- new HashMap();
-
- protected String compiler = null;
-
- protected String compilerTargetVM = "1.6";
- protected String compilerSourceVM = "1.6";
-
- protected boolean classDebugInfo = true;
-
- /**
- * Throw an exception if there's a compilation error, or swallow it.
- * Default is true to preserve old behavior.
- */
- protected boolean failOnError = true;
-
- /**
- * The file extensions to be handled as JSP files.
- * Default list is .jsp and .jspx.
- */
- protected List extensions;
-
- /**
- * The pages.
- */
- protected final List pages = new Vector();
-
- /**
- * Needs better documentation, this data member does.
- * True by default.
- */
- protected boolean errorOnUseBeanInvalidClassAttribute = true;
-
- /**
- * The java file encoding. Default
- * is UTF-8. Added per bugzilla 19622.
- */
- protected String javaEncoding = "UTF-8";
-
- // Generation of web.xml fragments
- protected String webxmlFile;
- protected int webxmlLevel;
- protected String webxmlEncoding;
- protected boolean addWebXmlMappings = false;
-
- protected Writer mapout;
- protected CharArrayWriter servletout;
- protected CharArrayWriter mappingout;
-
- /**
- * The servlet context.
- */
- protected JspCServletContext context;
-
- /**
- * The runtime context.
- * Maintain a dummy JspRuntimeContext for compiling tag files.
- */
- protected JspRuntimeContext rctxt;
-
- /**
- * Cache for the TLD locations
- */
- protected TldLocationsCache tldLocationsCache = null;
-
- protected JspConfig jspConfig = null;
- protected TagPluginManager tagPluginManager = null;
-
- protected boolean verbose = false;
- protected boolean listErrors = false;
- protected boolean showSuccess = false;
- protected int argPos;
- protected boolean fullstop = false;
- protected String args[];
-
- public static void main(String arg[]) {
- if (arg.length == 0) {
- System.out.println(Localizer.getMessage("jspc.usage"));
- } else {
- JspC jspc = new JspC();
- try {
- jspc.setArgs(arg);
- if (jspc.helpNeeded) {
- System.out.println(Localizer.getMessage("jspc.usage"));
- } else {
- jspc.execute();
- }
- } catch (JasperException je) {
- System.err.println(je);
- if (jspc.dieLevel != NO_DIE_LEVEL) {
- System.exit(jspc.dieLevel);
- }
- } catch (RuntimeException je) {
- System.err.println(je);
- if (jspc.dieLevel != NO_DIE_LEVEL) {
- System.exit(jspc.dieLevel);
- }
- }
- }
- }
-
- /**
- * Apply command-line arguments.
- *
- * @param arg
- * The arguments
- */
- public void setArgs(String[] arg) throws JasperException {
- args = arg;
- String tok;
-
- dieLevel = NO_DIE_LEVEL;
-
- while ((tok = nextArg()) != null) {
- if (tok.equals(SWITCH_VERBOSE)) {
- verbose = true;
- showSuccess = true;
- listErrors = true;
- } else if (tok.equals(SWITCH_OUTPUT_DIR)) {
- tok = nextArg();
- setOutputDir( tok );
- } else if (tok.equals(SWITCH_PACKAGE_NAME)) {
- targetPackage = nextArg();
- } else if (tok.equals(SWITCH_COMPILE)) {
- compile=true;
- } else if (tok.equals(SWITCH_CLASS_NAME)) {
- targetClassName = nextArg();
- } else if (tok.equals(SWITCH_URI_BASE)) {
- uriBase=nextArg();
- } else if (tok.equals(SWITCH_URI_ROOT)) {
- setUriroot( nextArg());
- } else if (tok.equals(SWITCH_FILE_WEBAPP)) {
- setUriroot( nextArg());
- } else if ( tok.equals( SHOW_SUCCESS ) ) {
- showSuccess = true;
- } else if ( tok.equals( LIST_ERRORS ) ) {
- listErrors = true;
- } else if (tok.equals(SWITCH_WEBAPP_INC)) {
- webxmlFile = nextArg();
- if (webxmlFile != null) {
- webxmlLevel = INC_WEBXML;
- }
- } else if (tok.equals(SWITCH_WEBAPP_XML)) {
- webxmlFile = nextArg();
- if (webxmlFile != null) {
- webxmlLevel = ALL_WEBXML;
- }
- } else if (tok.equals(SWITCH_WEBAPP_XML_ENCODING)) {
- setWebXmlEncoding(nextArg());
- } else if (tok.equals(SWITCH_ADD_WEBAPP_XML_MAPPINGS)) {
- setAddWebXmlMappings(true);
- } else if (tok.equals(SWITCH_MAPPED)) {
- mappedFile = true;
- } else if (tok.equals(SWITCH_XPOWERED_BY)) {
- xpoweredBy = true;
- } else if (tok.equals(SWITCH_TRIM_SPACES)) {
- setTrimSpaces(true);
- } else if (tok.equals(SWITCH_CACHE)) {
- tok = nextArg();
- if ("false".equals(tok)) {
- caching = false;
- } else {
- caching = true;
- }
- } else if (tok.equals(SWITCH_CLASSPATH)) {
- setClassPath(nextArg());
- } else if (tok.startsWith(SWITCH_DIE)) {
- try {
- dieLevel = Integer.parseInt(
- tok.substring(SWITCH_DIE.length()));
- } catch (NumberFormatException nfe) {
- dieLevel = DEFAULT_DIE_LEVEL;
- }
- } else if (tok.equals(SWITCH_HELP)) {
- helpNeeded = true;
- } else if (tok.equals(SWITCH_POOLING)) {
- tok = nextArg();
- if ("false".equals(tok)) {
- poolingEnabled = false;
- } else {
- poolingEnabled = true;
- }
- } else if (tok.equals(SWITCH_ENCODING)) {
- setJavaEncoding(nextArg());
- } else if (tok.equals(SWITCH_SOURCE)) {
- setCompilerSourceVM(nextArg());
- } else if (tok.equals(SWITCH_TARGET)) {
- setCompilerTargetVM(nextArg());
- } else if (tok.equals(SWITCH_SMAP)) {
- smapSuppressed = false;
- } else if (tok.equals(SWITCH_DUMP_SMAP)) {
- smapDumped = true;
- } else if (tok.equals(SWITCH_VALIDATE_TLD)) {
- setValidateTld(true);
- } else if (tok.equals(SWITCH_VALIDATE_XML)) {
- setValidateXml(true);
- } else if (tok.equals(SWITCH_BLOCK_EXTERNAL)) {
- setBlockExternal(true);
- } else if (tok.equals(SWITCH_NO_BLOCK_EXTERNAL)) {
- setBlockExternal(false);
- } else if (tok.equals(SWITCH_QUOTE_ATTRIBUTE_EL)) {
- setQuoteAttributeEL(true);
- } else if (tok.equals(SWITCH_NO_QUOTE_ATTRIBUTE_EL)) {
- setQuoteAttributeEL(false);
- } else {
- if (tok.startsWith("-")) {
- throw new JasperException("Unrecognized option: " + tok +
- ". Use -help for help.");
- }
- if (!fullstop) {
- argPos--;
- }
- // Start treating the rest as JSP Pages
- break;
- }
- }
-
- // Add all extra arguments to the list of files
- while( true ) {
- String file = nextFile();
- if( file==null ) {
- break;
- }
- pages.add( file );
- }
- }
-
- /**
- * In JspC this always returns true.
- * {@inheritDoc}
- */
- @Override
- public boolean getKeepGenerated() {
- // isn't this why we are running jspc?
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getTrimSpaces() {
- return trimSpaces;
- }
-
- /**
- * Sets the option to trim white spaces between directives or actions.
- */
- public void setTrimSpaces(boolean ts) {
- this.trimSpaces = ts;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isPoolingEnabled() {
- return poolingEnabled;
- }
-
- /**
- * Sets the option to enable the tag handler pooling.
- */
- public void setPoolingEnabled(boolean poolingEnabled) {
- this.poolingEnabled = poolingEnabled;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isXpoweredBy() {
- return xpoweredBy;
- }
-
- /**
- * Sets the option to enable generation of X-Powered-By response header.
- */
- public void setXpoweredBy(boolean xpoweredBy) {
- this.xpoweredBy = xpoweredBy;
- }
-
- /**
- * In JspC this always returns true.
- * {@inheritDoc}
- */
- @Override
- public boolean getDisplaySourceFragment() {
- return true;
- }
-
- @Override
- public int getMaxLoadedJsps() {
- return -1;
- }
-
- @Override
- public int getJspIdleTimeout() {
- return -1;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getErrorOnUseBeanInvalidClassAttribute() {
- return errorOnUseBeanInvalidClassAttribute;
- }
-
- /**
- * Sets the option to issue a compilation error if the class attribute
- * specified in useBean action is invalid.
- */
- public void setErrorOnUseBeanInvalidClassAttribute(boolean b) {
- errorOnUseBeanInvalidClassAttribute = b;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getMappedFile() {
- return mappedFile;
- }
-
- public void setMappedFile(boolean b) {
- mappedFile = b;
- }
-
- /**
- * Sets the option to include debug information in compiled class.
- */
- public void setClassDebugInfo( boolean b ) {
- classDebugInfo=b;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getClassDebugInfo() {
- // compile with debug info
- return classDebugInfo;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isCaching() {
- return caching;
- }
-
- /**
- * Sets the option to enable caching.
- *
- * @see Options#isCaching()
- */
- public void setCaching(boolean caching) {
- this.caching = caching;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Map getCache() {
- return cache;
- }
-
- /**
- * In JspC this always returns 0.
- * {@inheritDoc}
- */
- @Override
- public int getCheckInterval() {
- return 0;
- }
-
- /**
- * In JspC this always returns 0.
- * {@inheritDoc}
- */
- @Override
- public int getModificationTestInterval() {
- return 0;
- }
-
-
- /**
- * In JspC this always returns false.
- * {@inheritDoc}
- */
- @Override
- public boolean getRecompileOnFail() {
- return false;
- }
-
-
- /**
- * In JspC this always returns false.
- * {@inheritDoc}
- */
- @Override
- public boolean getDevelopment() {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isSmapSuppressed() {
- return smapSuppressed;
- }
-
- /**
- * Sets smapSuppressed flag.
- */
- public void setSmapSuppressed(boolean smapSuppressed) {
- this.smapSuppressed = smapSuppressed;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isSmapDumped() {
- return smapDumped;
- }
-
- /**
- * Sets smapDumped flag.
- *
- * @see Options#isSmapDumped()
- */
- public void setSmapDumped(boolean smapDumped) {
- this.smapDumped = smapDumped;
- }
-
-
- /**
- * Determines whether text strings are to be generated as char arrays,
- * which improves performance in some cases.
- *
- * @param genStringAsCharArray true if text strings are to be generated as
- * char arrays, false otherwise
- */
- public void setGenStringAsCharArray(boolean genStringAsCharArray) {
- this.genStringAsCharArray = genStringAsCharArray;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean genStringAsCharArray() {
- return genStringAsCharArray;
- }
-
- /**
- * Sets the class-id value to be sent to Internet Explorer when using
- * <jsp:plugin> tags.
- *
- * @param ieClassId
- * Class-id value
- */
- public void setIeClassId(String ieClassId) {
- this.ieClassId = ieClassId;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getIeClassId() {
- return ieClassId;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public File getScratchDir() {
- return scratchDir;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getCompiler() {
- return compiler;
- }
-
- /**
- * Sets the option to determine what compiler to use.
- *
- * @see Options#getCompiler()
- */
- public void setCompiler(String c) {
- compiler=c;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getCompilerClassName() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getCompilerTargetVM() {
- return compilerTargetVM;
- }
-
- /**
- * Sets the compiler target VM.
- *
- * @see Options#getCompilerTargetVM()
- */
- public void setCompilerTargetVM(String vm) {
- compilerTargetVM = vm;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getCompilerSourceVM() {
- return compilerSourceVM;
- }
-
- /**
- * Sets the compiler source VM.
- *
- * @see Options#getCompilerSourceVM()
- */
- public void setCompilerSourceVM(String vm) {
- compilerSourceVM = vm;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public TldLocationsCache getTldLocationsCache() {
- return tldLocationsCache;
- }
-
- /**
- * Returns the encoding to use for
- * java files. The default is UTF-8.
- *
- * @return String The encoding
- */
- @Override
- public String getJavaEncoding() {
- return javaEncoding;
- }
-
- /**
- * Sets the encoding to use for
- * java files.
- *
- * @param encodingName The name, e.g. "UTF-8"
- */
- public void setJavaEncoding(String encodingName) {
- javaEncoding = encodingName;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getFork() {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getClassPath() {
- if( classPath != null )
- return classPath;
- return System.getProperty("java.class.path");
- }
-
- /**
- * Sets the classpath used while compiling the servlets generated from JSP
- * files
- */
- public void setClassPath(String s) {
- classPath=s;
- }
-
- /**
- * Returns the list of file extensions
- * that are treated as JSP files.
- *
- * @return The list of extensions
- */
- public List getExtensions() {
- return extensions;
- }
-
- /**
- * Adds the given file extension to the
- * list of extensions handled as JSP files.
- *
- * @param extension The extension to add, e.g. "myjsp"
- */
- protected void addExtension(final String extension) {
- if(extension != null) {
- if(extensions == null) {
- extensions = new Vector();
- }
-
- extensions.add(extension);
- }
- }
-
- /**
- * Base dir for the webapp. Used to generate class names and resolve
- * includes.
- */
- public void setUriroot( String s ) {
- if (s == null) {
- uriRoot = null;
- return;
- }
- try {
- uriRoot = resolveFile(s).getCanonicalPath();
- } catch( Exception ex ) {
- uriRoot = s;
- }
- }
-
- /**
- * Parses comma-separated list of JSP files to be processed. If the argument
- * is null, nothing is done.
- *
- * Each file is interpreted relative to uriroot, unless it is absolute,
- * in which case it must start with uriroot.
- *
- * @param jspFiles Comma-separated list of JSP files to be processed
- */
- public void setJspFiles(final String jspFiles) {
- if(jspFiles == null) {
- return;
- }
-
- StringTokenizer tok = new StringTokenizer(jspFiles, ",");
- while (tok.hasMoreTokens()) {
- pages.add(tok.nextToken());
- }
- }
-
- /**
- * Sets the compile flag.
- *
- * @param b Flag value
- */
- public void setCompile( final boolean b ) {
- compile = b;
- }
-
- /**
- * Sets the verbosity level. The actual number doesn't
- * matter: if it's greater than zero, the verbose flag will
- * be true.
- *
- * @param level Positive means verbose
- */
- public void setVerbose( final int level ) {
- if (level > 0) {
- verbose = true;
- showSuccess = true;
- listErrors = true;
- }
- }
-
- public void setValidateTld( boolean b ) {
- this.validateTld = b;
- }
-
- public boolean isValidateTld() {
- return validateTld;
- }
-
- public void setValidateXml( boolean b ) {
- this.validateXml = b;
- }
-
- public boolean isValidateXml() {
- return validateXml;
- }
-
- public void setBlockExternal( boolean b ) {
- this.blockExternal = b;
- }
-
- public boolean isBlockExternal() {
- return blockExternal;
- }
-
- public void setQuoteAttributeEL(boolean b) {
- quoteAttributeEL = b;
- }
-
- @Override
- public boolean getQuoteAttributeEL() {
- return quoteAttributeEL;
- }
-
- public void setListErrors( boolean b ) {
- listErrors = b;
- }
-
- public void setOutputDir( String s ) {
- if( s!= null ) {
- scratchDir = resolveFile(s).getAbsoluteFile();
- } else {
- scratchDir=null;
- }
- }
-
- /**
- * Sets the package name to be used for the generated servlet classes.
- */
- public void setPackage( String p ) {
- targetPackage=p;
- }
-
- /**
- * Class name of the generated file ( without package ).
- * Can only be used if a single file is converted.
- * XXX Do we need this feature ?
- */
- public void setClassName( String p ) {
- targetClassName=p;
- }
-
- /**
- * File where we generate a web.xml fragment with the class definitions.
- */
- public void setWebXmlFragment( String s ) {
- webxmlFile=resolveFile(s).getAbsolutePath();
- webxmlLevel=INC_WEBXML;
- }
-
- /**
- * File where we generate a complete web.xml with the class definitions.
- */
- public void setWebXml( String s ) {
- webxmlFile=resolveFile(s).getAbsolutePath();
- webxmlLevel=ALL_WEBXML;
- }
-
- /**
- * Sets the encoding to be used to read and write web.xml files.
- *
- *
- * If not specified, defaults to the platform default encoding.
- *
- *
- * @param encoding
- * Encoding, e.g. "UTF-8".
- */
- public void setWebXmlEncoding(String encoding) {
- webxmlEncoding = encoding;
- }
-
- /**
- * Sets the option to merge generated web.xml fragment into the
- * WEB-INF/web.xml file of the web application that we were processing.
- *
- * @param b
- * true to merge the fragment into the existing
- * web.xml file of the processed web application
- * ({uriroot}/WEB-INF/web.xml), false to keep the
- * generated web.xml fragment
- */
- public void setAddWebXmlMappings(boolean b) {
- addWebXmlMappings = b;
- }
-
- /**
- * Sets the option that throws an exception in case of a compilation error.
- */
- public void setFailOnError(final boolean b) {
- failOnError = b;
- }
-
- /**
- * Returns true if an exception will be thrown in case of a compilation
- * error.
- */
- public boolean getFailOnError() {
- return failOnError;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public JspConfig getJspConfig() {
- return jspConfig;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public TagPluginManager getTagPluginManager() {
- return tagPluginManager;
- }
-
- /**
- * Adds servlet declaration and mapping for the JSP page servlet to the
- * generated web.xml fragment.
- *
- * @param file
- * Context-relative path to the JSP file, e.g.
- * /index.jsp
- * @param clctxt
- * Compilation context of the servlet
- */
- public void generateWebMapping( String file, JspCompilationContext clctxt )
- throws IOException
- {
- if (log.isDebugEnabled()) {
- log.debug("Generating web mapping for file " + file
- + " using compilation context " + clctxt);
- }
-
- String className = clctxt.getServletClassName();
- String packageName = clctxt.getServletPackageName();
-
- String thisServletName;
- if ("".equals(packageName)) {
- thisServletName = className;
- } else {
- thisServletName = packageName + '.' + className;
- }
-
- if (servletout != null) {
- servletout.write("\n \n ");
- servletout.write(thisServletName);
- servletout.write("\n ");
- servletout.write(thisServletName);
- servletout.write("\n \n");
- }
- if (mappingout != null) {
- mappingout.write("\n \n ");
- mappingout.write(thisServletName);
- mappingout.write("\n ");
- mappingout.write(file.replace('\\', '/'));
- mappingout.write("\n \n");
-
- }
- }
-
- /**
- * Include the generated web.xml inside the webapp's web.xml.
- */
- protected void mergeIntoWebXml() throws IOException {
-
- File webappBase = new File(uriRoot);
- File webXml = new File(webappBase, "WEB-INF/web.xml");
- File webXml2 = new File(webappBase, "WEB-INF/web2.xml");
- String insertStartMarker =
- Localizer.getMessage("jspc.webinc.insertStart");
- String insertEndMarker =
- Localizer.getMessage("jspc.webinc.insertEnd");
-
- BufferedReader reader = null;
- BufferedReader fragmentReader = null;
- PrintWriter writer = null;
- try {
- reader = new BufferedReader(openWebxmlReader(webXml));
- fragmentReader = new BufferedReader(openWebxmlReader(new File(webxmlFile)));
- writer = new PrintWriter(openWebxmlWriter(webXml2));
- // Insert the and declarations
- boolean inserted = false;
- int current = reader.read();
- while (current > -1) {
- if (current == '<') {
- String element = getElement(reader);
- if (!inserted && insertBefore.contains(element)) {
- // Insert generated content here
- writer.println(insertStartMarker);
- while (true) {
- String line = fragmentReader.readLine();
- if (line == null) {
- writer.println();
- break;
- }
- writer.println(line);
- }
- writer.println(insertEndMarker);
- writer.println();
- writer.write(element);
- inserted = true;
- } else if (element.equals(insertStartMarker)) {
- // Skip the previous auto-generated content
- while (true) {
- current = reader.read();
- if (current < 0) {
- throw new EOFException();
- }
- if (current == '<') {
- element = getElement(reader);
- if (element.equals(insertEndMarker)) {
- break;
- }
- }
- }
- current = reader.read();
- while (current == '\n' || current == '\r') {
- current = reader.read();
- }
- continue;
- } else {
- writer.write(element);
- }
- } else {
- writer.write(current);
- }
- current = reader.read();
- }
- } finally {
- if (writer != null) {
- try {
- writer.close();
- } catch (Exception e) {
- }
- }
- if (reader != null) {
- try {
- reader.close();
- } catch (Exception e) {
- }
- }
- if (fragmentReader != null) {
- try {
- fragmentReader.close();
- } catch (Exception e) {
- }
- }
- }
-
- FileInputStream fis = null;
- FileOutputStream fos = null;
- try {
- fis = new FileInputStream(webXml2);
- fos = new FileOutputStream(webXml);
- byte buf[] = new byte[512];
- while (true) {
- int n = fis.read(buf);
- if (n < 0) {
- break;
- }
- fos.write(buf, 0, n);
- }
- } finally {
- if (fis != null) {
- try {
- fis.close();
- } catch (Exception e) {
- }
- }
- if (fos != null) {
- try {
- fos.close();
- } catch (Exception e) {
- }
- }
- }
-
- if(!webXml2.delete() && log.isDebugEnabled())
- log.debug(Localizer.getMessage("jspc.delete.fail",
- webXml2.toString()));
-
- if (!(new File(webxmlFile)).delete() && log.isDebugEnabled())
- log.debug(Localizer.getMessage("jspc.delete.fail", webxmlFile));
-
- }
-
- /*
- * Assumes valid xml
- */
- private String getElement(Reader reader) throws IOException {
- StringBuilder result = new StringBuilder();
- result.append('<');
-
- boolean done = false;
-
- while (!done) {
- int current = reader.read();
- while (current != '>') {
- if (current < 0) {
- throw new EOFException();
- }
- result.append((char) current);
- current = reader.read();
- }
- result.append((char) current);
-
- int len = result.length();
- if (len > 4 && result.substring(0, 4).equals("")) {
- done = true;
- }
- } else {
- done = true;
- }
- }
-
-
- return result.toString();
- }
-
- protected void processFile(String file)
- throws JasperException
- {
- if (log.isDebugEnabled()) {
- log.debug("Processing file: " + file);
- }
-
- ClassLoader originalClassLoader = null;
-
- try {
- // set up a scratch/output dir if none is provided
- if (scratchDir == null) {
- String temp = System.getProperty("java.io.tmpdir");
- if (temp == null) {
- temp = "";
- }
- scratchDir = new File(new File(temp).getAbsolutePath());
- }
-
- String jspUri=file.replace('\\','/');
- JspCompilationContext clctxt = new JspCompilationContext
- ( jspUri, this, context, null, rctxt );
-
- /* Override the defaults */
- if ((targetClassName != null) && (targetClassName.length() > 0)) {
- clctxt.setServletClassName(targetClassName);
- targetClassName = null;
- }
- if (targetPackage != null) {
- clctxt.setServletPackageName(targetPackage);
- }
-
- originalClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(loader);
-
- clctxt.setClassLoader(loader);
- clctxt.setClassPath(classPath);
-
- Compiler clc = clctxt.createCompiler();
-
- // If compile is set, generate both .java and .class, if
- // .jsp file is newer than .class file;
- // Otherwise only generate .java, if .jsp file is newer than
- // the .java file
- if( clc.isOutDated(compile) ) {
- if (log.isDebugEnabled()) {
- log.debug(jspUri + " is out dated, compiling...");
- }
-
- clc.compile(compile, true);
- }
-
- // Generate mapping
- generateWebMapping( file, clctxt );
- if ( showSuccess ) {
- log.info( "Built File: " + file );
- }
-
- } catch (JasperException je) {
- Throwable rootCause = je;
- while (rootCause instanceof JasperException
- && ((JasperException) rootCause).getRootCause() != null) {
- rootCause = ((JasperException) rootCause).getRootCause();
- }
- if (rootCause != je) {
- log.error(Localizer.getMessage("jspc.error.generalException",
- file),
- rootCause);
- }
-
- // Bugzilla 35114.
- if(getFailOnError()) {
- throw je;
- } else {
- log.error(je.getMessage());
- }
-
- } catch (Exception e) {
- if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist",
- e.getMessage()));
- }
- throw new JasperException(e);
- } finally {
- if(originalClassLoader != null) {
- Thread.currentThread().setContextClassLoader(originalClassLoader);
- }
- }
- }
-
- /**
- * Locate all jsp files in the webapp. Used if no explicit
- * jsps are specified.
- */
- public void scanFiles( File base ) throws JasperException {
- Stack dirs = new Stack();
- dirs.push(base.toString());
-
- // Make sure default extensions are always included
- if ((getExtensions() == null) || (getExtensions().size() < 2)) {
- addExtension("jsp");
- addExtension("jspx");
- }
-
- while (!dirs.isEmpty()) {
- String s = dirs.pop();
- File f = new File(s);
- if (f.exists() && f.isDirectory()) {
- String[] files = f.list();
- String ext;
- for (int i = 0; (files != null) && i < files.length; i++) {
- File f2 = new File(s, files[i]);
- if (f2.isDirectory()) {
- dirs.push(f2.getPath());
- } else {
- String path = f2.getPath();
- String uri = path.substring(uriRoot.length());
- ext = files[i].substring(files[i].lastIndexOf('.') +1);
- if (getExtensions().contains(ext) ||
- jspConfig.isJspPage(uri)) {
- pages.add(path);
- }
- }
- }
- }
- }
- }
-
- /**
- * Executes the compilation.
- */
- public void execute() {
- if(log.isDebugEnabled()) {
- log.debug("execute() starting for " + pages.size() + " pages.");
- }
-
- try {
- if (uriRoot == null) {
- if( pages.size() == 0 ) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.missingTarget"));
- }
- String firstJsp = pages.get( 0 );
- File firstJspF = new File( firstJsp );
- if (!firstJspF.exists()) {
- throw new JasperException(
- Localizer.getMessage("jspc.error.fileDoesNotExist",
- firstJsp));
- }
- locateUriRoot( firstJspF );
- }
-
- if (uriRoot == null) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.no_uriroot"));
- }
-
- File uriRootF = new File(uriRoot);
- if (!uriRootF.isDirectory()) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.uriroot_not_dir"));
- }
-
- if (loader == null) {
- loader = initClassLoader();
- }
- if (context == null) {
- initServletContext(loader);
- }
-
- // No explicit pages, we'll process all .jsp in the webapp
- if (pages.size() == 0) {
- scanFiles(uriRootF);
- }
-
- initWebXml();
-
- Iterator iter = pages.iterator();
- while (iter.hasNext()) {
- String nextjsp = iter.next();
- File fjsp = new File(nextjsp);
- if (!fjsp.isAbsolute()) {
- fjsp = new File(uriRootF, nextjsp);
- }
- if (!fjsp.exists()) {
- if (log.isWarnEnabled()) {
- log.warn
- (Localizer.getMessage
- ("jspc.error.fileDoesNotExist", fjsp.toString()));
- }
- continue;
- }
- String s = fjsp.getAbsolutePath();
- if (s.startsWith(uriRoot)) {
- nextjsp = s.substring(uriRoot.length());
- }
- if (nextjsp.startsWith("." + File.separatorChar)) {
- nextjsp = nextjsp.substring(2);
- }
- processFile(nextjsp);
- }
-
- completeWebXml();
-
- if (addWebXmlMappings) {
- mergeIntoWebXml();
- }
-
- } catch (IOException ioe) {
- throw new RuntimeException(ioe); // TODO make it our own
-
- } catch (JasperException je) {
- Throwable rootCause = je;
- while (rootCause instanceof JasperException
- && ((JasperException) rootCause).getRootCause() != null) {
- rootCause = ((JasperException) rootCause).getRootCause();
- }
- if (rootCause != je) {
- rootCause.printStackTrace();
- }
- throw new RuntimeException(je); // TODO make it our own
- } finally {
- if (loader != null) {
- LogFactory.release(loader);
- }
- }
- }
-
- // ==================== protected utility methods ====================
-
- protected String nextArg() {
- if ((argPos >= args.length)
- || (fullstop = SWITCH_FULL_STOP.equals(args[argPos]))) {
- return null;
- } else {
- return args[argPos++];
- }
- }
-
- protected String nextFile() {
- if (fullstop) argPos++;
- if (argPos >= args.length) {
- return null;
- } else {
- return args[argPos++];
- }
- }
-
- protected void initWebXml() {
- try {
- if (webxmlLevel >= INC_WEBXML) {
- mapout = openWebxmlWriter(new File(webxmlFile));
- servletout = new CharArrayWriter();
- mappingout = new CharArrayWriter();
- } else {
- mapout = null;
- servletout = null;
- mappingout = null;
- }
- if (webxmlLevel >= ALL_WEBXML) {
- mapout.write(Localizer.getMessage("jspc.webxml.header"));
- mapout.flush();
- } else if ((webxmlLevel>= INC_WEBXML) && !addWebXmlMappings) {
- mapout.write(Localizer.getMessage("jspc.webinc.header"));
- mapout.flush();
- }
- } catch (IOException ioe) {
- mapout = null;
- servletout = null;
- mappingout = null;
- }
- }
-
- protected void completeWebXml() {
- if (mapout != null) {
- try {
- servletout.writeTo(mapout);
- mappingout.writeTo(mapout);
- if (webxmlLevel >= ALL_WEBXML) {
- mapout.write(Localizer.getMessage("jspc.webxml.footer"));
- } else if ((webxmlLevel >= INC_WEBXML) && !addWebXmlMappings) {
- mapout.write(Localizer.getMessage("jspc.webinc.footer"));
- }
- mapout.close();
- } catch (IOException ioe) {
- // noting to do if it fails since we are done with it
- }
- }
- }
-
- protected void initServletContext(ClassLoader classLoader)
- throws IOException, JasperException {
- // TODO: should we use the Ant Project's log?
- PrintWriter log = new PrintWriter(System.out);
- URL resourceBase = new File(uriRoot).getCanonicalFile().toURI().toURL();
- context = new JspCServletContext(log, resourceBase, classLoader);
- if (isValidateTld()) {
- context.setInitParameter(Constants.XML_VALIDATION_TLD_INIT_PARAM, "true");
- }
- if (isValidateXml()) {
- context.setInitParameter(Constants.XML_VALIDATION_INIT_PARAM, "true");
- }
- context.setInitParameter(Constants.XML_BLOCK_EXTERNAL_INIT_PARAM,
- String.valueOf(isBlockExternal()));
-
- tldLocationsCache = TldLocationsCache.getInstance(context);
- rctxt = new JspRuntimeContext(context, this);
- jspConfig = new JspConfig(context);
- tagPluginManager = new TagPluginManager(context);
- }
-
- /**
- * Initializes the classloader as/if needed for the given
- * compilation context.
- *
- * @throws IOException If an error occurs
- */
- protected ClassLoader initClassLoader() throws IOException {
-
- classPath = getClassPath();
-
- ClassLoader jspcLoader = getClass().getClassLoader();
- // TODO add check for 7Bee/TJWS class loader and extend CP as needed
-
- // Turn the classPath into URLs
- ArrayList urls = new ArrayList();
- StringTokenizer tokenizer = new StringTokenizer(classPath,
- File.pathSeparator);
- while (tokenizer.hasMoreTokens()) {
- String path = tokenizer.nextToken();
- try {
- File libFile = new File(path);
- urls.add(libFile.toURI().toURL());
- } catch (IOException ioe) {
- // Failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak uot
- throw new RuntimeException(ioe.toString());
- }
- }
-
- File webappBase = new File(uriRoot);
- if (webappBase.exists()) {
- File classes = new File(webappBase, "/WEB-INF/classes");
- try {
- if (classes.exists()) {
- classPath = classPath + File.pathSeparator
- + classes.getCanonicalPath();
- urls.add(classes.getCanonicalFile().toURI().toURL());
- }
- } catch (IOException ioe) {
- // failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak out
- throw new RuntimeException(ioe.toString());
- }
- File lib = new File(webappBase, "/WEB-INF/lib");
- if (lib.exists() && lib.isDirectory()) {
- String[] libs = lib.list();
- if (libs != null) {
- for (int i = 0; i < libs.length; i++) {
- if( libs[i].length() <5 ) continue;
- String ext=libs[i].substring( libs[i].length() - 4 );
- if (! ".jar".equalsIgnoreCase(ext)) {
- if (".tld".equalsIgnoreCase(ext)) {
- log.warn("TLD files should not be placed in "
- + "/WEB-INF/lib");
- }
- continue;
- }
- try {
- File libFile = new File(lib, libs[i]);
- classPath = classPath + File.pathSeparator
- + libFile.getAbsolutePath();
- urls.add(libFile.getAbsoluteFile().toURI().toURL());
- } catch (IOException ioe) {
- // failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak out
- throw new RuntimeException(ioe.toString());
- }
- }
- }
- }
- }
-
- URL urlsA[]=new URL[urls.size()];
- urls.toArray(urlsA);
- loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());
- return loader;
- }
-
- /**
- * Find the WEB-INF dir by looking up in the directory tree.
- * This is used if no explicit docbase is set, but only files.
- * XXX Maybe we should require the docbase.
- */
- protected void locateUriRoot( File f ) {
- String tUriBase = uriBase;
- if (tUriBase == null) {
- tUriBase = "/";
- }
- try {
- if (f.exists()) {
- f = new File(f.getAbsolutePath());
- while (true) {
- File g = new File(f, "WEB-INF");
- if (g.exists() && g.isDirectory()) {
- uriRoot = f.getCanonicalPath();
- uriBase = tUriBase;
- if (log.isInfoEnabled()) {
- log.info(Localizer.getMessage(
- "jspc.implicit.uriRoot",
- uriRoot));
- }
- break;
- }
- if (f.exists() && f.isDirectory()) {
- tUriBase = "/" + f.getName() + "/" + tUriBase;
- }
-
- String fParent = f.getParent();
- if (fParent == null) {
- break;
- } else {
- f = new File(fParent);
- }
-
- // If there is no acceptable candidate, uriRoot will
- // remain null to indicate to the CompilerContext to
- // use the current working/user dir.
- }
-
- if (uriRoot != null) {
- File froot = new File(uriRoot);
- uriRoot = froot.getCanonicalPath();
- }
- }
- } catch (IOException ioe) {
- // since this is an optional default and a null value
- // for uriRoot has a non-error meaning, we can just
- // pass straight through
- }
- }
-
- /**
- * Resolves the relative or absolute pathname correctly
- * in both Ant and command-line situations. If Ant launched
- * us, we should use the basedir of the current project
- * to resolve relative paths.
- *
- * See Bugzilla 35571.
- *
- * @param s The file
- * @return The file resolved
- */
- protected File resolveFile(final String s) {
- // TODO consider some massaging of s as relative path to project home for TJWS
- return new File(s);
- }
-
- private Reader openWebxmlReader(File file) throws IOException {
- FileInputStream fis = new FileInputStream(file);
- try {
- return webxmlEncoding != null ? new InputStreamReader(fis,
- webxmlEncoding) : new InputStreamReader(fis);
- } catch (IOException ex) {
- fis.close();
- throw ex;
- }
- }
-
- private Writer openWebxmlWriter(File file) throws IOException {
- FileOutputStream fos = new FileOutputStream(file);
- try {
- return webxmlEncoding != null ? new OutputStreamWriter(fos,
- webxmlEncoding) : new OutputStreamWriter(fos);
- } catch (IOException ex) {
- fos.close();
- throw ex;
- }
- }
-}
diff --git a/1.x/src/jasper7/BeeCompiler.java b/1.x/src/jasper7/BeeCompiler.java
deleted file mode 100644
index 4a1783f..0000000
--- a/1.x/src/jasper7/BeeCompiler.java
+++ /dev/null
@@ -1,441 +0,0 @@
-/*
- * 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.File;
-import java.io.FileNotFoundException;
-import java.io.PrintStream;
-import java.io.IOException;
-import java.io.ByteArrayOutputStream;
-import java.util.StringTokenizer;
-import java.util.List;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.lang.reflect.Method;
-import java.lang.reflect.InvocationTargetException;
-import java.net.URL;
-import java.net.URLClassLoader;
-
-import org.apache.jasper.JasperException;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-
-/**
- * Main JSP compiler class. This class uses 7Bee for compiling.
- *
- * @author Dmitriy Rogatkin
- */
-public class BeeCompiler extends Compiler {
- private final Log log = LogFactory.getLog(BeeCompiler.class); // must not be static
-
- protected static Object javacLock = new Object();
-
- private Class javaCompiler;
-
- static {
- System.setErr(new SystemLogHandler(System.err));
- }
-
- /**
- * Compile the servlet from .java file to .class file
- */
- protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception {
-
- long t1 = 0;
- if (log.isDebugEnabled())
- t1 = System.currentTimeMillis();
-
- List parameters = new ArrayList(20);
- parameters.add("-encoding");
- parameters.add(ctxt.getOptions().getJavaEncoding());
-
- String javaFileName = new File(ctxt.getServletJavaFileName()).getPath();
- String classpath = ctxt.getClassPath();
-
- String sep = File.pathSeparator; // System.getProperty("path.separator");
-
- StringBuffer errorReport = new StringBuffer();
-
- StringBuffer info = new StringBuffer();
- info.append("Compile: javaFileName=" + javaFileName + "\n");
-
- // Start capturing the System.err output for this thread
- SystemLogHandler.setThread();
-
- // Initializing classpath
- String path = System.getProperty("java.class.path");
- info.append(" cmd cp=" + path + "\n");
- info.append(" ctx cp=" + classpath + "\n");
- path += sep;
- path += classpath;
-
- if (log.isDebugEnabled())
- log.debug("Using classpath: " + path);
-
- parameters.add("-classpath");
- parameters.add(path);
-
- // Initializing sourcepath
- parameters.add("-sourcepath");
- parameters.add(options.getScratchDir().getPath());
-
- info.append(" work dir=" + options.getScratchDir() + "\n");
-
- // Initialize and set java extensions
- String extdirs = System.getProperty("java.ext.dirs");
- if (extdirs != null) {
- parameters.add("-extdirs");
- parameters.add(extdirs);
- info.append(" extension dir=" + extdirs + "\n");
- }
-
- if (ctxt.getOptions().getFork()) {
- String endorsed = System.getProperty("java.endorsed.dirs");
- if (endorsed != null) {
- parameters.add("-endorseddirs"); // "-J-Djava.endorsed.dirs="+endorsed
- parameters.add(endorsed);
- info.append(" endorsed dir=" + endorsed + "\n");
- } else {
- info.append(" no endorsed dirs specified\n");
- }
- }
-
- if (ctxt.getOptions().getClassDebugInfo())
- parameters.add("-g");
-
- Exception ie = null;
-
- // Set the Java compiler to use
- if (javaCompiler == null) {
- // assumption, there is no dynamic changing Java compiler
- String compiler = options.getCompiler();
- if (compiler == null)
- compiler = "com.sun.tools.javac.Main";
- // verify compiler
- try {
- javaCompiler = Class.forName(compiler);
- } catch (ClassNotFoundException cnfe) {
- // try to figure out class path to compiler
- String compileClassPath = System.getProperty("java.home");
- if (compileClassPath == null)
- try {
- compileClassPath = System.getenv("JAVA_HOME");
- if (compileClassPath == null)
- compileClassPath = System.getenv("java_home");
- } catch (SecurityException se) {
-
- }
-
- if (compileClassPath != null) {
- // HACK for now
- compileClassPath = compileClassPath.replace("jre", "jdk");
- compileClassPath += "/lib/tools.jar";
- info.append(" checking default compiler in " + compileClassPath + "\n");
- try {
- javaCompiler = Class.forName(compiler, true, new URLClassLoader(new URL[] { new URL("file",
- "localhost", compileClassPath) }));
- } catch (Error er) {
- log.error("Setting up Java compiler error ", er);
- } catch (Exception ex) {
- log.error("Setting up Java compiler exception ", ex);
- }
- } else
- info.append(" no Java home path specified\n");
- }
- info.append(" compiler=" + compiler + "\n");
- }
-
- if (options.getCompilerTargetVM() != null) {
- parameters.add("-target");
- parameters.add(options.getCompilerTargetVM());
- info.append(" compilerTargetVM=" + options.getCompilerTargetVM() + "\n");
- }
-
- if (options.getCompilerSourceVM() != null) {
- parameters.add("-source");
- parameters.add(options.getCompilerSourceVM());
- info.append(" compilerSourceVM=" + options.getCompilerSourceVM() + "\n");
- }
-
- info.append(" JavaPath=" + ctxt.getJavaPath() + "\n");
-
- parameters.add(javaFileName);
-
- boolean compilationErrors = false;
- String errorCapture = null;
- if (javaCompiler != null)
- try {
- Integer success;
- Method cm = javaCompiler.getMethod("compile", new Class[] { String[].class });
- if (ctxt.getOptions().getFork()) {
- success = (Integer) cm.invoke(null, new Object[] { parameters
- .toArray(new String[parameters.size()]) });
- } else {
- synchronized (javacLock) {
- success = (Integer) cm.invoke(null, new Object[] { parameters.toArray(new String[parameters
- .size()]) });
- }
- }
- if (success.intValue() != 0)
- compilationErrors = true;
- } catch (Throwable t) {
- if (t instanceof ThreadDeath)
- throw (ThreadDeath) t;
- if (t instanceof InvocationTargetException)
- t = t.getCause();
- if (t instanceof Exception)
- ie = (Exception) t;
- else
- ie = new Exception(t);
- log.error("Javac exception ", t);
- log.error("Env: " + info.toString());
- } finally {
- // Stop capturing the System.err output for this thread
- errorCapture = SystemLogHandler.unsetThread();
- }
- if (compilationErrors && errorCapture != null) {
- errorReport.append(System.getProperty("line.separator"));
- errorReport.append(errorCapture);
- }
-
- if (!ctxt.keepGenerated()) {
- if (new File(javaFileName).delete() == false)
- log.error("Couldn't delete source: " + javaFileName);
- }
-
- if (compilationErrors || ie != null) {
- String errorReportString = errorReport.toString();
- log.error("Error compiling file: " + javaFileName + " " + errorReportString);
- JavacErrorDetail[] javacErrors = ErrorDispatcher.parseJavacErrors(errorReportString, javaFileName,
- pageNodes);
- if (javacErrors != null) {
- errDispatcher.javacError(javacErrors);
- } else {
- errDispatcher.javacError(errorReportString, ie);
- }
- }
-
- if (log.isDebugEnabled()) {
- long t2 = System.currentTimeMillis();
- log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2 - t1) + "ms");
- }
-
- if (ctxt.isPrototypeMode()) {
- return;
- }
-
- // JSR45 Support
- if (!options.isSmapSuppressed()) {
- log.debug("Install Smap " + (smap == null ? "null" : Arrays.toString(smap)));
- SmapUtil.installSmap(smap);
- }
- }
-
- protected static class SystemLogHandler extends PrintStream {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Construct the handler to capture the output of the given steam.
- */
- public SystemLogHandler(PrintStream wrapped) {
- super(wrapped);
- this.wrapped = wrapped;
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * Wrapped PrintStream.
- */
- protected PrintStream wrapped = null;
-
-
- /**
- * Thread <-> PrintStream associations.
- */
- protected static ThreadLocal streams = new ThreadLocal();
-
-
- /**
- * Thread <-> ByteArrayOutputStream associations.
- */
- protected static ThreadLocal data = new ThreadLocal();
-
-
- // --------------------------------------------------------- Public Methods
-
-
- public PrintStream getWrapped() {
- return wrapped;
- }
-
- /**
- * Start capturing thread's output.
- */
- public static void setThread() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- data.set(baos);
- streams.set(new PrintStream(baos));
- }
-
-
- /**
- * Stop capturing thread's output and return captured data as a String.
- */
- public static String unsetThread() {
- ByteArrayOutputStream baos =
- (ByteArrayOutputStream) data.get();
- if (baos == null) {
- return null;
- }
- streams.set(null);
- data.set(null);
- return baos.toString();
- }
-
-
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * Find PrintStream to which the output must be written to.
- */
- protected PrintStream findStream() {
- PrintStream ps = (PrintStream) streams.get();
- if (ps == null) {
- ps = wrapped;
- }
- return ps;
- }
-
-
- // ---------------------------------------------------- PrintStream Methods
-
-
- public void flush() {
- findStream().flush();
- }
-
- public void close() {
- findStream().close();
- }
-
- public boolean checkError() {
- return findStream().checkError();
- }
-
- protected void setError() {
- //findStream().setError();
- }
-
- public void write(int b) {
- findStream().write(b);
- }
-
- public void write(byte[] b)
- throws IOException {
- findStream().write(b);
- }
-
- public void write(byte[] buf, int off, int len) {
- findStream().write(buf, off, len);
- }
-
- public void print(boolean b) {
- findStream().print(b);
- }
-
- public void print(char c) {
- findStream().print(c);
- }
-
- public void print(int i) {
- findStream().print(i);
- }
-
- public void print(long l) {
- findStream().print(l);
- }
-
- public void print(float f) {
- findStream().print(f);
- }
-
- public void print(double d) {
- findStream().print(d);
- }
-
- public void print(char[] s) {
- findStream().print(s);
- }
-
- public void print(String s) {
- findStream().print(s);
- }
-
- public void print(Object obj) {
- findStream().print(obj);
- }
-
- public void println() {
- findStream().println();
- }
-
- public void println(boolean x) {
- findStream().println(x);
- }
-
- public void println(char x) {
- findStream().println(x);
- }
-
- public void println(int x) {
- findStream().println(x);
- }
-
- public void println(long x) {
- findStream().println(x);
- }
-
- public void println(float x) {
- findStream().println(x);
- }
-
- public void println(double x) {
- findStream().println(x);
- }
-
- public void println(char[] x) {
- findStream().println(x);
- }
-
- public void println(String x) {
- findStream().println(x);
- }
-
- public void println(Object x) {
- findStream().println(x);
- }
-
- }
-
-}
diff --git a/1.x/src/jasper7/JspC.java b/1.x/src/jasper7/JspC.java
deleted file mode 100644
index cf0ae68..0000000
--- a/1.x/src/jasper7/JspC.java
+++ /dev/null
@@ -1,1603 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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;
-
-import java.io.BufferedReader;
-import java.io.CharArrayWriter;
-import java.io.EOFException;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.io.Reader;
-import java.io.Writer;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.Stack;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
-import javax.servlet.jsp.tagext.TagLibraryInfo;
-
-import org.apache.jasper.compiler.Compiler;
-import org.apache.jasper.compiler.JspConfig;
-import org.apache.jasper.compiler.JspRuntimeContext;
-import org.apache.jasper.compiler.Localizer;
-import org.apache.jasper.compiler.TagPluginManager;
-import org.apache.jasper.compiler.TldLocationsCache;
-import org.apache.jasper.servlet.JspCServletContext;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-
-/**
- * Shell for the jspc compiler. Handles all options associated with the
- * command line and creates compilation contexts which it then compiles
- * according to the specified options.
- *
- * This version can process files from a _single_ webapp at once, i.e.
- * a single docbase can be specified.
- *
- * It can be used as an Ant task using:
- *
- * <taskdef classname="org.apache.jasper.JspC" name="jasper" >
- * <classpath>
- * <pathelement location="${java.home}/../lib/tools.jar"/>
- * <fileset dir="${ENV.CATALINA_HOME}/lib">
- * <include name="*.jar"/>
- * </fileset>
- * <path refid="myjars"/>
- * </classpath>
- * </taskdef>
- *
- * <jasper verbose="0"
- * package="my.package"
- * uriroot="${webapps.dir}/${webapp.name}"
- * webXmlFragment="${build.dir}/generated_web.xml"
- * outputDir="${webapp.dir}/${webapp.name}/WEB-INF/src/my/package" />
- *
- *
- * @author Danno Ferrin
- * @author Pierre Delisle
- * @author Costin Manolache
- * @author Yoav Shapira
- */
-public class JspC implements Options {
-
- public static final String DEFAULT_IE_CLASS_ID =
- "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";
-
- // Logger
- private static final Log log = LogFactory.getLog(JspC.class);
-
- protected static final String SWITCH_VERBOSE = "-v";
- protected static final String SWITCH_HELP = "-help";
- protected static final String SWITCH_OUTPUT_DIR = "-d";
- protected static final String SWITCH_PACKAGE_NAME = "-p";
- protected static final String SWITCH_CACHE = "-cache";
- protected static final String SWITCH_CLASS_NAME = "-c";
- protected static final String SWITCH_FULL_STOP = "--";
- protected static final String SWITCH_COMPILE = "-compile";
- protected static final String SWITCH_SOURCE = "-source";
- protected static final String SWITCH_TARGET = "-target";
- protected static final String SWITCH_URI_BASE = "-uribase";
- protected static final String SWITCH_URI_ROOT = "-uriroot";
- protected static final String SWITCH_FILE_WEBAPP = "-webapp";
- protected static final String SWITCH_WEBAPP_INC = "-webinc";
- protected static final String SWITCH_WEBAPP_XML = "-webxml";
- protected static final String SWITCH_WEBAPP_XML_ENCODING = "-webxmlencoding";
- protected static final String SWITCH_ADD_WEBAPP_XML_MAPPINGS = "-addwebxmlmappings";
- protected static final String SWITCH_MAPPED = "-mapped";
- protected static final String SWITCH_XPOWERED_BY = "-xpoweredBy";
- protected static final String SWITCH_TRIM_SPACES = "-trimSpaces";
- protected static final String SWITCH_CLASSPATH = "-classpath";
- protected static final String SWITCH_DIE = "-die";
- protected static final String SWITCH_POOLING = "-poolingEnabled";
- protected static final String SWITCH_ENCODING = "-javaEncoding";
- protected static final String SWITCH_SMAP = "-smap";
- protected static final String SWITCH_DUMP_SMAP = "-dumpsmap";
- protected static final String SHOW_SUCCESS ="-s";
- protected static final String LIST_ERRORS = "-l";
- protected static final int INC_WEBXML = 10;
- protected static final int ALL_WEBXML = 20;
- protected static final int DEFAULT_DIE_LEVEL = 1;
- protected static final int NO_DIE_LEVEL = 0;
- protected static final Set insertBefore = new HashSet();
-
- static {
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- insertBefore.add("");
- }
-
- protected String classPath = null;
- protected URLClassLoader loader = null;
- protected boolean trimSpaces = false;
- protected boolean genStringAsCharArray = false;
- protected boolean xpoweredBy;
- protected boolean mappedFile = false;
- protected boolean poolingEnabled = true;
- protected File scratchDir;
- protected String ieClassId = DEFAULT_IE_CLASS_ID;
- protected String targetPackage;
- protected String targetClassName;
- protected String uriBase;
- protected String uriRoot;
- protected int dieLevel;
- protected boolean helpNeeded = false;
- protected boolean compile = false;
- protected boolean smapSuppressed = true;
- protected boolean smapDumped = false;
- protected boolean caching = true;
- protected final Map cache =
- new HashMap();
-
- protected String compiler = null;
-
- protected String compilerTargetVM = "1.6";
- protected String compilerSourceVM = "1.6";
-
- protected boolean classDebugInfo = true;
-
- /**
- * Throw an exception if there's a compilation error, or swallow it.
- * Default is true to preserve old behavior.
- */
- protected boolean failOnError = true;
-
- /**
- * The file extensions to be handled as JSP files.
- * Default list is .jsp and .jspx.
- */
- protected List extensions;
-
- /**
- * The pages.
- */
- protected final List pages = new Vector();
-
- /**
- * Needs better documentation, this data member does.
- * True by default.
- */
- protected boolean errorOnUseBeanInvalidClassAttribute = true;
-
- /**
- * The java file encoding. Default
- * is UTF-8. Added per bugzilla 19622.
- */
- protected String javaEncoding = "UTF-8";
-
- // Generation of web.xml fragments
- protected String webxmlFile;
- protected int webxmlLevel;
- protected String webxmlEncoding;
- protected boolean addWebXmlMappings = false;
-
- protected Writer mapout;
- protected CharArrayWriter servletout;
- protected CharArrayWriter mappingout;
-
- /**
- * The servlet context.
- */
- protected JspCServletContext context;
-
- /**
- * The runtime context.
- * Maintain a dummy JspRuntimeContext for compiling tag files.
- */
- protected JspRuntimeContext rctxt;
-
- /**
- * Cache for the TLD locations
- */
- protected TldLocationsCache tldLocationsCache = null;
-
- protected JspConfig jspConfig = null;
- protected TagPluginManager tagPluginManager = null;
-
- protected boolean verbose = false;
- protected boolean listErrors = false;
- protected boolean showSuccess = false;
- protected int argPos;
- protected boolean fullstop = false;
- protected String args[];
-
- public static void main(String arg[]) {
- if (arg.length == 0) {
- System.out.println(Localizer.getMessage("jspc.usage"));
- } else {
- JspC jspc = new JspC();
- try {
- jspc.setArgs(arg);
- if (jspc.helpNeeded) {
- System.out.println(Localizer.getMessage("jspc.usage"));
- } else {
- jspc.execute();
- }
- } catch (JasperException je) {
- System.err.println(je);
- if (jspc.dieLevel != NO_DIE_LEVEL) {
- System.exit(jspc.dieLevel);
- }
- } catch (Exception je) {
- System.err.println(je);
- if (jspc.dieLevel != NO_DIE_LEVEL) {
- System.exit(jspc.dieLevel);
- }
- }
- }
- }
-
- /**
- * Apply command-line arguments.
- *
- * @param arg
- * The arguments
- */
- public void setArgs(String[] arg) throws JasperException {
- args = arg;
- String tok;
-
- dieLevel = NO_DIE_LEVEL;
-
- while ((tok = nextArg()) != null) {
- if (tok.equals(SWITCH_VERBOSE)) {
- verbose = true;
- showSuccess = true;
- listErrors = true;
- } else if (tok.equals(SWITCH_OUTPUT_DIR)) {
- tok = nextArg();
- setOutputDir( tok );
- } else if (tok.equals(SWITCH_PACKAGE_NAME)) {
- targetPackage = nextArg();
- } else if (tok.equals(SWITCH_COMPILE)) {
- compile=true;
- } else if (tok.equals(SWITCH_CLASS_NAME)) {
- targetClassName = nextArg();
- } else if (tok.equals(SWITCH_URI_BASE)) {
- uriBase=nextArg();
- } else if (tok.equals(SWITCH_URI_ROOT)) {
- setUriroot( nextArg());
- } else if (tok.equals(SWITCH_FILE_WEBAPP)) {
- setUriroot( nextArg());
- } else if ( tok.equals( SHOW_SUCCESS ) ) {
- showSuccess = true;
- } else if ( tok.equals( LIST_ERRORS ) ) {
- listErrors = true;
- } else if (tok.equals(SWITCH_WEBAPP_INC)) {
- webxmlFile = nextArg();
- if (webxmlFile != null) {
- webxmlLevel = INC_WEBXML;
- }
- } else if (tok.equals(SWITCH_WEBAPP_XML)) {
- webxmlFile = nextArg();
- if (webxmlFile != null) {
- webxmlLevel = ALL_WEBXML;
- }
- } else if (tok.equals(SWITCH_WEBAPP_XML_ENCODING)) {
- setWebXmlEncoding(nextArg());
- } else if (tok.equals(SWITCH_ADD_WEBAPP_XML_MAPPINGS)) {
- setAddWebXmlMappings(true);
- } else if (tok.equals(SWITCH_MAPPED)) {
- mappedFile = true;
- } else if (tok.equals(SWITCH_XPOWERED_BY)) {
- xpoweredBy = true;
- } else if (tok.equals(SWITCH_TRIM_SPACES)) {
- setTrimSpaces(true);
- } else if (tok.equals(SWITCH_CACHE)) {
- tok = nextArg();
- if ("false".equals(tok)) {
- caching = false;
- } else {
- caching = true;
- }
- } else if (tok.equals(SWITCH_CLASSPATH)) {
- setClassPath(nextArg());
- } else if (tok.startsWith(SWITCH_DIE)) {
- try {
- dieLevel = Integer.parseInt(
- tok.substring(SWITCH_DIE.length()));
- } catch (NumberFormatException nfe) {
- dieLevel = DEFAULT_DIE_LEVEL;
- }
- } else if (tok.equals(SWITCH_HELP)) {
- helpNeeded = true;
- } else if (tok.equals(SWITCH_POOLING)) {
- tok = nextArg();
- if ("false".equals(tok)) {
- poolingEnabled = false;
- } else {
- poolingEnabled = true;
- }
- } else if (tok.equals(SWITCH_ENCODING)) {
- setJavaEncoding(nextArg());
- } else if (tok.equals(SWITCH_SOURCE)) {
- setCompilerSourceVM(nextArg());
- } else if (tok.equals(SWITCH_TARGET)) {
- setCompilerTargetVM(nextArg());
- } else if (tok.equals(SWITCH_SMAP)) {
- smapSuppressed = false;
- } else if (tok.equals(SWITCH_DUMP_SMAP)) {
- smapDumped = true;
- } else {
- if (tok.startsWith("-")) {
- throw new JasperException("Unrecognized option: " + tok +
- ". Use -help for help.");
- }
- if (!fullstop) {
- argPos--;
- }
- // Start treating the rest as JSP Pages
- break;
- }
- }
-
- // Add all extra arguments to the list of files
- while( true ) {
- String file = nextFile();
- if( file==null ) {
- break;
- }
- pages.add( file );
- }
- }
-
- /**
- * In JspC this always returns true.
- * {@inheritDoc}
- */
- @Override
- public boolean getKeepGenerated() {
- // isn't this why we are running jspc?
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getTrimSpaces() {
- return trimSpaces;
- }
-
- /**
- * Sets the option to trim white spaces between directives or actions.
- */
- public void setTrimSpaces(boolean ts) {
- this.trimSpaces = ts;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isPoolingEnabled() {
- return poolingEnabled;
- }
-
- /**
- * Sets the option to enable the tag handler pooling.
- */
- public void setPoolingEnabled(boolean poolingEnabled) {
- this.poolingEnabled = poolingEnabled;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isXpoweredBy() {
- return xpoweredBy;
- }
-
- /**
- * Sets the option to enable generation of X-Powered-By response header.
- */
- public void setXpoweredBy(boolean xpoweredBy) {
- this.xpoweredBy = xpoweredBy;
- }
-
- /**
- * In JspC this always returns true.
- * {@inheritDoc}
- */
- @Override
- public boolean getDisplaySourceFragment() {
- return true;
- }
-
- @Override
- public int getMaxLoadedJsps() {
- return -1;
- }
-
- @Override
- public int getJspIdleTimeout() {
- return -1;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getErrorOnUseBeanInvalidClassAttribute() {
- return errorOnUseBeanInvalidClassAttribute;
- }
-
- /**
- * Sets the option to issue a compilation error if the class attribute
- * specified in useBean action is invalid.
- */
- public void setErrorOnUseBeanInvalidClassAttribute(boolean b) {
- errorOnUseBeanInvalidClassAttribute = b;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getMappedFile() {
- return mappedFile;
- }
-
- /**
- * Sets the option to include debug information in compiled class.
- */
- public void setClassDebugInfo( boolean b ) {
- classDebugInfo=b;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getClassDebugInfo() {
- // compile with debug info
- return classDebugInfo;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isCaching() {
- return caching;
- }
-
- /**
- * Sets the option to enable caching.
- *
- * @see Options#isCaching()
- */
- public void setCaching(boolean caching) {
- this.caching = caching;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Map getCache() {
- return cache;
- }
-
- /**
- * In JspC this always returns 0.
- * {@inheritDoc}
- */
- @Override
- public int getCheckInterval() {
- return 0;
- }
-
- /**
- * In JspC this always returns 0.
- * {@inheritDoc}
- */
- @Override
- public int getModificationTestInterval() {
- return 0;
- }
-
-
- /**
- * In JspC this always returns false.
- * {@inheritDoc}
- */
- @Override
- public boolean getRecompileOnFail() {
- return false;
- }
-
-
- /**
- * In JspC this always returns false.
- * {@inheritDoc}
- */
- @Override
- public boolean getDevelopment() {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isSmapSuppressed() {
- return smapSuppressed;
- }
-
- /**
- * Sets smapSuppressed flag.
- */
- public void setSmapSuppressed(boolean smapSuppressed) {
- this.smapSuppressed = smapSuppressed;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isSmapDumped() {
- return smapDumped;
- }
-
- /**
- * Sets smapDumped flag.
- *
- * @see Options#isSmapDumped()
- */
- public void setSmapDumped(boolean smapDumped) {
- this.smapDumped = smapDumped;
- }
-
-
- /**
- * Determines whether text strings are to be generated as char arrays,
- * which improves performance in some cases.
- *
- * @param genStringAsCharArray true if text strings are to be generated as
- * char arrays, false otherwise
- */
- public void setGenStringAsCharArray(boolean genStringAsCharArray) {
- this.genStringAsCharArray = genStringAsCharArray;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean genStringAsCharArray() {
- return genStringAsCharArray;
- }
-
- /**
- * Sets the class-id value to be sent to Internet Explorer when using
- * <jsp:plugin> tags.
- *
- * @param ieClassId
- * Class-id value
- */
- public void setIeClassId(String ieClassId) {
- this.ieClassId = ieClassId;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getIeClassId() {
- return ieClassId;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public File getScratchDir() {
- return scratchDir;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getCompiler() {
- return compiler;
- }
-
- /**
- * Sets the option to determine what compiler to use.
- *
- * @see Options#getCompiler()
- */
- public void setCompiler(String c) {
- compiler=c;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getCompilerClassName() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getCompilerTargetVM() {
- return compilerTargetVM;
- }
-
- /**
- * Sets the compiler target VM.
- *
- * @see Options#getCompilerTargetVM()
- */
- public void setCompilerTargetVM(String vm) {
- compilerTargetVM = vm;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getCompilerSourceVM() {
- return compilerSourceVM;
- }
-
- /**
- * Sets the compiler source VM.
- *
- * @see Options#getCompilerSourceVM()
- */
- public void setCompilerSourceVM(String vm) {
- compilerSourceVM = vm;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public TldLocationsCache getTldLocationsCache() {
- return tldLocationsCache;
- }
-
- /**
- * Returns the encoding to use for
- * java files. The default is UTF-8.
- *
- * @return String The encoding
- */
- @Override
- public String getJavaEncoding() {
- return javaEncoding;
- }
-
- /**
- * Sets the encoding to use for
- * java files.
- *
- * @param encodingName The name, e.g. "UTF-8"
- */
- public void setJavaEncoding(String encodingName) {
- javaEncoding = encodingName;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean getFork() {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getClassPath() {
- if( classPath != null )
- return classPath;
- return System.getProperty("java.class.path");
- }
-
- /**
- * Sets the classpath used while compiling the servlets generated from JSP
- * files
- */
- public void setClassPath(String s) {
- classPath=s;
- }
-
- /**
- * Returns the list of file extensions
- * that are treated as JSP files.
- *
- * @return The list of extensions
- */
- public List getExtensions() {
- return extensions;
- }
-
- /**
- * Adds the given file extension to the
- * list of extensions handled as JSP files.
- *
- * @param extension The extension to add, e.g. "myjsp"
- */
- protected void addExtension(final String extension) {
- if(extension != null) {
- if(extensions == null) {
- extensions = new Vector();
- }
-
- extensions.add(extension);
- }
- }
-
- /**
- * Base dir for the webapp. Used to generate class names and resolve
- * includes.
- */
- public void setUriroot( String s ) {
- if (s == null) {
- uriRoot = null;
- return;
- }
- try {
- uriRoot = resolveFile(s).getCanonicalPath();
- } catch( Exception ex ) {
- uriRoot = s;
- }
- }
-
- /**
- * Parses comma-separated list of JSP files to be processed. If the argument
- * is null, nothing is done.
- *
- * Each file is interpreted relative to uriroot, unless it is absolute,
- * in which case it must start with uriroot.
- *
- * @param jspFiles Comma-separated list of JSP files to be processed
- */
- public void setJspFiles(final String jspFiles) {
- if(jspFiles == null) {
- return;
- }
-
- StringTokenizer tok = new StringTokenizer(jspFiles, ",");
- while (tok.hasMoreTokens()) {
- pages.add(tok.nextToken());
- }
- }
-
- /**
- * Sets the compile flag.
- *
- * @param b Flag value
- */
- public void setCompile( final boolean b ) {
- compile = b;
- }
-
- /**
- * Sets the verbosity level. The actual number doesn't
- * matter: if it's greater than zero, the verbose flag will
- * be true.
- *
- * @param level Positive means verbose
- */
- public void setVerbose( final int level ) {
- if (level > 0) {
- verbose = true;
- showSuccess = true;
- listErrors = true;
- }
- }
-
- public void setValidateXml( boolean b ) {
- org.apache.jasper.xmlparser.ParserUtils.validating=b;
- }
-
- public void setListErrors( boolean b ) {
- listErrors = b;
- }
-
- public void setOutputDir( String s ) {
- if( s!= null ) {
- scratchDir = resolveFile(s).getAbsoluteFile();
- } else {
- scratchDir=null;
- }
- }
-
- /**
- * Sets the package name to be used for the generated servlet classes.
- */
- public void setPackage( String p ) {
- targetPackage=p;
- }
-
- /**
- * Class name of the generated file ( without package ).
- * Can only be used if a single file is converted.
- * XXX Do we need this feature ?
- */
- public void setClassName( String p ) {
- targetClassName=p;
- }
-
- /**
- * File where we generate a web.xml fragment with the class definitions.
- */
- public void setWebXmlFragment( String s ) {
- webxmlFile=resolveFile(s).getAbsolutePath();
- webxmlLevel=INC_WEBXML;
- }
-
- /**
- * File where we generate a complete web.xml with the class definitions.
- */
- public void setWebXml( String s ) {
- webxmlFile=resolveFile(s).getAbsolutePath();
- webxmlLevel=ALL_WEBXML;
- }
-
- /**
- * Sets the encoding to be used to read and write web.xml files.
- *
- *
- * If not specified, defaults to the platform default encoding.
- *
- *
- * @param encoding
- * Encoding, e.g. "UTF-8".
- */
- public void setWebXmlEncoding(String encoding) {
- webxmlEncoding = encoding;
- }
-
- /**
- * Sets the option to merge generated web.xml fragment into the
- * WEB-INF/web.xml file of the web application that we were processing.
- *
- * @param b
- * true to merge the fragment into the existing
- * web.xml file of the processed web application
- * ({uriroot}/WEB-INF/web.xml), false to keep the
- * generated web.xml fragment
- */
- public void setAddWebXmlMappings(boolean b) {
- addWebXmlMappings = b;
- }
-
- /**
- * Sets the option that throws an exception in case of a compilation error.
- */
- public void setFailOnError(final boolean b) {
- failOnError = b;
- }
-
- /**
- * Returns true if an exception will be thrown in case of a compilation
- * error.
- */
- public boolean getFailOnError() {
- return failOnError;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public JspConfig getJspConfig() {
- return jspConfig;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public TagPluginManager getTagPluginManager() {
- return tagPluginManager;
- }
-
- /**
- * Adds servlet declaration and mapping for the JSP page servlet to the
- * generated web.xml fragment.
- *
- * @param file
- * Context-relative path to the JSP file, e.g.
- * /index.jsp
- * @param clctxt
- * Compilation context of the servlet
- */
- public void generateWebMapping( String file, JspCompilationContext clctxt )
- throws IOException
- {
- if (log.isDebugEnabled()) {
- log.debug("Generating web mapping for file " + file
- + " using compilation context " + clctxt);
- }
-
- String className = clctxt.getServletClassName();
- String packageName = clctxt.getServletPackageName();
-
- String thisServletName;
- if ("".equals(packageName)) {
- thisServletName = className;
- } else {
- thisServletName = packageName + '.' + className;
- }
-
- if (servletout != null) {
- servletout.write("\n \n ");
- servletout.write(thisServletName);
- servletout.write("\n ");
- servletout.write(thisServletName);
- servletout.write("\n \n");
- }
- if (mappingout != null) {
- mappingout.write("\n \n ");
- mappingout.write(thisServletName);
- mappingout.write("\n ");
- mappingout.write(file.replace('\\', '/'));
- mappingout.write("\n \n");
-
- }
- }
-
- /**
- * Include the generated web.xml inside the webapp's web.xml.
- */
- protected void mergeIntoWebXml() throws IOException {
-
- File webappBase = new File(uriRoot);
- File webXml = new File(webappBase, "WEB-INF/web.xml");
- File webXml2 = new File(webappBase, "WEB-INF/web2.xml");
- String insertStartMarker =
- Localizer.getMessage("jspc.webinc.insertStart");
- String insertEndMarker =
- Localizer.getMessage("jspc.webinc.insertEnd");
-
- BufferedReader reader = new BufferedReader(openWebxmlReader(webXml));
- BufferedReader fragmentReader = new BufferedReader(
- openWebxmlReader(new File(webxmlFile)));
- PrintWriter writer = new PrintWriter(openWebxmlWriter(webXml2));
-
- // Insert the and declarations
- boolean inserted = false;
- int current = reader.read();
- while (current > -1) {
- if (current == '<') {
- String element = getElement(reader);
- if (!inserted && insertBefore.contains(element)) {
- // Insert generated content here
- writer.println(insertStartMarker);
- while (true) {
- String line = fragmentReader.readLine();
- if (line == null) {
- writer.println();
- break;
- }
- writer.println(line);
- }
- writer.println(insertEndMarker);
- writer.println();
- writer.write(element);
- inserted = true;
- } else if (element.equals(insertStartMarker)) {
- // Skip the previous auto-generated content
- while (true) {
- current = reader.read();
- if (current < 0) {
- throw new EOFException();
- }
- if (current == '<') {
- element = getElement(reader);
- if (element.equals(insertEndMarker)) {
- break;
- }
- }
- }
- current = reader.read();
- while (current == '\n' || current == '\r') {
- current = reader.read();
- }
- continue;
- } else {
- writer.write(element);
- }
- } else {
- writer.write(current);
- }
- current = reader.read();
- }
- writer.close();
-
- reader.close();
- fragmentReader.close();
-
- FileInputStream fis = new FileInputStream(webXml2);
- FileOutputStream fos = new FileOutputStream(webXml);
-
- byte buf[] = new byte[512];
- while (true) {
- int n = fis.read(buf);
- if (n < 0) {
- break;
- }
- fos.write(buf, 0, n);
- }
-
- fis.close();
- fos.close();
-
- if(!webXml2.delete() && log.isDebugEnabled())
- log.debug(Localizer.getMessage("jspc.delete.fail",
- webXml2.toString()));
-
- if (!(new File(webxmlFile)).delete() && log.isDebugEnabled())
- log.debug(Localizer.getMessage("jspc.delete.fail", webxmlFile));
-
- }
-
- /*
- * Assumes valid xml
- */
- private String getElement(Reader reader) throws IOException {
- StringBuilder result = new StringBuilder();
- result.append('<');
-
- boolean done = false;
-
- while (!done) {
- int current = reader.read();
- while (current != '>') {
- if (current < 0) {
- throw new EOFException();
- }
- result.append((char) current);
- current = reader.read();
- }
- result.append((char) current);
-
- int len = result.length();
- if (len > 4 && result.substring(0, 4).equals("")) {
- done = true;
- }
- } else {
- done = true;
- }
- }
-
-
- return result.toString();
- }
-
- protected void processFile(String file)
- throws JasperException
- {
- if (log.isDebugEnabled()) {
- log.debug("Processing file: " + file);
- }
-
- ClassLoader originalClassLoader = null;
-
- try {
- // set up a scratch/output dir if none is provided
- if (scratchDir == null) {
- String temp = System.getProperty("java.io.tmpdir");
- if (temp == null) {
- temp = "";
- }
- scratchDir = new File(new File(temp).getAbsolutePath());
- }
-
- String jspUri=file.replace('\\','/');
- JspCompilationContext clctxt = new JspCompilationContext
- ( jspUri, this, context, null, rctxt );
-
- /* Override the defaults */
- if ((targetClassName != null) && (targetClassName.length() > 0)) {
- clctxt.setServletClassName(targetClassName);
- targetClassName = null;
- }
- if (targetPackage != null) {
- clctxt.setServletPackageName(targetPackage);
- }
-
- originalClassLoader = Thread.currentThread().getContextClassLoader();
- if( loader==null ) {
- initClassLoader( clctxt );
- }
- Thread.currentThread().setContextClassLoader(loader);
-
- clctxt.setClassLoader(loader);
- clctxt.setClassPath(classPath);
-
- Compiler clc = clctxt.createCompiler();
-
- // If compile is set, generate both .java and .class, if
- // .jsp file is newer than .class file;
- // Otherwise only generate .java, if .jsp file is newer than
- // the .java file
- if( clc.isOutDated(compile) ) {
- if (log.isDebugEnabled()) {
- log.debug(jspUri + " is out dated, compiling...");
- }
-
- clc.compile(compile, true);
- }
-
- // Generate mapping
- generateWebMapping( file, clctxt );
- if ( showSuccess ) {
- log.info( "Built File: " + file );
- }
-
- } catch (JasperException je) {
- Throwable rootCause = je;
- while (rootCause instanceof JasperException
- && ((JasperException) rootCause).getRootCause() != null) {
- rootCause = ((JasperException) rootCause).getRootCause();
- }
- if (rootCause != je) {
- log.error(Localizer.getMessage("jspc.error.generalException",
- file),
- rootCause);
- }
-
- // Bugzilla 35114.
- if(getFailOnError()) {
- throw je;
- } else {
- log.error(je.getMessage());
- }
-
- } catch (Exception e) {
- if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) {
- log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist",
- e.getMessage()));
- }
- throw new JasperException(e);
- } finally {
- if(originalClassLoader != null) {
- Thread.currentThread().setContextClassLoader(originalClassLoader);
- }
- }
- }
-
- /**
- * Locate all jsp files in the webapp. Used if no explicit
- * jsps are specified.
- */
- public void scanFiles( File base ) throws JasperException {
- Stack dirs = new Stack();
- dirs.push(base.toString());
-
- // Make sure default extensions are always included
- if ((getExtensions() == null) || (getExtensions().size() < 2)) {
- addExtension("jsp");
- addExtension("jspx");
- }
-
- while (!dirs.isEmpty()) {
- String s = dirs.pop();
- File f = new File(s);
- if (f.exists() && f.isDirectory()) {
- String[] files = f.list();
- String ext;
- for (int i = 0; (files != null) && i < files.length; i++) {
- File f2 = new File(s, files[i]);
- if (f2.isDirectory()) {
- dirs.push(f2.getPath());
- } else {
- String path = f2.getPath();
- String uri = path.substring(uriRoot.length());
- ext = files[i].substring(files[i].lastIndexOf('.') +1);
- if (getExtensions().contains(ext) ||
- jspConfig.isJspPage(uri)) {
- pages.add(path);
- }
- }
- }
- }
- }
- }
-
- /**
- * Executes the compilation.
- *
- * @throws JasperException If an error occurs
- */
- public void execute() {
- if(log.isDebugEnabled()) {
- log.debug("execute() starting for " + pages.size() + " pages.");
- }
-
- try {
- if (uriRoot == null) {
- if( pages.size() == 0 ) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.missingTarget"));
- }
- String firstJsp = pages.get( 0 );
- File firstJspF = new File( firstJsp );
- if (!firstJspF.exists()) {
- throw new JasperException(
- Localizer.getMessage("jspc.error.fileDoesNotExist",
- firstJsp));
- }
- locateUriRoot( firstJspF );
- }
-
- if (uriRoot == null) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.no_uriroot"));
- }
-
- File uriRootF = new File(uriRoot);
- if (!uriRootF.isDirectory()) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.uriroot_not_dir"));
- }
-
- if(context == null) {
- initServletContext();
- }
-
- // No explicit pages, we'll process all .jsp in the webapp
- if (pages.size() == 0) {
- scanFiles(uriRootF);
- }
-
- initWebXml();
-
- Iterator iter = pages.iterator();
- while (iter.hasNext()) {
- String nextjsp = iter.next().toString();
- File fjsp = new File(nextjsp);
- if (!fjsp.isAbsolute()) {
- fjsp = new File(uriRootF, nextjsp);
- }
- if (!fjsp.exists()) {
- if (log.isWarnEnabled()) {
- log.warn
- (Localizer.getMessage
- ("jspc.error.fileDoesNotExist", fjsp.toString()));
- }
- continue;
- }
- String s = fjsp.getAbsolutePath();
- if (s.startsWith(uriRoot)) {
- nextjsp = s.substring(uriRoot.length());
- }
- if (nextjsp.startsWith("." + File.separatorChar)) {
- nextjsp = nextjsp.substring(2);
- }
- processFile(nextjsp);
- }
-
- completeWebXml();
-
- if (addWebXmlMappings) {
- mergeIntoWebXml();
- }
-
- } catch (IOException ioe) {
- throw new RuntimeException("Build - "+ioe, ioe);
-
- } catch (JasperException je) {
- Throwable rootCause = je;
- while (rootCause instanceof JasperException
- && ((JasperException) rootCause).getRootCause() != null) {
- rootCause = ((JasperException) rootCause).getRootCause();
- }
- if (rootCause != je) {
- rootCause.printStackTrace();
- }
- throw new RuntimeException("Build - "+je, je);
- } finally {
- if (loader != null) {
- LogFactory.release(loader);
- }
- }
- }
-
- // ==================== protected utility methods ====================
-
- protected String nextArg() {
- if ((argPos >= args.length)
- || (fullstop = SWITCH_FULL_STOP.equals(args[argPos]))) {
- return null;
- } else {
- return args[argPos++];
- }
- }
-
- protected String nextFile() {
- if (fullstop) argPos++;
- if (argPos >= args.length) {
- return null;
- } else {
- return args[argPos++];
- }
- }
-
- protected void initWebXml() {
- try {
- if (webxmlLevel >= INC_WEBXML) {
- mapout = openWebxmlWriter(new File(webxmlFile));
- servletout = new CharArrayWriter();
- mappingout = new CharArrayWriter();
- } else {
- mapout = null;
- servletout = null;
- mappingout = null;
- }
- if (webxmlLevel >= ALL_WEBXML) {
- mapout.write(Localizer.getMessage("jspc.webxml.header"));
- mapout.flush();
- } else if ((webxmlLevel>= INC_WEBXML) && !addWebXmlMappings) {
- mapout.write(Localizer.getMessage("jspc.webinc.header"));
- mapout.flush();
- }
- } catch (IOException ioe) {
- mapout = null;
- servletout = null;
- mappingout = null;
- }
- }
-
- protected void completeWebXml() {
- if (mapout != null) {
- try {
- servletout.writeTo(mapout);
- mappingout.writeTo(mapout);
- if (webxmlLevel >= ALL_WEBXML) {
- mapout.write(Localizer.getMessage("jspc.webxml.footer"));
- } else if ((webxmlLevel >= INC_WEBXML) && !addWebXmlMappings) {
- mapout.write(Localizer.getMessage("jspc.webinc.footer"));
- }
- mapout.close();
- } catch (IOException ioe) {
- // noting to do if it fails since we are done with it
- }
- }
- }
-
- protected void initServletContext() {
- try {
- context =new JspCServletContext
- (new PrintWriter(System.out),
- new URL("file:" + uriRoot.replace('\\','/') + '/'));
- tldLocationsCache = TldLocationsCache.getInstance(context);
- } catch (MalformedURLException me) {
- System.out.println("**" + me);
- }
- rctxt = new JspRuntimeContext(context, this);
- jspConfig = new JspConfig(context);
- tagPluginManager = new TagPluginManager(context);
- }
-
- /**
- * Initializes the classloader as/if needed for the given
- * compilation context.
- *
- * @param clctxt The compilation context
- * @throws IOException If an error occurs
- */
- protected void initClassLoader(JspCompilationContext clctxt)
- throws IOException {
-
- classPath = getClassPath();
-
- ClassLoader jspcLoader = getClass().getClassLoader();
- // TODO add 7Bee class loader
- // Turn the classPath into URLs
- ArrayList urls = new ArrayList();
- StringTokenizer tokenizer = new StringTokenizer(classPath,
- File.pathSeparator);
- while (tokenizer.hasMoreTokens()) {
- String path = tokenizer.nextToken();
- try {
- File libFile = new File(path);
- urls.add(libFile.toURI().toURL());
- } catch (IOException ioe) {
- // Failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak uot
- throw new RuntimeException(ioe.toString());
- }
- }
-
- File webappBase = new File(uriRoot);
- if (webappBase.exists()) {
- File classes = new File(webappBase, "/WEB-INF/classes");
- try {
- if (classes.exists()) {
- classPath = classPath + File.pathSeparator
- + classes.getCanonicalPath();
- urls.add(classes.getCanonicalFile().toURI().toURL());
- }
- } catch (IOException ioe) {
- // failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak out
- throw new RuntimeException(ioe.toString());
- }
- File lib = new File(webappBase, "/WEB-INF/lib");
- if (lib.exists() && lib.isDirectory()) {
- String[] libs = lib.list();
- for (int i = 0; i < libs.length; i++) {
- if( libs[i].length() <5 ) continue;
- String ext=libs[i].substring( libs[i].length() - 4 );
- if (! ".jar".equalsIgnoreCase(ext)) {
- if (".tld".equalsIgnoreCase(ext)) {
- log.warn("TLD files should not be placed in "
- + "/WEB-INF/lib");
- }
- continue;
- }
- try {
- File libFile = new File(lib, libs[i]);
- classPath = classPath + File.pathSeparator
- + libFile.getAbsolutePath();
- urls.add(libFile.getAbsoluteFile().toURI().toURL());
- } catch (IOException ioe) {
- // failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak out
- throw new RuntimeException(ioe.toString());
- }
- }
- }
- }
-
- // What is this ??
- urls.add(new File(
- clctxt.getRealPath("/")).getCanonicalFile().toURI().toURL());
-
- URL urlsA[]=new URL[urls.size()];
- urls.toArray(urlsA);
- loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());
- context.setClassLoader(loader);
- }
-
- /**
- * Find the WEB-INF dir by looking up in the directory tree.
- * This is used if no explicit docbase is set, but only files.
- * XXX Maybe we should require the docbase.
- */
- protected void locateUriRoot( File f ) {
- String tUriBase = uriBase;
- if (tUriBase == null) {
- tUriBase = "/";
- }
- try {
- if (f.exists()) {
- f = new File(f.getAbsolutePath());
- while (true) {
- File g = new File(f, "WEB-INF");
- if (g.exists() && g.isDirectory()) {
- uriRoot = f.getCanonicalPath();
- uriBase = tUriBase;
- if (log.isInfoEnabled()) {
- log.info(Localizer.getMessage(
- "jspc.implicit.uriRoot",
- uriRoot));
- }
- break;
- }
- if (f.exists() && f.isDirectory()) {
- tUriBase = "/" + f.getName() + "/" + tUriBase;
- }
-
- String fParent = f.getParent();
- if (fParent == null) {
- break;
- } else {
- f = new File(fParent);
- }
-
- // If there is no acceptable candidate, uriRoot will
- // remain null to indicate to the CompilerContext to
- // use the current working/user dir.
- }
-
- if (uriRoot != null) {
- File froot = new File(uriRoot);
- uriRoot = froot.getCanonicalPath();
- }
- }
- } catch (IOException ioe) {
- // since this is an optional default and a null value
- // for uriRoot has a non-error meaning, we can just
- // pass straight through
- }
- }
-
- /**
- * Resolves the relative or absolute pathname correctly
- * in both Ant and command-line situations. If Ant launched
- * us, we should use the basedir of the current project
- * to resolve relative paths.
- *
- * See Bugzilla 35571.
- *
- * @param s The file
- * @return The file resolved
- */
- protected File resolveFile(final String s) {
- // TODO consider some massaging of s as relative path to project home
- return new File(s);
- }
-
- private Reader openWebxmlReader(File file) throws IOException {
- FileInputStream fis = new FileInputStream(file);
- try {
- return webxmlEncoding != null ? new InputStreamReader(fis,
- webxmlEncoding) : new InputStreamReader(fis);
- } catch (IOException ex) {
- fis.close();
- throw ex;
- }
- }
-
- private Writer openWebxmlWriter(File file) throws IOException {
- FileOutputStream fos = new FileOutputStream(file);
- try {
- return webxmlEncoding != null ? new OutputStreamWriter(fos,
- webxmlEncoding) : new OutputStreamWriter(fos);
- } catch (IOException ex) {
- fos.close();
- throw ex;
- }
- }
-}
diff --git a/1.x/src/jasper7/JspCompilationContext.java b/1.x/src/jasper7/JspCompilationContext.java
deleted file mode 100644
index df5a177..0000000
--- a/1.x/src/jasper7/JspCompilationContext.java
+++ /dev/null
@@ -1,794 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.net.JarURLConnection;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.net.URLConnection;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import javax.servlet.ServletContext;
-import javax.servlet.jsp.tagext.TagInfo;
-
-import org.apache.jasper.compiler.Compiler;
-import org.apache.jasper.compiler.JarResource;
-import org.apache.jasper.compiler.JspRuntimeContext;
-import org.apache.jasper.compiler.JspUtil;
-import org.apache.jasper.compiler.Localizer;
-import org.apache.jasper.compiler.ServletWriter;
-import org.apache.jasper.compiler.TldLocation;
-import org.apache.jasper.servlet.JasperLoader;
-import org.apache.jasper.servlet.JspServletWrapper;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-
-/**
- * A place holder for various things that are used through out the JSP
- * engine. This is a per-request/per-context data structure. Some of
- * the instance variables are set at different points.
- *
- * Most of the path-related stuff is here - mangling names, versions, dirs,
- * loading resources and dealing with uris.
- *
- * @author Anil K. Vijendran
- * @author Harish Prabandham
- * @author Pierre Delisle
- * @author Costin Manolache
- * @author Kin-man Chung
- */
-public class JspCompilationContext {
-
- private final Log log = LogFactory.getLog(JspCompilationContext.class); // must not be static
-
- protected Map tagFileJarUrls;
-
- protected String className;
- protected String jspUri;
- protected String basePackageName;
- protected String derivedPackageName;
- protected String servletJavaFileName;
- protected String javaPath;
- protected String classFileName;
- protected ServletWriter writer;
- protected Options options;
- protected JspServletWrapper jsw;
- protected Compiler jspCompiler;
- protected String classPath;
-
- protected String baseURI;
- protected String outputDir;
- protected ServletContext context;
- protected ClassLoader loader;
-
- protected JspRuntimeContext rctxt;
-
- protected volatile int removed = 0;
-
- protected URLClassLoader jspLoader;
- protected URL baseUrl;
- protected Class> servletClass;
-
- protected boolean isTagFile;
- protected boolean protoTypeMode;
- protected TagInfo tagInfo;
- protected JarResource tagJarResource;
-
- // jspURI _must_ be relative to the context
- public JspCompilationContext(String jspUri,
- Options options,
- ServletContext context,
- JspServletWrapper jsw,
- JspRuntimeContext rctxt) {
-
- this.jspUri = canonicalURI(jspUri);
- this.options = options;
- this.jsw = jsw;
- this.context = context;
-
- this.baseURI = jspUri.substring(0, jspUri.lastIndexOf('/') + 1);
- // hack fix for resolveRelativeURI
- if (baseURI == null) {
- 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.rctxt = rctxt;
- this.tagFileJarUrls = new HashMap();
- this.basePackageName = Constants.JSP_PACKAGE_NAME;
- }
-
- public JspCompilationContext(String tagfile,
- TagInfo tagInfo,
- Options options,
- ServletContext context,
- JspServletWrapper jsw,
- JspRuntimeContext rctxt,
- JarResource tagJarResource) {
- this(tagfile, options, context, jsw, rctxt);
- this.isTagFile = true;
- this.tagInfo = tagInfo;
- this.tagJarResource = tagJarResource;
- }
-
- /* ==================== Methods to override ==================== */
-
- /** ---------- Class path and loader ---------- */
-
- /**
- * The classpath that is passed off to the Java compiler.
- */
- public String getClassPath() {
- if( classPath != null )
- return classPath;
- return rctxt.getClassPath();
- }
-
- /**
- * The classpath that is passed off to the Java compiler.
- */
- public void setClassPath(String classPath) {
- this.classPath = classPath;
- }
-
- /**
- * What class loader to use for loading classes while compiling
- * this JSP?
- */
- public ClassLoader getClassLoader() {
- if( loader != null )
- return loader;
- return rctxt.getParentClassLoader();
- }
-
- public void setClassLoader(ClassLoader loader) {
- this.loader = loader;
- }
-
- public ClassLoader getJspLoader() {
- if( jspLoader == null ) {
- jspLoader = new JasperLoader
- (new URL[] {baseUrl},
- getClassLoader(),
- rctxt.getPermissionCollection());
- }
- return jspLoader;
- }
-
- /** ---------- Input/Output ---------- */
-
- /**
- * The output directory to generate code into. The output directory
- * is make up of the scratch directory, which is provide in Options,
- * plus the directory derived from the package name.
- */
- public String getOutputDir() {
- if (outputDir == null) {
- createOutputDir();
- }
-
- return outputDir;
- }
-
- /**
- * Create a "Compiler" object based on some init param data. This
- * is not done yet. Right now we're just hardcoding the actual
- * compilers that are created.
- */
- public Compiler createCompiler() {
- if (jspCompiler != null ) {
- return jspCompiler;
- }
- jspCompiler = createCompiler("org.apache.jasper.compiler.BeeCompiler");
- if (jspCompiler == null) {
- throw new IllegalStateException(Localizer.getMessage("jsp.error.compiler"));
- }
- jspCompiler.init(this, jsw);
- return jspCompiler;
- }
-
- protected Compiler createCompiler(String className) {
- Compiler compiler = null;
- try {
- compiler = (Compiler) Class.forName(className).newInstance();
- } catch (InstantiationException e) {
- log.warn(Localizer.getMessage("jsp.error.compiler"), e);
- } catch (IllegalAccessException e) {
- log.warn(Localizer.getMessage("jsp.error.compiler"), e);
- } catch (NoClassDefFoundError e) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage("jsp.error.compiler"), e);
- }
- } catch (ClassNotFoundException e) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage("jsp.error.compiler"), e);
- }
- }
- return compiler;
- }
-
- public Compiler getCompiler() {
- return jspCompiler;
- }
-
- /** ---------- Access resources in the webapp ---------- */
-
- /**
- * Get the full value of a URI relative to this compilations context
- * uses current file as the base.
- */
- public String resolveRelativeUri(String uri) {
- // sometimes we get uri's massaged from File(String), so check for
- // a root directory separator char
- if (uri.startsWith("/") || uri.startsWith(File.separator)) {
- return uri;
- } else {
- return baseURI + uri;
- }
- }
-
- /**
- * Gets a resource as a stream, relative to the meanings of this
- * context's implementation.
- * @return a null if the resource cannot be found or represented
- * as an InputStream.
- */
- public java.io.InputStream getResourceAsStream(String res) {
- return context.getResourceAsStream(canonicalURI(res));
- }
-
-
- public URL getResource(String res) throws MalformedURLException {
- URL result = null;
-
- if (res.startsWith("/META-INF/")) {
- // This is a tag file packaged in a jar that is being compiled
- JarResource jarResource = tagFileJarUrls.get(res);
- if (jarResource == null) {
- jarResource = tagJarResource;
- }
- if (jarResource != null) {
- result = jarResource.getEntry(res.substring(1));
- } else {
- // May not be in a JAR in some IDE environments
- result = context.getResource(canonicalURI(res));
- }
- } else if (res.startsWith("jar:jndi:")) {
- // This is a tag file packaged in a jar that is being checked
- // for a dependency
- result = new URL(res);
-
- } else {
- result = context.getResource(canonicalURI(res));
- }
- return result;
- }
-
-
- public Set getResourcePaths(String path) {
- return context.getResourcePaths(canonicalURI(path));
- }
-
- /**
- * Gets the actual path of a URI relative to the context of
- * the compilation.
- */
- public String getRealPath(String path) {
- if (context != null) {
- return context.getRealPath(path);
- }
- return path;
- }
-
- /**
- * Returns the tag-file-name-to-JAR-file map of this compilation unit,
- * which maps tag file names to the JAR files in which the tag files are
- * packaged.
- *
- * The map is populated when parsing the tag-file elements of the TLDs
- * of any imported taglibs.
- */
- public JarResource getTagFileJarResource(String tagFile) {
- return this.tagFileJarUrls.get(tagFile);
- }
-
- public void setTagFileJarResource(String tagFile, JarResource jarResource) {
- this.tagFileJarUrls.put(tagFile, jarResource);
- }
-
- /**
- * Returns the JAR file in which the tag file for which this
- * JspCompilationContext was created is packaged, or null if this
- * JspCompilationContext does not correspond to a tag file, or if the
- * corresponding tag file is not packaged in a JAR.
- */
- public JarResource getTagFileJarResource() {
- return this.tagJarResource;
- }
-
- /* ==================== Common implementation ==================== */
-
- /**
- * Just the class name (does not include package name) of the
- * generated class.
- */
- public String getServletClassName() {
-
- if (className != null) {
- return className;
- }
-
- if (isTagFile) {
- className = tagInfo.getTagClassName();
- int lastIndex = className.lastIndexOf('.');
- if (lastIndex != -1) {
- className = className.substring(lastIndex + 1);
- }
- } else {
- int iSep = jspUri.lastIndexOf('/') + 1;
- className = JspUtil.makeJavaIdentifier(jspUri.substring(iSep));
- }
- return className;
- }
-
- public void setServletClassName(String className) {
- this.className = className;
- }
-
- /**
- * Path of the JSP URI. Note that this is not a file name. This is
- * the context rooted URI of the JSP file.
- */
- public String getJspFile() {
- return jspUri;
- }
-
- /**
- * @deprecated Will be removed in Tomcat 8.0.x. Use
- * {@link #getLastModified(String)} instead.
- */
- @Deprecated
- public long getJspLastModified() {
- long result = -1;
- URLConnection uc = null;
- try {
- URL jspUrl = getResource(getJspFile());
- if (jspUrl == null) {
- incrementRemoved();
- return result;
- }
- uc = jspUrl.openConnection();
- if (uc instanceof JarURLConnection) {
- result = ((JarURLConnection) uc).getJarEntry().getTime();
- } else {
- result = uc.getLastModified();
- }
- } catch (IOException e) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage(
- "jsp.error.lastModified", getJspFile()), e);
- }
- result = -1;
- } finally {
- if (uc != null) {
- try {
- uc.getInputStream().close();
- } catch (IOException e) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage(
- "jsp.error.lastModified", getJspFile()), e);
- }
- result = -1;
- }
- }
- }
- return result;
- }
-
-
- public Long getLastModified(String resource) {
- long result = -1;
- URLConnection uc = null;
- try {
- URL jspUrl = getResource(resource);
- if (jspUrl == null) {
- incrementRemoved();
- return Long.valueOf(result);
- }
- File resFile = new File(jspUrl.getFile()); // TJWS on Android
- if (resFile.exists()) {
- result = resFile.lastModified();
- } else {
- uc = jspUrl.openConnection();
- if (uc instanceof JarURLConnection) {
- result = ((JarURLConnection) uc).getJarEntry().getTime();
- } else {
- result = uc.getLastModified();
- }
- }
- //System.out.printf("Jasper ctx %s modified %d / %s%n", uc, result, resFile);
- } catch (IOException e) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage(
- "jsp.error.lastModified", getJspFile()), e);
- }
- result = -1;
- } finally {
- if (uc != null) {
- try {
- uc.getInputStream().close();
- } catch (IOException e) {
- if (log.isDebugEnabled()) {
- log.debug(Localizer.getMessage(
- "jsp.error.lastModified", getJspFile()), e);
- }
- result = -1;
- }
- }
- }
- return Long.valueOf(result);
- }
-
- public boolean isTagFile() {
- return isTagFile;
- }
-
- public TagInfo getTagInfo() {
- return tagInfo;
- }
-
- public void setTagInfo(TagInfo tagi) {
- tagInfo = tagi;
- }
-
- /**
- * True if we are compiling a tag file in prototype mode.
- * ie we only generate codes with class for the tag handler with empty
- * method bodies.
- */
- public boolean isPrototypeMode() {
- return protoTypeMode;
- }
-
- public void setPrototypeMode(boolean pm) {
- protoTypeMode = pm;
- }
-
- /**
- * Package name for the generated class is make up of the base package
- * name, which is user settable, and the derived package name. The
- * derived package name directly mirrors the file hierarchy of the JSP page.
- */
- public String getServletPackageName() {
- if (isTagFile()) {
- String className = tagInfo.getTagClassName();
- int lastIndex = className.lastIndexOf('.');
- String pkgName = "";
- if (lastIndex != -1) {
- pkgName = className.substring(0, lastIndex);
- }
- return pkgName;
- } else {
- String dPackageName = getDerivedPackageName();
- if (dPackageName.length() == 0) {
- return basePackageName;
- }
- return basePackageName + '.' + getDerivedPackageName();
- }
- }
-
- protected String getDerivedPackageName() {
- if (derivedPackageName == null) {
- int iSep = jspUri.lastIndexOf('/');
- derivedPackageName = (iSep > 0) ?
- JspUtil.makeJavaPackage(jspUri.substring(1,iSep)) : "";
- }
- return derivedPackageName;
- }
-
- /**
- * The package name into which the servlet class is generated.
- */
- public void setServletPackageName(String servletPackageName) {
- this.basePackageName = servletPackageName;
- }
-
- /**
- * Full path name of the Java file into which the servlet is being
- * generated.
- */
- public String getServletJavaFileName() {
- if (servletJavaFileName == null) {
- servletJavaFileName = getOutputDir() + getServletClassName() + ".java";
- }
- return servletJavaFileName;
- }
-
- /**
- * Get hold of the Options object for this context.
- */
- public Options getOptions() {
- return options;
- }
-
- public ServletContext getServletContext() {
- return context;
- }
-
- public JspRuntimeContext getRuntimeContext() {
- return rctxt;
- }
-
- /**
- * Path of the Java file relative to the work directory.
- */
- public String getJavaPath() {
-
- if (javaPath != null) {
- return javaPath;
- }
-
- if (isTagFile()) {
- String tagName = tagInfo.getTagClassName();
- javaPath = tagName.replace('.', '/') + ".java";
- } else {
- javaPath = getServletPackageName().replace('.', '/') + '/' +
- getServletClassName() + ".java";
- }
- return javaPath;
- }
-
- public String getClassFileName() {
- if (classFileName == null) {
- classFileName = getOutputDir() + getServletClassName() + ".class";
- }
- return classFileName;
- }
-
- /**
- * Where is the servlet being generated?
- */
- public ServletWriter getWriter() {
- return writer;
- }
-
- public void setWriter(ServletWriter writer) {
- this.writer = writer;
- }
-
- /**
- * Gets the 'location' of the TLD associated with the given taglib 'uri'.
- *
- * @return An array of two Strings: The first element denotes the real
- * 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.
- * Returns null if the given uri is not associated with any tag library
- * 'exposed' in the web application.
- */
- public TldLocation getTldLocation(String uri) throws JasperException {
- TldLocation location =
- getOptions().getTldLocationsCache().getLocation(uri);
- return location;
- }
-
- /**
- * Are we keeping generated code around?
- */
- public boolean keepGenerated() {
- return getOptions().getKeepGenerated();
- }
-
- // ==================== Removal ====================
-
- public void incrementRemoved() {
- if (removed == 0 && rctxt != null) {
- rctxt.removeWrapper(jspUri);
- }
- removed++;
- }
-
- public boolean isRemoved() {
- if (removed > 0 ) {
- return true;
- }
- return false;
- }
-
- // ==================== Compile and reload ====================
-
- public void compile() throws JasperException, FileNotFoundException {
- createCompiler();
- if (jspCompiler.isOutDated()) {
- if (isRemoved()) {
- throw new FileNotFoundException(jspUri);
- }
- try {
- jspCompiler.removeGeneratedFiles();
- jspLoader = null;
- jspCompiler.compile();
- jsw.setReload(true);
- jsw.setCompilationException(null);
- } catch (JasperException ex) {
- // Cache compilation exception
- jsw.setCompilationException(ex);
- if (options.getDevelopment() && options.getRecompileOnFail()) {
- // Force a recompilation attempt on next access
- jsw.setLastModificationTest(-1);
- }
- throw ex;
- } catch (Exception ex) {
- JasperException je = new JasperException(
- Localizer.getMessage("jsp.error.unable.compile"),
- ex);
- // Cache compilation exception
- jsw.setCompilationException(je);
- throw je;
- }
- }
- }
-
- // ==================== Manipulating the class ====================
-
- public Class> load() throws JasperException {
- try {
- getJspLoader();
-
- String name = getFQCN();
- servletClass = jspLoader.loadClass(name);
- } catch (ClassNotFoundException cex) {
- throw new JasperException(Localizer.getMessage("jsp.error.unable.load"),
- cex);
- } catch (Exception ex) {
- throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"),
- ex);
- }
- removed = 0;
- return servletClass;
- }
-
- public String getFQCN() {
- String name;
- if (isTagFile()) {
- name = tagInfo.getTagClassName();
- } else {
- name = getServletPackageName() + "." + getServletClassName();
- }
- return name;
- }
-
- // ==================== protected methods ====================
-
- static Object outputDirLock = new Object();
-
- public void checkOutputDir() {
- if (outputDir != null) {
- if (!(new File(outputDir)).exists()) {
- makeOutputDir();
- }
- } else {
- createOutputDir();
- }
- }
-
- protected boolean makeOutputDir() {
- synchronized(outputDirLock) {
- File outDirFile = new File(outputDir);
- return (outDirFile.exists() || outDirFile.mkdirs());
- }
- }
-
- protected void createOutputDir() {
- String path = null;
- if (isTagFile()) {
- String tagName = tagInfo.getTagClassName();
- path = tagName.replace('.', File.separatorChar);
- path = path.substring(0, path.lastIndexOf(File.separatorChar));
- } else {
- path = getServletPackageName().replace('.',File.separatorChar);
- }
-
- // Append servlet or tag handler path to scratch dir
- try {
- File base = options.getScratchDir();
- baseUrl = base.toURI().toURL();
- outputDir = base.getAbsolutePath() + File.separator + path +
- File.separator;
- if (!makeOutputDir()) {
- throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"));
- }
- } catch (MalformedURLException e) {
- throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e);
- }
- }
-
- protected static final boolean isPathSeparator(char c) {
- return (c == '/' || c == '\\');
- }
-
- protected static final String canonicalURI(String s) {
- if (s == null) return null;
- StringBuilder result = new StringBuilder();
- final int len = s.length();
- int pos = 0;
- while (pos < len) {
- char c = s.charAt(pos);
- if ( isPathSeparator(c) ) {
- /*
- * multiple path separators.
- * 'foo///bar' -> 'foo/bar'
- */
- while (pos+1 < len && isPathSeparator(s.charAt(pos+1))) {
- ++pos;
- }
-
- if (pos+1 < len && s.charAt(pos+1) == '.') {
- /*
- * a single dot at the end of the path - we are done.
- */
- if (pos+2 >= len) break;
-
- switch (s.charAt(pos+2)) {
- /*
- * self directory in path
- * foo/./bar -> foo/bar
- */
- case '/':
- case '\\':
- pos += 2;
- continue;
-
- /*
- * two dots in a path: go back one hierarchy.
- * foo/bar/../baz -> foo/baz
- */
- case '.':
- // only if we have exactly _two_ dots.
- if (pos+3 < len && isPathSeparator(s.charAt(pos+3))) {
- pos += 3;
- int separatorPos = result.length()-1;
- while (separatorPos >= 0 &&
- ! isPathSeparator(result
- .charAt(separatorPos))) {
- --separatorPos;
- }
- if (separatorPos >= 0)
- result.setLength(separatorPos);
- continue;
- }
- }
- }
- }
- result.append(c);
- ++pos;
- }
- return result.toString();
- }
-}
-
diff --git a/1.x/src/rogatkin/app/Main.java b/1.x/src/rogatkin/app/Main.java
deleted file mode 100644
index 68f8f49..0000000
--- a/1.x/src/rogatkin/app/Main.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/* tjws - Main.java
- * Copyright (C) 1999-2010 Dmitriy Rogatkin. All rights reserved.
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
- * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * Visit http://tjws.sourceforge.net to get the latest information
- * about Rogatkin's products.
- * $Id: Main.java,v 1.16 2013/03/20 03:49:46 cvs Exp $
- * Created on Mar 27, 2007
- * @author Dmitriy
- */
-package rogatkin.app;
-
-import java.io.File;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.Arrays;
-import java.util.HashSet;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
-import rogatkin.web.WebApp;
-import rogatkin.web.WebAppServlet;
-import Acme.Utils;
-
-public class Main {
- public static final String APP_MAIN_CLASS = "tjws.app.main";
-
- public static final String APP_MAIN_CLASSPATH = "tjws.app.main.classpath";
-
- public static final String APP_MAIN_STRIP_PARAM_RIGHT = "tjws.app.main.striprightparam";
-
- public static final String APP_MAIN_STRIP_PARAM_LEFT = "tjws.app.main.stripleftparam";
-
- /**
- * @param args
- */
- public static void main(String[] args) {
- String mainClass = System.getProperty(APP_MAIN_CLASS);
- if (mainClass == null)
- Acme.Serve.Main.main(initAppServer(args));
- else {
- URLClassLoader cl = null;
- try {
- String cp = System.getProperty(APP_MAIN_CLASSPATH);
- if (cp != null) {
- String[] cps = cp.split(File.pathSeparator);
- URL urls[] = new URL[cps.length];
- for (int i = 0; i < cps.length; i++) {
- if (cps[i].startsWith("file:") == false && cps[i].startsWith("http:") == false
- && cps[i].startsWith("https:") == false)
- urls[i] = new URL("file:/" + cps[i]); // new URL("file", "localhost/", cps[i])
- else
- urls[i] = new URL(cps[i]);
- }
- cl = new URLClassLoader(urls);
- }
- Class main = cl == null ? Class.forName(mainClass) : Class.forName(mainClass, true, cl);
- if (cl != null)
- Thread.currentThread().setContextClassLoader(cl);
- main.getDeclaredMethod("main", String[].class).invoke(null,
- new Object[] { rangeParam(initAppServer(args)) });
- } catch (Exception e) {
- System.err.printf("Can't launch a user app %s (%s) due: %s", mainClass,
- Arrays.toString(cl == null ? new URL[] {} : cl.getURLs()), e);
- e.printStackTrace();
- }
- }
- }
-
- protected static String[] rangeParam(String... params) {
- String range = System.getProperty(APP_MAIN_STRIP_PARAM_RIGHT);
- if (range != null)
- return Utils.copyOf(params, Integer.parseInt(range));
- range = System.getProperty(APP_MAIN_STRIP_PARAM_LEFT);
- if (range != null)
- return Utils.copyOfRange(params, Integer.parseInt(range), params.length);
- return params;
- }
-
- protected static String[] initAppServer(String... args) {
- // defaulting JNDI
- if (System.getProperty(Context.INITIAL_CONTEXT_FACTORY) == null)
- System.getProperties().setProperty(Context.INITIAL_CONTEXT_FACTORY, SimpleJndi.class.getName());
- if (System.getProperty(Context.PROVIDER_URL) == null)
- System.getProperties()
- .setProperty(Context.PROVIDER_URL, "http://localhost:1221"/*"tjws://localhost:1221"*/);
- try {
- final Context namingContext = new InitialContext();
- WebAppServlet.setAppContextDelegator(new WebAppServlet.AppContextDelegator() {
- public Object lookup(String name) {
- try {
- return namingContext.lookup(name);
- } catch (NamingException nce) {
- throw new RuntimeException("Can't delegate naming context operation", nce);
- }
- }
-
- public Object lookupLink(String name) {
- try {
- return namingContext.lookupLink(name);
- } catch (NamingException nce) {
- throw new RuntimeException("Can't delegate naming context operation", nce);
- }
- }
-
- public void add(String name, Object obj) {
-
- try {
- if (obj instanceof WebApp.MetaContext) {
- SimpleDataSource sds = new SimpleDataSource(((WebApp.MetaContext) obj).getPath(), ((WebApp.MetaContext) obj).getClassLoader());
- // TODO all data sources created form App class path have to be destroyed at the app destroy
- if (sds.isScopeApp()) {
- HashSet dsmap = (HashSet)namingContext.getEnvironment().get(name);
- if (dsmap == null) {
- dsmap = new HashSet();
- namingContext.addToEnvironment(name, dsmap);
- }
- dsmap.add(sds); //System.err.printf("Adding %s for %s%n", sds, name);
- }
- } else
- namingContext.addToEnvironment(name, obj);
- } catch (NamingException nce) {
- throw new RuntimeException("Can't delegate naming context operation", nce);
- }
- }
-
- @Override
- public Object remove(String name) {
- Object result = null;
- try {
- result = namingContext.removeFromEnvironment(name);
- if (result instanceof HashSet) {
- for (SimpleDataSource sds:(HashSet)result) //{
- sds.invalidate(); //System.err.printf("Invalidating %s for %s%n", sds, name);}
- }
- return result;
- } catch (NamingException e) {
- //throw new RuntimeException("Can't resolve context in environment");
- }
- return result;
- }
-
- });
- } catch (NamingException nce) {
- System.err.printf("Can not obtain initial naming context (%s) because %s%n",
- System.getProperty(Context.INITIAL_CONTEXT_FACTORY), nce);
- }
- // Perhaps it should be set Context.URL_PKG_PREFIXES
- //System.out.println("Xmx set "+Runtime.getRuntime().maxMemory());
- if (args.length == 0)
- args = Acme.Serve.Main.readArguments(System.getProperty("user.dir", "."), Acme.Serve.Main.CLI_FILENAME);
- if (args != null)
- for (int i = 0; i < args.length; i++) {
- if ("-dataSource".equals(args[i])) {
- try {
- new SimpleDataSource(args[++i], null);
- } catch (IllegalArgumentException e) {
- System.err.printf("Data source %s wasn't created because %s%n", args[i], e);
- }
- }
- }
- return args;
- }
-}
diff --git a/1.x/src/rogatkin/app/ObjectPool.java b/1.x/src/rogatkin/app/ObjectPool.java
deleted file mode 100644
index c692ee6..0000000
--- a/1.x/src/rogatkin/app/ObjectPool.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/* tjws - ObjectPool.java
- * Copyright (C) 2010 Dmitriy Rogatkin. All rights reserved.
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
- * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * Visit http://tjws.sourceforge.net to get the latest information
- * about Rogatkin's products.
- * $Id: ObjectPool.java,v 1.15 2012/06/23 06:59:29 dmitriy Exp $
- * Created on Mar 5, 2008
- * @author Dmitriy
- *
- */
-package rogatkin.app;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.TimeUnit;
-
-public abstract class ObjectPool {
- protected String[] descardMethods = { "destroy", "close" };
-
- protected BlockingQueue pool;
-
- protected ArrayList borrowed;
-
- protected int timeout;
-
- private boolean monitor;
-
- public static Class> Wrapper;
-
- static {
- try {
- Wrapper = Class.forName("java.sql.Wrapper");
- } catch (ClassNotFoundException e) {
- System.err.printf("Your Java runtime doesn't support JDBC 3.0 (%s), some functionality can be supressed.", e);
- }
- }
-
- protected abstract O create();
-
- protected void discard(O obj) {
- //System.err.printf("Discard %s%n", obj);
- if (Wrapper != null && Wrapper.isAssignableFrom(obj.getClass()))
- try {
- //obj = (O)((Wrapper)obj).unwrap(obj.getClass());
- obj = (O) obj.getClass().getMethod("unwrap", Class.class).invoke(obj, obj.getClass());
- } catch (Exception e1) {
- }
- for (int i = 0; i < descardMethods.length; i++) {
- try {
- obj.getClass().getMethod(descardMethods[i], new Class[] {}).invoke(obj, new Object[] {});
- break;
- } catch (IllegalArgumentException e) {
- } catch (SecurityException e) {
- } catch (IllegalAccessException e) {
- } catch (InvocationTargetException e) {
- } catch (NoSuchMethodException e) {
- }
- }
- }
-
- public ObjectPool(BlockingQueue bq) {
- if (bq != null) {
- pool = bq;
- borrowed = new ArrayList(bq.size());
- } else
- throw new NullPointerException();
- }
-
- public O get() {
- O result = get1();
- if (result != null) {
- assert (borrowed.contains(result) == false);
- synchronized (borrowed) {
- borrowed.add(result);
- // new Exception(String.format("Added in used %s size %d", result, borrowed.size())).printStackTrace();
- }
- if (monitor) {
- // get stack trace for identifying a caller and store the information among with request time
- if (result instanceof Monitor)
- ((Monitor) result).putMark(getClass().getName());
- }
- }
- return result;
- }
-
- private O get1() {
- if (pool.isEmpty() && borrowed.size() < getCapacity())
- return create();
- //System.err.printf("get %s%n", o);
- try {
- if (timeout > 0)
- return pool.poll(timeout, TimeUnit.MILLISECONDS);
- return pool.take();
- } catch (InterruptedException e) {
- }
- return null;
- }
-
- public void put(O obj) {
- assert borrowed.contains(obj);
- synchronized (borrowed) {
- if (borrowed.remove(obj) == false)
- return; // connection already removed
- }
- // no synchronization between increasing limit and offering the connection for consumption is considered
- // as acceptable, offering connection first and then decreasing limit can issue objects starvation,
- // it will also require using set for borrowing list
- //new Exception(String.format("returned %s, still in use: %d", obj, borrowed.size())).printStackTrace();
- if (pool.offer(obj) == false) {
- // no room, discard the object
- discard(obj);
- }
- }
-
- public void remove(O obj) {
- if (borrowed.contains(obj))
- synchronized (borrowed) {
- if (borrowed.remove(obj) == false)
- System.err.println("Object " + obj + " wasn't removed");
- }
- else {
- if (pool.remove(obj) == false)
- System.err.println("Object " + obj + " wasn't removed from pool");
- }
- // TODO generally discard can have side effect
- discard(obj);
- }
-
- public void setTimeout(int to) {
- timeout = to;
- }
-
- /** resizes the pool
- *
- * @param newSize
- */
- public abstract int getCapacity();
-
- public void invalidate() {
- ArrayList forDiscard = new ArrayList();
- pool.drainTo(forDiscard);
- for (O o : forDiscard)
- discard(o);
- if (borrowed.size() > 0)
- throw new IllegalStateException("Pool invalidate with borrowed objects");
- }
-
- /** The interface is used for marking pooled object by requester id
- * and access time
- * @author dmitriy
- *
- */
- public static interface Monitor {
- void putMark(String boundaryClassName);
-
- String getMarkCaller();
-
- long getMarkTime();
- }
-
-}
diff --git a/1.x/src/rogatkin/app/SimpleDataSource.java b/1.x/src/rogatkin/app/SimpleDataSource.java
deleted file mode 100644
index eb2b42b..0000000
--- a/1.x/src/rogatkin/app/SimpleDataSource.java
+++ /dev/null
@@ -1,522 +0,0 @@
-/* tjws - SimpleDataSource.java
- * Copyright (C) 1999-2010 Dmitriy Rogatkin. All rights reserved.
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
- * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * Visit http://tjws.sourceforge.net to get the latest information
- * about Rogatkin's products.
- * $Id: SimpleDataSource.java,v 1.30 2013/03/20 03:49:46 cvs Exp $
- * Created on Mar 25, 2007
- * @author Dmitriy
- */
-package rogatkin.app;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintWriter;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.sql.CallableStatement;
-import java.sql.Connection;
-import java.sql.Driver;
-import java.sql.DriverManager;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.Properties;
-import java.util.concurrent.ArrayBlockingQueue;
-import java.sql.SQLFeatureNotSupportedException;
-import java.util.logging.Logger;
-
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.sql.DataSource;
-import javax.sql.RowSet;
-import javax.xml.xpath.XPath;
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpressionException;
-import javax.xml.xpath.XPathFactory;
-
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-
-/**
- * The class presents data source, which is created based on a property file
- *
- * The following properties are allowed:
- *
- * - jndi-name - under this name the data source will be registered in
- * JNDI if name starts with jdbc, then prefix
- * java:comp/env/ will be added.
- *
- driver-class - class name of JDBC driver
- *
- url - JDBC connection URL
- *
- user - connection user
- *
- password - connection password
- *
- pool-size - max number of allocated connections, 0 = no size
- * limitation, -1 = no pool used
- *
- access-timeout - timeout in ms before getting an exception on
- * connection request when no connections are available, 0 means wait forever
- *
- driver-class-path - defines class path to driver archive, unless
- * it is already in boot classpath
- *
- prob-query defines a query to verify that given connection is
- * valid, executed at time getting a connection from pool. If
- * isValid is specified as value, then isValid() method of SQL
- * connection is used (note that it is available only in Java 6 drivers). If
- * isClosed is specified, then isClosed() method used for a
- * connection validation.
- *
- exception-handler - a name of class implementing static public
- * method boolean validate(SQLException, Connection). This class is used to
- * verify if SQLException indicates that the connection isn't valid anymore and
- * has to be removed from the pool. The method returns true, if the connection
- * still good for further use.
- *
- pool-shrink-size> - max available connections in pool (not implemented yet)
- *
- *
- * @author dmitriy
- *
- */
-public class SimpleDataSource extends ObjectPool implements DataSource {
- public final static String RW_ISVALID = "isValid";
-
- public final static String RW_ISCLOSED = "isClosed";
-
- public final static String CP_DEFAULT = "application";
-
- protected final static int DEFAULT_CAPACITY = 20;
-
- protected Properties dataSourceProperties, conectionProperties;
-
- protected Driver driver;
-
- private int capacity;
-
- private PrintWriter logWriter;
-
- private Method connectionValidateMethod;
-
- private String validateQuery;
-
- private boolean appCP;
-
- public SimpleDataSource(String definitionPropertiesLocation, ClassLoader appCL) {
- super(new ArrayBlockingQueue(DEFAULT_CAPACITY));
- logWriter = new PrintWriter(System.out);
- InputStream propertiesStream = null;
- File f = new File(definitionPropertiesLocation);
- try {
- if (f.exists())
- propertiesStream = new FileInputStream(f);
- else {
- propertiesStream = new URL(definitionPropertiesLocation).openStream();
- }
- dataSourceProperties = new Properties();
- if (definitionPropertiesLocation.toLowerCase().endsWith("context.xml"))
- contextToProperties(propertiesStream);
- else if (definitionPropertiesLocation.toLowerCase().endsWith(".xml"))
- dataSourceProperties.loadFromXML(propertiesStream);
- else
- dataSourceProperties.load(propertiesStream);
- init(appCL);
- } catch (FileNotFoundException e) {
- throw new IllegalArgumentException(e);
- } catch (MalformedURLException e) {
- throw new IllegalArgumentException(
- "Data source properties file doesn't exist, and can't be resolved as URL", e);
- } catch (NoSuchMethodException e) {
- throw new IllegalArgumentException("Connection validator class problem", e);
- } catch (Exception e) {
- throw new IllegalArgumentException(e);
- } finally {
- if (propertiesStream != null)
- try {
- propertiesStream.close();
- } catch (IOException e) {
- }
- }
- }
-
- protected void init(ClassLoader classLoader) throws Exception {
- String classPath = dataSourceProperties.getProperty("driver-class-path");
- if (classPath == null) {
- //if (classLoader != null)
- //Class.forName(dataSourceProperties.getProperty("driver-class"), true, classLoader);
- //else
- String driverClass = dataSourceProperties.getProperty("driver-class");
- if (driverClass == null)
- return; // no data source
- Class.forName(driverClass);
- driver = DriverManager.getDriver(dataSourceProperties.getProperty("url"));
- } else {
- String[] classPaths = classPath.split(File.pathSeparator);
- URL[] urls = new URL[classPaths.length];
- for (int i = 0; i < urls.length; i++)
- urls[i] = new URL("file:" + classPaths[i]);
- if (CP_DEFAULT.equalsIgnoreCase(classPath)) {
- driver = (Driver) Class
- .forName(dataSourceProperties.getProperty("driver-class"), true,
- classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader)
- .newInstance();
- appCP = true;
- } else
- driver = (Driver) Class
- .forName(dataSourceProperties.getProperty("driver-class"), true,
- classLoader = new URLClassLoader(urls, DriverManager.class.getClassLoader()))
- .newInstance();
- }
- conectionProperties = new Properties();
- if (dataSourceProperties.getProperty("user") != null) {
- conectionProperties.setProperty("user", dataSourceProperties.getProperty("user"));
- if (dataSourceProperties.getProperty("password") != null)
- conectionProperties.setProperty("password", dataSourceProperties.getProperty("password"));
- }
- try {
- setTimeout(Integer.parseInt(dataSourceProperties.getProperty("access-timeout")));
- } catch (Exception e) {
- }
- try {
- capacity = Integer.parseInt(dataSourceProperties.getProperty("pool-size"));
- this.pool = new ArrayBlockingQueue(capacity, true);
- this.borrowed = new ArrayList(capacity);
- } catch (Exception e) {
- capacity = DEFAULT_CAPACITY;
- }
- validateQuery = dataSourceProperties.getProperty("prob-query");
- String conValClass = dataSourceProperties.getProperty("exception-handler");
- if (conValClass != null)
- connectionValidateMethod = (classLoader == null ? Class.forName(conValClass)
- : Class.forName(conValClass, true, classLoader)).getMethod("validate", SQLException.class,
- Connection.class);
- String jndiName = dataSourceProperties.getProperty("jndi-name");
- if (jndiName != null) {
- if (jndiName.startsWith("jdbc/"))
- jndiName = "java:comp/env/" + jndiName;
- InitialContext ic = new InitialContext();
- try {
- ic.lookup(jndiName);
- ic.rebind(jndiName, this);
- } catch (NamingException ne) {
- ic.bind(jndiName, this);
- }
- }
- }
-
- public Connection getConnection() throws SQLException {
- Connection realConn = validateQuery == null ? get() : getValidated();
- return (Connection) Proxy.newProxyInstance(realConn.getClass().getClassLoader(), Wrapper != null ? new Class[] {
- Connection.class, Wrapper } : new Class[] { Connection.class }, new ConnectionWrapperHandler(realConn));
- }
-
- @Override
- public String toString() {
- Properties masked = (Properties) dataSourceProperties.clone();
- masked.setProperty("password", "*******");
- Properties maskedConn = (Properties) conectionProperties.clone();
- maskedConn.setProperty("password", "*******");
- return "Pooled data source : " + masked + "\n" + maskedConn + "\n capacity:" + capacity
- + ", available: " + pool.size() + ", borrowed: " + borrowed.size();
- }
-
- public boolean isScopeApp() {
- return appCP;
- }
-
- private Connection getValidated() {
- boolean bad = true;
- do {
- Connection result = get();
- Statement statement = null;
- try {
- if (validateQuery.equals(RW_ISVALID))
- try {
- if ((Boolean) result.getClass().getMethod("isValid", int.class).invoke(10))
- return result;
- else
- ;
- } catch (Exception e) {
- e.printStackTrace();
- }
- else if (validateQuery.equals(RW_ISCLOSED)) {
- if (result.isClosed() == false)
- return result;
- } else {
- // TODO it can be reasonable to execute the query in a
- // thread and join in millis
- // because dropped connection can hung a query
- statement = result.createStatement();
- statement.execute(validateQuery);
- return result;
- }
- } catch (SQLException e) {
- log("Discarding connection %s because %s%n", null, result, e);
- } finally {
- if (statement != null)
- try {
- statement.close();
- } catch (SQLException e) {
- }
- }
- remove(result);
- } while (bad);
- throw new IllegalStateException();
- }
-
- public Connection getConnection(String user, String password) throws SQLException {
- conectionProperties.setProperty("user", user);
- conectionProperties.setProperty("password", password);
- return getConnection();
- }
-
- public PrintWriter getLogWriter() throws SQLException {
- return logWriter;
- }
-
- public int getLoginTimeout() throws SQLException {
- return timeout;
- }
-
- public void setLogWriter(PrintWriter timeout) throws SQLException {
- logWriter = timeout;
- }
-
- public void setLoginTimeout(int timeout) throws SQLException {
- // not quite what it is
- setTimeout(timeout);
- }
-
- public boolean isWrapperFor(Class> cl) throws SQLException {
- return DataSource.class.equals(cl) || ObjectPool.class.equals(cl);
- }
-
- public T unwrap(Class arg0) throws SQLException {
- if (isWrapperFor(arg0))
- return (T) this;
- return null;
- }
-
- protected void log(String message, Throwable ex, Object... args) {
- if (args == null || args.length == 0)
- logWriter.write(message + "\n"); // ?? lineSeparator?
- else
- logWriter.write(String.format(message, args));
- if (ex != null)
- ex.printStackTrace(logWriter);
- logWriter.flush();
- }
-
- @Override
- protected void discard(Connection obj) {
- Connection unwrapped = null;
- try {//System.err.printf("Discarding %s%n", obj);
- unwrapped = (Connection) obj.getClass().getMethod("unwrap", Class.class).invoke(obj, Connection.class);
- unwrapped.close();
- } catch (Exception e) {//e.printStackTrace();
- if (unwrapped == null)
- try {
- obj.close();
- } catch (SQLException e1) {
- //e1.printStackTrace();
- }
- }
- }
-
- @Override
- protected Connection create() {
- try {
- return driver.connect(dataSourceProperties.getProperty("url"), conectionProperties);
- } catch (SQLException e) {
- log("Can't create connection for %s%n", e, dataSourceProperties.getProperty("url"));
- throw new IllegalArgumentException(
- "Can't create connection, check connection parameters and class path for JDBC driver", e);
- }
- }
-
- private Throwable processException(InvocationTargetException ite, Connection conn, Connection proxyConn)
- throws IllegalArgumentException, IllegalAccessException {
- if (connectionValidateMethod != null) {
- Throwable se = ite.getCause();
- //System.err.println("Cause*********"+se+" instance sql:"+(se instanceof SQLException));
- try {
- if (se instanceof SQLException && connectionValidateMethod.invoke(null, se, conn).equals(Boolean.FALSE))
- remove(conn);
- } catch (InvocationTargetException e) {
-
- }
- return se;
- }
- return ite.getCause();
- }
-
- @Override
- public int getCapacity() {
- return capacity;
- }
-
- //@Override
- public Logger getParentLogger() throws SQLFeatureNotSupportedException {
- throw new SQLFeatureNotSupportedException();
- }
-
- private void contextToProperties(InputStream contextXmlStream) throws XPathExpressionException {
- XPath xp = XPathFactory.newInstance().newXPath();
- Node document = (Node) xp.evaluate("/Context", new InputSource(contextXmlStream), XPathConstants.NODE);
- NodeList nodes = (NodeList) xp.evaluate("Resource", document, XPathConstants.NODESET);
- int nodesLen = nodes.getLength();
- if (nodesLen > 1)
- throw new IllegalArgumentException("Only one resource is supported");
- for (int p = 0; p < nodesLen; p++) {
- NamedNodeMap attrs = nodes.item(p).getAttributes();
- Node metadataAttr = attrs.getNamedItem("name");
- dataSourceProperties.setProperty("jndi-name", "java:comp/env/" + metadataAttr.getTextContent());
- metadataAttr = attrs.getNamedItem("type");
- if ("javax.sql.DataSource".equals(metadataAttr.getTextContent()) == false)
- throw new IllegalArgumentException("Only SQL data sources are supported");
- metadataAttr = attrs.getNamedItem("auth");
- metadataAttr = attrs.getNamedItem("username");
- if (metadataAttr != null)
- dataSourceProperties.setProperty("user", metadataAttr.getTextContent());
- metadataAttr = attrs.getNamedItem("password");
- if (metadataAttr != null)
- dataSourceProperties.setProperty("password", metadataAttr.getTextContent());
- metadataAttr = attrs.getNamedItem("driverClassName");
- if (metadataAttr != null)
- dataSourceProperties.setProperty("driver-class", metadataAttr.getTextContent());
- metadataAttr = attrs.getNamedItem("url");
- if (metadataAttr == null)
- throw new IllegalArgumentException("Data source URL is required");
- dataSourceProperties.setProperty("url", metadataAttr.getTextContent());
- metadataAttr = attrs.getNamedItem("driverClassPath");
- if (metadataAttr != null)
- dataSourceProperties.setProperty("driver-class-path", metadataAttr.getTextContent());
- metadataAttr = attrs.getNamedItem("validationQuery");
- if (metadataAttr != null)
- dataSourceProperties.setProperty("prob-query", metadataAttr.getTextContent());
- metadataAttr = attrs.getNamedItem("maxActive");
- if (metadataAttr != null)
- dataSourceProperties.setProperty("pool-size", metadataAttr.getTextContent());
- metadataAttr = attrs.getNamedItem("maxIdle");
- if (metadataAttr != null)
- dataSourceProperties.setProperty("pool-shrink-size", metadataAttr.getTextContent());
- }
- }
-
- class ConnectionWrapperHandler implements InvocationHandler {
-
- private Connection realConn;
-
- ConnectionWrapperHandler(Connection conn) {
- realConn = conn;
- }
-
- public Object invoke(final Object proxyConn, Method methd, Object[] params) throws Throwable {
- if (realConn == null)
- throw new SQLException("The connection is closed");
- if (methd.getName().equals("close")) {
- // log("Closing %s%n", null, proxyConn);
- if (realConn.getAutoCommit() == false)
- try {
- realConn.rollback();
- } catch (SQLException se) {
-
- }
- put(realConn);
- realConn = null;
- } else if (methd.getName().equals("unwrap")) // &&
- return realConn;
- else if (methd.getName().equals("isWrapperFor"))
- return ((Class) params[0]).isInstance(realConn);
- else if (methd.getName().equals("equals"))
- return proxyConn == params[0];
- else {
- try {
- final Object realStmt = methd.invoke(realConn, params);
- if (realStmt instanceof Statement == false)
- return realStmt;
- // wrap statement
- return Proxy.newProxyInstance(realStmt.getClass().getClassLoader(), Wrapper != null ? new Class[] {
- CallableStatement.class, PreparedStatement.class, Statement.class, Wrapper } : new Class[] {
- CallableStatement.class, PreparedStatement.class, Statement.class },
- new InvocationHandler() {
- public Object invoke(final Object proxyStmt, Method methd, Object[] params)
- throws Throwable {
- if (methd.getName().equals("getConnection")) {
- return proxyConn;
- } else if (methd.getName().equals("unwrap"))
- return realStmt; // real statement
- else if (methd.getName().equals("isWrapperFor"))
- return ((Class) params[0]).isInstance(realStmt);
- try {
- final Object realRS = methd.invoke(realStmt, params);
- if (realRS instanceof ResultSet == false)
- return realRS;
- return Proxy
- .newProxyInstance(realRS.getClass().getClassLoader(),
- Wrapper != null ? new Class[] { RowSet.class, ResultSet.class,
- Wrapper }
- : new Class[] { RowSet.class, ResultSet.class },
- new InvocationHandler() {
- public Object invoke(final Object proxyRS, Method methd,
- Object[] params) throws Throwable {
- if (methd.getName().equals("getStatement")) {
- return proxyStmt;
- } else if (methd.getName().equals("unwrap"))
- return realRS; // resultset
- else if (methd.getName().equals("isWrapperFor"))
- return ((Class) params[0]).isInstance(realRS);
- try {
- return methd.invoke(realRS, params);
- } catch (InvocationTargetException ite) {
- throw processException(ite, realConn,
- (Connection) proxyConn);
- }
- }
- });
- } catch (InvocationTargetException ite) {
- throw processException(ite, realConn, (Connection) proxyConn);
- }
- }
- });
- } catch (InvocationTargetException ite) {
- throw processException(ite, realConn, (Connection) proxyConn);
- }
- }
- return null;
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- //System.err.printf("finilize%s%n", dataSourceProperties);
- invalidate();
- super.finalize();
- }
-
-}
diff --git a/1.x/src/rogatkin/app/WebAppServ.java b/1.x/src/rogatkin/app/WebAppServ.java
deleted file mode 100644
index efdb9dd..0000000
--- a/1.x/src/rogatkin/app/WebAppServ.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/* TJWS WebAppServ
- * Copyright (C) 2010 Dmitriy Rogatkin. All rights reserved.
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
- * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * Visit http://tjws.sourceforge.net to get the latest information
- * about Rogatkin's products.
- * $Id: WebAppServ.java,v 1.3 2009/12/31 05:02:13 dmitriy Exp $
- * Created on Mar 5, 2008
- * @author dmitriy
- */
-package rogatkin.app;
-
-import rogatkin.web.WebApp;
-import Acme.Utils;
-
-public class WebAppServ extends Main {
-
- /** launches embedded app with app server settings
- * @param args
- */
- public static void main(String[] args) {
- if (args.length == 0)
- try {
- initAppServer(Utils.splitStr(WebApp.readDescriptor()[0]));
- } catch (NullPointerException npe) {
- //npe.printStackTrace();
- }
- else
- initAppServer(args);
- WebApp.main(args);
- }
-}
diff --git a/1.x/src/rogatkin/web/WarRoller.java b/1.x/src/rogatkin/web/WarRoller.java
deleted file mode 100644
index 9e9da9b..0000000
--- a/1.x/src/rogatkin/web/WarRoller.java
+++ /dev/null
@@ -1,409 +0,0 @@
-/* tjws - WarRoller.java
- * Copyright (C) 2004-2010 Dmitriy Rogatkin. All rights reserved.
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
- * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * $Id: WarRoller.java,v 1.30 2013/07/02 07:11:28 cvs Exp $
- * Created on Dec 13, 2004
- */
-package rogatkin.web;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipException;
-import java.util.zip.ZipFile;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.HashSet;
-
-import javax.servlet.ServletException;
-
-import Acme.Utils;
-import Acme.Serve.Serve;
-import Acme.Serve.WarDeployer;
-
-public class WarRoller implements WarDeployer {
-
- public static final String DEPLOY_ARCH_EXT = ".war";
-
- public static final String DEPLOYMENT_DIR_TARGET = ".web-apps-target";
-
- public static final String DEF_DEPLOY_DYNAMICALLY = "tjws.wardeploy.dynamically";
-
- public static final String DEF_DEPLOY_NOINCREMENTAL = "tjws.wardeploy.noincremental";
-
- public static final String DEF_VIRTUAL = "tjws.virtual";
-
- public static final String DEPLOY_FAILED_EXT = ".failed";
-
- /**
- * in deploy mode scans for all wars in war directory (app deployment dir)
- * for each war looks in corresponding place of deploy directory and figures
- * a difference, like any file in war exists and no corresponding file in
- * deploy directory or it's older if difference positive, then delete target
- * deploy directory unpack war if run mode process all WEB-INF/web.xml and
- * build app descriptor, including context name, servlet names, servlet
- * urls, class parameters process every app descriptor as standard servlet
- * connection proc dispatch for every context name assigned an app
- * dispatcher, it uses the rest to find servlet and do resource mapping
- *
- */
-
- public void deploy(File warDir, final File deployTarDir, final String virtualHost) {
- // by list
- if (warDir.listFiles(new FileFilter() {
- public boolean accept(File pathname) {
- if (pathname.isFile() && pathname.getName().toLowerCase().endsWith(DEPLOY_ARCH_EXT)) {
- deployWar(pathname, deployTarDir);
- return true;
- }
- return false;
- }
- }).length == 0)
- server.log("No .war packaged web apps found in " + (virtualHost == null ? "default" : virtualHost));
- if (deployTarDir.listFiles(new FileFilter() {
- public boolean accept(File file) {
- if (file.isDirectory())
- try {
- attachApp(WebAppServlet.create(file, file.getName(), server, virtualHost), virtualHost);
- markSucceeded(file.getParentFile(), file.getName()); // assumes that parent always exists
- return true;
- } catch (ServletException se) {
- server.log(
- "Deployment of aplication " + file.getName() + " failed, reason: " + se.getRootCause(),
- se.getRootCause());
- } catch (Throwable t) {
- if (t instanceof ThreadDeath)
- throw (ThreadDeath) t;
- server.log("Unexpected problem in deployment of application " + file.getName(), t);
- }
- return false;
- }
- }).length == 0)
- server.log("No web apps have been deployed in " + (virtualHost == null ? "default" : virtualHost));
- }
-
- public boolean deployWar(File warFile, File deployTarDir) {
- String context = warFile.getName();
- assert context.toLowerCase().endsWith(DEPLOY_ARCH_EXT);
- context = context.substring(0, context.length() - DEPLOY_ARCH_EXT.length());
- File failedMark = new File(deployTarDir, context + DEPLOY_FAILED_EXT);
- if (failedMark.exists() && failedMark.lastModified() > warFile.lastModified())
- return false; // skipping deploy failed
-
- server.log("Deploying " + context);
- ZipFile zipFile = null;
- File deployDir = new File(deployTarDir, context);
- boolean noincremental = System.getProperty(DEF_DEPLOY_NOINCREMENTAL) != null;
- if (assureDir(deployDir) == false) {
- server.log("Can't reach deployment dir " + deployDir);
- return false;
- }
- Exception lastException = null;
- deploy: do {
- try {
- // some overhead didn't check that doesn't exist
- zipFile = new ZipFile(warFile);
- Enumeration extends ZipEntry> entries = zipFile.entries();
- while (entries.hasMoreElements()) {
- ZipEntry ze = entries.nextElement();
- String en = ze.getName();
- if (File.separatorChar == '/')
- en = en.replace('\\', File.separatorChar);
- File outFile = new File(deployDir, en);
- if (ze.isDirectory()) {
- outFile.mkdirs();
- } else {
- OutputStream os = null;
- InputStream is = null;
- File parentFile = outFile.getParentFile();
- if (parentFile.exists() == false)
- parentFile.mkdirs();
- if (outFile.exists() && outFile.lastModified() >= ze.getTime()) {
- continue;
- }
- if (noincremental) {
- deleteFiles(deployDir, deployDir.list());
- noincremental = false;
- continue deploy;
- }
- try {
- os = new FileOutputStream(outFile);
- is = zipFile.getInputStream(ze);
- copyStream(is, os);
- } catch (IOException ioe2) {
- server.log("Problem in extracting " + en + " " + ioe2);
- // TODO decide to propagate the exception up and stop deployment?
- lastException = ioe2;
- } finally {
- try {
- os.close();
- } catch (Exception e2) {
-
- }
- try {
- is.close();
- } catch (Exception e2) {
-
- }
- }
- outFile.setLastModified(ze.getTime());
- }
- }
- } catch (ZipException ze) {
- server.log("Invalid .war format");
- lastException = ze;
- } catch (IOException ioe) {
- server.log("Can't read " + warFile + "/ " + ioe);
- lastException = ioe;
- } finally {
- try {
- zipFile.close();
- } catch (Exception e) {
-
- }
- zipFile = null;
- }
- } while (false);
- if (lastException == null) {
- deployDir.setLastModified(warFile.lastModified());
- return true;
- }
- deployDir.setLastModified(0);
- return false;
- }
-
- protected void attachApp(WebAppServlet appServlet, String virtualHost) {
- server.addServlet(appServlet.contextPath + "/*", appServlet, virtualHost);
- }
-
- /** Returns auto deployment directory
- *
- * The method can be overriden to give more control of choosing the directory
- * @return autodeployment directory location as local file system string
- */
- protected String getDeployDirectory() {
- String webapp_dir = System.getProperty(WebApp.DEF_WEBAPP_AUTODEPLOY_DIR);
- if (webapp_dir == null)
- webapp_dir = System.getProperty("user.dir") + File.separator + "webapps";
- return webapp_dir;
- }
-
- public void deploy(Serve server) {
- this.server = server;
- final File file_webapp = new File(getDeployDirectory());
- if (assureDir(file_webapp) == false) {
- server.log("Deployment source location " + file_webapp + " isn't a directory, deployment is impossible.");
- return;
- }
- final File file_deployDir = new File(file_webapp, DEPLOYMENT_DIR_TARGET);
- if (assureDir(file_deployDir) == false) {
- server.log("Target deployment location " + file_deployDir + " isn't a directory, deployment is impossible.");
- return;
- }
- deploy(file_webapp, file_deployDir, null);
-
- int td = 0;
- if (System.getProperty(DEF_DEPLOY_DYNAMICALLY) != null) {
- td = 20;
- try {
- td = Integer.parseInt(System.getProperty(DEF_DEPLOY_DYNAMICALLY));
- } catch (NumberFormatException nfe) {
- server.log("Default redeployment check interval: " + td + " is used");
- }
- }
- final int interval = td * 1000;
- createWatcherThread(file_webapp, file_deployDir, interval, null);
- if (null != System.getProperty(DEF_VIRTUAL)) {
- file_webapp.listFiles(new FileFilter() {
- @Override
- public boolean accept(File pathname) {
- String virtualHost;
- if (pathname.isDirectory()
- && (virtualHost = pathname.getName()).equals(DEPLOYMENT_DIR_TARGET) == false) {
-
- final File file_deployDir = new File(pathname, DEPLOYMENT_DIR_TARGET);
- if (assureDir(file_deployDir) == false) {
- WarRoller.this.server.log("Target deployment location " + file_deployDir
- + " isn't a directory, deployment is impossible.");
- } else {
- deploy(pathname, file_deployDir, virtualHost);
- createWatcherThread(pathname, file_deployDir, interval, virtualHost);
- return true;
- }
- }
- return false;
- }
- });
- }
- }
-
- protected void createWatcherThread(final File file_webapp, final File file_deployDir, final int interval,
- final String virtualHost) {
- if (interval <= 0)
- return;
- Thread watcher = new Thread("Deploy update watcher for " + (virtualHost == null ? "main" : virtualHost)) {
- public void run() {
- for (;;)
- try {
- deployWatch(file_webapp, file_deployDir, virtualHost);
- } catch (Throwable t) {
- if (t instanceof ThreadDeath)
- throw (ThreadDeath) t;
- WarRoller.this.server.log("Unhandled " + t, t);
- } finally {
- try {
- Thread.sleep(interval);
- } catch (InterruptedException e) {
- break;
- }
- }
- }
- };
- watcher.setDaemon(true);
- watcher.start();
- }
-
- protected boolean assureDir(File fileDir) {
- if (fileDir.exists() == false)
- fileDir.mkdirs();
- return fileDir.isDirectory();
- }
-
- protected synchronized void deployWatch(File warDir, final File deployTarDir, String virtualHost) {
- server.setHost(virtualHost);
- final HashSet apps = new HashSet();
- warDir.listFiles(new FileFilter() {
- public boolean accept(File file) {
- if (file.isDirectory() == false) {
- String name = file.getName();
- if (name.endsWith(DEPLOY_ARCH_EXT))
- apps.add(name.substring(0, name.length() - DEPLOY_ARCH_EXT.length()));
- }
- return false;
- }
- });
- Enumeration se = server.getServlets();
- ArrayList markedServlets = new ArrayList(10);
- while (se.hasMoreElements()) {
- Object servlet = se.nextElement();
- if (servlet instanceof WebAppServlet) {
- WebAppServlet was = (WebAppServlet) servlet;
- String name = was.deployDir.getName();
- File war = new File(warDir, name + DEPLOY_ARCH_EXT);
- apps.remove(name);
- if (war.exists() && war.lastModified() > was.deployDir.lastModified()) {
- // deployWar(new File(warDir, was.deployDir.getName() +
- // DEPLOY_ARCH_EXT), deployTarDir);
- markedServlets.add(was);
- }
- }
- }
- for (WebAppServlet was : markedServlets) {
- redeploy(warDir, deployTarDir, was, virtualHost);
- }
- for (String name : apps) {
- // remaining not deployed yet apps
- try {
- if (deployWar(new File(warDir, name + DEPLOY_ARCH_EXT), deployTarDir)) {
- WebAppServlet was = WebAppServlet.create(new File(deployTarDir, name), name, server, virtualHost);
- attachApp(was, virtualHost);
- }
- } catch (Throwable t) {
- if (t instanceof ThreadDeath)
- throw (ThreadDeath) t;
- markFailed(deployTarDir, name);
- server.log("Unexpected problem in deployment of aplication " + name, t);
- }
- }
- }
-
- public void redeploy(File warDir, File deployTarDir, WebAppServlet was, String virtualHost) {
- was = (WebAppServlet) server.unloadServlet(was);
- if (was == null)
- return;
- server.unloadSessions(was.getServletContext());
- was.destroy();
-
- // TODO use pre-saved war name
- if (deployWar(new File(warDir, was.deployDir.getName() + DEPLOY_ARCH_EXT), deployTarDir))
- try {
- was = WebAppServlet.create(was.deployDir, was.deployDir.getName(), server, virtualHost);
- attachApp(was, virtualHost);
- server.restoreSessions(was.getServletContext());
- markSucceeded(deployTarDir, was.deployDir.getName());
- } catch (ServletException sex) {
- markFailed(deployTarDir, was.deployDir.getName());
- server.log("Deployment of a web app " + was.contextName + " failed due " + sex.getRootCause(),
- sex.getRootCause());
- } catch (Throwable t) {
- if (t instanceof ThreadDeath)
- throw (ThreadDeath) t;
- markFailed(deployTarDir, was.deployDir.getName());
- server.log("Unexpected problem in deployment of aplication " + was.contextName, t);
- }
- }
-
- static private boolean markFailed(File deployTarDir, String appName) {
- File markFile = new File(deployTarDir, appName + DEPLOY_FAILED_EXT);
-
- if (markFile.exists()) {
- File appDeployDir = new File(deployTarDir, appName);
- if (appDeployDir.exists())
- markFile.setLastModified(appDeployDir.lastModified()+1);
- return true;
- }
- try {
- return markFile.createNewFile();
- } catch (IOException e) {
- return false;
- }
- }
-
- static private boolean markSucceeded(File deployTarDir, String appName) {
- if (new File(deployTarDir, appName + DEPLOY_FAILED_EXT).exists())
- return new File(deployTarDir, appName+DEPLOY_FAILED_EXT).delete();
- return true;
- }
-
- static void copyStream(InputStream is, OutputStream os) throws IOException {
- Utils.copyStream(is, os, -1);
- }
-
- static void deleteFiles(File folder, String[] files) throws IOException {
- for (String fn : files) {
- File f = new File(folder, fn);
- if (f.isDirectory()) {
- deleteFiles(f, f.list());
- if (f.delete() == false)
- throw new IOException("Can't delete :" + f);
- } else {
- if (f.delete() == false)
- throw new IOException("Can't delete :" + f);
- }
- }
- }
-
- protected Serve server;
-}
\ No newline at end of file
diff --git a/1.x/src/rogatkin/wskt/SimpleProvider.java b/1.x/src/rogatkin/wskt/SimpleProvider.java
deleted file mode 100644
index 8222766..0000000
--- a/1.x/src/rogatkin/wskt/SimpleProvider.java
+++ /dev/null
@@ -1,556 +0,0 @@
-/* tjws - JSR356
- * Copyright (C) 2004-2015 Dmitriy Rogatkin. All rights reserved.
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
- * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- *
- * Created on Jan 11, 2015
-*/
-package rogatkin.wskt;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.Socket;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.net.URLDecoder;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.nio.channels.ByteChannel;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.SocketChannel;
-
-import Acme.Utils;
-import Acme.Serve.Serve;
-import Acme.Serve.Serve.ServeConnection;
-import Acme.Serve.Serve.WebsocketProvider;
-
-import javax.servlet.ServletContext;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSessionBindingEvent;
-import javax.servlet.http.HttpSessionBindingListener;
-import javax.servlet.Servlet;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.ServletException;
-import javax.websocket.CloseReason;
-import javax.websocket.DeploymentException;
-import javax.websocket.Endpoint;
-import javax.websocket.Extension;
-import javax.websocket.server.HandshakeRequest;
-import javax.websocket.server.ServerApplicationConfig;
-import javax.websocket.server.ServerEndpoint;
-import javax.websocket.server.ServerEndpointConfig;
-
-import io.github.lukehutch.fastclasspathscanner.*;
-import io.github.lukehutch.fastclasspathscanner.matchprocessor.*;
-
-public class SimpleProvider implements WebsocketProvider, Runnable {
- public static final String WSKT_KEY = "Sec-WebSocket-Key";
- public static final String WSKT_ORIGIN = "Origin";
- public static final String WSKT_PROTOCOL = "Sec-WebSocket-Protocol";
- public static final String WSKT_VERSION = "Sec-WebSocket-Version";
- public static final String WSKT_ACEPT = "Sec-WebSocket-Accept";
- public static final String WSKT_EXTS = "Sec-WebSocket-Extensions"; // HandshakeRequest.SEC_WEBSOCKET_EXTENSIONS
-
- public static final String WSKT_RFC4122 = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
-
- public static final String PROP_WSKT_MAIN_CONTAINER = "tjws.websocket.container";
-
- //static final ForkJoinPool mainPool = new ForkJoinPool();
-
- protected Selector selector;
- protected Serve serve;
- protected ExecutorService messageFlowExec;
- protected ConcurrentLinkedQueue penndingSessions;
-
- protected boolean rootContainerUse;
-
- static final boolean __debugOn = false;
-
- @Override
- public void init(Serve s) {
- serve = s;
- try {
- penndingSessions = new ConcurrentLinkedQueue();
- selector = Selector.open();
- Thread t = new Thread(this, "websocket provider selector");
- t.setDaemon(true);
- t.start();
- } catch (IOException ioe) {
- throw new RuntimeException("Can't initialize selector, websocket functionality is disabled", ioe);
- }
- rootContainerUse = Boolean.getBoolean(PROP_WSKT_MAIN_CONTAINER);
-
- messageFlowExec = Executors.newCachedThreadPool();
- }
-
- @Override
- public void handshake(Socket socket, String path, Servlet servlet, HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
- if (socket.getChannel() == null) {
- resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "Websockets implemented only with SelectorAcceptor");
- return;
- }
- String ver = req.getHeader(WSKT_VERSION);
- if (ver == null || "13".equals(ver.trim()) == false) {
- resp.addHeader(WSKT_VERSION, "13");
- resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
- return;
- }
-
- String key = req.getHeader(WSKT_KEY);
- if (key == null) {
- resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Sec Key is missed");
- return;
- }
- String contextPath;
- try {
- contextPath = (String) servlet.getClass().getMethod("getContextPath").invoke(servlet);
- } catch (Exception e) {
- if (rootContainerUse)
- contextPath = "";
- else {
- resp.sendError(HttpServletResponse.SC_NOT_FOUND, "No endpoints associated with container allowed");
- return;
- }
- }
- SimpleServerContainer container;
- if (servlet != null)
- container = (SimpleServerContainer) servlet.getServletConfig().getServletContext()
- .getAttribute("javax.websocket.server.ServerContainer");
- else
- container = (SimpleServerContainer) serve.getAttribute("javax.websocket.server.ServerContainer");
-
- if (container == null) {
- resp.sendError(HttpServletResponse.SC_NOT_FOUND, "No end points associated with path " + path);
- return;
- }
-
- String found = null;
- int hops = -1;
- Map foundVarMap = null;
- for (String p : container.endpoints.keySet()) {
- Map varMap = matchTemplate(path, contextPath + p);
- if (varMap != null) {
- if (found == null || hops > varMap.size()) {
- found = p;
- hops = varMap.size();
- foundVarMap = varMap;
- }
- }
- }
- if (found == null) {
- resp.sendError(HttpServletResponse.SC_NOT_FOUND, "No matching endpoint found for " + path);
- return;
- }
- ServerEndpointConfig epc = container.endpoints.get(found);
- //Objects.requireNonNull(epc.getConfigurator());
- if (epc.getConfigurator().checkOrigin(req.getHeader(WSKT_ORIGIN)) == false) {
- resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Origin check failed : " + req.getHeader(WSKT_ORIGIN));
- return;
- }
- epc.getConfigurator().modifyHandshake(epc, new SimpleHSRequest(req), new SimpleHSResponse(resp));
-
- req.setAttribute("javax.websocket.server.ServerEndpointConfig", epc);
- req.setAttribute("javax.websocket.server.PathParametersMap", foundVarMap);
-
- resp.setHeader(WSKT_ACEPT, getSHA1Base64(key.trim() + WSKT_RFC4122));
- resp.setHeader(Serve.ServeConnection.UPGRADE, Serve.ServeConnection.WEBSOCKET);
- //resp.setHeader(Serve.ServeConnection.CONNECTION, Serve.ServeConnection.KEEPALIVE + ", "
- // + Serve.ServeConnection.UPGRADE);
- //resp.addHeader(Serve.ServeConnection.CONNECTION, Serve.ServeConnection.UPGRADE);
- if (container.getDefaultMaxSessionIdleTimeout() > 0)
- resp.setHeader(Serve.ServeConnection.KEEPALIVE, "timeout=" + container.getDefaultMaxSessionIdleTimeout()
- / 1000);
- resp.setStatus(resp.SC_SWITCHING_PROTOCOLS);
- }
-
- @Override
- public void upgrade(Socket socket, String path, Servlet servlet, HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
- SocketChannel sc = socket.getChannel();
- sc.configureBlocking(false);
- ByteChannel bc = sc;
- try {
- bc = (ByteChannel) socket.getClass().getMethod("getByteChannel").invoke(socket);
- } catch (Exception e) {
- if (__debugOn)
- serve.log(e, "No byte channel");
- }
- SimpleServerContainer container = null;
- if (servlet != null)
- container = (SimpleServerContainer) servlet.getServletConfig().getServletContext()
- .getAttribute("javax.websocket.server.ServerContainer");
- else if (rootContainerUse)
- container = (SimpleServerContainer) serve.getAttribute("javax.websocket.server.ServerContainer");
- ServerEndpointConfig epc = (ServerEndpointConfig) req
- .getAttribute("javax.websocket.server.ServerEndpointConfig");
-
- final SimpleSession ss = new SimpleSession(bc, container);
- ss.addMessageHandler(epc);
- ss.pathParamsMap = (Map) req.getAttribute("javax.websocket.server.PathParametersMap");
- if (req.getSession(false) != null) {
- ss.id = req.getSession(false).getId();
- // TODO this approach isn't robust and flexible, so consider as temporarly
- req.getSession(false).setAttribute("javax.websocket.server.session", new HttpSessionBindingListener() {
-
- @Override
- public void valueBound(HttpSessionBindingEvent arg0) {
-
- }
-
- @Override
- public void valueUnbound(HttpSessionBindingEvent arg0) {
- try {
- ss.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "Session invalidate"));
- } catch (IOException e) {
- if (__debugOn)
- serve.log(e, "At closing on session invalidation");
- }
-
- }
- });
- } else
- ss.id = "wskt-" + serve.generateSessionId();
- ss.principal = req.getUserPrincipal();
- ss.setMaxIdleTimeout(container.getDefaultMaxSessionIdleTimeout());
- ss.paramsMap = new HashMap>();
- for (Map.Entry e : req.getParameterMap().entrySet()) {
- ss.paramsMap.put(e.getKey(), Arrays.asList(e.getValue()));
- }
- ss.query = req.getQueryString();
- try {
- ss.uri = new URI(req.getRequestURL().toString());
- } catch (URISyntaxException e) {
-
- }
- String protocol = req.getHeader(WSKT_PROTOCOL);
- if (protocol != null) {
- ss.subprotocol = epc.getConfigurator().getNegotiatedSubprotocol(epc.getSubprotocols(),
- Arrays.asList(protocol.split(",")));
- }
- if (epc.getExtensions().size() > 0) {
- // TODO maybe it should be going in handshake?
- ss.extensions = epc.getConfigurator().getNegotiatedExtensions(epc.getExtensions(),
- parseToExtensions(req.getHeader(HandshakeRequest.SEC_WEBSOCKET_EXTENSIONS)));
- if (ss.extensions.size() == 0) {
- ss.close(new CloseReason(CloseReason.CloseCodes.NO_EXTENSION, ""));
- return;
- }
- }
- if (req instanceof ServeConnection) {
- ss.conn = (ServeConnection) req;
- ((ServeConnection) req).spawnAsync(ss);
- } else
- serve.log("Request isn't of ServeConnection type " + req.getClass());
- penndingSessions.add(ss);
- selector.wakeup();
- //sc.register(selector, SelectionKey.OP_READ, ss);
- //ss.open();
- }
-
- @Override
- public void destroy() {
- if (rootContainerUse)
- try {
- ((SimpleServerContainer) serve.getAttribute("javax.websocket.server.ServerContainer"))
- .contextDestroyed(null);
- } catch (Exception e) {
-
- }
- messageFlowExec.shutdown();
- try {
- selector.close();
- } catch (IOException e) {
-
- }
- }
-
- @Override
- public void deploy(final ServletContext servCtx, final List cp) {
- final SimpleServerContainer ssc = new SimpleServerContainer(this);
- final HashSet appCfgs = new HashSet();
- final HashSet> annSeps = new HashSet>();
- final HashSet> endps = new HashSet>();
- new FastClasspathScanner("") {
- @Override
- public List getUniqueClasspathElements() {
- if (cp == null) {
- if (servCtx != null) {
- ClassLoader ccl = servCtx.getClass().getClassLoader();
- if (ccl instanceof URLClassLoader) {
- URL[] urls = ((URLClassLoader) ccl).getURLs();
- if (urls != null && urls.length > 0) {
- ArrayList result = new ArrayList(urls.length);
- for (URL url : urls)
- try {
- result.add(new File(URLDecoder.decode(url.getFile(), "UTF-8")));
- } catch (UnsupportedEncodingException e) {
- serve.log("Can't add path component " + url + " :" + e);
- }
- return result;
- }
- }
- }
- return super.getUniqueClasspathElements();
- }
- return cp;
- }
-
- @Override
- public ClassLoader getClassLoader() {
- if (servCtx != null)
- try {
- return (ClassLoader) servCtx.getClass().getMethod("getClassLoader").invoke(servCtx);
- } catch (Exception e) {
- return servCtx.getClass().getClassLoader();
- }
- return null;
- }
- }.matchClassesImplementing(ServerApplicationConfig.class,
- new InterfaceMatchProcessor() {
-
- @Override
- public void processMatch(Class extends ServerApplicationConfig> arg0) {
- try {
- appCfgs.add(arg0.newInstance());
- } catch (InstantiationException e) {
- serve.log(e, "Error at deployment");
- } catch (IllegalAccessException e) {
- serve.log(e, "Error at deployment");
- }
- }
-
- }).matchClassesWithAnnotation(ServerEndpoint.class, new ClassAnnotationMatchProcessor() {
- public void processMatch(Class> matchingClass) {
- annSeps.add(matchingClass);
- }
- }).matchSubclassesOf(Endpoint.class, new SubclassMatchProcessor() {
-
- @Override
- public void processMatch(Class extends Endpoint> arg0) {
- endps.add(arg0);
- }
- }).scan();
-
- if (appCfgs.size() > 0) {
- for (ServerApplicationConfig sac : appCfgs) {
- for (Class> se : sac.getAnnotatedEndpointClasses(annSeps))
- try {
- ssc.addEndpoint(se);
- serve.log("Deployed ServerEndpoint " + se);
- } catch (DeploymentException de) {
-
- }
- for (ServerEndpointConfig epc : sac.getEndpointConfigs(endps))
- try {
- ssc.addEndpoint(epc);
- serve.log("Deployed ServerEndpointConfig " + epc);
- } catch (DeploymentException de) {
-
- }
- }
- } else {
- for (Class> se : annSeps)
- try {
- ssc.addEndpoint(se);
- serve.log("Deployed ServerEndpoint " + se);
- } catch (DeploymentException de) {
-
- }
- }
- servCtx.setAttribute("javax.websocket.server.ServerContainer", ssc);
- try {
- servCtx.addListener(ssc);
- } catch (Error e) {
- // serve is still on old servlet spec
- }
- }
-
- String getSHA1Base64(String key) {
- try {
- MessageDigest cript = MessageDigest.getInstance("SHA-1");
- cript.reset();
- cript.update(key.getBytes());
- return Utils.base64Encode(cript.digest());
- } catch (NoSuchAlgorithmException nsa) {
-
- }
- return null;
- }
-
- Map matchTemplate(String uri, String template) {
- //System.err.printf("Matching %s to %s%n", uri, template);
- Map parsed = parseTemplate(template);
- Pattern p = Pattern.compile(parsed.get(0));
- Matcher m = p.matcher(uri);
- if (m.matches()) {
- HashMap result = new HashMap();
- for (int i = 0; i < m.groupCount(); i++)
- result.put(parsed.get(i + 1), m.group(i + 1));
- //System.err.printf("Success %s%n", result);
- return result;
- }
- //System.err.printf("unsucc %s%n", parsed);
- return null;
- }
-
- static final int s_invar = 1, s_inuri = 0;
-
- Map parseTemplate(String template) {
- HashMap result = new HashMap();
- String regExp = "";
- int vi = 0;
- int st = s_inuri;
- String varName = null;
- for (int i = 0, n = template.length(); i < n; i++) {
- char c = template.charAt(i);
- switch (st) {
- case s_inuri:
- if (c == '/')
- regExp += c;
- else if (c == '{') {
- st = s_invar;
- varName = "";
- } else {
- // TODO check if reg exp escape needed
- regExp += c;
- }
- break;
- case s_invar:
- if (c == '}') {
- vi++;
- regExp += "((?:[a-zA-Z0-9-\\._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)";
- st = s_inuri;
- result.put(vi, varName);
- } else {
- // TODO check if valid character ALPHA, DIGIT, _, or %DD
- varName += c;
- }
- break;
- }
- }
- result.put(0, regExp);
- return result;
- }
-
- /**
- * parses ext1;param=val param=val, ext2
- *
- * @param parse
- * @return
- */
- List parseToExtensions(String parse) {
- if (parse == null || parse.isEmpty())
- return Collections.emptyList();
- return Collections.emptyList();
- }
-
- @Override
- public void run() {
- while (selector.isOpen()) {
- try {
- for (SimpleSession ss = penndingSessions.poll(); ss != null; ss = penndingSessions.poll()) {
- SocketChannel sc = null;
- if (ss.channel instanceof SocketChannel)
- sc = (SocketChannel) ss.channel;
- else
- try {
- sc = (SocketChannel) ss.channel.getClass().getMethod("unwrapChannel").invoke(ss.channel);
- } catch (Exception e) {
-
- }
- if (sc != null) {
- sc.register(selector, SelectionKey.OP_READ, ss);
- ss.open();
- } else
- serve.log("Session with not proper channel will be closed");
- }
-
- int readyChannels = selector.select(1000);
- if (readyChannels == 0)
- continue;
-
- Set selectedKeys = selector.selectedKeys();
-
- Iterator keyIterator = selectedKeys.iterator();
-
- while (keyIterator.hasNext()) {
-
- SelectionKey key = keyIterator.next();
- if (__debugOn)
- serve.log("key:" + key + " " + key.isValid() + " chan " + key.channel());
-
- if (!key.isValid()) {
- continue;
- }
- if (key.isAcceptable()) {
- // a connection was accepted by a ServerSocketChannel.
-
- } else if (key.isConnectable()) {
- // a connection was established with a remote server.
-
- } else if (key.isReadable()) {
- // a channel is ready for reading
- if (key.channel().isOpen() && !messageFlowExec.isShutdown()) {
- messageFlowExec.submit(((SimpleSession) key.attachment()));
- //((SimpleSession) key.attachment()).run();
- } else {
- if (__debugOn)
- serve.log("Cancel key :" + key + ", channel closed");
- key.cancel();
- }
- } else if (key.isWritable()) {
- // a channel is ready for writing
- // TODO perhaps trigger flag in session too execute writing bach
- }
-
- keyIterator.remove();
- }
- } catch (Exception e) {
- serve.log("Websocket runtime problem", e);
- if (!selector.isOpen())
- break;
- }
- }
- }
-}
diff --git a/1.x/test/java/tjws/test/EchoServer.java b/1.x/test/java/tjws/test/EchoServer.java
deleted file mode 100644
index 64846ba..0000000
--- a/1.x/test/java/tjws/test/EchoServer.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package tjws.test;
-
-import java.io.IOException;
-
-import java.util.Date;
-
-import javax.servlet.http.HttpSession;
-import javax.websocket.EndpointConfig;
-import javax.websocket.OnClose;
-import javax.websocket.OnMessage;
-import javax.websocket.OnOpen;
-import javax.websocket.Session;
-import javax.websocket.server.ServerEndpoint;
-
-/**
- * @ServerEndpoint gives the relative name for the end point
- * This will be accessed via ws://localhost:8080/EchoChamber/echo
- * Where "localhost" is the address of the host,
- * "EchoChamber" is the name of the package
- * and "echo" is the address to access this class from the server
- */
-@ServerEndpoint(value="/echo/{room}", configurator = GetHttpSessionConfigurator.class)
-public class EchoServer {
- /**
- * @OnOpen allows us to intercept the creation of a new session.
- * The session class allows us to send data to the user.
- * In the method onOpen, we'll let the user know that the handshake was
- * successful.
- */
- @OnOpen
- public void onOpen(Session session, EndpointConfig config){
- System.out.println(session.getId() + " has opened a connection");
- boolean htp_sess = config.getUserProperties()
- .containsKey(HttpSession.class.getName());
- try {
- session.getBasicRemote().sendText((session.isSecure()?"Secure c":"C")+"onnection Established at "+new Date() +" htp session "+htp_sess);
- session.setMaxIdleTimeout(60*1000);
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
-
- /**
- * When a user sends a message to the server, this method will intercept the message
- * and allow us to react to it. For now the message is read as a String.
- */
- @OnMessage
- public String onMessage(Session session, String message, @javax.websocket.server.PathParam("room") String room){
- System.out.printf("Message from %s/%dms : %s (%s)%n", session.getId(), session.getMaxIdleTimeout(), message, room);
- /*try {
- session.getBasicRemote().sendText(message);
-
- } catch (IOException ex) {
- ex.printStackTrace();
- }*/
- String fromShare = "";
- for (Session s : session.getOpenSessions()) {
- if (s != session && s.isOpen() && s.getUserProperties().get("SHARE") != null)
- fromShare += " "+ (String) s.getUserProperties().get("SHARE");
- }
- session.getUserProperties().put("SHARE", message);
- if (fromShare .length() > 0)
- message += " from others "+fromShare;
- return message;
- }
-
- /**
- * The user closes the connection.
- *
- * Note: you can't send messages to the client from this method
- */
- @OnClose
- public void onClose(Session session){
- System.out.println("Session " +session.getId()+" has ended at "+new Date());
- }
-}
\ No newline at end of file
diff --git a/1.x/test/java/tjws/test/GetHttpSessionConfigurator.java b/1.x/test/java/tjws/test/GetHttpSessionConfigurator.java
deleted file mode 100644
index e1adadd..0000000
--- a/1.x/test/java/tjws/test/GetHttpSessionConfigurator.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package tjws.test;
-
-import javax.servlet.http.HttpSession;
-import javax.websocket.HandshakeResponse;
-import javax.websocket.server.HandshakeRequest;
-import javax.websocket.server.ServerEndpointConfig;
-
-public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator {
- @Override
- public void modifyHandshake(ServerEndpointConfig config,
- HandshakeRequest request,
- HandshakeResponse response)
- {
- HttpSession httpSession = (HttpSession)request.getHttpSession();
- config.getUserProperties().put(HttpSession.class.getName(),httpSession);
- }
-}
diff --git a/ASTJWSApp/.gitignore b/ASTJWSApp/.gitignore
new file mode 100644
index 0000000..d0c26de
--- /dev/null
+++ b/ASTJWSApp/.gitignore
@@ -0,0 +1,7 @@
+/**/.DS_Store
+/**/build
+/**/captures
+.externalNativeBuild
+/.gradle
+/.idea
+/local.properties
diff --git a/ASTJWSApp/ADB Info.txt b/ASTJWSApp/ADB Info.txt
new file mode 100755
index 0000000..86b4a86
--- /dev/null
+++ b/ASTJWSApp/ADB Info.txt
@@ -0,0 +1,16 @@
+=> How to access your app data. <=
+adb shell
+run-as com.rslakra.android.tjwsasapp
+cp /data/data/com.rslakra.android.tjwsasapp/
+cp /data/user/0/com.rslakra.android.tjwsasapp/
+
+
+
+adb shell su -c "chmod 777 /data"
+adb shell su -c "chmod 777 /data/data"
+adb shell su -c "chmod 777 /data/user/0/com.rslakra.android.tjwsasapp/files"
+
+
+Pull Command: Copies the file from android device to local machine
+Convention: adb pull
+adb pull "/data/user/0/com.rslakra.android.tjwsasapp/files/logs/android.log" android.log
\ No newline at end of file
diff --git a/ASTJWSApp/ASTJWSApp.iml b/ASTJWSApp/ASTJWSApp.iml
new file mode 100644
index 0000000..016b11d
--- /dev/null
+++ b/ASTJWSApp/ASTJWSApp.iml
@@ -0,0 +1,19 @@
+
+
+
+
+