Re-added test case lost in large merge

- Removed imageio-jmagick (again)

- Removed internal Maven repo

- fixed line endings on a number of files to avoid a humongous merge
  diff when getting changes into upstream

- Re-enabled a few tests
This commit is contained in:
Torstein Krause Johansen
2016-06-28 14:24:25 +02:00
parent 1e3c8b26f6
commit 0db676f1be
89 changed files with 15925 additions and 15631 deletions

View File

@@ -1,336 +1,336 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name "TwelveMonkeys" nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
*/
package com.twelvemonkeys.servlet.image;
import com.twelvemonkeys.lang.StringUtil;
import com.twelvemonkeys.servlet.ServletUtil;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.geom.Rectangle2D;
/**
* This servlet is capable of rendereing a text string and output it as an
* image. The text can be rendered in any given font, size,
* style or color, into an image, and output it as a GIF, JPEG or PNG image,
* with optional caching of the rendered image files.
*
* <P><HR><P>
*
* <A name="parameters"></A><STRONG>Parameters:</STRONG><BR>
* <DL>
* <DT>{@code text}</DT>
* <DD>string, the text string to render.
* <DT>{@code width}</DT>
* <DD>integer, the width of the image
* <DT>{@code height}</DT>
* <DD>integer, the height of the image
* <DT>{@code fontFamily}</DT>
* <DD>string, the name of the font family.
* Default is {@code "Helvetica"}.
* <DT>{@code fontSize}</DT>
* <DD>integer, the size of the font. Default is {@code 12}.
* <DT>{@code fontStyle}</DT>
* <DD>string, the tyle of the font. Can be one of the constants
* {@code plain} (default), {@code bold}, {@code italic} or
* {@code bolditalic}. Any other will result in {@code plain}.
* <DT>{@code fgcolor}</DT>
* <DD>color (HTML form, {@code #RRGGBB}), or color constant from
* {@link java.awt.Color}, default is {@code "black"}.
* <DT>{@code bgcolor}</DT>
* <DD>color (HTML form, {@code #RRGGBB}), or color constant from
* {@link java.awt.Color}, default is {@code "transparent"}.
* Note that the hash character ({@code "#"}) used in colors must be
* escaped as {@code %23} in the query string. See
* {@link StringUtil#toColor(String)}, <A href="#examples">examples</A>.
*
* <!-- inherited from ImageServlet below: -->
*
* <DT>{@code cache}</DT>
* <DD>boolean, {@code true} if you want to cache the result
* to disk (default).
*
* <DT>{@code compression}</DT>
* <DD>float, the optional compression ratio for the output image. For JPEG
* images, the quality is the inverse of the compression ratio. See
* {@link #JPEG_DEFAULT_COMPRESSION_LEVEL},
* {@link #PNG_DEFAULT_COMPRESSION_LEVEL}.
* <DD>Applies to JPEG and PNG images only.
*
* <DT>{@code dither}</DT>
* <DD>enumerated, one of {@code NONE}, {@code DEFAULT} or
* {@code FS}, if you want to dither the result ({@code DEFAULT} is
* default).
* {@code FS} will produce the best results, but it's slower.
* <DD>Use in conjuction with {@code indexed}, {@code palette}
* and {@code websafe}.
* <DD>Applies to GIF and PNG images only.
*
* <DT>{@code fileName}</DT>
* <DD>string, an optional filename. If not set, the path after the servlet
* ({@link HttpServletRequest#getPathInfo}) will be used for the cache
* filename. See {@link #getCacheFile(ServletRequest)},
* {@link #getCacheRoot}.
*
* <DT>{@code height}</DT>
* <DD>integer, the height of the image.
*
* <DT>{@code width}</DT>
* <DD>integer, the width of the image.
*
* <DT>{@code indexed}</DT>
* <DD>integer, the number of colors in the resulting image, or -1 (default).
* If the value is set and positive, the image will use an
* {@code IndexColorModel} with
* the number of colors specified. Otherwise the image will be true color.
* <DD>Applies to GIF and PNG images only.
*
* <DT>{@code palette}</DT>
* <DD>string, an optional filename. If set, the image will use IndexColorModel
* with a palette read from the given file.
* <DD>Applies to GIF and PNG images only.
*
* <DT>{@code websafe}</DT>
* <DD>boolean, {@code true} if you want the result to use the 216 color
* websafe palette (default is false).
* <DD>Applies to GIF and PNG images only.
* </DL>
*
* @example
* &lt;IMG src="/text/test.gif?height=40&width=600
* &fontFamily=TimesRoman&fontSize=30&fontStyle=italic&fgcolor=%23990033
* &bgcolor=%23cccccc&text=the%20quick%20brown%20fox%20jumps%20over%20the
* %20lazy%20dog&cache=false" /&gt;
*
* @example
* &lt;IMG src="/text/test.jpg?height=40&width=600
* &fontFamily=TimesRoman&fontSize=30&fontStyle=italic&fgcolor=black
* &bgcolor=%23cccccc&text=the%20quick%20brown%20fox%20jumps%20over%20the
* %20lazy%20dog&compression=3&cache=false" /&gt;
*
* @example
* &lt;IMG src="/text/test.png?height=40&width=600
* &fontFamily=TimesRoman&fontSize=30&fontStyle=italic&fgcolor=%23336699
* &bgcolor=%23cccccc&text=the%20quick%20brown%20fox%20jumps%20over%20the
* %20lazy%20dog&cache=true" /&gt;
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: TextRenderer.java#2 $
*/
class TextRenderer /*extends ImageServlet implements ImagePainterServlet*/ {
// TODO: Create something usable out of this piece of old junk.. ;-)
// It just needs a graphics object to write onto
// Alternatively, defer, and compute the size needed
// Or, make it a filter...
/** {@code "italic"} */
public final static String FONT_STYLE_ITALIC = "italic";
/** {@code "plain"} */
public final static String FONT_STYLE_PLAIN = "plain";
/** {@code "bold"} */
public final static String FONT_STYLE_BOLD = "bold";
/** {@code text} */
public final static String PARAM_TEXT = "text";
/** {@code marginLeft} */
public final static String PARAM_MARGIN_LEFT = "marginLeft";
/** {@code marginTop} */
public final static String PARAM_MARGIN_TOP = "marginTop";
/** {@code fontFamily} */
public final static String PARAM_FONT_FAMILY = "fontFamily";
/** {@code fontSize} */
public final static String PARAM_FONT_SIZE = "fontSize";
/** {@code fontStyle} */
public final static String PARAM_FONT_STYLE = "fontStyle";
/** {@code textRotation} */
public final static String PARAM_TEXT_ROTATION = "textRotation";
/** {@code textRotation} */
public final static String PARAM_TEXT_ROTATION_UNITS = "textRotationUnits";
/** {@code bgcolor} */
public final static String PARAM_BGCOLOR = "bgcolor";
/** {@code fgcolor} */
public final static String PARAM_FGCOLOR = "fgcolor";
protected final static String ROTATION_DEGREES = "DEGREES";
protected final static String ROTATION_RADIANS = "RADIANS";
/**
* Creates the TextRender servlet.
*/
public TextRenderer() {
}
/**
* Renders the text string for this servlet request.
*/
private void paint(ServletRequest pReq, Graphics2D pRes, int pWidth, int pHeight)
throws ImageServletException {
// Get parameters
String text = pReq.getParameter(PARAM_TEXT);
String[] lines = StringUtil.toStringArray(text, "\n\r");
String fontFamily = pReq.getParameter(PARAM_FONT_FAMILY);
String fontSize = pReq.getParameter(PARAM_FONT_SIZE);
String fontStyle = pReq.getParameter(PARAM_FONT_STYLE);
String bgcolor = pReq.getParameter(PARAM_BGCOLOR);
String fgcolor = pReq.getParameter(PARAM_FGCOLOR);
// TODO: Make them static..
pRes.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
pRes.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
pRes.addRenderingHints(new RenderingHints(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY));
// pRes.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
//System.out.println(pRes.getBackground());
// Clear area with bgcolor
if (!StringUtil.isEmpty(bgcolor)) {
pRes.setBackground(StringUtil.toColor(bgcolor));
pRes.clearRect(0, 0, pWidth, pHeight);
//System.out.println(pRes.getBackground());
}
// Create and set font
Font font = new Font(
fontFamily != null ? fontFamily : "Helvetica",
getFontStyle(fontStyle),
fontSize != null ? Integer.parseInt(fontSize) : 12
);
pRes.setFont(font);
// Set rotation
double angle = getAngle(pReq);
pRes.rotate(angle, pWidth / 2.0, pHeight / 2.0);
// Draw string in fgcolor
pRes.setColor(fgcolor != null ? StringUtil.toColor(fgcolor) : Color.black);
float x = ServletUtil.getFloatParameter(pReq, PARAM_MARGIN_LEFT, Float.MIN_VALUE);
Rectangle2D[] bounds = new Rectangle2D[lines.length];
if (x <= Float.MIN_VALUE) {
// Center
float longest = 0f;
for (int i = 0; i < lines.length; i++) {
bounds[i] = font.getStringBounds(lines[i], pRes.getFontRenderContext());
if (bounds[i].getWidth() > longest) {
longest = (float) bounds[i].getWidth();
}
}
//x = (float) ((pWidth - bounds.getWidth()) / 2f);
x = (float) ((pWidth - longest) / 2f);
//System.out.println("marginLeft: " + x);
}
//else {
//System.out.println("marginLeft (from param): " + x);
//}
float y = ServletUtil.getFloatParameter(pReq, PARAM_MARGIN_TOP, Float.MIN_VALUE);
float lineHeight = (float) (bounds[0] != null ?
bounds[0].getHeight() : font.getStringBounds(lines[0], pRes.getFontRenderContext()).getHeight());
if (y <= Float.MIN_VALUE) {
// Center
y = (float) ((pHeight - lineHeight) / 2f)
- (lineHeight * (lines.length - 2.5f) / 2f);
//System.out.println("marginTop: " + y);
}
else {
// Todo: Correct for font height?
y += font.getSize2D();
//System.out.println("marginTop (from param):" + y);
}
//System.out.println("Font size: " + font.getSize2D());
//System.out.println("Line height: " + lineHeight);
// Draw
for (int i = 0; i < lines.length; i++) {
pRes.drawString(lines[i], x, y + lineHeight * i);
}
}
/**
* Returns the font style constant.
*
* @param pStyle a string containing either the word {@code "plain"} or one
* or more of {@code "bold"} and {@code italic}.
* @return the font style constant as defined in {@link Font}.
*
* @see Font#PLAIN
* @see Font#BOLD
* @see Font#ITALIC
*/
private int getFontStyle(String pStyle) {
if (pStyle == null || StringUtil.containsIgnoreCase(pStyle, FONT_STYLE_PLAIN)) {
return Font.PLAIN;
}
// Try to find bold/italic
int style = Font.PLAIN;
if (StringUtil.containsIgnoreCase(pStyle, FONT_STYLE_BOLD)) {
style |= Font.BOLD;
}
if (StringUtil.containsIgnoreCase(pStyle, FONT_STYLE_ITALIC)) {
style |= Font.ITALIC;
}
return style;
}
/**
* Gets the angle of rotation from the request.
*
* @param pRequest the servlet request to get parameters from
* @return the angle in radians.
*/
private double getAngle(ServletRequest pRequest) {
// Get angle
double angle = ServletUtil.getDoubleParameter(pRequest, PARAM_TEXT_ROTATION, 0.0);
// Convert to radians, if needed
String units = pRequest.getParameter(PARAM_TEXT_ROTATION_UNITS);
if (!StringUtil.isEmpty(units) && ROTATION_DEGREES.equalsIgnoreCase(units)) {
angle = Math.toRadians(angle);
}
return angle;
}
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name "TwelveMonkeys" nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
*/
package com.twelvemonkeys.servlet.image;
import com.twelvemonkeys.lang.StringUtil;
import com.twelvemonkeys.servlet.ServletUtil;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.geom.Rectangle2D;
/**
* This servlet is capable of rendereing a text string and output it as an
* image. The text can be rendered in any given font, size,
* style or color, into an image, and output it as a GIF, JPEG or PNG image,
* with optional caching of the rendered image files.
*
* <P><HR><P>
*
* <A name="parameters"></A><STRONG>Parameters:</STRONG><BR>
* <DL>
* <DT>{@code text}</DT>
* <DD>string, the text string to render.
* <DT>{@code width}</DT>
* <DD>integer, the width of the image
* <DT>{@code height}</DT>
* <DD>integer, the height of the image
* <DT>{@code fontFamily}</DT>
* <DD>string, the name of the font family.
* Default is {@code "Helvetica"}.
* <DT>{@code fontSize}</DT>
* <DD>integer, the size of the font. Default is {@code 12}.
* <DT>{@code fontStyle}</DT>
* <DD>string, the tyle of the font. Can be one of the constants
* {@code plain} (default), {@code bold}, {@code italic} or
* {@code bolditalic}. Any other will result in {@code plain}.
* <DT>{@code fgcolor}</DT>
* <DD>color (HTML form, {@code #RRGGBB}), or color constant from
* {@link java.awt.Color}, default is {@code "black"}.
* <DT>{@code bgcolor}</DT>
* <DD>color (HTML form, {@code #RRGGBB}), or color constant from
* {@link java.awt.Color}, default is {@code "transparent"}.
* Note that the hash character ({@code "#"}) used in colors must be
* escaped as {@code %23} in the query string. See
* {@link StringUtil#toColor(String)}, <A href="#examples">examples</A>.
*
* <!-- inherited from ImageServlet below: -->
*
* <DT>{@code cache}</DT>
* <DD>boolean, {@code true} if you want to cache the result
* to disk (default).
*
* <DT>{@code compression}</DT>
* <DD>float, the optional compression ratio for the output image. For JPEG
* images, the quality is the inverse of the compression ratio. See
* {@link #JPEG_DEFAULT_COMPRESSION_LEVEL},
* {@link #PNG_DEFAULT_COMPRESSION_LEVEL}.
* <DD>Applies to JPEG and PNG images only.
*
* <DT>{@code dither}</DT>
* <DD>enumerated, one of {@code NONE}, {@code DEFAULT} or
* {@code FS}, if you want to dither the result ({@code DEFAULT} is
* default).
* {@code FS} will produce the best results, but it's slower.
* <DD>Use in conjuction with {@code indexed}, {@code palette}
* and {@code websafe}.
* <DD>Applies to GIF and PNG images only.
*
* <DT>{@code fileName}</DT>
* <DD>string, an optional filename. If not set, the path after the servlet
* ({@link HttpServletRequest#getPathInfo}) will be used for the cache
* filename. See {@link #getCacheFile(ServletRequest)},
* {@link #getCacheRoot}.
*
* <DT>{@code height}</DT>
* <DD>integer, the height of the image.
*
* <DT>{@code width}</DT>
* <DD>integer, the width of the image.
*
* <DT>{@code indexed}</DT>
* <DD>integer, the number of colors in the resulting image, or -1 (default).
* If the value is set and positive, the image will use an
* {@code IndexColorModel} with
* the number of colors specified. Otherwise the image will be true color.
* <DD>Applies to GIF and PNG images only.
*
* <DT>{@code palette}</DT>
* <DD>string, an optional filename. If set, the image will use IndexColorModel
* with a palette read from the given file.
* <DD>Applies to GIF and PNG images only.
*
* <DT>{@code websafe}</DT>
* <DD>boolean, {@code true} if you want the result to use the 216 color
* websafe palette (default is false).
* <DD>Applies to GIF and PNG images only.
* </DL>
*
* @example
* &lt;IMG src="/text/test.gif?height=40&width=600
* &fontFamily=TimesRoman&fontSize=30&fontStyle=italic&fgcolor=%23990033
* &bgcolor=%23cccccc&text=the%20quick%20brown%20fox%20jumps%20over%20the
* %20lazy%20dog&cache=false" /&gt;
*
* @example
* &lt;IMG src="/text/test.jpg?height=40&width=600
* &fontFamily=TimesRoman&fontSize=30&fontStyle=italic&fgcolor=black
* &bgcolor=%23cccccc&text=the%20quick%20brown%20fox%20jumps%20over%20the
* %20lazy%20dog&compression=3&cache=false" /&gt;
*
* @example
* &lt;IMG src="/text/test.png?height=40&width=600
* &fontFamily=TimesRoman&fontSize=30&fontStyle=italic&fgcolor=%23336699
* &bgcolor=%23cccccc&text=the%20quick%20brown%20fox%20jumps%20over%20the
* %20lazy%20dog&cache=true" /&gt;
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: TextRenderer.java#2 $
*/
class TextRenderer /*extends ImageServlet implements ImagePainterServlet*/ {
// TODO: Create something usable out of this piece of old junk.. ;-)
// It just needs a graphics object to write onto
// Alternatively, defer, and compute the size needed
// Or, make it a filter...
/** {@code "italic"} */
public final static String FONT_STYLE_ITALIC = "italic";
/** {@code "plain"} */
public final static String FONT_STYLE_PLAIN = "plain";
/** {@code "bold"} */
public final static String FONT_STYLE_BOLD = "bold";
/** {@code text} */
public final static String PARAM_TEXT = "text";
/** {@code marginLeft} */
public final static String PARAM_MARGIN_LEFT = "marginLeft";
/** {@code marginTop} */
public final static String PARAM_MARGIN_TOP = "marginTop";
/** {@code fontFamily} */
public final static String PARAM_FONT_FAMILY = "fontFamily";
/** {@code fontSize} */
public final static String PARAM_FONT_SIZE = "fontSize";
/** {@code fontStyle} */
public final static String PARAM_FONT_STYLE = "fontStyle";
/** {@code textRotation} */
public final static String PARAM_TEXT_ROTATION = "textRotation";
/** {@code textRotation} */
public final static String PARAM_TEXT_ROTATION_UNITS = "textRotationUnits";
/** {@code bgcolor} */
public final static String PARAM_BGCOLOR = "bgcolor";
/** {@code fgcolor} */
public final static String PARAM_FGCOLOR = "fgcolor";
protected final static String ROTATION_DEGREES = "DEGREES";
protected final static String ROTATION_RADIANS = "RADIANS";
/**
* Creates the TextRender servlet.
*/
public TextRenderer() {
}
/**
* Renders the text string for this servlet request.
*/
private void paint(ServletRequest pReq, Graphics2D pRes, int pWidth, int pHeight)
throws ImageServletException {
// Get parameters
String text = pReq.getParameter(PARAM_TEXT);
String[] lines = StringUtil.toStringArray(text, "\n\r");
String fontFamily = pReq.getParameter(PARAM_FONT_FAMILY);
String fontSize = pReq.getParameter(PARAM_FONT_SIZE);
String fontStyle = pReq.getParameter(PARAM_FONT_STYLE);
String bgcolor = pReq.getParameter(PARAM_BGCOLOR);
String fgcolor = pReq.getParameter(PARAM_FGCOLOR);
// TODO: Make them static..
pRes.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
pRes.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
pRes.addRenderingHints(new RenderingHints(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY));
// pRes.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
//System.out.println(pRes.getBackground());
// Clear area with bgcolor
if (!StringUtil.isEmpty(bgcolor)) {
pRes.setBackground(StringUtil.toColor(bgcolor));
pRes.clearRect(0, 0, pWidth, pHeight);
//System.out.println(pRes.getBackground());
}
// Create and set font
Font font = new Font(
fontFamily != null ? fontFamily : "Helvetica",
getFontStyle(fontStyle),
fontSize != null ? Integer.parseInt(fontSize) : 12
);
pRes.setFont(font);
// Set rotation
double angle = getAngle(pReq);
pRes.rotate(angle, pWidth / 2.0, pHeight / 2.0);
// Draw string in fgcolor
pRes.setColor(fgcolor != null ? StringUtil.toColor(fgcolor) : Color.black);
float x = ServletUtil.getFloatParameter(pReq, PARAM_MARGIN_LEFT, Float.MIN_VALUE);
Rectangle2D[] bounds = new Rectangle2D[lines.length];
if (x <= Float.MIN_VALUE) {
// Center
float longest = 0f;
for (int i = 0; i < lines.length; i++) {
bounds[i] = font.getStringBounds(lines[i], pRes.getFontRenderContext());
if (bounds[i].getWidth() > longest) {
longest = (float) bounds[i].getWidth();
}
}
//x = (float) ((pWidth - bounds.getWidth()) / 2f);
x = (float) ((pWidth - longest) / 2f);
//System.out.println("marginLeft: " + x);
}
//else {
//System.out.println("marginLeft (from param): " + x);
//}
float y = ServletUtil.getFloatParameter(pReq, PARAM_MARGIN_TOP, Float.MIN_VALUE);
float lineHeight = (float) (bounds[0] != null ?
bounds[0].getHeight() : font.getStringBounds(lines[0], pRes.getFontRenderContext()).getHeight());
if (y <= Float.MIN_VALUE) {
// Center
y = (float) ((pHeight - lineHeight) / 2f)
- (lineHeight * (lines.length - 2.5f) / 2f);
//System.out.println("marginTop: " + y);
}
else {
// Todo: Correct for font height?
y += font.getSize2D();
//System.out.println("marginTop (from param):" + y);
}
//System.out.println("Font size: " + font.getSize2D());
//System.out.println("Line height: " + lineHeight);
// Draw
for (int i = 0; i < lines.length; i++) {
pRes.drawString(lines[i], x, y + lineHeight * i);
}
}
/**
* Returns the font style constant.
*
* @param pStyle a string containing either the word {@code "plain"} or one
* or more of {@code "bold"} and {@code italic}.
* @return the font style constant as defined in {@link Font}.
*
* @see Font#PLAIN
* @see Font#BOLD
* @see Font#ITALIC
*/
private int getFontStyle(String pStyle) {
if (pStyle == null || StringUtil.containsIgnoreCase(pStyle, FONT_STYLE_PLAIN)) {
return Font.PLAIN;
}
// Try to find bold/italic
int style = Font.PLAIN;
if (StringUtil.containsIgnoreCase(pStyle, FONT_STYLE_BOLD)) {
style |= Font.BOLD;
}
if (StringUtil.containsIgnoreCase(pStyle, FONT_STYLE_ITALIC)) {
style |= Font.ITALIC;
}
return style;
}
/**
* Gets the angle of rotation from the request.
*
* @param pRequest the servlet request to get parameters from
* @return the angle in radians.
*/
private double getAngle(ServletRequest pRequest) {
// Get angle
double angle = ServletUtil.getDoubleParameter(pRequest, PARAM_TEXT_ROTATION, 0.0);
// Convert to radians, if needed
String units = pRequest.getParameter(PARAM_TEXT_ROTATION_UNITS);
if (!StringUtil.isEmpty(units) && ROTATION_DEGREES.equalsIgnoreCase(units)) {
angle = Math.toRadians(angle);
}
return angle;
}
}

View File

@@ -1,76 +1,76 @@
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: Droplet.java,v $
* Revision 1.3 2003/10/06 14:25:19 WMHAKUR
* Code clean-up only.
*
* Revision 1.2 2002/10/18 14:12:16 WMHAKUR
* Now, it even compiles. :-/
*
* Revision 1.1 2002/10/18 14:02:16 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet;
import com.twelvemonkeys.servlet.jsp.droplet.taglib.IncludeTag;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
/**
* Dynamo Droplet like Servlet.
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*
*/
public abstract class Droplet extends HttpServlet implements JspFragment {
public abstract void service(PageContext pPageContext)
throws ServletException, IOException;
/**
* Services a parameter. Programatically equivalent to the
* <d:valueof param="pParameter"/> JSP tag.
*/
public void serviceParameter(String pParameter, PageContext pPageContext) throws ServletException, IOException {
Object param = pPageContext.getRequest().getAttribute(pParameter);
if (param != null) {
if (param instanceof Param) {
((Param) param).service(pPageContext);
}
else {
pPageContext.getOut().print(param);
}
}
else {
// Try to get value from parameters
Object obj = pPageContext.getRequest().getParameter(pParameter);
// Print parameter or default value
pPageContext.getOut().print((obj != null) ? obj : "");
}
}
/**
* "There's no need to override this method." :-)
*/
final public void service(HttpServletRequest pRequest, HttpServletResponse pResponse) throws ServletException, IOException {
PageContext pageContext = (PageContext) pRequest.getAttribute(IncludeTag.PAGE_CONTEXT);
// TODO: What if pageContext == null
service(pageContext);
}
}
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: Droplet.java,v $
* Revision 1.3 2003/10/06 14:25:19 WMHAKUR
* Code clean-up only.
*
* Revision 1.2 2002/10/18 14:12:16 WMHAKUR
* Now, it even compiles. :-/
*
* Revision 1.1 2002/10/18 14:02:16 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet;
import com.twelvemonkeys.servlet.jsp.droplet.taglib.IncludeTag;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
/**
* Dynamo Droplet like Servlet.
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*
*/
public abstract class Droplet extends HttpServlet implements JspFragment {
public abstract void service(PageContext pPageContext)
throws ServletException, IOException;
/**
* Services a parameter. Programatically equivalent to the
* <d:valueof param="pParameter"/> JSP tag.
*/
public void serviceParameter(String pParameter, PageContext pPageContext) throws ServletException, IOException {
Object param = pPageContext.getRequest().getAttribute(pParameter);
if (param != null) {
if (param instanceof Param) {
((Param) param).service(pPageContext);
}
else {
pPageContext.getOut().print(param);
}
}
else {
// Try to get value from parameters
Object obj = pPageContext.getRequest().getParameter(pParameter);
// Print parameter or default value
pPageContext.getOut().print((obj != null) ? obj : "");
}
}
/**
* "There's no need to override this method." :-)
*/
final public void service(HttpServletRequest pRequest, HttpServletResponse pResponse) throws ServletException, IOException {
PageContext pageContext = (PageContext) pRequest.getAttribute(IncludeTag.PAGE_CONTEXT);
// TODO: What if pageContext == null
service(pageContext);
}
}

View File

@@ -1,42 +1,42 @@
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: JspFragment.java,v $
* Revision 1.2 2003/10/06 14:25:36 WMHAKUR
* Code clean-up only.
*
* Revision 1.1 2002/10/18 14:02:16 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet;
import javax.servlet.ServletException;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
/**
* Interface for JSP sub pages or page fragments to implement.
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*/
public interface JspFragment {
/**
* Services a sub page or a page fragment inside another page
* (or PageContext).
*
* @param pContext the PageContext that is used to render the subpage.
*
* @throws ServletException if an exception occurs that interferes with the
* subpage's normal operation
* @throws IOException if an input or output exception occurs
*/
public void service(PageContext pContext) throws ServletException, IOException;
}
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: JspFragment.java,v $
* Revision 1.2 2003/10/06 14:25:36 WMHAKUR
* Code clean-up only.
*
* Revision 1.1 2002/10/18 14:02:16 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet;
import javax.servlet.ServletException;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
/**
* Interface for JSP sub pages or page fragments to implement.
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*/
public interface JspFragment {
/**
* Services a sub page or a page fragment inside another page
* (or PageContext).
*
* @param pContext the PageContext that is used to render the subpage.
*
* @throws ServletException if an exception occurs that interferes with the
* subpage's normal operation
* @throws IOException if an input or output exception occurs
*/
public void service(PageContext pContext) throws ServletException, IOException;
}

View File

@@ -1,26 +1,26 @@
package com.twelvemonkeys.servlet.jsp.droplet;
import javax.servlet.ServletException;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
/**
* Oparam (Open parameter)
*/
public class Oparam extends Param implements JspFragment {
/**
* Creates an Oparam.
*
* @param pValue the value of the parameter
*/
public Oparam(String pValue) {
super(pValue);
}
public void service(PageContext pContext) throws ServletException, IOException {
pContext.getServletContext().log("Service subpage " + pContext.getServletContext().getRealPath(value));
pContext.include(value);
}
}
package com.twelvemonkeys.servlet.jsp.droplet;
import javax.servlet.ServletException;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
/**
* Oparam (Open parameter)
*/
public class Oparam extends Param implements JspFragment {
/**
* Creates an Oparam.
*
* @param pValue the value of the parameter
*/
public Oparam(String pValue) {
super(pValue);
}
public void service(PageContext pContext) throws ServletException, IOException {
pContext.getServletContext().log("Service subpage " + pContext.getServletContext().getRealPath(value));
pContext.include(value);
}
}

View File

@@ -1,41 +1,41 @@
package com.twelvemonkeys.servlet.jsp.droplet;
import javax.servlet.ServletException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
/**
* Param
*/
public class Param implements JspFragment {
/** The value member field. */
protected String value = null;
/**
* Creates a Param.
*
* @param pValue the value of the parameter
*/
public Param(String pValue) {
value = pValue;
}
/**
* Gets the value of the parameter.
*/
public String getValue() {
return value;
}
/**
* Services the page fragment. This version simply prints the value of
* this parameter to teh PageContext's out.
*/
public void service(PageContext pContext)
throws ServletException, IOException {
JspWriter writer = pContext.getOut();
writer.print(value);
}
}
package com.twelvemonkeys.servlet.jsp.droplet;
import javax.servlet.ServletException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
/**
* Param
*/
public class Param implements JspFragment {
/** The value member field. */
protected String value = null;
/**
* Creates a Param.
*
* @param pValue the value of the parameter
*/
public Param(String pValue) {
value = pValue;
}
/**
* Gets the value of the parameter.
*/
public String getValue() {
return value;
}
/**
* Services the page fragment. This version simply prints the value of
* this parameter to teh PageContext's out.
*/
public void service(PageContext pContext)
throws ServletException, IOException {
JspWriter writer = pContext.getOut();
writer.print(value);
}
}

View File

@@ -1,214 +1,214 @@
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: IncludeTag.java,v $
* Revision 1.2 2003/10/06 14:25:36 WMHAKUR
* Code clean-up only.
*
* Revision 1.1 2002/10/18 14:03:09 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet.taglib
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet.taglib;
import com.twelvemonkeys.servlet.jsp.taglib.ExTagSupport;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
/**
* Include tag tag that emulates ATG Dynamo Droplet tag JHTML behaviour for
* JSP.
*
* @author Thomas Purcell (CSC Australia)
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*
*/
public class IncludeTag extends ExTagSupport {
/**
* This will contain the names of all the parameters that have been
* added to the PageContext.REQUEST_SCOPE scope by this tag.
*/
private ArrayList<String> parameterNames = null;
/**
* If any of the parameters we insert for this tag already exist, then
* we back up the older parameter in this {@code HashMap} and
* restore them when the tag is finished.
*/
private HashMap<String, Object> oldParameters = null;
/**
* This is the URL for the JSP page that the parameters contained in this
* tag are to be inserted into.
*/
private String page;
/**
* The name of the PageContext attribute
*/
public final static String PAGE_CONTEXT = "com.twelvemonkeys.servlet.jsp.PageContext";
/**
* Sets the value for the JSP page to insert the parameters into. This
* will be set by the tag attribute within the original JSP page.
*
* @param pPage The URL for the JSP page to insert parameters into.
*/
public void setPage(String pPage) {
page = pPage;
}
/**
* Adds a parameter to the {@code PageContext.REQUEST_SCOPE} scope.
* If a parameter with the same name as {@code pName} already exists,
* then the old parameter is first placed in the {@code OldParameters}
* member variable. When this tag is finished, the old value will be
* restored.
*
* @param pName The name of the new parameter to be stored in the
* {@code PageContext.REQUEST_SCOPE} scope.
* @param pValue The value for the parmeter to be stored in the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
public void addParameter(String pName, Object pValue) {
// Check that we haven't already saved this parameter
if (!parameterNames.contains(pName)) {
parameterNames.add(pName);
// Now check if this parameter already exists in the page.
Object obj = getRequest().getAttribute(pName);
if (obj != null) {
oldParameters.put(pName, obj);
}
}
// Finally, insert the parameter in the request scope.
getRequest().setAttribute(pName, pValue);
}
/**
* This is the method called when the JSP interpreter first hits the tag
* associated with this class. This method will firstly determine whether
* the page referenced by the {@code page} attribute exists. If the
* page doesn't exist, this method will throw a {@code JspException}.
* If the page does exist, this method will hand control over to that JSP
* page.
*
* @exception JspException
*/
public int doStartTag() throws JspException {
oldParameters = new HashMap<String, Object>();
parameterNames = new ArrayList<String>();
return EVAL_BODY_INCLUDE;
}
/**
* This method is called when the JSP page compiler hits the end tag. By
* now all the data should have been passed and parameters entered into
* the {@code PageContext.REQUEST_SCOPE} scope. This method includes
* the JSP page whose URL is stored in the {@code mPage} member
* variable.
*
* @exception JspException
*/
public int doEndTag() throws JspException {
String msg;
try {
Iterator<String> iterator;
String parameterName;
// -- Harald K 20020726
// Include the page, in place
//getDispatcher().include(getRequest(), getResponse());
addParameter(PAGE_CONTEXT, pageContext); // Will be cleared later
pageContext.include(page);
// Remove all the parameters that were added to the request scope
// for this insert tag.
iterator = parameterNames.iterator();
while (iterator.hasNext()) {
parameterName = iterator.next();
getRequest().removeAttribute(parameterName);
}
iterator = oldParameters.keySet().iterator();
// Restore the parameters we temporarily replaced (if any).
while (iterator.hasNext()) {
parameterName = iterator.next();
getRequest().setAttribute(parameterName, oldParameters.get(parameterName));
}
return super.doEndTag();
}
catch (IOException ioe) {
msg = "Caught an IOException while including " + page
+ "\n" + ioe.toString();
log(msg, ioe);
throw new JspException(msg);
}
catch (ServletException se) {
msg = "Caught a ServletException while including " + page
+ "\n" + se.toString();
log(msg, se);
throw new JspException(msg);
}
}
/**
* Free up the member variables that we've used throughout this tag.
*/
protected void clearServiceState() {
oldParameters = null;
parameterNames = null;
}
/**
* Returns the request dispatcher for the JSP page whose URL is stored in
* the {@code mPage} member variable.
*
* @return The RequestDispatcher for the JSP page whose URL is stored in
* the {@code mPage} member variable.
*/
/*
private RequestDispatcher getDispatcher() {
return getRequest().getRequestDispatcher(page);
}
*/
/**
* Returns the HttpServletRequest object for the current user request.
*
* @return The HttpServletRequest object for the current user request.
*/
private HttpServletRequest getRequest() {
return (HttpServletRequest) pageContext.getRequest();
}
/**
* Returns the HttpServletResponse object for the current user request.
*
* @return The HttpServletResponse object for the current user request.
*/
private HttpServletResponse getResponse() {
return (HttpServletResponse) pageContext.getResponse();
}
}
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: IncludeTag.java,v $
* Revision 1.2 2003/10/06 14:25:36 WMHAKUR
* Code clean-up only.
*
* Revision 1.1 2002/10/18 14:03:09 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet.taglib
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet.taglib;
import com.twelvemonkeys.servlet.jsp.taglib.ExTagSupport;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
/**
* Include tag tag that emulates ATG Dynamo Droplet tag JHTML behaviour for
* JSP.
*
* @author Thomas Purcell (CSC Australia)
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*
*/
public class IncludeTag extends ExTagSupport {
/**
* This will contain the names of all the parameters that have been
* added to the PageContext.REQUEST_SCOPE scope by this tag.
*/
private ArrayList<String> parameterNames = null;
/**
* If any of the parameters we insert for this tag already exist, then
* we back up the older parameter in this {@code HashMap} and
* restore them when the tag is finished.
*/
private HashMap<String, Object> oldParameters = null;
/**
* This is the URL for the JSP page that the parameters contained in this
* tag are to be inserted into.
*/
private String page;
/**
* The name of the PageContext attribute
*/
public final static String PAGE_CONTEXT = "com.twelvemonkeys.servlet.jsp.PageContext";
/**
* Sets the value for the JSP page to insert the parameters into. This
* will be set by the tag attribute within the original JSP page.
*
* @param pPage The URL for the JSP page to insert parameters into.
*/
public void setPage(String pPage) {
page = pPage;
}
/**
* Adds a parameter to the {@code PageContext.REQUEST_SCOPE} scope.
* If a parameter with the same name as {@code pName} already exists,
* then the old parameter is first placed in the {@code OldParameters}
* member variable. When this tag is finished, the old value will be
* restored.
*
* @param pName The name of the new parameter to be stored in the
* {@code PageContext.REQUEST_SCOPE} scope.
* @param pValue The value for the parmeter to be stored in the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
public void addParameter(String pName, Object pValue) {
// Check that we haven't already saved this parameter
if (!parameterNames.contains(pName)) {
parameterNames.add(pName);
// Now check if this parameter already exists in the page.
Object obj = getRequest().getAttribute(pName);
if (obj != null) {
oldParameters.put(pName, obj);
}
}
// Finally, insert the parameter in the request scope.
getRequest().setAttribute(pName, pValue);
}
/**
* This is the method called when the JSP interpreter first hits the tag
* associated with this class. This method will firstly determine whether
* the page referenced by the {@code page} attribute exists. If the
* page doesn't exist, this method will throw a {@code JspException}.
* If the page does exist, this method will hand control over to that JSP
* page.
*
* @exception JspException
*/
public int doStartTag() throws JspException {
oldParameters = new HashMap<String, Object>();
parameterNames = new ArrayList<String>();
return EVAL_BODY_INCLUDE;
}
/**
* This method is called when the JSP page compiler hits the end tag. By
* now all the data should have been passed and parameters entered into
* the {@code PageContext.REQUEST_SCOPE} scope. This method includes
* the JSP page whose URL is stored in the {@code mPage} member
* variable.
*
* @exception JspException
*/
public int doEndTag() throws JspException {
String msg;
try {
Iterator<String> iterator;
String parameterName;
// -- Harald K 20020726
// Include the page, in place
//getDispatcher().include(getRequest(), getResponse());
addParameter(PAGE_CONTEXT, pageContext); // Will be cleared later
pageContext.include(page);
// Remove all the parameters that were added to the request scope
// for this insert tag.
iterator = parameterNames.iterator();
while (iterator.hasNext()) {
parameterName = iterator.next();
getRequest().removeAttribute(parameterName);
}
iterator = oldParameters.keySet().iterator();
// Restore the parameters we temporarily replaced (if any).
while (iterator.hasNext()) {
parameterName = iterator.next();
getRequest().setAttribute(parameterName, oldParameters.get(parameterName));
}
return super.doEndTag();
}
catch (IOException ioe) {
msg = "Caught an IOException while including " + page
+ "\n" + ioe.toString();
log(msg, ioe);
throw new JspException(msg);
}
catch (ServletException se) {
msg = "Caught a ServletException while including " + page
+ "\n" + se.toString();
log(msg, se);
throw new JspException(msg);
}
}
/**
* Free up the member variables that we've used throughout this tag.
*/
protected void clearServiceState() {
oldParameters = null;
parameterNames = null;
}
/**
* Returns the request dispatcher for the JSP page whose URL is stored in
* the {@code mPage} member variable.
*
* @return The RequestDispatcher for the JSP page whose URL is stored in
* the {@code mPage} member variable.
*/
/*
private RequestDispatcher getDispatcher() {
return getRequest().getRequestDispatcher(page);
}
*/
/**
* Returns the HttpServletRequest object for the current user request.
*
* @return The HttpServletRequest object for the current user request.
*/
private HttpServletRequest getRequest() {
return (HttpServletRequest) pageContext.getRequest();
}
/**
* Returns the HttpServletResponse object for the current user request.
*
* @return The HttpServletResponse object for the current user request.
*/
private HttpServletResponse getResponse() {
return (HttpServletResponse) pageContext.getResponse();
}
}

View File

@@ -1,183 +1,183 @@
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: NestingHandler.java,v $
* Revision 1.4 2003/10/06 14:25:44 WMHAKUR
* Code clean-up only.
*
* Revision 1.3 2003/08/04 15:26:30 WMHAKUR
* Code clean-up.
*
* Revision 1.2 2002/10/18 14:28:07 WMHAKUR
* Fixed package error.
*
* Revision 1.1 2002/10/18 14:03:09 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet.taglib
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet.taglib;
import com.twelvemonkeys.lang.StringUtil;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
/**
* A SAX handler that returns an exception if the nesting of
* {@code param}, {@code oparam}, {@code droplet} and
* {@code valueof} is not correct.
*
* Based on the NestingHandler.java,
* taken from More Servlets and JavaServer Pages
* from Prentice Hall and Sun Microsystems Press,
* http://www.moreservlets.com/.
* &copy; 2002 Marty Hall; may be freely used or adapted.
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*/
public class NestingHandler extends DefaultHandler {
private String includeTagName = "include";
private String paramTagName = "param";
private String openParamTagName = "oparam";
//private Stack mParents = new Stack();
private boolean inIncludeTag = false;
private String namespacePrefix = null;
private String namespaceURI = null;
private NestingValidator validator = null;
public NestingHandler(String pNamespacePrefix, String pNameSpaceURI,
NestingValidator pValidator) {
namespacePrefix = pNamespacePrefix;
namespaceURI = pNameSpaceURI;
validator = pValidator;
}
public void startElement(String pNamespaceURI, String pLocalName,
String pQualifiedName, Attributes pAttributes)
throws SAXException {
String namespacePrefix = !StringUtil.isEmpty(pNamespaceURI)
? getNSPrefixFromURI(pNamespaceURI)
: getNamespacePrefix(pQualifiedName);
String localName = !StringUtil.isEmpty(pLocalName)
? pLocalName : getLocalName(pQualifiedName);
/*
if (namespacePrefix.equals(namespacePrefix)) {
System.out.println("startElement:\nnamespaceURI=" + pNamespaceURI
+ " namespacePrefix=" + namespacePrefix
+ " localName=" + localName
+ " qName=" + pQualifiedName
+ " attributes=" + pAttributes);
}
*/
if (localName.equals(includeTagName)) {
// include
//System.out.println("<" + namespacePrefix + ":"
// + includeTagName + ">");
if (inIncludeTag) {
validator.reportError("Cannot nest " + namespacePrefix + ":"
+ includeTagName);
}
inIncludeTag = true;
}
else if (localName.equals(paramTagName)) {
// param
//System.out.println("<" + namespacePrefix + ":"
// + paramTagName + "/>");
if (!inIncludeTag) {
validator.reportError(this.namespacePrefix + ":"
+ paramTagName
+ " can only appear within "
+ this.namespacePrefix + ":"
+ includeTagName);
}
}
else if (localName.equals(openParamTagName)) {
// oparam
//System.out.println("<" + namespacePrefix + ":"
// + openParamTagName + ">");
if (!inIncludeTag) {
validator.reportError(this.namespacePrefix + ":"
+ openParamTagName
+ " can only appear within "
+ this.namespacePrefix + ":"
+ includeTagName);
}
inIncludeTag = false;
}
else {
// Only jsp:text allowed inside include!
if (inIncludeTag && !localName.equals("text")) {
validator.reportError(namespacePrefix + ":" + localName
+ " can not appear within "
+ this.namespacePrefix + ":"
+ includeTagName);
}
}
}
public void endElement(String pNamespaceURI,
String pLocalName,
String pQualifiedName)
throws SAXException {
String namespacePrefix = !StringUtil.isEmpty(pNamespaceURI)
? getNSPrefixFromURI(pNamespaceURI)
: getNamespacePrefix(pQualifiedName);
String localName = !StringUtil.isEmpty(pLocalName)
? pLocalName : getLocalName(pQualifiedName);
/*
if (namespacePrefix.equals(namespacePrefix)) {
System.out.println("endElement:\nnamespaceURI=" + pNamespaceURI
+ " namespacePrefix=" + namespacePrefix
+ " localName=" + localName
+ " qName=" + pQualifiedName);
}
*/
if (namespacePrefix.equals(this.namespacePrefix)
&& localName.equals(includeTagName)) {
//System.out.println("</" + namespacePrefix + ":"
// + includeTagName + ">");
inIncludeTag = false;
}
else if (namespacePrefix.equals(this.namespacePrefix)
&& localName.equals(openParamTagName)) {
//System.out.println("</" + namespacePrefix + ":"
// + openParamTagName + ">");
inIncludeTag = true; // assuming no errors before this...
}
}
/**
* Stupid broken namespace-support "fix"..
*/
private String getNSPrefixFromURI(String pNamespaceURI) {
return (pNamespaceURI.equals(namespaceURI)
? namespacePrefix : "");
}
private String getNamespacePrefix(String pQualifiedName) {
return pQualifiedName.substring(0, pQualifiedName.indexOf(':'));
}
private String getLocalName(String pQualifiedName) {
return pQualifiedName.substring(pQualifiedName.indexOf(':') + 1);
}
}
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: NestingHandler.java,v $
* Revision 1.4 2003/10/06 14:25:44 WMHAKUR
* Code clean-up only.
*
* Revision 1.3 2003/08/04 15:26:30 WMHAKUR
* Code clean-up.
*
* Revision 1.2 2002/10/18 14:28:07 WMHAKUR
* Fixed package error.
*
* Revision 1.1 2002/10/18 14:03:09 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet.taglib
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet.taglib;
import com.twelvemonkeys.lang.StringUtil;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
/**
* A SAX handler that returns an exception if the nesting of
* {@code param}, {@code oparam}, {@code droplet} and
* {@code valueof} is not correct.
*
* Based on the NestingHandler.java,
* taken from More Servlets and JavaServer Pages
* from Prentice Hall and Sun Microsystems Press,
* http://www.moreservlets.com/.
* &copy; 2002 Marty Hall; may be freely used or adapted.
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*/
public class NestingHandler extends DefaultHandler {
private String includeTagName = "include";
private String paramTagName = "param";
private String openParamTagName = "oparam";
//private Stack mParents = new Stack();
private boolean inIncludeTag = false;
private String namespacePrefix = null;
private String namespaceURI = null;
private NestingValidator validator = null;
public NestingHandler(String pNamespacePrefix, String pNameSpaceURI,
NestingValidator pValidator) {
namespacePrefix = pNamespacePrefix;
namespaceURI = pNameSpaceURI;
validator = pValidator;
}
public void startElement(String pNamespaceURI, String pLocalName,
String pQualifiedName, Attributes pAttributes)
throws SAXException {
String namespacePrefix = !StringUtil.isEmpty(pNamespaceURI)
? getNSPrefixFromURI(pNamespaceURI)
: getNamespacePrefix(pQualifiedName);
String localName = !StringUtil.isEmpty(pLocalName)
? pLocalName : getLocalName(pQualifiedName);
/*
if (namespacePrefix.equals(namespacePrefix)) {
System.out.println("startElement:\nnamespaceURI=" + pNamespaceURI
+ " namespacePrefix=" + namespacePrefix
+ " localName=" + localName
+ " qName=" + pQualifiedName
+ " attributes=" + pAttributes);
}
*/
if (localName.equals(includeTagName)) {
// include
//System.out.println("<" + namespacePrefix + ":"
// + includeTagName + ">");
if (inIncludeTag) {
validator.reportError("Cannot nest " + namespacePrefix + ":"
+ includeTagName);
}
inIncludeTag = true;
}
else if (localName.equals(paramTagName)) {
// param
//System.out.println("<" + namespacePrefix + ":"
// + paramTagName + "/>");
if (!inIncludeTag) {
validator.reportError(this.namespacePrefix + ":"
+ paramTagName
+ " can only appear within "
+ this.namespacePrefix + ":"
+ includeTagName);
}
}
else if (localName.equals(openParamTagName)) {
// oparam
//System.out.println("<" + namespacePrefix + ":"
// + openParamTagName + ">");
if (!inIncludeTag) {
validator.reportError(this.namespacePrefix + ":"
+ openParamTagName
+ " can only appear within "
+ this.namespacePrefix + ":"
+ includeTagName);
}
inIncludeTag = false;
}
else {
// Only jsp:text allowed inside include!
if (inIncludeTag && !localName.equals("text")) {
validator.reportError(namespacePrefix + ":" + localName
+ " can not appear within "
+ this.namespacePrefix + ":"
+ includeTagName);
}
}
}
public void endElement(String pNamespaceURI,
String pLocalName,
String pQualifiedName)
throws SAXException {
String namespacePrefix = !StringUtil.isEmpty(pNamespaceURI)
? getNSPrefixFromURI(pNamespaceURI)
: getNamespacePrefix(pQualifiedName);
String localName = !StringUtil.isEmpty(pLocalName)
? pLocalName : getLocalName(pQualifiedName);
/*
if (namespacePrefix.equals(namespacePrefix)) {
System.out.println("endElement:\nnamespaceURI=" + pNamespaceURI
+ " namespacePrefix=" + namespacePrefix
+ " localName=" + localName
+ " qName=" + pQualifiedName);
}
*/
if (namespacePrefix.equals(this.namespacePrefix)
&& localName.equals(includeTagName)) {
//System.out.println("</" + namespacePrefix + ":"
// + includeTagName + ">");
inIncludeTag = false;
}
else if (namespacePrefix.equals(this.namespacePrefix)
&& localName.equals(openParamTagName)) {
//System.out.println("</" + namespacePrefix + ":"
// + openParamTagName + ">");
inIncludeTag = true; // assuming no errors before this...
}
}
/**
* Stupid broken namespace-support "fix"..
*/
private String getNSPrefixFromURI(String pNamespaceURI) {
return (pNamespaceURI.equals(namespaceURI)
? namespacePrefix : "");
}
private String getNamespacePrefix(String pQualifiedName) {
return pQualifiedName.substring(0, pQualifiedName.indexOf(':'));
}
private String getLocalName(String pQualifiedName) {
return pQualifiedName.substring(pQualifiedName.indexOf(':') + 1);
}
}

View File

@@ -1,102 +1,102 @@
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: NestingValidator.java,v $
* Revision 1.4 2003/08/04 15:26:40 WMHAKUR
* Code clean-up.
*
* Revision 1.3 2002/11/18 14:12:43 WMHAKUR
* *** empty log message ***
*
* Revision 1.2 2002/10/18 14:28:07 WMHAKUR
* Fixed package error.
*
* Revision 1.1 2002/10/18 14:03:09 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet.taglib
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet.taglib;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import javax.servlet.jsp.tagext.PageData;
import javax.servlet.jsp.tagext.TagLibraryValidator;
import javax.servlet.jsp.tagext.ValidationMessage;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.util.ArrayList;
import java.util.List;
/**
* A validator that verifies that tags follow
* proper nesting order.
* <P>
* Based on NestingValidator.java,
* taken from More Servlets and JavaServer Pages
* from Prentice Hall and Sun Microsystems Press,
* http://www.moreservlets.com/.
* &copy; 2002 Marty Hall; may be freely used or adapted.
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*
*/
public class NestingValidator extends TagLibraryValidator {
private List<ValidationMessage> errors = new ArrayList<ValidationMessage>();
/**
*
*/
public ValidationMessage[] validate(String pPrefix, String pURI, PageData pPage) {
//System.out.println("Validating " + pPrefix + " (" + pURI + ") for "
// + pPage + ".");
// Pass the parser factory in on the command line with
// -D to override the use of the Apache parser.
DefaultHandler handler = new NestingHandler(pPrefix, pURI, this);
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
// FileUtil.copy(pPage.getInputStream(), System.out);
SAXParser parser = factory.newSAXParser();
InputSource source =
new InputSource(pPage.getInputStream());
// Parse, handler will use callback to report errors
parser.parse(source, handler);
}
catch (Exception e) {
String errorMessage = e.getMessage();
reportError(errorMessage);
}
// Return any errors and exceptions, empty array means okay
return errors.toArray(new ValidationMessage[errors.size()]);
}
/**
* Callback method for the handler to report errors
*/
public void reportError(String pMessage) {
// The first argument to the ValidationMessage
// constructor can be a tag ID. Since tag IDs
// are not universally supported, use null for
// portability. The important part is the second
// argument: the error message.
errors.add(new ValidationMessage(null, pMessage));
}
}
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: NestingValidator.java,v $
* Revision 1.4 2003/08/04 15:26:40 WMHAKUR
* Code clean-up.
*
* Revision 1.3 2002/11/18 14:12:43 WMHAKUR
* *** empty log message ***
*
* Revision 1.2 2002/10/18 14:28:07 WMHAKUR
* Fixed package error.
*
* Revision 1.1 2002/10/18 14:03:09 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet.taglib
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet.taglib;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import javax.servlet.jsp.tagext.PageData;
import javax.servlet.jsp.tagext.TagLibraryValidator;
import javax.servlet.jsp.tagext.ValidationMessage;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.util.ArrayList;
import java.util.List;
/**
* A validator that verifies that tags follow
* proper nesting order.
* <P>
* Based on NestingValidator.java,
* taken from More Servlets and JavaServer Pages
* from Prentice Hall and Sun Microsystems Press,
* http://www.moreservlets.com/.
* &copy; 2002 Marty Hall; may be freely used or adapted.
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*
*/
public class NestingValidator extends TagLibraryValidator {
private List<ValidationMessage> errors = new ArrayList<ValidationMessage>();
/**
*
*/
public ValidationMessage[] validate(String pPrefix, String pURI, PageData pPage) {
//System.out.println("Validating " + pPrefix + " (" + pURI + ") for "
// + pPage + ".");
// Pass the parser factory in on the command line with
// -D to override the use of the Apache parser.
DefaultHandler handler = new NestingHandler(pPrefix, pURI, this);
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
// FileUtil.copy(pPage.getInputStream(), System.out);
SAXParser parser = factory.newSAXParser();
InputSource source =
new InputSource(pPage.getInputStream());
// Parse, handler will use callback to report errors
parser.parse(source, handler);
}
catch (Exception e) {
String errorMessage = e.getMessage();
reportError(errorMessage);
}
// Return any errors and exceptions, empty array means okay
return errors.toArray(new ValidationMessage[errors.size()]);
}
/**
* Callback method for the handler to report errors
*/
public void reportError(String pMessage) {
// The first argument to the ValidationMessage
// constructor can be a tag ID. Since tag IDs
// are not universally supported, use null for
// portability. The important part is the second
// argument: the error message.
errors.add(new ValidationMessage(null, pMessage));
}
}

View File

@@ -1,220 +1,220 @@
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: OparamTag.java,v $
* Revision 1.4 2003/10/06 14:25:53 WMHAKUR
* Code clean-up only.
*
* Revision 1.3 2002/11/18 14:12:43 WMHAKUR
* *** empty log message ***
*
* Revision 1.2 2002/11/07 12:20:14 WMHAKUR
* Updated to reflect changes in com.twelvemonkeys.util.*Util
*
* Revision 1.1 2002/10/18 14:03:09 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet.taglib
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet.taglib;
import com.twelvemonkeys.io.FileUtil;
import com.twelvemonkeys.lang.StringUtil;
import com.twelvemonkeys.servlet.jsp.droplet.Oparam;
import com.twelvemonkeys.servlet.jsp.taglib.BodyReaderTag;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import java.io.File;
import java.io.IOException;
/**
* Open parameter tag that emulates ATG Dynamo JHTML behaviour for JSP.
*
* @author Thomas Purcell (CSC Australia)
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: jsp/droplet/taglib/OparamTag.java#1 $
*/
public class OparamTag extends BodyReaderTag {
protected final static String COUNTER = "com.twelvemonkeys.servlet.jsp.taglib.OparamTag.counter";
private File subpage = null;
/**
* This is the name of the parameter to be inserted into the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
private String parameterName = null;
private String language = null;
private String prefix = null;
/**
* This method allows the JSP page to set the name for the parameter by
* using the {@code name} tag attribute.
*
* @param pName The name for the parameter to insert into the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
public void setName(String pName) {
parameterName = pName;
}
public void setLanguage(String pLanguage) {
//System.out.println("setLanguage:"+pLanguage);
language = pLanguage;
}
public void setPrefix(String pPrefix) {
//System.out.println("setPrefix:"+pPrefix);
prefix = pPrefix;
}
/**
* Ensure that the tag implemented by this class is enclosed by an {@code IncludeTag}.
* If the tag is not enclosed by an {@code IncludeTag} then a {@code JspException} is thrown.
*
* @return If this tag is enclosed within an {@code IncludeTag}, then the default return value
* from this method is the {@code TagSupport.EVAL_BODY_TAG} value.
*
* @throws JspException
*/
public int doStartTag() throws JspException {
//checkEnclosedInIncludeTag(); // Moved to TagLibValidator
// Get request
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
// Get filename
subpage = createFileNameFromRequest(request);
// Get include tag, and add to parameters
IncludeTag includeTag = (IncludeTag) getParent();
includeTag.addParameter(parameterName, new Oparam(subpage.getName()));
// if ! subpage.exist || jsp newer than subpage, write new
File jsp = new File(pageContext.getServletContext().getRealPath(request.getServletPath()));
if (!subpage.exists() || jsp.lastModified() > subpage.lastModified()) {
return EVAL_BODY_BUFFERED;
}
// No need to evaluate body again!
return SKIP_BODY;
}
/**
* This is the method responsible for actually testing that the tag
* implemented by this class is enclosed within an {@code IncludeTag}.
*
* @exception JspException
*/
/*
protected void checkEnclosedInIncludeTag() throws JspException {
Tag parentTag = getParent();
if ((parentTag != null) && (parentTag instanceof IncludeTag)) {
return;
}
String msg = "A class that extends EnclosedIncludeBodyReaderTag " +
"is not enclosed within an IncludeTag.";
log(msg);
throw new JspException(msg);
}
*/
/**
* This method cleans up the member variables for this tag in preparation
* for being used again. This method is called when the tag finishes it's
* current call with in the page but could be called upon again within this
* same page. This method is also called in the release stage of the tag
* life cycle just in case a JspException was thrown during the tag
* execution.
*/
protected void clearServiceState() {
parameterName = null;
}
/**
* This is the method responsible for taking the result of the JSP code
* that forms the body of this tag and inserts it as a parameter into the
* request scope session. If any problems occur while loading the body
* into the session scope then a {@code JspException} will be thrown.
*
* @param pContent The body of the tag as a String.
* @throws JspException
*/
protected void processBody(String pContent) throws JspException {
// Okay, we have the content, we need to write it to disk somewhere
String content = pContent;
if (!StringUtil.isEmpty(language)) {
content = "<%@page language=\"" + language + "\" %>" + content;
}
if (!StringUtil.isEmpty(prefix)) {
content = "<%@taglib uri=\"/twelvemonkeys-common\" prefix=\"" + prefix + "\" %>" + content;
}
// Write the content of the oparam to disk
try {
log("Processing subpage " + subpage.getPath());
FileUtil.write(subpage, content.getBytes());
}
catch (IOException ioe) {
throw new JspException(ioe);
}
}
/** Creates a unique filename for each (nested) oparam */
private File createFileNameFromRequest(HttpServletRequest pRequest) {
//System.out.println("ServletPath" + pRequest.getServletPath());
String path = pRequest.getServletPath();
// Find last '/'
int splitIndex = path.lastIndexOf("/");
// Split -> path + name
String name = path.substring(splitIndex + 1);
path = path.substring(0, splitIndex);
// Replace special chars in name with '_'
name = name.replace('.', '_');
String param = parameterName.replace('.', '_');
param = param.replace('/', '_');
param = param.replace('\\', '_');
param = param.replace(':', '_');
// tempfile = realPath(path) + name + "_oparam_" + number + ".jsp"
int count = getOparamCountFromRequest(pRequest);
// Hmm.. Would be great, but seems like I can't serve pages from within the temp dir
//File temp = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
//return new File(new File(temp, path), name + "_oparam_" + count + "_" + param + ".jsp");
return new File(new File(pageContext.getServletContext().getRealPath(path)), name + "_oparam_" + count + "_" + param + ".jsp");
}
/** Gets the current oparam count for this request */
private int getOparamCountFromRequest(HttpServletRequest pRequest) {
// Use request.attribute for incrementing oparam counter
Integer count = (Integer) pRequest.getAttribute(COUNTER);
if (count == null) {
count = new Integer(0);
}
else {
count = new Integer(count.intValue() + 1);
}
// ... and set it back
pRequest.setAttribute(COUNTER, count);
return count.intValue();
}
}
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: OparamTag.java,v $
* Revision 1.4 2003/10/06 14:25:53 WMHAKUR
* Code clean-up only.
*
* Revision 1.3 2002/11/18 14:12:43 WMHAKUR
* *** empty log message ***
*
* Revision 1.2 2002/11/07 12:20:14 WMHAKUR
* Updated to reflect changes in com.twelvemonkeys.util.*Util
*
* Revision 1.1 2002/10/18 14:03:09 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet.taglib
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet.taglib;
import com.twelvemonkeys.io.FileUtil;
import com.twelvemonkeys.lang.StringUtil;
import com.twelvemonkeys.servlet.jsp.droplet.Oparam;
import com.twelvemonkeys.servlet.jsp.taglib.BodyReaderTag;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import java.io.File;
import java.io.IOException;
/**
* Open parameter tag that emulates ATG Dynamo JHTML behaviour for JSP.
*
* @author Thomas Purcell (CSC Australia)
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: jsp/droplet/taglib/OparamTag.java#1 $
*/
public class OparamTag extends BodyReaderTag {
protected final static String COUNTER = "com.twelvemonkeys.servlet.jsp.taglib.OparamTag.counter";
private File subpage = null;
/**
* This is the name of the parameter to be inserted into the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
private String parameterName = null;
private String language = null;
private String prefix = null;
/**
* This method allows the JSP page to set the name for the parameter by
* using the {@code name} tag attribute.
*
* @param pName The name for the parameter to insert into the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
public void setName(String pName) {
parameterName = pName;
}
public void setLanguage(String pLanguage) {
//System.out.println("setLanguage:"+pLanguage);
language = pLanguage;
}
public void setPrefix(String pPrefix) {
//System.out.println("setPrefix:"+pPrefix);
prefix = pPrefix;
}
/**
* Ensure that the tag implemented by this class is enclosed by an {@code IncludeTag}.
* If the tag is not enclosed by an {@code IncludeTag} then a {@code JspException} is thrown.
*
* @return If this tag is enclosed within an {@code IncludeTag}, then the default return value
* from this method is the {@code TagSupport.EVAL_BODY_TAG} value.
*
* @throws JspException
*/
public int doStartTag() throws JspException {
//checkEnclosedInIncludeTag(); // Moved to TagLibValidator
// Get request
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
// Get filename
subpage = createFileNameFromRequest(request);
// Get include tag, and add to parameters
IncludeTag includeTag = (IncludeTag) getParent();
includeTag.addParameter(parameterName, new Oparam(subpage.getName()));
// if ! subpage.exist || jsp newer than subpage, write new
File jsp = new File(pageContext.getServletContext().getRealPath(request.getServletPath()));
if (!subpage.exists() || jsp.lastModified() > subpage.lastModified()) {
return EVAL_BODY_BUFFERED;
}
// No need to evaluate body again!
return SKIP_BODY;
}
/**
* This is the method responsible for actually testing that the tag
* implemented by this class is enclosed within an {@code IncludeTag}.
*
* @exception JspException
*/
/*
protected void checkEnclosedInIncludeTag() throws JspException {
Tag parentTag = getParent();
if ((parentTag != null) && (parentTag instanceof IncludeTag)) {
return;
}
String msg = "A class that extends EnclosedIncludeBodyReaderTag " +
"is not enclosed within an IncludeTag.";
log(msg);
throw new JspException(msg);
}
*/
/**
* This method cleans up the member variables for this tag in preparation
* for being used again. This method is called when the tag finishes it's
* current call with in the page but could be called upon again within this
* same page. This method is also called in the release stage of the tag
* life cycle just in case a JspException was thrown during the tag
* execution.
*/
protected void clearServiceState() {
parameterName = null;
}
/**
* This is the method responsible for taking the result of the JSP code
* that forms the body of this tag and inserts it as a parameter into the
* request scope session. If any problems occur while loading the body
* into the session scope then a {@code JspException} will be thrown.
*
* @param pContent The body of the tag as a String.
* @throws JspException
*/
protected void processBody(String pContent) throws JspException {
// Okay, we have the content, we need to write it to disk somewhere
String content = pContent;
if (!StringUtil.isEmpty(language)) {
content = "<%@page language=\"" + language + "\" %>" + content;
}
if (!StringUtil.isEmpty(prefix)) {
content = "<%@taglib uri=\"/twelvemonkeys-common\" prefix=\"" + prefix + "\" %>" + content;
}
// Write the content of the oparam to disk
try {
log("Processing subpage " + subpage.getPath());
FileUtil.write(subpage, content.getBytes());
}
catch (IOException ioe) {
throw new JspException(ioe);
}
}
/** Creates a unique filename for each (nested) oparam */
private File createFileNameFromRequest(HttpServletRequest pRequest) {
//System.out.println("ServletPath" + pRequest.getServletPath());
String path = pRequest.getServletPath();
// Find last '/'
int splitIndex = path.lastIndexOf("/");
// Split -> path + name
String name = path.substring(splitIndex + 1);
path = path.substring(0, splitIndex);
// Replace special chars in name with '_'
name = name.replace('.', '_');
String param = parameterName.replace('.', '_');
param = param.replace('/', '_');
param = param.replace('\\', '_');
param = param.replace(':', '_');
// tempfile = realPath(path) + name + "_oparam_" + number + ".jsp"
int count = getOparamCountFromRequest(pRequest);
// Hmm.. Would be great, but seems like I can't serve pages from within the temp dir
//File temp = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
//return new File(new File(temp, path), name + "_oparam_" + count + "_" + param + ".jsp");
return new File(new File(pageContext.getServletContext().getRealPath(path)), name + "_oparam_" + count + "_" + param + ".jsp");
}
/** Gets the current oparam count for this request */
private int getOparamCountFromRequest(HttpServletRequest pRequest) {
// Use request.attribute for incrementing oparam counter
Integer count = (Integer) pRequest.getAttribute(COUNTER);
if (count == null) {
count = new Integer(0);
}
else {
count = new Integer(count.intValue() + 1);
}
// ... and set it back
pRequest.setAttribute(COUNTER, count);
return count.intValue();
}
}

View File

@@ -1,129 +1,129 @@
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: ParamTag.java,v $
* Revision 1.2 2003/10/06 14:26:00 WMHAKUR
* Code clean-up only.
*
* Revision 1.1 2002/10/18 14:03:09 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet.taglib
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet.taglib;
import com.twelvemonkeys.servlet.jsp.droplet.Param;
import com.twelvemonkeys.servlet.jsp.taglib.ExTagSupport;
import javax.servlet.jsp.JspException;
/**
* Parameter tag that emulates ATG Dynamo JHTML behaviour for JSP.
*
* @author Thomas Purcell (CSC Australia)
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*
*/
public class ParamTag extends ExTagSupport {
/**
* This is the name of the parameter to be inserted into the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
private String parameterName;
/**
* This is the value for the parameter to be inserted into the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
private Object parameterValue;
/**
* This method allows the JSP page to set the name for the parameter by
* using the {@code name} tag attribute.
*
* @param pName The name for the parameter to insert into the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
public void setName(String pName) {
parameterName = pName;
}
/**
* This method allows the JSP page to set the value for hte parameter by
* using the {@code value} tag attribute.
*
* @param pValue The value for the parameter to insert into the <code>
* PageContext.REQUEST_SCOPE</page> scope.
*/
public void setValue(String pValue) {
parameterValue = new Param(pValue);
}
/**
* Ensure that the tag implemented by this class is enclosed by an {@code
* IncludeTag}. If the tag is not enclosed by an
* {@code IncludeTag} then a {@code JspException} is thrown.
*
* @return If this tag is enclosed within an {@code IncludeTag}, then
* the default return value from this method is the {@code
* TagSupport.SKIP_BODY} value.
* @exception JspException
*/
public int doStartTag() throws JspException {
//checkEnclosedInIncludeTag();
addParameter();
return SKIP_BODY;
}
/**
* This is the method responsible for actually testing that the tag
* implemented by this class is enclosed within an {@code IncludeTag}.
*
* @exception JspException
*/
/*
protected void checkEnclosedInIncludeTag() throws JspException {
Tag parentTag = getParent();
if ((parentTag != null) && (parentTag instanceof IncludeTag)) {
return;
}
String msg = "A class that extends EnclosedIncludeBodyReaderTag " +
"is not enclosed within an IncludeTag.";
log(msg);
throw new JspException(msg);
}
*/
/**
* This method adds the parameter whose name and value were passed to this
* object via the tag attributes to the parent {@code Include} tag.
*/
private void addParameter() {
IncludeTag includeTag = (IncludeTag) getParent();
includeTag.addParameter(parameterName, parameterValue);
}
/**
* This method cleans up the member variables for this tag in preparation
* for being used again. This method is called when the tag finishes it's
* current call with in the page but could be called upon again within this
* same page. This method is also called in the release stage of the tag
* life cycle just in case a JspException was thrown during the tag
* execution.
*/
protected void clearServiceState() {
parameterName = null;
parameterValue = null;
}
}
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: ParamTag.java,v $
* Revision 1.2 2003/10/06 14:26:00 WMHAKUR
* Code clean-up only.
*
* Revision 1.1 2002/10/18 14:03:09 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet.taglib
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet.taglib;
import com.twelvemonkeys.servlet.jsp.droplet.Param;
import com.twelvemonkeys.servlet.jsp.taglib.ExTagSupport;
import javax.servlet.jsp.JspException;
/**
* Parameter tag that emulates ATG Dynamo JHTML behaviour for JSP.
*
* @author Thomas Purcell (CSC Australia)
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*
*/
public class ParamTag extends ExTagSupport {
/**
* This is the name of the parameter to be inserted into the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
private String parameterName;
/**
* This is the value for the parameter to be inserted into the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
private Object parameterValue;
/**
* This method allows the JSP page to set the name for the parameter by
* using the {@code name} tag attribute.
*
* @param pName The name for the parameter to insert into the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
public void setName(String pName) {
parameterName = pName;
}
/**
* This method allows the JSP page to set the value for hte parameter by
* using the {@code value} tag attribute.
*
* @param pValue The value for the parameter to insert into the <code>
* PageContext.REQUEST_SCOPE</page> scope.
*/
public void setValue(String pValue) {
parameterValue = new Param(pValue);
}
/**
* Ensure that the tag implemented by this class is enclosed by an {@code
* IncludeTag}. If the tag is not enclosed by an
* {@code IncludeTag} then a {@code JspException} is thrown.
*
* @return If this tag is enclosed within an {@code IncludeTag}, then
* the default return value from this method is the {@code
* TagSupport.SKIP_BODY} value.
* @exception JspException
*/
public int doStartTag() throws JspException {
//checkEnclosedInIncludeTag();
addParameter();
return SKIP_BODY;
}
/**
* This is the method responsible for actually testing that the tag
* implemented by this class is enclosed within an {@code IncludeTag}.
*
* @exception JspException
*/
/*
protected void checkEnclosedInIncludeTag() throws JspException {
Tag parentTag = getParent();
if ((parentTag != null) && (parentTag instanceof IncludeTag)) {
return;
}
String msg = "A class that extends EnclosedIncludeBodyReaderTag " +
"is not enclosed within an IncludeTag.";
log(msg);
throw new JspException(msg);
}
*/
/**
* This method adds the parameter whose name and value were passed to this
* object via the tag attributes to the parent {@code Include} tag.
*/
private void addParameter() {
IncludeTag includeTag = (IncludeTag) getParent();
includeTag.addParameter(parameterName, parameterValue);
}
/**
* This method cleans up the member variables for this tag in preparation
* for being used again. This method is called when the tag finishes it's
* current call with in the page but could be called upon again within this
* same page. This method is also called in the release stage of the tag
* life cycle just in case a JspException was thrown during the tag
* execution.
*/
protected void clearServiceState() {
parameterName = null;
parameterValue = null;
}
}

View File

@@ -1,47 +1,47 @@
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: ValueOfTEI.java,v $
* Revision 1.3 2003/10/06 14:26:07 WMHAKUR
* Code clean-up only.
*
* Revision 1.2 2002/10/18 14:28:07 WMHAKUR
* Fixed package error.
*
* Revision 1.1 2002/10/18 14:03:52 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet.taglib
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet.taglib;
import javax.servlet.jsp.tagext.TagData;
import javax.servlet.jsp.tagext.TagExtraInfo;
/**
* TagExtraInfo for ValueOf.
* @todo More meaningful response to the user.
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*
*/
public class ValueOfTEI extends TagExtraInfo {
public boolean isValid(TagData pTagData) {
Object nameAttr = pTagData.getAttribute("name");
Object paramAttr = pTagData.getAttribute("param");
if ((nameAttr != null && paramAttr == null) || (nameAttr == null && paramAttr != null)) {
return true; // Exactly one of name or param set
}
// Either both or none,
return false;
}
}
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: ValueOfTEI.java,v $
* Revision 1.3 2003/10/06 14:26:07 WMHAKUR
* Code clean-up only.
*
* Revision 1.2 2002/10/18 14:28:07 WMHAKUR
* Fixed package error.
*
* Revision 1.1 2002/10/18 14:03:52 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet.taglib
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet.taglib;
import javax.servlet.jsp.tagext.TagData;
import javax.servlet.jsp.tagext.TagExtraInfo;
/**
* TagExtraInfo for ValueOf.
* @todo More meaningful response to the user.
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*
*/
public class ValueOfTEI extends TagExtraInfo {
public boolean isValid(TagData pTagData) {
Object nameAttr = pTagData.getAttribute("name");
Object paramAttr = pTagData.getAttribute("param");
if ((nameAttr != null && paramAttr == null) || (nameAttr == null && paramAttr != null)) {
return true; // Exactly one of name or param set
}
// Either both or none,
return false;
}
}

View File

@@ -1,148 +1,148 @@
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: ValueOfTag.java,v $
* Revision 1.2 2003/10/06 14:26:14 WMHAKUR
* Code clean-up only.
*
* Revision 1.1 2002/10/18 14:03:52 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet.taglib
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet.taglib;
import com.twelvemonkeys.servlet.jsp.droplet.JspFragment;
import com.twelvemonkeys.servlet.jsp.taglib.ExTagSupport;
import javax.servlet.ServletException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
/**
* ValueOf tag that emulates ATG Dynamo JHTML behaviour for JSP.
*
* @author Thomas Purcell (CSC Australia)
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*/
public class ValueOfTag extends ExTagSupport {
/**
* This is the name of the parameter whose value is to be inserted into
* the current JSP page. This value will be set via the {@code name}
* attribute.
*/
private String parameterName;
/**
* This is the value of the parameter read from the {@code
* PageContext.REQUEST_SCOPE} scope. If the parameter doesn't exist,
* then this will be null.
*/
private Object parameterValue;
/**
* This method is called as part of the initialisation phase of the tag
* life cycle. It sets the parameter name to be read from the {@code
* PageContext.REQUEST_SCOPE} scope.
*
* @param pName The name of the parameter to be read from the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
public void setName(String pName) {
parameterName = pName;
}
/**
* This method is called as part of the initialisation phase of the tag
* life cycle. It sets the parameter name to be read from the {@code
* PageContext.REQUEST_SCOPE} scope. This is just a synonym for
* setName, to be more like ATG Dynamo.
*
* @param pName The name of the parameter to be read from the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
public void setParam(String pName) {
parameterName = pName;
}
/**
* This method looks in the session scope for the session-scoped attribute
* whose name matches the {@code name} tag attribute for this tag.
* If it finds it, then it replaces this tag with the value for the
* session-scoped attribute. If it fails to find the session-scoped
* attribute, it displays the body for this tag.
*
* @return If the session-scoped attribute is found, then this method will
* return {@code TagSupport.SKIP_BODY}, otherwise it will return
* {@code TagSupport.EVAL_BODY_INCLUDE}.
* @exception JspException
*
*/
public int doStartTag() throws JspException {
try {
if (parameterExists()) {
if (parameterValue instanceof JspFragment) {
// OPARAM or PARAM
((JspFragment) parameterValue).service(pageContext);
/*
log("Service subpage " + pageContext.getServletContext().getRealPath(((Oparam) parameterValue).getName()));
pageContext.include(((Oparam) parameterValue).getName());
*/
}
else {
// Normal JSP parameter value
JspWriter writer = pageContext.getOut();
writer.print(parameterValue);
}
return SKIP_BODY;
}
else {
return EVAL_BODY_INCLUDE;
}
}
catch (ServletException se) {
log(se.getMessage(), se);
throw new JspException(se);
}
catch (IOException ioe) {
String msg = "Caught an IOException in ValueOfTag.doStartTag()\n"
+ ioe.toString();
log(msg, ioe);
throw new JspException(msg);
}
}
/**
* This method is used to determine whether the parameter whose name is
* stored in {@code mParameterName} exists within the {@code
* PageContext.REQUEST_SCOPE} scope. If the parameter does exist,
* then this method will return {@code true}, otherwise it returns
* {@code false}. This method has the side affect of loading the
* parameter value into {@code mParameterValue} if the parameter
* does exist.
*
* @return {@code true} if the parameter whose name is in {@code
* mParameterName} exists in the {@code PageContext.REQUEST_SCOPE
* } scope, {@code false} otherwise.
*/
private boolean parameterExists() {
parameterValue = pageContext.getAttribute(parameterName, PageContext.REQUEST_SCOPE);
// -- Harald K 20020726
if (parameterValue == null) {
parameterValue = pageContext.getRequest().getParameter(parameterName);
}
return (parameterValue != null);
}
}
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: ValueOfTag.java,v $
* Revision 1.2 2003/10/06 14:26:14 WMHAKUR
* Code clean-up only.
*
* Revision 1.1 2002/10/18 14:03:52 WMHAKUR
* Moved to com.twelvemonkeys.servlet.jsp.droplet.taglib
*
*
*/
package com.twelvemonkeys.servlet.jsp.droplet.taglib;
import com.twelvemonkeys.servlet.jsp.droplet.JspFragment;
import com.twelvemonkeys.servlet.jsp.taglib.ExTagSupport;
import javax.servlet.ServletException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
/**
* ValueOf tag that emulates ATG Dynamo JHTML behaviour for JSP.
*
* @author Thomas Purcell (CSC Australia)
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
*
* @version $Revision: #1 $, ($Date: 2008/05/05 $)
*/
public class ValueOfTag extends ExTagSupport {
/**
* This is the name of the parameter whose value is to be inserted into
* the current JSP page. This value will be set via the {@code name}
* attribute.
*/
private String parameterName;
/**
* This is the value of the parameter read from the {@code
* PageContext.REQUEST_SCOPE} scope. If the parameter doesn't exist,
* then this will be null.
*/
private Object parameterValue;
/**
* This method is called as part of the initialisation phase of the tag
* life cycle. It sets the parameter name to be read from the {@code
* PageContext.REQUEST_SCOPE} scope.
*
* @param pName The name of the parameter to be read from the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
public void setName(String pName) {
parameterName = pName;
}
/**
* This method is called as part of the initialisation phase of the tag
* life cycle. It sets the parameter name to be read from the {@code
* PageContext.REQUEST_SCOPE} scope. This is just a synonym for
* setName, to be more like ATG Dynamo.
*
* @param pName The name of the parameter to be read from the {@code
* PageContext.REQUEST_SCOPE} scope.
*/
public void setParam(String pName) {
parameterName = pName;
}
/**
* This method looks in the session scope for the session-scoped attribute
* whose name matches the {@code name} tag attribute for this tag.
* If it finds it, then it replaces this tag with the value for the
* session-scoped attribute. If it fails to find the session-scoped
* attribute, it displays the body for this tag.
*
* @return If the session-scoped attribute is found, then this method will
* return {@code TagSupport.SKIP_BODY}, otherwise it will return
* {@code TagSupport.EVAL_BODY_INCLUDE}.
* @exception JspException
*
*/
public int doStartTag() throws JspException {
try {
if (parameterExists()) {
if (parameterValue instanceof JspFragment) {
// OPARAM or PARAM
((JspFragment) parameterValue).service(pageContext);
/*
log("Service subpage " + pageContext.getServletContext().getRealPath(((Oparam) parameterValue).getName()));
pageContext.include(((Oparam) parameterValue).getName());
*/
}
else {
// Normal JSP parameter value
JspWriter writer = pageContext.getOut();
writer.print(parameterValue);
}
return SKIP_BODY;
}
else {
return EVAL_BODY_INCLUDE;
}
}
catch (ServletException se) {
log(se.getMessage(), se);
throw new JspException(se);
}
catch (IOException ioe) {
String msg = "Caught an IOException in ValueOfTag.doStartTag()\n"
+ ioe.toString();
log(msg, ioe);
throw new JspException(msg);
}
}
/**
* This method is used to determine whether the parameter whose name is
* stored in {@code mParameterName} exists within the {@code
* PageContext.REQUEST_SCOPE} scope. If the parameter does exist,
* then this method will return {@code true}, otherwise it returns
* {@code false}. This method has the side affect of loading the
* parameter value into {@code mParameterValue} if the parameter
* does exist.
*
* @return {@code true} if the parameter whose name is in {@code
* mParameterName} exists in the {@code PageContext.REQUEST_SCOPE
* } scope, {@code false} otherwise.
*/
private boolean parameterExists() {
parameterValue = pageContext.getAttribute(parameterName, PageContext.REQUEST_SCOPE);
// -- Harald K 20020726
if (parameterValue == null) {
parameterValue = pageContext.getRequest().getParameter(parameterName);
}
return (parameterValue != null);
}
}

View File

@@ -1,39 +1,39 @@
package com.twelvemonkeys.servlet.jsp.taglib;
import javax.servlet.jsp.JspException;
/**
*
*
* @author Thomas Purcell (CSC Australia)
*
* @version 1.0
*/
public abstract class BodyReaderTag extends ExBodyTagSupport {
/**
* This is the method called by the JSP engine when the body for a tag
* has been parsed and is ready for inclusion in this current tag. This
* method takes the content as a string and passes it to the {@code
* processBody} method.
*
* @return This method returns the {@code BodyTagSupport.SKIP_BODY}
* constant. This means that the body of the tag will only be
* processed the one time.
* @exception JspException
*/
public int doAfterBody() throws JspException {
processBody(bodyContent.getString());
return SKIP_BODY;
}
/**
* This is the method that child classes must implement. It takes the
* body of the tag converted to a String as it's parameter. The body of
* the tag will have been interpreted to a String by the JSP engine before
* this method is called.
*
* @param pContent The body for the custom tag converted to a String.
* @exception JspException
*/
protected abstract void processBody(String pContent) throws JspException;
}
package com.twelvemonkeys.servlet.jsp.taglib;
import javax.servlet.jsp.JspException;
/**
*
*
* @author Thomas Purcell (CSC Australia)
*
* @version 1.0
*/
public abstract class BodyReaderTag extends ExBodyTagSupport {
/**
* This is the method called by the JSP engine when the body for a tag
* has been parsed and is ready for inclusion in this current tag. This
* method takes the content as a string and passes it to the {@code
* processBody} method.
*
* @return This method returns the {@code BodyTagSupport.SKIP_BODY}
* constant. This means that the body of the tag will only be
* processed the one time.
* @exception JspException
*/
public int doAfterBody() throws JspException {
processBody(bodyContent.getString());
return SKIP_BODY;
}
/**
* This is the method that child classes must implement. It takes the
* body of the tag converted to a String as it's parameter. The body of
* the tag will have been interpreted to a String by the JSP engine before
* this method is called.
*
* @param pContent The body for the custom tag converted to a String.
* @exception JspException
*/
protected abstract void processBody(String pContent) throws JspException;
}

View File

@@ -1,235 +1,235 @@
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: CSVToTableTag.java,v $
* Revision 1.3 2003/10/06 14:24:50 WMHAKUR
* Code clean-up only.
*
* Revision 1.2 2002/11/26 17:33:49 WMHAKUR
* Added documentation & removed System.out.println()s.
*
* Revision 1.1 2002/11/19 10:50:10 WMHAKUR
* Renamed from CSVToTable, to follow naming conventions.
*
* Revision 1.1 2002/11/18 22:11:16 WMHAKUR
* Tag to convert CSV to HTML table.
* Can be further transformed, using XSLT.
*
*/
package com.twelvemonkeys.servlet.jsp.taglib;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
/**
* Creates a table from a string of "comma-separated values" (CSV).
* The delimiter character can be any character (or combination of characters).
* The default delimiter is TAB ({@code \t}).
*
* <P/>
* <HR/>
* <P/>
*
* The input may look like this:
* <PRE>
* &lt;c:totable firstRowIsHeader="true" delimiter=";"&gt;
* header A;header B
* data 1A; data 1B
* data 2A; data 2B
* &lt;/c:totable&gt;
* </PRE>
*
* The output (source) will look like this:
* <PRE>
* &lt;TABLE&gt;
* &lt;TR&gt;
* &lt;TH&gt;header A&lt;/TH&gt;&lt;TH&gt;header B&lt;/TH&gt;
* &lt;/TR&gt;
* &lt;TR&gt;
* &lt;TD&gt;data 1A&lt;/TD&gt;&lt;TD&gt;data 1B&lt;/TD&gt;
* &lt;/TR&gt;
* &lt;TR&gt;
* &lt;TD&gt;data 2A&lt;/TD&gt;&lt;TD&gt;data 2B&lt;/TD&gt;
* &lt;/TR&gt;
* &lt;/TABLE&gt;
* </PRE>
* You wil probably want to use XSLT to make the final output look nicer. :-)
*
* @see StringTokenizer
* @see <A href="http://www.w3.org/TR/xslt">XSLT spec</A>
*
* @author Harald Kuhr
*
* @version $Id: jsp/taglib/CSVToTableTag.java#1 $
*/
public class CSVToTableTag extends ExBodyTagSupport {
public final static String TAB = "\t";
protected String delimiter = null;
protected boolean firstRowIsHeader = false;
protected boolean firstColIsHeader = false;
public void setDelimiter(String pDelimiter) {
delimiter = pDelimiter;
}
public String getDelimiter() {
return delimiter != null ? delimiter : TAB;
}
public void setFirstRowIsHeader(String pBoolean) {
firstRowIsHeader = Boolean.valueOf(pBoolean);
}
public void setFirstColIsHeader(String pBoolean) {
firstColIsHeader = Boolean.valueOf(pBoolean);
}
public int doEndTag() throws JspException {
BodyContent content = getBodyContent();
try {
Table table =
Table.parseContent(content.getReader(), getDelimiter());
JspWriter out = pageContext.getOut();
//System.out.println("CSVToTable: " + table.getRows() + " rows, "
// + table.getCols() + " cols.");
if (table.getRows() > 0) {
out.println("<TABLE>");
// Loop over rows
for (int row = 0; row < table.getRows(); row++) {
out.println("<TR>");
// Loop over cells in each row
for (int col = 0; col < table.getCols(); col++) {
// Test if we are using headers, else normal cell
if (firstRowIsHeader && row == 0 || firstColIsHeader && col == 0) {
out.println("<TH>" + table.get(row, col) + " </TH>");
}
else {
out.println("<TD>" + table.get(row, col) + " </TD>");
}
}
out.println("</TR>");
}
out.println("</TABLE>");
}
}
catch (IOException ioe) {
throw new JspException(ioe);
}
return super.doEndTag();
}
static class Table {
List rows = null;
int cols = 0;
private Table(List pRows, int pCols) {
rows = pRows;
cols = pCols;
}
int getRows() {
return rows != null ? rows.size() : 0;
}
int getCols() {
return cols;
}
List getTableRows() {
return rows;
}
List getTableRow(int pRow) {
return rows != null
? (List) rows.get(pRow)
: Collections.EMPTY_LIST;
}
String get(int pRow, int pCol) {
List row = getTableRow(pRow);
// Rows may contain unequal number of cols
return (row.size() > pCol) ? (String) row.get(pCol) : "";
}
/**
* Parses a BodyContent to a table.
*
*/
static Table parseContent(Reader pContent, String pDelim) throws IOException {
List<List<String>> tableRows = new ArrayList<List<String>>();
int tdsPerTR = 0;
// Loop through TRs
BufferedReader reader = new BufferedReader(pContent);
String tr;
while ((tr = reader.readLine()) != null) {
// Discard blank lines
if (tr.trim().length() <= 0 && tr.indexOf(pDelim) < 0) {
continue;
}
//System.out.println("CSVToTable: read LINE=\"" + tr + "\"");
List<String> tableDatas = new ArrayList<String>();
StringTokenizer tableRow = new StringTokenizer(tr, pDelim,
true);
boolean lastWasDelim = false;
while (tableRow.hasMoreTokens()) {
String td = tableRow.nextToken();
//System.out.println("CSVToTable: read data=\"" + td + "\"");
// Test if we have empty TD
if (td.equals(pDelim)) {
if (lastWasDelim) {
// Add empty TD
tableDatas.add("");
}
// We just read a delimitter
lastWasDelim = true;
}
else {
// No tab, normal data
lastWasDelim = false;
// Add normal TD
tableDatas.add(td);
}
} // end while (tableRow.hasNext())
// Store max TD count
if (tableDatas.size() > tdsPerTR) {
tdsPerTR = tableDatas.size();
}
// Add a table row
tableRows.add(tableDatas);
}
// Return TABLE
return new Table(tableRows, tdsPerTR);
}
}
}
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: CSVToTableTag.java,v $
* Revision 1.3 2003/10/06 14:24:50 WMHAKUR
* Code clean-up only.
*
* Revision 1.2 2002/11/26 17:33:49 WMHAKUR
* Added documentation & removed System.out.println()s.
*
* Revision 1.1 2002/11/19 10:50:10 WMHAKUR
* Renamed from CSVToTable, to follow naming conventions.
*
* Revision 1.1 2002/11/18 22:11:16 WMHAKUR
* Tag to convert CSV to HTML table.
* Can be further transformed, using XSLT.
*
*/
package com.twelvemonkeys.servlet.jsp.taglib;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
/**
* Creates a table from a string of "comma-separated values" (CSV).
* The delimiter character can be any character (or combination of characters).
* The default delimiter is TAB ({@code \t}).
*
* <P/>
* <HR/>
* <P/>
*
* The input may look like this:
* <PRE>
* &lt;c:totable firstRowIsHeader="true" delimiter=";"&gt;
* header A;header B
* data 1A; data 1B
* data 2A; data 2B
* &lt;/c:totable&gt;
* </PRE>
*
* The output (source) will look like this:
* <PRE>
* &lt;TABLE&gt;
* &lt;TR&gt;
* &lt;TH&gt;header A&lt;/TH&gt;&lt;TH&gt;header B&lt;/TH&gt;
* &lt;/TR&gt;
* &lt;TR&gt;
* &lt;TD&gt;data 1A&lt;/TD&gt;&lt;TD&gt;data 1B&lt;/TD&gt;
* &lt;/TR&gt;
* &lt;TR&gt;
* &lt;TD&gt;data 2A&lt;/TD&gt;&lt;TD&gt;data 2B&lt;/TD&gt;
* &lt;/TR&gt;
* &lt;/TABLE&gt;
* </PRE>
* You wil probably want to use XSLT to make the final output look nicer. :-)
*
* @see StringTokenizer
* @see <A href="http://www.w3.org/TR/xslt">XSLT spec</A>
*
* @author Harald Kuhr
*
* @version $Id: jsp/taglib/CSVToTableTag.java#1 $
*/
public class CSVToTableTag extends ExBodyTagSupport {
public final static String TAB = "\t";
protected String delimiter = null;
protected boolean firstRowIsHeader = false;
protected boolean firstColIsHeader = false;
public void setDelimiter(String pDelimiter) {
delimiter = pDelimiter;
}
public String getDelimiter() {
return delimiter != null ? delimiter : TAB;
}
public void setFirstRowIsHeader(String pBoolean) {
firstRowIsHeader = Boolean.valueOf(pBoolean);
}
public void setFirstColIsHeader(String pBoolean) {
firstColIsHeader = Boolean.valueOf(pBoolean);
}
public int doEndTag() throws JspException {
BodyContent content = getBodyContent();
try {
Table table =
Table.parseContent(content.getReader(), getDelimiter());
JspWriter out = pageContext.getOut();
//System.out.println("CSVToTable: " + table.getRows() + " rows, "
// + table.getCols() + " cols.");
if (table.getRows() > 0) {
out.println("<TABLE>");
// Loop over rows
for (int row = 0; row < table.getRows(); row++) {
out.println("<TR>");
// Loop over cells in each row
for (int col = 0; col < table.getCols(); col++) {
// Test if we are using headers, else normal cell
if (firstRowIsHeader && row == 0 || firstColIsHeader && col == 0) {
out.println("<TH>" + table.get(row, col) + " </TH>");
}
else {
out.println("<TD>" + table.get(row, col) + " </TD>");
}
}
out.println("</TR>");
}
out.println("</TABLE>");
}
}
catch (IOException ioe) {
throw new JspException(ioe);
}
return super.doEndTag();
}
static class Table {
List rows = null;
int cols = 0;
private Table(List pRows, int pCols) {
rows = pRows;
cols = pCols;
}
int getRows() {
return rows != null ? rows.size() : 0;
}
int getCols() {
return cols;
}
List getTableRows() {
return rows;
}
List getTableRow(int pRow) {
return rows != null
? (List) rows.get(pRow)
: Collections.EMPTY_LIST;
}
String get(int pRow, int pCol) {
List row = getTableRow(pRow);
// Rows may contain unequal number of cols
return (row.size() > pCol) ? (String) row.get(pCol) : "";
}
/**
* Parses a BodyContent to a table.
*
*/
static Table parseContent(Reader pContent, String pDelim) throws IOException {
List<List<String>> tableRows = new ArrayList<List<String>>();
int tdsPerTR = 0;
// Loop through TRs
BufferedReader reader = new BufferedReader(pContent);
String tr;
while ((tr = reader.readLine()) != null) {
// Discard blank lines
if (tr.trim().length() <= 0 && tr.indexOf(pDelim) < 0) {
continue;
}
//System.out.println("CSVToTable: read LINE=\"" + tr + "\"");
List<String> tableDatas = new ArrayList<String>();
StringTokenizer tableRow = new StringTokenizer(tr, pDelim,
true);
boolean lastWasDelim = false;
while (tableRow.hasMoreTokens()) {
String td = tableRow.nextToken();
//System.out.println("CSVToTable: read data=\"" + td + "\"");
// Test if we have empty TD
if (td.equals(pDelim)) {
if (lastWasDelim) {
// Add empty TD
tableDatas.add("");
}
// We just read a delimitter
lastWasDelim = true;
}
else {
// No tab, normal data
lastWasDelim = false;
// Add normal TD
tableDatas.add(td);
}
} // end while (tableRow.hasNext())
// Store max TD count
if (tableDatas.size() > tdsPerTR) {
tdsPerTR = tableDatas.size();
}
// Add a table row
tableRows.add(tableDatas);
}
// Return TABLE
return new Table(tableRows, tdsPerTR);
}
}
}

View File

@@ -1,290 +1,290 @@
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: ExBodyTagSupport.java,v $
* Revision 1.3 2003/10/06 14:24:57 WMHAKUR
* Code clean-up only.
*
* Revision 1.2 2002/11/18 22:10:27 WMHAKUR
* *** empty log message ***
*
*
*/
package com.twelvemonkeys.servlet.jsp.taglib;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.StringTokenizer;
/**
* This is the class that should be extended by all jsp pages that do use their
* body. It contains a lot of helper methods for simplifying common tasks.
*
* @author Thomas Purcell (CSC Australia)
* @author Harald Kuhr
*
* @version $Id: jsp/taglib/ExBodyTagSupport.java#1 $
*/
public class ExBodyTagSupport extends BodyTagSupport implements ExTag {
/**
* writeHtml ensures that the text being outputted appears as it was
* entered. This prevents users from hacking the system by entering
* html or jsp code into an entry form where that value will be displayed
* later in the site.
*
* @param pOut The JspWriter to write the output to.
* @param pHtml The original html to filter and output to the user.
* @throws IOException If the user clicks Stop in the browser, or their
* browser crashes, then the JspWriter will throw an IOException when
* the jsp tries to write to it.
*/
public void writeHtml(JspWriter pOut, String pHtml) throws IOException {
StringTokenizer parser = new StringTokenizer(pHtml, "<>&", true);
while (parser.hasMoreTokens()) {
String token = parser.nextToken();
if (token.equals("<")) {
pOut.print("&lt;");
}
else if (token.equals(">")) {
pOut.print("&gt;");
}
else if (token.equals("&")) {
pOut.print("&amp;");
}
else {
pOut.print(token);
}
}
}
/**
* Log a message to the servlet context.
*
* @param pMsg The error message to log.
*/
public void log(String pMsg) {
getServletContext().log(pMsg);
}
/**
* Log a message to the servlet context and include the exception that is
* passed in as the second parameter.
*
* @param pMsg The error message to log.
* @param pException The exception that caused this error message to be
* logged.
*/
public void log(String pMsg, Throwable pException) {
getServletContext().log(pMsg, pException);
}
/**
* Retrieves the ServletContext object associated with the current
* PageContext object.
*
* @return The ServletContext object associated with the current
* PageContext object.
*/
public ServletContext getServletContext() {
return pageContext.getServletContext();
}
/**
* Called when the tag has finished running. Any clean up that needs
* to be done between calls to this tag but within the same JSP page is
* called in the {@code clearServiceState()} method call.
*
* @exception JspException
*/
public int doEndTag() throws JspException {
clearServiceState();
return super.doEndTag();
}
/**
* Called when a tag's role in the current JSP page is finished. After
* the {@code clearProperties()} method is called, the custom tag
* should be in an identical state as when it was first created. The
* {@code clearServiceState()} method is called here just in case an
* exception was thrown in the custom tag. If an exception was thrown,
* then the {@code doEndTag()} method will not have been called and
* the tag might not have been cleaned up properly.
*/
public void release() {
clearServiceState();
clearProperties();
super.release();
}
/**
* The default implementation for the {@code clearProperties()}. Not
* all tags will need to overload this method call. By implementing it
* here, all classes that extend this object are able to call {@code
* super.clearProperties()}. So, if the class extends a different
* tag, or this one, the parent method should always be called. This
* method will be called when the tag is to be released. That is, the
* tag has finished for the current page and should be returned to it's
* initial state.
*/
protected void clearProperties() {
}
/**
* The default implementation for the {@code clearServiceState()}.
* Not all tags will need to overload this method call. By implementing it
* here, all classes that extend this object are able to call {@code
* super.clearServiceState()}. So, if the class extends a different
* tag, or this one, the parent method should always be called. This
* method will be called when the tag has finished it's current tag
* within the page, but may be called upon again in this same JSP page.
*/
protected void clearServiceState() {
}
/**
* Returns the initialisation parameter from the {@code
* PageContext.APPLICATION_SCOPE} scope. These initialisation
* parameters are defined in the {@code web.xml} configuration file.
*
* @param pName The name of the initialisation parameter to return the
* value for.
* @return The value for the parameter whose name was passed in as a
* parameter. If the parameter does not exist, then {@code null}
* will be returned.
*/
public String getInitParameter(String pName) {
return getInitParameter(pName, PageContext.APPLICATION_SCOPE);
}
/**
* Returns an Enumeration containing all the names for all the
* initialisation parametes defined in the {@code
* PageContext.APPLICATION_SCOPE} scope.
*
* @return An {@code Enumeration} containing all the names for all the
* initialisation parameters.
*/
public Enumeration getInitParameterNames() {
return getInitParameterNames(PageContext.APPLICATION_SCOPE);
}
/**
* Returns the initialisation parameter from the scope specified with the
* name specified.
*
* @param pName The name of the initialisation parameter to return the
* value for.
* @param pScope The scope to search for the initialisation parameter
* within.
* @return The value of the parameter found. If no parameter with the
* name specified is found in the scope specified, then {@code null
* } is returned.
*/
public String getInitParameter(String pName, int pScope) {
switch (pScope) {
case PageContext.PAGE_SCOPE:
return getServletConfig().getInitParameter(pName);
case PageContext.APPLICATION_SCOPE:
return getServletContext().getInitParameter(pName);
default:
throw new IllegalArgumentException("Illegal scope.");
}
}
/**
* Returns an enumeration containing all the parameters defined in the
* scope specified by the parameter.
*
* @param pScope The scope to return the names of all the parameters
* defined within.
* @return An {@code Enumeration} containing all the names for all the
* parameters defined in the scope passed in as a parameter.
*/
public Enumeration getInitParameterNames(int pScope) {
switch (pScope) {
case PageContext.PAGE_SCOPE:
return getServletConfig().getInitParameterNames();
case PageContext.APPLICATION_SCOPE:
return getServletContext().getInitParameterNames();
default:
throw new IllegalArgumentException("Illegal scope");
}
}
/**
* Returns the servlet config associated with the current JSP page request.
*
* @return The {@code ServletConfig} associated with the current
* request.
*/
public ServletConfig getServletConfig() {
return pageContext.getServletConfig();
}
/**
* Gets the context path associated with the current JSP page request.
* If the request is not a HttpServletRequest, this method will
* return "/".
*
* @return a path relative to the current context's root, or
* {@code "/"} if this is not a HTTP request.
*/
public String getContextPath() {
ServletRequest request = pageContext.getRequest();
if (request instanceof HttpServletRequest) {
return ((HttpServletRequest) request).getContextPath();
}
return "/";
}
/**
* Gets the resource associated with the given relative path for the
* current JSP page request.
* The path may be absolute, or relative to the current context root.
*
* @param pPath the path
*
* @return a path relative to the current context root
*/
public InputStream getResourceAsStream(String pPath) {
// throws MalformedURLException {
String path = pPath;
if (pPath != null && !pPath.startsWith("/")) {
path = getContextPath() + pPath;
}
return pageContext.getServletContext().getResourceAsStream(path);
}
}
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: ExBodyTagSupport.java,v $
* Revision 1.3 2003/10/06 14:24:57 WMHAKUR
* Code clean-up only.
*
* Revision 1.2 2002/11/18 22:10:27 WMHAKUR
* *** empty log message ***
*
*
*/
package com.twelvemonkeys.servlet.jsp.taglib;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.StringTokenizer;
/**
* This is the class that should be extended by all jsp pages that do use their
* body. It contains a lot of helper methods for simplifying common tasks.
*
* @author Thomas Purcell (CSC Australia)
* @author Harald Kuhr
*
* @version $Id: jsp/taglib/ExBodyTagSupport.java#1 $
*/
public class ExBodyTagSupport extends BodyTagSupport implements ExTag {
/**
* writeHtml ensures that the text being outputted appears as it was
* entered. This prevents users from hacking the system by entering
* html or jsp code into an entry form where that value will be displayed
* later in the site.
*
* @param pOut The JspWriter to write the output to.
* @param pHtml The original html to filter and output to the user.
* @throws IOException If the user clicks Stop in the browser, or their
* browser crashes, then the JspWriter will throw an IOException when
* the jsp tries to write to it.
*/
public void writeHtml(JspWriter pOut, String pHtml) throws IOException {
StringTokenizer parser = new StringTokenizer(pHtml, "<>&", true);
while (parser.hasMoreTokens()) {
String token = parser.nextToken();
if (token.equals("<")) {
pOut.print("&lt;");
}
else if (token.equals(">")) {
pOut.print("&gt;");
}
else if (token.equals("&")) {
pOut.print("&amp;");
}
else {
pOut.print(token);
}
}
}
/**
* Log a message to the servlet context.
*
* @param pMsg The error message to log.
*/
public void log(String pMsg) {
getServletContext().log(pMsg);
}
/**
* Log a message to the servlet context and include the exception that is
* passed in as the second parameter.
*
* @param pMsg The error message to log.
* @param pException The exception that caused this error message to be
* logged.
*/
public void log(String pMsg, Throwable pException) {
getServletContext().log(pMsg, pException);
}
/**
* Retrieves the ServletContext object associated with the current
* PageContext object.
*
* @return The ServletContext object associated with the current
* PageContext object.
*/
public ServletContext getServletContext() {
return pageContext.getServletContext();
}
/**
* Called when the tag has finished running. Any clean up that needs
* to be done between calls to this tag but within the same JSP page is
* called in the {@code clearServiceState()} method call.
*
* @exception JspException
*/
public int doEndTag() throws JspException {
clearServiceState();
return super.doEndTag();
}
/**
* Called when a tag's role in the current JSP page is finished. After
* the {@code clearProperties()} method is called, the custom tag
* should be in an identical state as when it was first created. The
* {@code clearServiceState()} method is called here just in case an
* exception was thrown in the custom tag. If an exception was thrown,
* then the {@code doEndTag()} method will not have been called and
* the tag might not have been cleaned up properly.
*/
public void release() {
clearServiceState();
clearProperties();
super.release();
}
/**
* The default implementation for the {@code clearProperties()}. Not
* all tags will need to overload this method call. By implementing it
* here, all classes that extend this object are able to call {@code
* super.clearProperties()}. So, if the class extends a different
* tag, or this one, the parent method should always be called. This
* method will be called when the tag is to be released. That is, the
* tag has finished for the current page and should be returned to it's
* initial state.
*/
protected void clearProperties() {
}
/**
* The default implementation for the {@code clearServiceState()}.
* Not all tags will need to overload this method call. By implementing it
* here, all classes that extend this object are able to call {@code
* super.clearServiceState()}. So, if the class extends a different
* tag, or this one, the parent method should always be called. This
* method will be called when the tag has finished it's current tag
* within the page, but may be called upon again in this same JSP page.
*/
protected void clearServiceState() {
}
/**
* Returns the initialisation parameter from the {@code
* PageContext.APPLICATION_SCOPE} scope. These initialisation
* parameters are defined in the {@code web.xml} configuration file.
*
* @param pName The name of the initialisation parameter to return the
* value for.
* @return The value for the parameter whose name was passed in as a
* parameter. If the parameter does not exist, then {@code null}
* will be returned.
*/
public String getInitParameter(String pName) {
return getInitParameter(pName, PageContext.APPLICATION_SCOPE);
}
/**
* Returns an Enumeration containing all the names for all the
* initialisation parametes defined in the {@code
* PageContext.APPLICATION_SCOPE} scope.
*
* @return An {@code Enumeration} containing all the names for all the
* initialisation parameters.
*/
public Enumeration getInitParameterNames() {
return getInitParameterNames(PageContext.APPLICATION_SCOPE);
}
/**
* Returns the initialisation parameter from the scope specified with the
* name specified.
*
* @param pName The name of the initialisation parameter to return the
* value for.
* @param pScope The scope to search for the initialisation parameter
* within.
* @return The value of the parameter found. If no parameter with the
* name specified is found in the scope specified, then {@code null
* } is returned.
*/
public String getInitParameter(String pName, int pScope) {
switch (pScope) {
case PageContext.PAGE_SCOPE:
return getServletConfig().getInitParameter(pName);
case PageContext.APPLICATION_SCOPE:
return getServletContext().getInitParameter(pName);
default:
throw new IllegalArgumentException("Illegal scope.");
}
}
/**
* Returns an enumeration containing all the parameters defined in the
* scope specified by the parameter.
*
* @param pScope The scope to return the names of all the parameters
* defined within.
* @return An {@code Enumeration} containing all the names for all the
* parameters defined in the scope passed in as a parameter.
*/
public Enumeration getInitParameterNames(int pScope) {
switch (pScope) {
case PageContext.PAGE_SCOPE:
return getServletConfig().getInitParameterNames();
case PageContext.APPLICATION_SCOPE:
return getServletContext().getInitParameterNames();
default:
throw new IllegalArgumentException("Illegal scope");
}
}
/**
* Returns the servlet config associated with the current JSP page request.
*
* @return The {@code ServletConfig} associated with the current
* request.
*/
public ServletConfig getServletConfig() {
return pageContext.getServletConfig();
}
/**
* Gets the context path associated with the current JSP page request.
* If the request is not a HttpServletRequest, this method will
* return "/".
*
* @return a path relative to the current context's root, or
* {@code "/"} if this is not a HTTP request.
*/
public String getContextPath() {
ServletRequest request = pageContext.getRequest();
if (request instanceof HttpServletRequest) {
return ((HttpServletRequest) request).getContextPath();
}
return "/";
}
/**
* Gets the resource associated with the given relative path for the
* current JSP page request.
* The path may be absolute, or relative to the current context root.
*
* @param pPath the path
*
* @return a path relative to the current context root
*/
public InputStream getResourceAsStream(String pPath) {
// throws MalformedURLException {
String path = pPath;
if (pPath != null && !pPath.startsWith("/")) {
path = getContextPath() + pPath;
}
return pageContext.getServletContext().getResourceAsStream(path);
}
}

View File

@@ -1,163 +1,163 @@
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: ExTag.java,v $
* Revision 1.2 2003/10/06 14:25:05 WMHAKUR
* Code clean-up only.
*
* Revision 1.1 2002/11/18 22:10:27 WMHAKUR
* *** empty log message ***
*
*
*/
package com.twelvemonkeys.servlet.jsp.taglib;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.Tag;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
/**
* This interface contains a lot of helper methods for simplifying common
* taglib related tasks.
*
* @author Harald Kuhr
*
* @version $Id: jsp/taglib/ExTag.java#1 $
*/
public interface ExTag extends Tag {
/**
* writeHtml ensures that the text being outputted appears as it was
* entered. This prevents users from hacking the system by entering
* html or jsp code into an entry form where that value will be displayed
* later in the site.
*
* @param pOut The JspWriter to write the output to.
* @param pHtml The original html to filter and output to the user.
* @throws IOException If the user clicks Stop in the browser, or their
* browser crashes, then the JspWriter will throw an IOException when
* the jsp tries to write to it.
*/
public void writeHtml(JspWriter pOut, String pHtml) throws IOException;
/**
* Log a message to the servlet context.
*
* @param pMsg The error message to log.
*/
public void log(String pMsg);
/**
* Logs a message to the servlet context and include the exception that is
* passed in as the second parameter.
*
* @param pMsg The error message to log.
* @param pException The exception that caused this error message to be
* logged.
*/
public void log(String pMsg, Throwable pException);
/**
* Retrieves the ServletContext object associated with the current
* PageContext object.
*
* @return The ServletContext object associated with the current
* PageContext object.
*/
public ServletContext getServletContext();
/**
* Returns the initialisation parameter from the {@code
* PageContext.APPLICATION_SCOPE} scope. These initialisation
* parameters are defined in the {@code web.xml} configuration file.
*
* @param pName The name of the initialisation parameter to return the
* value for.
* @return The value for the parameter whose name was passed in as a
* parameter. If the parameter does not exist, then {@code null}
* will be returned.
*/
public String getInitParameter(String pName);
/**
* Returns an Enumeration containing all the names for all the
* initialisation parametes defined in the {@code
* PageContext.APPLICATION_SCOPE} scope.
*
* @return An {@code Enumeration} containing all the names for all the
* initialisation parameters.
*/
public Enumeration getInitParameterNames();
/**
* Returns the initialisation parameter from the scope specified with the
* name specified.
*
* @param pName The name of the initialisation parameter to return the
* value for.
* @param pScope The scope to search for the initialisation parameter
* within.
* @return The value of the parameter found. If no parameter with the
* name specified is found in the scope specified, then {@code null
* } is returned.
*/
public String getInitParameter(String pName, int pScope);
/**
* Returns an enumeration containing all the parameters defined in the
* scope specified by the parameter.
*
* @param pScope The scope to return the names of all the parameters
* defined within.
* @return An {@code Enumeration} containing all the names for all the
* parameters defined in the scope passed in as a parameter.
*/
public Enumeration getInitParameterNames(int pScope);
/**
* Returns the servlet config associated with the current JSP page request.
*
* @return The {@code ServletConfig} associated with the current
* request.
*/
public ServletConfig getServletConfig();
/**
* Gets the context path associated with the current JSP page request.
*
* @return a path relative to the current context's root.
*/
public String getContextPath();
/**
* Gets the resource associated with the given relative path for the
* current JSP page request.
* The path may be absolute, or relative to the current context root.
*
* @param pPath the path
*
* @return a path relative to the current context root
*/
public InputStream getResourceAsStream(String pPath);
}
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: ExTag.java,v $
* Revision 1.2 2003/10/06 14:25:05 WMHAKUR
* Code clean-up only.
*
* Revision 1.1 2002/11/18 22:10:27 WMHAKUR
* *** empty log message ***
*
*
*/
package com.twelvemonkeys.servlet.jsp.taglib;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.Tag;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
/**
* This interface contains a lot of helper methods for simplifying common
* taglib related tasks.
*
* @author Harald Kuhr
*
* @version $Id: jsp/taglib/ExTag.java#1 $
*/
public interface ExTag extends Tag {
/**
* writeHtml ensures that the text being outputted appears as it was
* entered. This prevents users from hacking the system by entering
* html or jsp code into an entry form where that value will be displayed
* later in the site.
*
* @param pOut The JspWriter to write the output to.
* @param pHtml The original html to filter and output to the user.
* @throws IOException If the user clicks Stop in the browser, or their
* browser crashes, then the JspWriter will throw an IOException when
* the jsp tries to write to it.
*/
public void writeHtml(JspWriter pOut, String pHtml) throws IOException;
/**
* Log a message to the servlet context.
*
* @param pMsg The error message to log.
*/
public void log(String pMsg);
/**
* Logs a message to the servlet context and include the exception that is
* passed in as the second parameter.
*
* @param pMsg The error message to log.
* @param pException The exception that caused this error message to be
* logged.
*/
public void log(String pMsg, Throwable pException);
/**
* Retrieves the ServletContext object associated with the current
* PageContext object.
*
* @return The ServletContext object associated with the current
* PageContext object.
*/
public ServletContext getServletContext();
/**
* Returns the initialisation parameter from the {@code
* PageContext.APPLICATION_SCOPE} scope. These initialisation
* parameters are defined in the {@code web.xml} configuration file.
*
* @param pName The name of the initialisation parameter to return the
* value for.
* @return The value for the parameter whose name was passed in as a
* parameter. If the parameter does not exist, then {@code null}
* will be returned.
*/
public String getInitParameter(String pName);
/**
* Returns an Enumeration containing all the names for all the
* initialisation parametes defined in the {@code
* PageContext.APPLICATION_SCOPE} scope.
*
* @return An {@code Enumeration} containing all the names for all the
* initialisation parameters.
*/
public Enumeration getInitParameterNames();
/**
* Returns the initialisation parameter from the scope specified with the
* name specified.
*
* @param pName The name of the initialisation parameter to return the
* value for.
* @param pScope The scope to search for the initialisation parameter
* within.
* @return The value of the parameter found. If no parameter with the
* name specified is found in the scope specified, then {@code null
* } is returned.
*/
public String getInitParameter(String pName, int pScope);
/**
* Returns an enumeration containing all the parameters defined in the
* scope specified by the parameter.
*
* @param pScope The scope to return the names of all the parameters
* defined within.
* @return An {@code Enumeration} containing all the names for all the
* parameters defined in the scope passed in as a parameter.
*/
public Enumeration getInitParameterNames(int pScope);
/**
* Returns the servlet config associated with the current JSP page request.
*
* @return The {@code ServletConfig} associated with the current
* request.
*/
public ServletConfig getServletConfig();
/**
* Gets the context path associated with the current JSP page request.
*
* @return a path relative to the current context's root.
*/
public String getContextPath();
/**
* Gets the resource associated with the given relative path for the
* current JSP page request.
* The path may be absolute, or relative to the current context root.
*
* @param pPath the path
*
* @return a path relative to the current context root
*/
public InputStream getResourceAsStream(String pPath);
}

View File

@@ -1,293 +1,293 @@
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: ExTagSupport.java,v $
* Revision 1.3 2003/10/06 14:25:11 WMHAKUR
* Code clean-up only.
*
* Revision 1.2 2002/11/18 22:10:27 WMHAKUR
* *** empty log message ***
*
*
*/
package com.twelvemonkeys.servlet.jsp.taglib;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.StringTokenizer;
/**
* This is the class that should be extended by all jsp pages that don't use
* their body. It contains a lot of helper methods for simplifying common
* tasks.
*
* @author Thomas Purcell (CSC Australia)
* @author Harald Kuhr
*
* @version $Id: jsp/taglib/ExTagSupport.java#1 $
*/
public class ExTagSupport extends TagSupport implements ExTag {
/**
* writeHtml ensures that the text being outputted appears as it was
* entered. This prevents users from hacking the system by entering
* html or jsp code into an entry form where that value will be displayed
* later in the site.
*
* @param pOut The JspWriter to write the output to.
* @param pHtml The original html to filter and output to the user.
* @throws IOException If the user clicks Stop in the browser, or their
* browser crashes, then the JspWriter will throw an IOException when
* the jsp tries to write to it.
*/
public void writeHtml(JspWriter pOut, String pHtml) throws IOException {
StringTokenizer parser = new StringTokenizer(pHtml, "<>&", true);
while (parser.hasMoreTokens()) {
String token = parser.nextToken();
if (token.equals("<")) {
pOut.print("&lt;");
}
else if (token.equals(">")) {
pOut.print("&gt;");
}
else if (token.equals("&")) {
pOut.print("&amp;");
}
else {
pOut.print(token);
}
}
}
/**
* Log a message to the servlet context.
*
* @param pMsg The error message to log.
*/
public void log(String pMsg) {
getServletContext().log(pMsg);
}
/**
* Log a message to the servlet context and include the exception that is
* passed in as the second parameter.
*
* @param pMsg The error message to log.
* @param pException The exception that caused this error message to be
* logged.
*/
public void log(String pMsg, Throwable pException) {
getServletContext().log(pMsg, pException);
}
/**
* Retrieves the ServletContext object associated with the current
* PageContext object.
*
* @return The ServletContext object associated with the current
* PageContext object.
*/
public ServletContext getServletContext() {
return pageContext.getServletContext();
}
/**
* Called when the tag has finished running. Any clean up that needs
* to be done between calls to this tag but within the same JSP page is
* called in the {@code clearServiceState()} method call.
*
* @exception JspException
*/
public int doEndTag() throws JspException {
clearServiceState();
return super.doEndTag();
}
/**
* Called when a tag's role in the current JSP page is finished. After
* the {@code clearProperties()} method is called, the custom tag
* should be in an identical state as when it was first created. The
* {@code clearServiceState()} method is called here just in case an
* exception was thrown in the custom tag. If an exception was thrown,
* then the {@code doEndTag()} method will not have been called and
* the tag might not have been cleaned up properly.
*/
public void release() {
clearServiceState();
clearProperties();
super.release();
}
/**
* The default implementation for the {@code clearProperties()}. Not
* all tags will need to overload this method call. By implementing it
* here, all classes that extend this object are able to call {@code
* super.clearProperties()}. So, if the class extends a different
* tag, or this one, the parent method should always be called. This
* method will be called when the tag is to be released. That is, the
* tag has finished for the current page and should be returned to it's
* initial state.
*/
protected void clearProperties() {
}
/**
* The default implementation for the {@code clearServiceState()}.
* Not all tags will need to overload this method call. By implementing it
* here, all classes that extend this object are able to call {@code
* super.clearServiceState()}. So, if the class extends a different
* tag, or this one, the parent method should always be called. This
* method will be called when the tag has finished it's current tag
* within the page, but may be called upon again in this same JSP page.
*/
protected void clearServiceState() {
}
/**
* Returns the initialisation parameter from the {@code
* PageContext.APPLICATION_SCOPE} scope. These initialisation
* parameters are defined in the {@code web.xml} configuration file.
*
* @param pName The name of the initialisation parameter to return the
* value for.
* @return The value for the parameter whose name was passed in as a
* parameter. If the parameter does not exist, then {@code null}
* will be returned.
*/
public String getInitParameter(String pName) {
return getInitParameter(pName, PageContext.APPLICATION_SCOPE);
}
/**
* Returns an Enumeration containing all the names for all the
* initialisation parametes defined in the {@code
* PageContext.APPLICATION_SCOPE} scope.
*
* @return An {@code Enumeration} containing all the names for all the
* initialisation parameters.
*/
public Enumeration getInitParameterNames() {
return getInitParameterNames(PageContext.APPLICATION_SCOPE);
}
/**
* Returns the initialisation parameter from the scope specified with the
* name specified.
*
* @param pName The name of the initialisation parameter to return the
* value for.
* @param pScope The scope to search for the initialisation parameter
* within.
* @return The value of the parameter found. If no parameter with the
* name specified is found in the scope specified, then {@code null
* } is returned.
*/
public String getInitParameter(String pName, int pScope) {
switch (pScope) {
case PageContext.PAGE_SCOPE:
return getServletConfig().getInitParameter(pName);
case PageContext.APPLICATION_SCOPE:
return getServletContext().getInitParameter(pName);
default:
throw new IllegalArgumentException("Illegal scope.");
}
}
/**
* Returns an enumeration containing all the parameters defined in the
* scope specified by the parameter.
*
* @param pScope The scope to return the names of all the parameters
* defined within.
* @return An {@code Enumeration} containing all the names for all the
* parameters defined in the scope passed in as a parameter.
*/
public Enumeration getInitParameterNames(int pScope) {
switch (pScope) {
case PageContext.PAGE_SCOPE:
return getServletConfig().getInitParameterNames();
case PageContext.APPLICATION_SCOPE:
return getServletContext().getInitParameterNames();
default:
throw new IllegalArgumentException("Illegal scope");
}
}
/**
* Returns the servlet config associated with the current JSP page request.
*
* @return The {@code ServletConfig} associated with the current
* request.
*/
public ServletConfig getServletConfig() {
return pageContext.getServletConfig();
}
/**
* Gets the context path associated with the current JSP page request.
* If the request is not a HttpServletRequest, this method will
* return "/".
*
* @return a path relative to the current context's root, or
* {@code "/"} if this is not a HTTP request.
*/
public String getContextPath() {
ServletRequest request = pageContext.getRequest();
if (request instanceof HttpServletRequest) {
return ((HttpServletRequest) request).getContextPath();
}
return "/";
}
/**
* Gets the resource associated with the given relative path for the
* current JSP page request.
* The path may be absolute, or relative to the current context root.
*
* @param pPath the path
*
* @return a path relative to the current context root
*/
public InputStream getResourceAsStream(String pPath) {
//throws MalformedURLException {
String path = pPath;
if (pPath != null && !pPath.startsWith("/")) {
path = getContextPath() + pPath;
}
return pageContext.getServletContext().getResourceAsStream(path);
}
}
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: ExTagSupport.java,v $
* Revision 1.3 2003/10/06 14:25:11 WMHAKUR
* Code clean-up only.
*
* Revision 1.2 2002/11/18 22:10:27 WMHAKUR
* *** empty log message ***
*
*
*/
package com.twelvemonkeys.servlet.jsp.taglib;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.StringTokenizer;
/**
* This is the class that should be extended by all jsp pages that don't use
* their body. It contains a lot of helper methods for simplifying common
* tasks.
*
* @author Thomas Purcell (CSC Australia)
* @author Harald Kuhr
*
* @version $Id: jsp/taglib/ExTagSupport.java#1 $
*/
public class ExTagSupport extends TagSupport implements ExTag {
/**
* writeHtml ensures that the text being outputted appears as it was
* entered. This prevents users from hacking the system by entering
* html or jsp code into an entry form where that value will be displayed
* later in the site.
*
* @param pOut The JspWriter to write the output to.
* @param pHtml The original html to filter and output to the user.
* @throws IOException If the user clicks Stop in the browser, or their
* browser crashes, then the JspWriter will throw an IOException when
* the jsp tries to write to it.
*/
public void writeHtml(JspWriter pOut, String pHtml) throws IOException {
StringTokenizer parser = new StringTokenizer(pHtml, "<>&", true);
while (parser.hasMoreTokens()) {
String token = parser.nextToken();
if (token.equals("<")) {
pOut.print("&lt;");
}
else if (token.equals(">")) {
pOut.print("&gt;");
}
else if (token.equals("&")) {
pOut.print("&amp;");
}
else {
pOut.print(token);
}
}
}
/**
* Log a message to the servlet context.
*
* @param pMsg The error message to log.
*/
public void log(String pMsg) {
getServletContext().log(pMsg);
}
/**
* Log a message to the servlet context and include the exception that is
* passed in as the second parameter.
*
* @param pMsg The error message to log.
* @param pException The exception that caused this error message to be
* logged.
*/
public void log(String pMsg, Throwable pException) {
getServletContext().log(pMsg, pException);
}
/**
* Retrieves the ServletContext object associated with the current
* PageContext object.
*
* @return The ServletContext object associated with the current
* PageContext object.
*/
public ServletContext getServletContext() {
return pageContext.getServletContext();
}
/**
* Called when the tag has finished running. Any clean up that needs
* to be done between calls to this tag but within the same JSP page is
* called in the {@code clearServiceState()} method call.
*
* @exception JspException
*/
public int doEndTag() throws JspException {
clearServiceState();
return super.doEndTag();
}
/**
* Called when a tag's role in the current JSP page is finished. After
* the {@code clearProperties()} method is called, the custom tag
* should be in an identical state as when it was first created. The
* {@code clearServiceState()} method is called here just in case an
* exception was thrown in the custom tag. If an exception was thrown,
* then the {@code doEndTag()} method will not have been called and
* the tag might not have been cleaned up properly.
*/
public void release() {
clearServiceState();
clearProperties();
super.release();
}
/**
* The default implementation for the {@code clearProperties()}. Not
* all tags will need to overload this method call. By implementing it
* here, all classes that extend this object are able to call {@code
* super.clearProperties()}. So, if the class extends a different
* tag, or this one, the parent method should always be called. This
* method will be called when the tag is to be released. That is, the
* tag has finished for the current page and should be returned to it's
* initial state.
*/
protected void clearProperties() {
}
/**
* The default implementation for the {@code clearServiceState()}.
* Not all tags will need to overload this method call. By implementing it
* here, all classes that extend this object are able to call {@code
* super.clearServiceState()}. So, if the class extends a different
* tag, or this one, the parent method should always be called. This
* method will be called when the tag has finished it's current tag
* within the page, but may be called upon again in this same JSP page.
*/
protected void clearServiceState() {
}
/**
* Returns the initialisation parameter from the {@code
* PageContext.APPLICATION_SCOPE} scope. These initialisation
* parameters are defined in the {@code web.xml} configuration file.
*
* @param pName The name of the initialisation parameter to return the
* value for.
* @return The value for the parameter whose name was passed in as a
* parameter. If the parameter does not exist, then {@code null}
* will be returned.
*/
public String getInitParameter(String pName) {
return getInitParameter(pName, PageContext.APPLICATION_SCOPE);
}
/**
* Returns an Enumeration containing all the names for all the
* initialisation parametes defined in the {@code
* PageContext.APPLICATION_SCOPE} scope.
*
* @return An {@code Enumeration} containing all the names for all the
* initialisation parameters.
*/
public Enumeration getInitParameterNames() {
return getInitParameterNames(PageContext.APPLICATION_SCOPE);
}
/**
* Returns the initialisation parameter from the scope specified with the
* name specified.
*
* @param pName The name of the initialisation parameter to return the
* value for.
* @param pScope The scope to search for the initialisation parameter
* within.
* @return The value of the parameter found. If no parameter with the
* name specified is found in the scope specified, then {@code null
* } is returned.
*/
public String getInitParameter(String pName, int pScope) {
switch (pScope) {
case PageContext.PAGE_SCOPE:
return getServletConfig().getInitParameter(pName);
case PageContext.APPLICATION_SCOPE:
return getServletContext().getInitParameter(pName);
default:
throw new IllegalArgumentException("Illegal scope.");
}
}
/**
* Returns an enumeration containing all the parameters defined in the
* scope specified by the parameter.
*
* @param pScope The scope to return the names of all the parameters
* defined within.
* @return An {@code Enumeration} containing all the names for all the
* parameters defined in the scope passed in as a parameter.
*/
public Enumeration getInitParameterNames(int pScope) {
switch (pScope) {
case PageContext.PAGE_SCOPE:
return getServletConfig().getInitParameterNames();
case PageContext.APPLICATION_SCOPE:
return getServletContext().getInitParameterNames();
default:
throw new IllegalArgumentException("Illegal scope");
}
}
/**
* Returns the servlet config associated with the current JSP page request.
*
* @return The {@code ServletConfig} associated with the current
* request.
*/
public ServletConfig getServletConfig() {
return pageContext.getServletConfig();
}
/**
* Gets the context path associated with the current JSP page request.
* If the request is not a HttpServletRequest, this method will
* return "/".
*
* @return a path relative to the current context's root, or
* {@code "/"} if this is not a HTTP request.
*/
public String getContextPath() {
ServletRequest request = pageContext.getRequest();
if (request instanceof HttpServletRequest) {
return ((HttpServletRequest) request).getContextPath();
}
return "/";
}
/**
* Gets the resource associated with the given relative path for the
* current JSP page request.
* The path may be absolute, or relative to the current context root.
*
* @param pPath the path
*
* @return a path relative to the current context root
*/
public InputStream getResourceAsStream(String pPath) {
//throws MalformedURLException {
String path = pPath;
if (pPath != null && !pPath.startsWith("/")) {
path = getContextPath() + pPath;
}
return pageContext.getServletContext().getResourceAsStream(path);
}
}

View File

@@ -1,20 +1,20 @@
package com.twelvemonkeys.servlet.jsp.taglib;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
/**
* TagExtraInfo for LastModifiedTag
*
* @author Harald Kuhr
*
* @version 1.1
*/
public class LastModifiedTEI extends TagExtraInfo {
public VariableInfo[] getVariableInfo(TagData pData) {
return new VariableInfo[]{
new VariableInfo("lastModified", "java.lang.String", true, VariableInfo.NESTED),
};
}
}
package com.twelvemonkeys.servlet.jsp.taglib;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
/**
* TagExtraInfo for LastModifiedTag
*
* @author Harald Kuhr
*
* @version 1.1
*/
public class LastModifiedTEI extends TagExtraInfo {
public VariableInfo[] getVariableInfo(TagData pData) {
return new VariableInfo[]{
new VariableInfo("lastModified", "java.lang.String", true, VariableInfo.NESTED),
};
}
}

View File

@@ -1,87 +1,87 @@
package com.twelvemonkeys.servlet.jsp.taglib;
import java.io.IOException;
import javax.servlet.jsp.JspException;
/**
* This tag truncates all consecutive whitespace in sequence inside its body,
* to one whitespace character. The first whitespace character in the sequence
* will be left untouched (except for CR/LF, which will always leave a LF).
*
* @author Harald Kuhr
*
* @version 1.0
*/
public class TrimWhiteSpaceTag extends ExBodyTagSupport {
/**
* doStartTag implementation, simply returns
* {@code BodyTag.EVAL_BODY_BUFFERED}.
*
* @return {@code BodyTag.EVAL_BODY_BUFFERED}
*/
public int doStartTag() throws JspException {
return EVAL_BODY_BUFFERED;
}
/**
* doEndTag implementation, truncates all whitespace.
*
* @return {@code super.doEndTag()}
*/
public int doEndTag() throws JspException {
// Trim
String trimmed = truncateWS(bodyContent.getString());
try {
// Print trimmed content
//pageContext.getOut().print("<!--TWS-->\n");
pageContext.getOut().print(trimmed);
//pageContext.getOut().print("\n<!--/TWS-->");
}
catch (IOException ioe) {
throw new JspException(ioe);
}
return super.doEndTag();
}
/**
* Truncates whitespace from the given string.
*
* @todo Candidate for StringUtil?
*/
private static String truncateWS(String pStr) {
char[] chars = pStr.toCharArray();
int count = 0;
boolean lastWasWS = true; // Avoids leading WS
for (int i = 0; i < chars.length; i++) {
if (!Character.isWhitespace(chars[i])) {
// if char is not WS, just store
chars[count++] = chars[i];
lastWasWS = false;
}
else {
// else, if char is WS, store first, skip the rest
if (!lastWasWS) {
if (chars[i] == 0x0d) {
chars[count++] = 0x0a; //Always new line
}
else {
chars[count++] = chars[i];
}
}
lastWasWS = true;
}
}
// Return the trucated string
return new String(chars, 0, count);
}
}
package com.twelvemonkeys.servlet.jsp.taglib;
import java.io.IOException;
import javax.servlet.jsp.JspException;
/**
* This tag truncates all consecutive whitespace in sequence inside its body,
* to one whitespace character. The first whitespace character in the sequence
* will be left untouched (except for CR/LF, which will always leave a LF).
*
* @author Harald Kuhr
*
* @version 1.0
*/
public class TrimWhiteSpaceTag extends ExBodyTagSupport {
/**
* doStartTag implementation, simply returns
* {@code BodyTag.EVAL_BODY_BUFFERED}.
*
* @return {@code BodyTag.EVAL_BODY_BUFFERED}
*/
public int doStartTag() throws JspException {
return EVAL_BODY_BUFFERED;
}
/**
* doEndTag implementation, truncates all whitespace.
*
* @return {@code super.doEndTag()}
*/
public int doEndTag() throws JspException {
// Trim
String trimmed = truncateWS(bodyContent.getString());
try {
// Print trimmed content
//pageContext.getOut().print("<!--TWS-->\n");
pageContext.getOut().print(trimmed);
//pageContext.getOut().print("\n<!--/TWS-->");
}
catch (IOException ioe) {
throw new JspException(ioe);
}
return super.doEndTag();
}
/**
* Truncates whitespace from the given string.
*
* @todo Candidate for StringUtil?
*/
private static String truncateWS(String pStr) {
char[] chars = pStr.toCharArray();
int count = 0;
boolean lastWasWS = true; // Avoids leading WS
for (int i = 0; i < chars.length; i++) {
if (!Character.isWhitespace(chars[i])) {
// if char is not WS, just store
chars[count++] = chars[i];
lastWasWS = false;
}
else {
// else, if char is WS, store first, skip the rest
if (!lastWasWS) {
if (chars[i] == 0x0d) {
chars[count++] = 0x0a; //Always new line
}
else {
chars[count++] = chars[i];
}
}
lastWasWS = true;
}
}
// Return the trucated string
return new String(chars, 0, count);
}
}

View File

@@ -1,158 +1,158 @@
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: XMLTransformTag.java,v $
* Revision 1.2 2003/10/06 14:25:43 WMHAKUR
* Code clean-up only.
*
* Revision 1.1 2002/11/19 10:50:41 WMHAKUR
* *** empty log message ***
*
*/
package com.twelvemonkeys.servlet.jsp.taglib;
import java.io.*;
import java.net.*;
import javax.servlet.jsp.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
/**
* This tag performs XSL Transformations (XSLT) on a given XML document or its
* body content.
*
* @author Harald Kuhr
*
* @version $Id: jsp/taglib/XMLTransformTag.java#1 $
*/
public class XMLTransformTag extends ExBodyTagSupport {
private String mDocumentURI = null;
private String mStylesheetURI = null;
/**
* Sets the document attribute for this tag.
*/
public void setDocumentURI(String pDocumentURI) {
mDocumentURI = pDocumentURI;
}
/**
* Sets the stylesheet attribute for this tag.
*/
public void setStylesheetURI(String pStylesheetURI) {
mStylesheetURI = pStylesheetURI;
}
/**
* doStartTag implementation, that performs XML Transformation on the
* given document, if any.
* If the documentURI attribute is set, then the transformation is
* performed on the document at that location, and
* {@code Tag.SKIP_BODY} is returned.
* Otherwise, this method simply returns
* {@code BodyTag.EVAL_BODY_BUFFERED} and leaves the transformation to
* the doEndTag.
*
* @return {@code Tag.SKIP_BODY} if {@code documentURI} is not
* {@code null}, otherwise
* {@code BodyTag.EVAL_BODY_BUFFERED}.
*
* @todo Is it really a good idea to allow "inline" XML in a JSP?
*/
public int doStartTag() throws JspException {
//log("XML: " + mDocumentURI + " XSL: " + mStylesheetURI);
if (mDocumentURI != null) {
// If document given, transform and skip body...
try {
transform(getSource(mDocumentURI));
}
catch (MalformedURLException murle) {
throw new JspException(murle.getMessage(), murle);
}
catch (IOException ioe) {
throw new JspException(ioe.getMessage(), ioe);
}
return SKIP_BODY;
}
// ...else process the body
return EVAL_BODY_BUFFERED;
}
/**
* doEndTag implementation, that will perform XML Transformation on the
* body content.
*
* @return super.doEndTag()
*/
public int doEndTag() throws JspException {
// Get body content (trim is CRUCIAL, as some XML parsers are picky...)
String body = bodyContent.getString().trim();
// Do transformation
transform(new StreamSource(new ByteArrayInputStream(body.getBytes())));
return super.doEndTag();
}
/**
* Performs the transformation and writes the result to the JSP writer.
*
* @param in the source document to transform.
*/
public void transform(Source pIn) throws JspException {
try {
// Create transformer
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(getSource(mStylesheetURI));
// Store temporary output in a bytearray, as the transformer will
// usually try to flush the stream (illegal operation from a custom
// tag).
ByteArrayOutputStream os = new ByteArrayOutputStream();
StreamResult out = new StreamResult(os);
// Perform the transformation
transformer.transform(pIn, out);
// Write the result back to the JSP writer
pageContext.getOut().print(os.toString());
}
catch (MalformedURLException murle) {
throw new JspException(murle.getMessage(), murle);
}
catch (IOException ioe) {
throw new JspException(ioe.getMessage(), ioe);
}
catch (TransformerException te) {
throw new JspException("XSLT Trandformation failed: " + te.getMessage(), te);
}
}
/**
* Returns a StreamSource object, for the given URI
*/
private StreamSource getSource(String pURI)
throws IOException, MalformedURLException {
if (pURI != null && pURI.indexOf("://") < 0) {
// If local, get as stream
return new StreamSource(getResourceAsStream(pURI));
}
// ...else, create from URI string
return new StreamSource(pURI);
}
}
/*
* Copyright (c) 2002 TwelveMonkeys.
* All rights reserved.
*
* $Log: XMLTransformTag.java,v $
* Revision 1.2 2003/10/06 14:25:43 WMHAKUR
* Code clean-up only.
*
* Revision 1.1 2002/11/19 10:50:41 WMHAKUR
* *** empty log message ***
*
*/
package com.twelvemonkeys.servlet.jsp.taglib;
import java.io.*;
import java.net.*;
import javax.servlet.jsp.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
/**
* This tag performs XSL Transformations (XSLT) on a given XML document or its
* body content.
*
* @author Harald Kuhr
*
* @version $Id: jsp/taglib/XMLTransformTag.java#1 $
*/
public class XMLTransformTag extends ExBodyTagSupport {
private String mDocumentURI = null;
private String mStylesheetURI = null;
/**
* Sets the document attribute for this tag.
*/
public void setDocumentURI(String pDocumentURI) {
mDocumentURI = pDocumentURI;
}
/**
* Sets the stylesheet attribute for this tag.
*/
public void setStylesheetURI(String pStylesheetURI) {
mStylesheetURI = pStylesheetURI;
}
/**
* doStartTag implementation, that performs XML Transformation on the
* given document, if any.
* If the documentURI attribute is set, then the transformation is
* performed on the document at that location, and
* {@code Tag.SKIP_BODY} is returned.
* Otherwise, this method simply returns
* {@code BodyTag.EVAL_BODY_BUFFERED} and leaves the transformation to
* the doEndTag.
*
* @return {@code Tag.SKIP_BODY} if {@code documentURI} is not
* {@code null}, otherwise
* {@code BodyTag.EVAL_BODY_BUFFERED}.
*
* @todo Is it really a good idea to allow "inline" XML in a JSP?
*/
public int doStartTag() throws JspException {
//log("XML: " + mDocumentURI + " XSL: " + mStylesheetURI);
if (mDocumentURI != null) {
// If document given, transform and skip body...
try {
transform(getSource(mDocumentURI));
}
catch (MalformedURLException murle) {
throw new JspException(murle.getMessage(), murle);
}
catch (IOException ioe) {
throw new JspException(ioe.getMessage(), ioe);
}
return SKIP_BODY;
}
// ...else process the body
return EVAL_BODY_BUFFERED;
}
/**
* doEndTag implementation, that will perform XML Transformation on the
* body content.
*
* @return super.doEndTag()
*/
public int doEndTag() throws JspException {
// Get body content (trim is CRUCIAL, as some XML parsers are picky...)
String body = bodyContent.getString().trim();
// Do transformation
transform(new StreamSource(new ByteArrayInputStream(body.getBytes())));
return super.doEndTag();
}
/**
* Performs the transformation and writes the result to the JSP writer.
*
* @param in the source document to transform.
*/
public void transform(Source pIn) throws JspException {
try {
// Create transformer
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(getSource(mStylesheetURI));
// Store temporary output in a bytearray, as the transformer will
// usually try to flush the stream (illegal operation from a custom
// tag).
ByteArrayOutputStream os = new ByteArrayOutputStream();
StreamResult out = new StreamResult(os);
// Perform the transformation
transformer.transform(pIn, out);
// Write the result back to the JSP writer
pageContext.getOut().print(os.toString());
}
catch (MalformedURLException murle) {
throw new JspException(murle.getMessage(), murle);
}
catch (IOException ioe) {
throw new JspException(ioe.getMessage(), ioe);
}
catch (TransformerException te) {
throw new JspException("XSLT Trandformation failed: " + te.getMessage(), te);
}
}
/**
* Returns a StreamSource object, for the given URI
*/
private StreamSource getSource(String pURI)
throws IOException, MalformedURLException {
if (pURI != null && pURI.indexOf("://") < 0) {
// If local, get as stream
return new StreamSource(getResourceAsStream(pURI));
}
// ...else, create from URI string
return new StreamSource(pURI);
}
}

View File

@@ -1,138 +1,138 @@
/****************************************************
* *
* (c) 2000-2003 TwelveMonkeys *
* All rights reserved *
* http://www.twelvemonkeys.no *
* *
* $RCSfile: ConditionalTagBase.java,v $
* @version $Revision: #1 $
* $Date: 2008/05/05 $
* *
* @author Last modified by: $Author: haku $
* *
****************************************************/
/*
* Produced (p) 2002 TwelveMonkeys
* Address : Svovelstikka 1, Box 6432 Etterstad, 0605 Oslo, Norway.
* Phone : +47 22 57 70 00
* Fax : +47 22 57 70 70
*/
package com.twelvemonkeys.servlet.jsp.taglib.logic;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
/**
* <p>An abstract base class for tags with some kind of conditional presentation of the tag body.</p>
*
* @version 1.0
* @author <a href="mailto:eirik.torske@twelvemonkeys.no">Eirik Torske</a>
*/
public abstract class ConditionalTagBase extends TagSupport {
// Members
protected String objectName;
protected String objectValue;
// Properties
/**
* Method getName
*
*
* @return
*
*/
public String getName() {
return objectName;
}
/**
* Method setName
*
*
* @param pObjectName
*
*/
public void setName(String pObjectName) {
this.objectName = pObjectName;
}
/**
* Method getValue
*
*
* @return
*
*/
public String getValue() {
return objectValue;
}
/**
* Method setValue
*
*
* @param pObjectValue
*
*/
public void setValue(String pObjectValue) {
this.objectValue = pObjectValue;
}
/**
* <p>Perform the test required for this particular tag, and either evaluate or skip the body of this tag.</p>
*
*
* @return
* @exception JspException if a JSP exception occurs.
*/
public int doStartTag() throws JspException {
if (condition()) {
return (EVAL_BODY_INCLUDE);
} else {
return (SKIP_BODY);
}
}
/**
* <p>Evaluate the remainder of the current page as normal.</p>
*
*
* @return
* @exception JspException if a JSP exception occurs.
*/
public int doEndTag() throws JspException {
return (EVAL_PAGE);
}
/**
* <p>Release all allocated resources.</p>
*/
public void release() {
super.release();
objectName = null;
objectValue = null;
}
/**
* <p>The condition that must be met in order to display the body of this tag.</p>
*
* @exception JspException if a JSP exception occurs.
* @return {@code true} if and only if all conditions are met.
*/
protected abstract boolean condition() throws JspException;
}
/*--- Formatted in Sun Java Convention Style on ma, des 1, '03 ---*/
/*------ Formatted by Jindent 3.23 Basic 1.0 --- http://www.jindent.de ------*/
/****************************************************
* *
* (c) 2000-2003 TwelveMonkeys *
* All rights reserved *
* http://www.twelvemonkeys.no *
* *
* $RCSfile: ConditionalTagBase.java,v $
* @version $Revision: #1 $
* $Date: 2008/05/05 $
* *
* @author Last modified by: $Author: haku $
* *
****************************************************/
/*
* Produced (p) 2002 TwelveMonkeys
* Address : Svovelstikka 1, Box 6432 Etterstad, 0605 Oslo, Norway.
* Phone : +47 22 57 70 00
* Fax : +47 22 57 70 70
*/
package com.twelvemonkeys.servlet.jsp.taglib.logic;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
/**
* <p>An abstract base class for tags with some kind of conditional presentation of the tag body.</p>
*
* @version 1.0
* @author <a href="mailto:eirik.torske@twelvemonkeys.no">Eirik Torske</a>
*/
public abstract class ConditionalTagBase extends TagSupport {
// Members
protected String objectName;
protected String objectValue;
// Properties
/**
* Method getName
*
*
* @return
*
*/
public String getName() {
return objectName;
}
/**
* Method setName
*
*
* @param pObjectName
*
*/
public void setName(String pObjectName) {
this.objectName = pObjectName;
}
/**
* Method getValue
*
*
* @return
*
*/
public String getValue() {
return objectValue;
}
/**
* Method setValue
*
*
* @param pObjectValue
*
*/
public void setValue(String pObjectValue) {
this.objectValue = pObjectValue;
}
/**
* <p>Perform the test required for this particular tag, and either evaluate or skip the body of this tag.</p>
*
*
* @return
* @exception JspException if a JSP exception occurs.
*/
public int doStartTag() throws JspException {
if (condition()) {
return (EVAL_BODY_INCLUDE);
} else {
return (SKIP_BODY);
}
}
/**
* <p>Evaluate the remainder of the current page as normal.</p>
*
*
* @return
* @exception JspException if a JSP exception occurs.
*/
public int doEndTag() throws JspException {
return (EVAL_PAGE);
}
/**
* <p>Release all allocated resources.</p>
*/
public void release() {
super.release();
objectName = null;
objectValue = null;
}
/**
* <p>The condition that must be met in order to display the body of this tag.</p>
*
* @exception JspException if a JSP exception occurs.
* @return {@code true} if and only if all conditions are met.
*/
protected abstract boolean condition() throws JspException;
}
/*--- Formatted in Sun Java Convention Style on ma, des 1, '03 ---*/
/*------ Formatted by Jindent 3.23 Basic 1.0 --- http://www.jindent.de ------*/

View File

@@ -1,168 +1,168 @@
/*
* Produced (p) 2002 TwelveMonkeys
* Address : Svovelstikka 1, Box 6432 Etterstad, 0605 Oslo, Norway.
* Phone : +47 22 57 70 00
* Fax : +47 22 57 70 70
*/
package com.twelvemonkeys.servlet.jsp.taglib.logic;
import com.twelvemonkeys.lang.StringUtil;
import javax.servlet.http.Cookie;
import javax.servlet.jsp.JspException;
/**
* <p>
* Custom tag for testing equality of an attribute against a given value.
* The attribute types supported so far is:
* <ul>
* <li>{@code java.lang.String} (ver. 1.0)
* <li>{@code javax.servlet.http.Cookie} (ver. 1.0)
* </ul>
* </p>
* See the implemented <a href="#condition">{@code condition}</a> method for details regarding the equality conditions.
*
* <p><hr></p>
*
* <h3>Tag Reference</h3>
* <table border="0" cellspacing="3" cellpadding="3" width="90%">
* <tr bgcolor="#cccccc">
* <td colspan="5" class="body"><b>equal</b></td>
* <td width="17%" align="right" class="body">Availability:&nbsp;1.0</td>
* </tr>
* <tr>
* <td colspan="6" class="body"><p>Tag for testing if an attribute is equal to a given value.</p></td>
* </tr>
* <tr>
* <td width="15%" class="body"><b>Tag Body</b></td>
* <td width="17%" class="body">JSP</td>
* <td width="17%" class="body">&nbsp;</td>
* <td width="17%" class="body">&nbsp;</td>
* <td width="17%" class="body">&nbsp;</td>
* <td width="17%" class="body">&nbsp;</td>
* </tr>
* <tr>
* <td class="body"><b>Restrictions</b></td>
* <td colspan="5" class="body"><p>None</p></td>
* </tr>
*
* <tr>
* <td class="body"><b>Attributes</b></td>
* <td class="body">Name</td>
* <td class="body">Required</td>
* <td colspan="2" class="body">Runtime&nbsp;Expression&nbsp;Evaluation</td>
* <td class="body">Availability</td>
* </tr>
*
* <tr bgcolor="#cccccc">
* <td bgcolor="#ffffff">&nbsp;</td>
* <td class="body_grey"><b>name</b></td>
* <td class="body_grey">&nbsp;Yes</td>
* <td colspan="2" class="body_grey">&nbsp;Yes</td>
* <td class="body_grey">&nbsp;1.0</td>
* </tr>
* <tr>
* <td bgcolor="#ffffff">&nbsp;</td>
* <td colspan="5" class="body"><p>The attribute name</p></td>
* </tr>
*
* <tr bgcolor="#cccccc">
* <td bgcolor="#ffffff">&nbsp;</td>
* <td class="body_grey"><b>value</b></td>
* <td class="body_grey">&nbsp;No</td>
* <td colspan="2" class="body_grey">&nbsp;Yes</td>
* <td class="body_grey">&nbsp;1.0</td>
* </tr>
* <tr>
* <td bgcolor="#ffffff" class="body">&nbsp;</td>
* <td colspan="5" class="body"><p>The value for equality testing</p></td>
* </tr>
*
* <tr>
* <td class="body" valign="top"><b>Variables</b></td>
* <td colspan="5" class="body">None</td>
* </tr>
*
* <tr>
* <td class="body" valign="top"><b>Examples</b></td>
* <td colspan="5" class="body">
* <pre>
*&lt;%@ taglib prefix="twelvemonkeys" uri="twelvemonkeys-logic" %&gt;
*&lt;bean:cookie id="logonUsernameCookie"
* name="&lt;%= com.strutscommand.Constants.LOGON_USERNAME_COOKIE_NAME %&gt;"
* value="no_username_set" /&gt;
*&lt;twelvemonkeys:equal name="logonUsernameCookie" value="no_username_set"&gt;
* &lt;html:text property="username" /&gt;
*&lt;/twelvemonkeys:equal&gt;
* </pre>
* </td>
* </tr>
* </table>
*
* <hr>
*
* @version 1.0
* @author <a href="mailto:eirik.torske@twelvemonkeys.no">Eirik Torske</a>
* @see <a href="NotEqualTag.html">notEqual</a>
*/
public class EqualTag extends ConditionalTagBase {
/**
* <a name="condition"></a>
*
* The conditions that must be met in order to display the body of this tag:
* <ol>
* <li>The attribute name property ({@code name} -> {@code mObjectName}) must not be empty.
* <li>The attribute must exist.
* <li>The attribute must be an instance of one of the supported classes:
* <ul>
* <li>{@code java.lang.String}
* <li>{@code javax.servlet.http.Cookie}
* </ul>
* <li>The value of the attribute must be equal to the object value property ({@code value} -> {@code mObjectValue}).
* </ol>
* <p>
* NB! If the object value property ({@code value} -> {@code mObjectValue}) is empty than {@code true} will be returned.
* </p>
*
* @return {@code true} if and only if all conditions are met.
*/
protected boolean condition() throws JspException {
if (StringUtil.isEmpty(objectName)) {
return false;
}
if (StringUtil.isEmpty(objectValue)) {
return true;
}
Object pageScopedAttribute = pageContext.getAttribute(objectName);
if (pageScopedAttribute == null) {
return false;
}
String pageScopedStringAttribute;
// String
if (pageScopedAttribute instanceof String) {
pageScopedStringAttribute = (String) pageScopedAttribute;
// Cookie
}
else if (pageScopedAttribute instanceof Cookie) {
pageScopedStringAttribute = ((Cookie) pageScopedAttribute).getValue();
// Type not yet supported...
}
else {
return false;
}
return (pageScopedStringAttribute.equals(objectValue));
}
}
/*
* Produced (p) 2002 TwelveMonkeys
* Address : Svovelstikka 1, Box 6432 Etterstad, 0605 Oslo, Norway.
* Phone : +47 22 57 70 00
* Fax : +47 22 57 70 70
*/
package com.twelvemonkeys.servlet.jsp.taglib.logic;
import com.twelvemonkeys.lang.StringUtil;
import javax.servlet.http.Cookie;
import javax.servlet.jsp.JspException;
/**
* <p>
* Custom tag for testing equality of an attribute against a given value.
* The attribute types supported so far is:
* <ul>
* <li>{@code java.lang.String} (ver. 1.0)
* <li>{@code javax.servlet.http.Cookie} (ver. 1.0)
* </ul>
* </p>
* See the implemented <a href="#condition">{@code condition}</a> method for details regarding the equality conditions.
*
* <p><hr></p>
*
* <h3>Tag Reference</h3>
* <table border="0" cellspacing="3" cellpadding="3" width="90%">
* <tr bgcolor="#cccccc">
* <td colspan="5" class="body"><b>equal</b></td>
* <td width="17%" align="right" class="body">Availability:&nbsp;1.0</td>
* </tr>
* <tr>
* <td colspan="6" class="body"><p>Tag for testing if an attribute is equal to a given value.</p></td>
* </tr>
* <tr>
* <td width="15%" class="body"><b>Tag Body</b></td>
* <td width="17%" class="body">JSP</td>
* <td width="17%" class="body">&nbsp;</td>
* <td width="17%" class="body">&nbsp;</td>
* <td width="17%" class="body">&nbsp;</td>
* <td width="17%" class="body">&nbsp;</td>
* </tr>
* <tr>
* <td class="body"><b>Restrictions</b></td>
* <td colspan="5" class="body"><p>None</p></td>
* </tr>
*
* <tr>
* <td class="body"><b>Attributes</b></td>
* <td class="body">Name</td>
* <td class="body">Required</td>
* <td colspan="2" class="body">Runtime&nbsp;Expression&nbsp;Evaluation</td>
* <td class="body">Availability</td>
* </tr>
*
* <tr bgcolor="#cccccc">
* <td bgcolor="#ffffff">&nbsp;</td>
* <td class="body_grey"><b>name</b></td>
* <td class="body_grey">&nbsp;Yes</td>
* <td colspan="2" class="body_grey">&nbsp;Yes</td>
* <td class="body_grey">&nbsp;1.0</td>
* </tr>
* <tr>
* <td bgcolor="#ffffff">&nbsp;</td>
* <td colspan="5" class="body"><p>The attribute name</p></td>
* </tr>
*
* <tr bgcolor="#cccccc">
* <td bgcolor="#ffffff">&nbsp;</td>
* <td class="body_grey"><b>value</b></td>
* <td class="body_grey">&nbsp;No</td>
* <td colspan="2" class="body_grey">&nbsp;Yes</td>
* <td class="body_grey">&nbsp;1.0</td>
* </tr>
* <tr>
* <td bgcolor="#ffffff" class="body">&nbsp;</td>
* <td colspan="5" class="body"><p>The value for equality testing</p></td>
* </tr>
*
* <tr>
* <td class="body" valign="top"><b>Variables</b></td>
* <td colspan="5" class="body">None</td>
* </tr>
*
* <tr>
* <td class="body" valign="top"><b>Examples</b></td>
* <td colspan="5" class="body">
* <pre>
*&lt;%@ taglib prefix="twelvemonkeys" uri="twelvemonkeys-logic" %&gt;
*&lt;bean:cookie id="logonUsernameCookie"
* name="&lt;%= com.strutscommand.Constants.LOGON_USERNAME_COOKIE_NAME %&gt;"
* value="no_username_set" /&gt;
*&lt;twelvemonkeys:equal name="logonUsernameCookie" value="no_username_set"&gt;
* &lt;html:text property="username" /&gt;
*&lt;/twelvemonkeys:equal&gt;
* </pre>
* </td>
* </tr>
* </table>
*
* <hr>
*
* @version 1.0
* @author <a href="mailto:eirik.torske@twelvemonkeys.no">Eirik Torske</a>
* @see <a href="NotEqualTag.html">notEqual</a>
*/
public class EqualTag extends ConditionalTagBase {
/**
* <a name="condition"></a>
*
* The conditions that must be met in order to display the body of this tag:
* <ol>
* <li>The attribute name property ({@code name} -> {@code mObjectName}) must not be empty.
* <li>The attribute must exist.
* <li>The attribute must be an instance of one of the supported classes:
* <ul>
* <li>{@code java.lang.String}
* <li>{@code javax.servlet.http.Cookie}
* </ul>
* <li>The value of the attribute must be equal to the object value property ({@code value} -> {@code mObjectValue}).
* </ol>
* <p>
* NB! If the object value property ({@code value} -> {@code mObjectValue}) is empty than {@code true} will be returned.
* </p>
*
* @return {@code true} if and only if all conditions are met.
*/
protected boolean condition() throws JspException {
if (StringUtil.isEmpty(objectName)) {
return false;
}
if (StringUtil.isEmpty(objectValue)) {
return true;
}
Object pageScopedAttribute = pageContext.getAttribute(objectName);
if (pageScopedAttribute == null) {
return false;
}
String pageScopedStringAttribute;
// String
if (pageScopedAttribute instanceof String) {
pageScopedStringAttribute = (String) pageScopedAttribute;
// Cookie
}
else if (pageScopedAttribute instanceof Cookie) {
pageScopedStringAttribute = ((Cookie) pageScopedAttribute).getValue();
// Type not yet supported...
}
else {
return false;
}
return (pageScopedStringAttribute.equals(objectValue));
}
}

View File

@@ -1,40 +1,40 @@
package com.twelvemonkeys.servlet.jsp.taglib.logic;
import javax.servlet.jsp.tagext.*;
/**
* TagExtraInfo class for IteratorProvider tags.
*
* @author Harald Kuhr
* @version $id: $
*/
public class IteratorProviderTEI extends TagExtraInfo {
/**
* Gets the variable info for IteratorProvider tags. The attribute with the
* name defined by the "id" attribute and type defined by the "type"
* attribute is declared with scope {@code VariableInfo.AT_END}.
*
* @param pData TagData instance provided by container
* @return an VariableInfo array of lenght 1, containing the attribute
* defined by the id parameter, declared, and with scope
* {@code VariableInfo.AT_END}.
*/
public VariableInfo[] getVariableInfo(TagData pData) {
// Get attribute name
String attributeName = pData.getId();
if (attributeName == null) {
attributeName = IteratorProviderTag.getDefaultIteratorName();
}
// Get type
String type = pData.getAttributeString(IteratorProviderTag.ATTRIBUTE_TYPE);
if (type == null) {
type = IteratorProviderTag.getDefaultIteratorType();
}
// Return the variable info
return new VariableInfo[]{
new VariableInfo(attributeName, type, true, VariableInfo.AT_END),
};
}
}
package com.twelvemonkeys.servlet.jsp.taglib.logic;
import javax.servlet.jsp.tagext.*;
/**
* TagExtraInfo class for IteratorProvider tags.
*
* @author Harald Kuhr
* @version $id: $
*/
public class IteratorProviderTEI extends TagExtraInfo {
/**
* Gets the variable info for IteratorProvider tags. The attribute with the
* name defined by the "id" attribute and type defined by the "type"
* attribute is declared with scope {@code VariableInfo.AT_END}.
*
* @param pData TagData instance provided by container
* @return an VariableInfo array of lenght 1, containing the attribute
* defined by the id parameter, declared, and with scope
* {@code VariableInfo.AT_END}.
*/
public VariableInfo[] getVariableInfo(TagData pData) {
// Get attribute name
String attributeName = pData.getId();
if (attributeName == null) {
attributeName = IteratorProviderTag.getDefaultIteratorName();
}
// Get type
String type = pData.getAttributeString(IteratorProviderTag.ATTRIBUTE_TYPE);
if (type == null) {
type = IteratorProviderTag.getDefaultIteratorType();
}
// Return the variable info
return new VariableInfo[]{
new VariableInfo(attributeName, type, true, VariableInfo.AT_END),
};
}
}

View File

@@ -1,86 +1,86 @@
package com.twelvemonkeys.servlet.jsp.taglib.logic;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.Iterator;
/**
* Abstract base class for adding iterators to a page.
*
* @todo Possible to use same strategy for all types of objects? Rename class
* to ObjectProviderTag? Hmmm... Might work.
*
* @author Harald Kuhr
* @version $id: $
*/
public abstract class IteratorProviderTag extends TagSupport {
/** {@code iterator} */
protected final static String DEFAULT_ITERATOR_NAME = "iterator";
/** {@code java.util.iterator} */
protected final static String DEFAULT_ITERATOR_TYPE = "java.util.Iterator";
/** {@code type} */
public final static String ATTRIBUTE_TYPE = "type";
/** */
private String type = null;
/**
* Gets the type.
*
* @return the type (class name)
*/
public String getType() {
return type;
}
/**
* Sets the type.
*
* @param pType
*/
public void setType(String pType) {
type = pType;
}
/**
* doEndTag implementation.
*
* @return {@code Tag.EVAL_PAGE}
* @throws JspException
*/
public int doEndTag() throws JspException {
// Set the iterator
pageContext.setAttribute(getId(), getIterator());
return Tag.EVAL_PAGE;
}
/**
* Gets the iterator for this tag.
*
* @return an {@link java.util.Iterator}
*/
protected abstract Iterator getIterator();
/**
* Gets the default iterator name.
*
* @return {@link #DEFAULT_ITERATOR_NAME}
*/
protected static String getDefaultIteratorName() {
return DEFAULT_ITERATOR_NAME;
}
/**
* Gets the default iterator type.
*
* @return {@link #DEFAULT_ITERATOR_TYPE}
*/
protected static String getDefaultIteratorType() {
return DEFAULT_ITERATOR_TYPE;
}
}
package com.twelvemonkeys.servlet.jsp.taglib.logic;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.Iterator;
/**
* Abstract base class for adding iterators to a page.
*
* @todo Possible to use same strategy for all types of objects? Rename class
* to ObjectProviderTag? Hmmm... Might work.
*
* @author Harald Kuhr
* @version $id: $
*/
public abstract class IteratorProviderTag extends TagSupport {
/** {@code iterator} */
protected final static String DEFAULT_ITERATOR_NAME = "iterator";
/** {@code java.util.iterator} */
protected final static String DEFAULT_ITERATOR_TYPE = "java.util.Iterator";
/** {@code type} */
public final static String ATTRIBUTE_TYPE = "type";
/** */
private String type = null;
/**
* Gets the type.
*
* @return the type (class name)
*/
public String getType() {
return type;
}
/**
* Sets the type.
*
* @param pType
*/
public void setType(String pType) {
type = pType;
}
/**
* doEndTag implementation.
*
* @return {@code Tag.EVAL_PAGE}
* @throws JspException
*/
public int doEndTag() throws JspException {
// Set the iterator
pageContext.setAttribute(getId(), getIterator());
return Tag.EVAL_PAGE;
}
/**
* Gets the iterator for this tag.
*
* @return an {@link java.util.Iterator}
*/
protected abstract Iterator getIterator();
/**
* Gets the default iterator name.
*
* @return {@link #DEFAULT_ITERATOR_NAME}
*/
protected static String getDefaultIteratorName() {
return DEFAULT_ITERATOR_NAME;
}
/**
* Gets the default iterator type.
*
* @return {@link #DEFAULT_ITERATOR_TYPE}
*/
protected static String getDefaultIteratorType() {
return DEFAULT_ITERATOR_TYPE;
}
}

View File

@@ -1,168 +1,168 @@
/*
* Produced (p) 2002 TwelveMonkeys
* Address : Svovelstikka 1, Box 6432 Etterstad, 0605 Oslo, Norway.
* Phone : +47 22 57 70 00
* Fax : +47 22 57 70 70
*/
package com.twelvemonkeys.servlet.jsp.taglib.logic;
import com.twelvemonkeys.lang.StringUtil;
import javax.servlet.http.Cookie;
import javax.servlet.jsp.JspException;
/**
* <p>
* Custom tag for testing non-equality of an attribute against a given value.
* The attribute types supported so far is:
* <ul>
* <li>{@code java.lang.String} (ver. 1.0)
* <li>{@code javax.servlet.http.Cookie} (ver. 1.0)
* </ul>
* </p>
* See the implemented <a href="#condition">{@code condition}</a> method for details regarding the non-equality conditions.
*
* <p><hr></p>
*
* <h3>Tag Reference</h3>
* <table border="0" cellspacing="3" cellpadding="3" width="90%">
* <tr bgcolor="#cccccc">
* <td colspan="5" class="body"><b>notEqual</b></td>
* <td width="17%" align="right" class="body">Availability:&nbsp;1.0</td>
* </tr>
* <tr>
* <td colspan="6" class="body"><p>Tag for testing if an attribute is NOT equal to a given value.</p></td>
* </tr>
* <tr>
* <td width="15%" class="body"><b>Tag Body</b></td>
* <td width="17%" class="body">JSP</td>
* <td width="17%" class="body">&nbsp;</td>
* <td width="17%" class="body">&nbsp;</td>
* <td width="17%" class="body">&nbsp;</td>
* <td width="17%" class="body">&nbsp;</td>
* </tr>
* <tr>
* <td class="body"><b>Restrictions</b></td>
* <td colspan="5" class="body"><p>None</p></td>
* </tr>
*
* <tr>
* <td class="body"><b>Attributes</b></td>
* <td class="body">Name</td>
* <td class="body">Required</td>
* <td colspan="2" class="body">Runtime&nbsp;Expression&nbsp;Evaluation</td>
* <td class="body">Availability</td>
* </tr>
*
* <tr bgcolor="#cccccc">
* <td bgcolor="#ffffff">&nbsp;</td>
* <td class="body_grey"><b>name</b></td>
* <td class="body_grey">&nbsp;Yes</td>
* <td colspan="2" class="body_grey">&nbsp;Yes</td>
* <td class="body_grey">&nbsp;1.0</td>
* </tr>
* <tr>
* <td bgcolor="#ffffff">&nbsp;</td>
* <td colspan="5" class="body"><p>The attribute name</p></td>
* </tr>
*
* <tr bgcolor="#cccccc">
* <td bgcolor="#ffffff">&nbsp;</td>
* <td class="body_grey"><b>value</b></td>
* <td class="body_grey">&nbsp;No</td>
* <td colspan="2" class="body_grey">&nbsp;Yes</td>
* <td class="body_grey">&nbsp;1.0</td>
* </tr>
* <tr>
* <td bgcolor="#ffffff" class="body">&nbsp;</td>
* <td colspan="5" class="body"><p>The value for equality testing</p></td>
* </tr>
*
* <tr>
* <td class="body" valign="top"><b>Variables</b></td>
* <td colspan="5" class="body">None</td>
* </tr>
*
* <tr>
* <td class="body" valign="top"><b>Examples</b></td>
* <td colspan="5" class="body">
* <pre>
*&lt;%@ taglib prefix="twelvemonkeys" uri="twelvemonkeys-logic" %&gt;
*&lt;bean:cookie id="logonUsernameCookie"
* name="&lt;%= com.strutscommand.Constants.LOGON_USERNAME_COOKIE_NAME %&gt;"
* value="no_username_set" /&gt;
*&lt;twelvemonkeys:notEqual name="logonUsernameCookie" value="no_username_set"&gt;
* &lt;html:text property="username" value="&lt;%= logonUsernameCookie.getValue() %&gt;" /&gt;
*&lt;/twelvemonkeys:notEqual&gt;
* </pre>
* </td>
* </tr>
* </table>
*
* <hr>
*
* @version 1.0
* @author <a href="mailto:eirik.torske@twelvemonkeys.no">Eirik Torske</a>
* @see <a href="EqualTag.html">equal</a>
*/
public class NotEqualTag extends ConditionalTagBase {
/**
* <a name="condition"></a>
*
* The condition that must be met in order to display the body of this tag:
* <ol>
* <li>The attribute name property ({@code name} -> {@code mObjectName}) must not be empty.
* <li>The attribute must exist.
* <li>The attribute must be an instance of one of the supported classes:
* <ul>
* <li>{@code java.lang.String}
* <li>{@code javax.servlet.http.Cookie}
* </ul>
* <li>The value of the attribute must NOT be equal to the object value property ({@code value} -> {@code mObjectValue}).
* </ol>
* <p>
* NB! If the object value property ({@code value} -> {@code mObjectValue}) is empty than {@code true} will be returned.
* </p>
*
* @return {@code true} if and only if all conditions are met.
*/
protected boolean condition() throws JspException {
if (StringUtil.isEmpty(objectName)) {
return false;
}
if (StringUtil.isEmpty(objectValue)) {
return true;
}
Object pageScopedAttribute = pageContext.getAttribute(objectName);
if (pageScopedAttribute == null) {
return false;
}
String pageScopedStringAttribute;
// String
if (pageScopedAttribute instanceof String) {
pageScopedStringAttribute = (String) pageScopedAttribute;
// Cookie
}
else if (pageScopedAttribute instanceof Cookie) {
pageScopedStringAttribute = ((Cookie) pageScopedAttribute).getValue();
// Type not yet supported...
}
else {
return false;
}
return (!(pageScopedStringAttribute.equals(objectValue)));
}
}
/*
* Produced (p) 2002 TwelveMonkeys
* Address : Svovelstikka 1, Box 6432 Etterstad, 0605 Oslo, Norway.
* Phone : +47 22 57 70 00
* Fax : +47 22 57 70 70
*/
package com.twelvemonkeys.servlet.jsp.taglib.logic;
import com.twelvemonkeys.lang.StringUtil;
import javax.servlet.http.Cookie;
import javax.servlet.jsp.JspException;
/**
* <p>
* Custom tag for testing non-equality of an attribute against a given value.
* The attribute types supported so far is:
* <ul>
* <li>{@code java.lang.String} (ver. 1.0)
* <li>{@code javax.servlet.http.Cookie} (ver. 1.0)
* </ul>
* </p>
* See the implemented <a href="#condition">{@code condition}</a> method for details regarding the non-equality conditions.
*
* <p><hr></p>
*
* <h3>Tag Reference</h3>
* <table border="0" cellspacing="3" cellpadding="3" width="90%">
* <tr bgcolor="#cccccc">
* <td colspan="5" class="body"><b>notEqual</b></td>
* <td width="17%" align="right" class="body">Availability:&nbsp;1.0</td>
* </tr>
* <tr>
* <td colspan="6" class="body"><p>Tag for testing if an attribute is NOT equal to a given value.</p></td>
* </tr>
* <tr>
* <td width="15%" class="body"><b>Tag Body</b></td>
* <td width="17%" class="body">JSP</td>
* <td width="17%" class="body">&nbsp;</td>
* <td width="17%" class="body">&nbsp;</td>
* <td width="17%" class="body">&nbsp;</td>
* <td width="17%" class="body">&nbsp;</td>
* </tr>
* <tr>
* <td class="body"><b>Restrictions</b></td>
* <td colspan="5" class="body"><p>None</p></td>
* </tr>
*
* <tr>
* <td class="body"><b>Attributes</b></td>
* <td class="body">Name</td>
* <td class="body">Required</td>
* <td colspan="2" class="body">Runtime&nbsp;Expression&nbsp;Evaluation</td>
* <td class="body">Availability</td>
* </tr>
*
* <tr bgcolor="#cccccc">
* <td bgcolor="#ffffff">&nbsp;</td>
* <td class="body_grey"><b>name</b></td>
* <td class="body_grey">&nbsp;Yes</td>
* <td colspan="2" class="body_grey">&nbsp;Yes</td>
* <td class="body_grey">&nbsp;1.0</td>
* </tr>
* <tr>
* <td bgcolor="#ffffff">&nbsp;</td>
* <td colspan="5" class="body"><p>The attribute name</p></td>
* </tr>
*
* <tr bgcolor="#cccccc">
* <td bgcolor="#ffffff">&nbsp;</td>
* <td class="body_grey"><b>value</b></td>
* <td class="body_grey">&nbsp;No</td>
* <td colspan="2" class="body_grey">&nbsp;Yes</td>
* <td class="body_grey">&nbsp;1.0</td>
* </tr>
* <tr>
* <td bgcolor="#ffffff" class="body">&nbsp;</td>
* <td colspan="5" class="body"><p>The value for equality testing</p></td>
* </tr>
*
* <tr>
* <td class="body" valign="top"><b>Variables</b></td>
* <td colspan="5" class="body">None</td>
* </tr>
*
* <tr>
* <td class="body" valign="top"><b>Examples</b></td>
* <td colspan="5" class="body">
* <pre>
*&lt;%@ taglib prefix="twelvemonkeys" uri="twelvemonkeys-logic" %&gt;
*&lt;bean:cookie id="logonUsernameCookie"
* name="&lt;%= com.strutscommand.Constants.LOGON_USERNAME_COOKIE_NAME %&gt;"
* value="no_username_set" /&gt;
*&lt;twelvemonkeys:notEqual name="logonUsernameCookie" value="no_username_set"&gt;
* &lt;html:text property="username" value="&lt;%= logonUsernameCookie.getValue() %&gt;" /&gt;
*&lt;/twelvemonkeys:notEqual&gt;
* </pre>
* </td>
* </tr>
* </table>
*
* <hr>
*
* @version 1.0
* @author <a href="mailto:eirik.torske@twelvemonkeys.no">Eirik Torske</a>
* @see <a href="EqualTag.html">equal</a>
*/
public class NotEqualTag extends ConditionalTagBase {
/**
* <a name="condition"></a>
*
* The condition that must be met in order to display the body of this tag:
* <ol>
* <li>The attribute name property ({@code name} -> {@code mObjectName}) must not be empty.
* <li>The attribute must exist.
* <li>The attribute must be an instance of one of the supported classes:
* <ul>
* <li>{@code java.lang.String}
* <li>{@code javax.servlet.http.Cookie}
* </ul>
* <li>The value of the attribute must NOT be equal to the object value property ({@code value} -> {@code mObjectValue}).
* </ol>
* <p>
* NB! If the object value property ({@code value} -> {@code mObjectValue}) is empty than {@code true} will be returned.
* </p>
*
* @return {@code true} if and only if all conditions are met.
*/
protected boolean condition() throws JspException {
if (StringUtil.isEmpty(objectName)) {
return false;
}
if (StringUtil.isEmpty(objectValue)) {
return true;
}
Object pageScopedAttribute = pageContext.getAttribute(objectName);
if (pageScopedAttribute == null) {
return false;
}
String pageScopedStringAttribute;
// String
if (pageScopedAttribute instanceof String) {
pageScopedStringAttribute = (String) pageScopedAttribute;
// Cookie
}
else if (pageScopedAttribute instanceof Cookie) {
pageScopedStringAttribute = ((Cookie) pageScopedAttribute).getValue();
// Type not yet supported...
}
else {
return false;
}
return (!(pageScopedStringAttribute.equals(objectValue)));
}
}

View File

@@ -1,183 +1,183 @@
package com.twelvemonkeys.servlet.log4j;
import org.apache.log4j.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Set;
/**
* Log4JContextWrapper
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: log4j/Log4JContextWrapper.java#1 $
*/
final class Log4JContextWrapper implements ServletContext {
// TODO: Move to sandbox
// TODO: This solution sucks...
// How about starting to create some kind of pluggable decorator system,
// something along the lines of AOP mixins/interceptor pattern..
// Probably using a dynamic Proxy, delegating to the mixins and or the
// wrapped object based on configuration.
// This way we could simply call ServletUtil.decorate(ServletContext):ServletContext
// And the context would be decorated with all configured mixins at once,
// requiring less boilerplate delegation code, and less layers of wrapping
// (alternatively we could decorate the Servlet/FilterConfig objects).
// See the ServletUtil.createWrapper methods for some hints..
// Something like this:
public static ServletContext wrap(final ServletContext pContext, final Object[] pDelegates, final ClassLoader pLoader) {
ClassLoader cl = pLoader != null ? pLoader : Thread.currentThread().getContextClassLoader();
// TODO: Create a "static" mapping between methods in the ServletContext
// and the corresponding delegate
// TODO: Resolve super-invokations, to delegate to next delegate in
// chain, and finally invoke pContext
return (ServletContext) Proxy.newProxyInstance(cl, new Class[] {ServletContext.class}, new InvocationHandler() {
public Object invoke(Object pProxy, Method pMethod, Object[] pArgs) throws Throwable {
// TODO: Test if any of the delegates should receive, if so invoke
// Else, invoke on original object
return pMethod.invoke(pContext, pArgs);
}
});
}
private final ServletContext context;
private final Logger logger;
Log4JContextWrapper(ServletContext pContext) {
context = pContext;
// TODO: We want a logger per servlet, not per servlet context, right?
logger = Logger.getLogger(pContext.getServletContextName());
// TODO: Automatic init/config of Log4J using context parameter for log4j.xml?
// See Log4JInit.java
// TODO: Automatic config of properties in the context wrapper?
}
public final void log(final Exception pException, final String pMessage) {
log(pMessage, pException);
}
// TODO: Add more logging methods to interface info/warn/error?
// TODO: Implement these mehtods in GenericFilter/GenericServlet?
public void log(String pMessage) {
// TODO: Get logger for caller..
// Should be possible using some stack peek hack, but that's slow...
// Find a good way...
// Maybe just pass it into the constuctor, and have one wrapper per servlet
logger.info(pMessage);
}
public void log(String pMessage, Throwable pCause) {
// TODO: Get logger for caller..
logger.error(pMessage, pCause);
}
public Object getAttribute(String pMessage) {
return context.getAttribute(pMessage);
}
public Enumeration getAttributeNames() {
return context.getAttributeNames();
}
public ServletContext getContext(String pMessage) {
return context.getContext(pMessage);
}
public String getInitParameter(String pMessage) {
return context.getInitParameter(pMessage);
}
public Enumeration getInitParameterNames() {
return context.getInitParameterNames();
}
public int getMajorVersion() {
return context.getMajorVersion();
}
public String getMimeType(String pMessage) {
return context.getMimeType(pMessage);
}
public int getMinorVersion() {
return context.getMinorVersion();
}
public RequestDispatcher getNamedDispatcher(String pMessage) {
return context.getNamedDispatcher(pMessage);
}
public String getRealPath(String pMessage) {
return context.getRealPath(pMessage);
}
public RequestDispatcher getRequestDispatcher(String pMessage) {
return context.getRequestDispatcher(pMessage);
}
public URL getResource(String pMessage) throws MalformedURLException {
return context.getResource(pMessage);
}
public InputStream getResourceAsStream(String pMessage) {
return context.getResourceAsStream(pMessage);
}
public Set getResourcePaths(String pMessage) {
return context.getResourcePaths(pMessage);
}
public String getServerInfo() {
return context.getServerInfo();
}
public Servlet getServlet(String pMessage) throws ServletException {
//noinspection deprecation
return context.getServlet(pMessage);
}
public String getServletContextName() {
return context.getServletContextName();
}
public Enumeration getServletNames() {
//noinspection deprecation
return context.getServletNames();
}
public Enumeration getServlets() {
//noinspection deprecation
return context.getServlets();
}
public void removeAttribute(String pMessage) {
context.removeAttribute(pMessage);
}
public void setAttribute(String pMessage, Object pExtension) {
context.setAttribute(pMessage, pExtension);
}
}
package com.twelvemonkeys.servlet.log4j;
import org.apache.log4j.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Set;
/**
* Log4JContextWrapper
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: log4j/Log4JContextWrapper.java#1 $
*/
final class Log4JContextWrapper implements ServletContext {
// TODO: Move to sandbox
// TODO: This solution sucks...
// How about starting to create some kind of pluggable decorator system,
// something along the lines of AOP mixins/interceptor pattern..
// Probably using a dynamic Proxy, delegating to the mixins and or the
// wrapped object based on configuration.
// This way we could simply call ServletUtil.decorate(ServletContext):ServletContext
// And the context would be decorated with all configured mixins at once,
// requiring less boilerplate delegation code, and less layers of wrapping
// (alternatively we could decorate the Servlet/FilterConfig objects).
// See the ServletUtil.createWrapper methods for some hints..
// Something like this:
public static ServletContext wrap(final ServletContext pContext, final Object[] pDelegates, final ClassLoader pLoader) {
ClassLoader cl = pLoader != null ? pLoader : Thread.currentThread().getContextClassLoader();
// TODO: Create a "static" mapping between methods in the ServletContext
// and the corresponding delegate
// TODO: Resolve super-invokations, to delegate to next delegate in
// chain, and finally invoke pContext
return (ServletContext) Proxy.newProxyInstance(cl, new Class[] {ServletContext.class}, new InvocationHandler() {
public Object invoke(Object pProxy, Method pMethod, Object[] pArgs) throws Throwable {
// TODO: Test if any of the delegates should receive, if so invoke
// Else, invoke on original object
return pMethod.invoke(pContext, pArgs);
}
});
}
private final ServletContext context;
private final Logger logger;
Log4JContextWrapper(ServletContext pContext) {
context = pContext;
// TODO: We want a logger per servlet, not per servlet context, right?
logger = Logger.getLogger(pContext.getServletContextName());
// TODO: Automatic init/config of Log4J using context parameter for log4j.xml?
// See Log4JInit.java
// TODO: Automatic config of properties in the context wrapper?
}
public final void log(final Exception pException, final String pMessage) {
log(pMessage, pException);
}
// TODO: Add more logging methods to interface info/warn/error?
// TODO: Implement these mehtods in GenericFilter/GenericServlet?
public void log(String pMessage) {
// TODO: Get logger for caller..
// Should be possible using some stack peek hack, but that's slow...
// Find a good way...
// Maybe just pass it into the constuctor, and have one wrapper per servlet
logger.info(pMessage);
}
public void log(String pMessage, Throwable pCause) {
// TODO: Get logger for caller..
logger.error(pMessage, pCause);
}
public Object getAttribute(String pMessage) {
return context.getAttribute(pMessage);
}
public Enumeration getAttributeNames() {
return context.getAttributeNames();
}
public ServletContext getContext(String pMessage) {
return context.getContext(pMessage);
}
public String getInitParameter(String pMessage) {
return context.getInitParameter(pMessage);
}
public Enumeration getInitParameterNames() {
return context.getInitParameterNames();
}
public int getMajorVersion() {
return context.getMajorVersion();
}
public String getMimeType(String pMessage) {
return context.getMimeType(pMessage);
}
public int getMinorVersion() {
return context.getMinorVersion();
}
public RequestDispatcher getNamedDispatcher(String pMessage) {
return context.getNamedDispatcher(pMessage);
}
public String getRealPath(String pMessage) {
return context.getRealPath(pMessage);
}
public RequestDispatcher getRequestDispatcher(String pMessage) {
return context.getRequestDispatcher(pMessage);
}
public URL getResource(String pMessage) throws MalformedURLException {
return context.getResource(pMessage);
}
public InputStream getResourceAsStream(String pMessage) {
return context.getResourceAsStream(pMessage);
}
public Set getResourcePaths(String pMessage) {
return context.getResourcePaths(pMessage);
}
public String getServerInfo() {
return context.getServerInfo();
}
public Servlet getServlet(String pMessage) throws ServletException {
//noinspection deprecation
return context.getServlet(pMessage);
}
public String getServletContextName() {
return context.getServletContextName();
}
public Enumeration getServletNames() {
//noinspection deprecation
return context.getServletNames();
}
public Enumeration getServlets() {
//noinspection deprecation
return context.getServlets();
}
public void removeAttribute(String pMessage) {
context.removeAttribute(pMessage);
}
public void setAttribute(String pMessage, Object pExtension) {
context.setAttribute(pMessage, pExtension);
}
}