0001: /**
0002: * Copyright (C) 2006, 2007 David Bulmore, Software Sensation Inc.
0003: * All Rights Reserved.
0004: *
0005: * This file is part of jWebApp.
0006: *
0007: * jWebApp is free software; you can redistribute it and/or modify it under
0008: * the terms of the GNU General Public License (Version 2) as published by
0009: * the Free Software Foundation.
0010: *
0011: * jWebApp is distributed in the hope that it will be useful, but WITHOUT
0012: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0013: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0014: * for more details.
0015: *
0016: * You should have received a copy of the GNU General Public License
0017: * along with jWebApp; if not, write to the Free Software Foundation,
0018: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
0019: */package jwebapp.controller;
0020:
0021: import jcommontk.object.ObjectFiller;
0022: import java.io.File;
0023: import java.io.InputStream;
0024: import java.io.PrintStream;
0025: import java.net.URI;
0026: import java.util.Enumeration;
0027: import java.util.Hashtable;
0028: import java.util.Iterator;
0029: import java.util.List;
0030: import java.util.Map;
0031: import java.util.Set;
0032: import java.util.Vector;
0033: import java.util.logging.Level;
0034: import java.util.logging.Logger;
0035: import javax.servlet.RequestDispatcher;
0036: import javax.servlet.ServletContext;
0037: import javax.servlet.http.HttpServletRequest;
0038: import javax.servlet.http.HttpServletResponse;
0039: import jcommontk.object.ObjectFiller.GetHandler;
0040: import jwebtk.validator.Validator;
0041: import org.apache.commons.fileupload.disk.DiskFileItem;
0042: import org.apache.commons.fileupload.disk.DiskFileItemFactory;
0043: import org.apache.commons.fileupload.servlet.ServletFileUpload;
0044:
0045: /**
0046: * Provides access to the jWebApp/servlet environment.
0047: */
0048: @SuppressWarnings("unchecked")
0049: // working to complete a Java 1.5 version
0050: public class ServerInterface {
0051: public static final int UNDEFINED_ERROR = 0;
0052: public static final int VALIDATION_ERROR = 1;
0053: public static final int NOT_SECURE_ERROR = 2;
0054: public static final int AUTHENTICATION_ERROR = 3;
0055:
0056: private static Logger logger = Logger
0057: .getLogger(ServerInterface.class.getName());
0058:
0059: private HttpServletRequest servletRequest;
0060: private HttpServletResponse servletResponse;
0061: private Hashtable multipartFormDataHash;
0062: private Vector multipartFormDataVector;
0063: private ServletContext servletContext;
0064: private DataManager dataManager;
0065: private DataManager.RequestData requestData;
0066: private UrlDataWrapper urlDataWrapper = new UrlDataWrapper();
0067: private String returnedUrlKey, useDomainName;
0068: private boolean urlRewriting;
0069:
0070: protected ServerInterface(HttpServletRequest servletRequest,
0071: HttpServletResponse servletResponse,
0072: ServletContext servletContext, DataManager dataManager,
0073: String useDomainName, boolean urlRewriting) {
0074: this .servletRequest = servletRequest;
0075: this .servletResponse = servletResponse;
0076: this .servletContext = servletContext;
0077: this .dataManager = dataManager;
0078: this .useDomainName = useDomainName;
0079: this .urlRewriting = urlRewriting;
0080: }
0081:
0082: /**
0083: * Returns the logger.
0084: */
0085: public static Logger getLogger() {
0086: return logger;
0087: }
0088:
0089: /**
0090: * Returns a vector of the current users request history. The vector contains
0091: * string objects representing the request URIs (plus their query strings) that
0092: * the user has visited during this session. This information
0093: * can be used in conjunction with ServerInterface.forwardRequest() to forward the user to the last/previous
0094: * relevant request after signing on.
0095: *
0096: * @return returns a vector of string objects
0097: */
0098: public Vector getRequestHistory() {
0099: return (Vector) getSessionAttribute("jwaRequestHistory");
0100: }
0101:
0102: /**
0103: * Add URI to the request history (stored in the users session).
0104: */
0105:
0106: public void addToRequestHistory() {
0107: addToRequestHistory(20);
0108: }
0109:
0110: /**
0111: * Add URI to the request history (stored in the users session).
0112: *
0113: * @param limit the maximum number of URIs in the history vector
0114: */
0115:
0116: public void addToRequestHistory(int limit) {
0117: addToRequestHistory(limit, servletRequest.getRequestURI()
0118: + (servletRequest.getQueryString() == null ? "" : "?"
0119: + servletRequest.getQueryString()));
0120: }
0121:
0122: /**
0123: * Add URI to the request history (stored in the users session).
0124: *
0125: * @param limit the maximum number of URIs in the history vector
0126: * @param uri the URI being stored
0127: */
0128:
0129: public void addToRequestHistory(int limit, String uri) {
0130: Vector requestHistory = (Vector) getSessionAttribute("jwaRequestHistory");
0131:
0132: if (requestHistory == null)
0133: setSessionAttribute("jwaRequestHistory",
0134: requestHistory = new Vector());
0135:
0136: requestHistory.addElement(uri);
0137:
0138: if (requestHistory.size() > limit)
0139: requestHistory.remove(0);
0140: }
0141:
0142: /**
0143: * Forward request to another URL within the same web application context. The calling RequestHandler method
0144: * must return "noForwarding", as forwarding/redirects can not be called twice. This method calls
0145: * ServletRequest.getRequestDispatcher().
0146: *
0147: * @param forwardUrl the URL to forward to
0148: */
0149: public void forwardRequest(String forwardUrl)
0150: throws JWebAppException {
0151: if (logger.isLoggable(Level.FINER))
0152: logger.finer("forward URL=" + forwardUrl);
0153:
0154: RequestDispatcher requestDispatcher = getServletRequest()
0155: .getRequestDispatcher(forwardUrl);
0156:
0157: try {
0158: if (requestDispatcher != null)
0159: requestDispatcher.forward(getServletRequest(),
0160: getServletResponse());
0161: } catch (Exception e) {
0162: throw new JWebAppException(e);
0163: }
0164: }
0165:
0166: /**
0167: * Redirect the request to another URL. This URL can be anywhere inside or outside the web application context.
0168: * The calling RequestHandler method must return "noForwarding", as forwarding/redirects can not be called twice. This
0169: * method calls ServletResponse.sendRedirect().
0170: *
0171: * @param redirectUrl the URL to forward to
0172: */
0173: public void redirectRequest(String redirectUrl)
0174: throws JWebAppException {
0175: try {
0176: getServletResponse().sendRedirect(redirectUrl);
0177: } catch (Exception e) {
0178: throw new JWebAppException(e);
0179: }
0180: }
0181:
0182: /**
0183: * Returns the validation handler.
0184: *
0185: * @return the validation handler
0186: */
0187: public Validator getValidator() {
0188: return ValidationManager.getValidator();
0189: }
0190:
0191: /**
0192: * Validates the request data with XML defined validations.
0193: *
0194: * @return true if the validation passes, false if it does not pass.
0195: */
0196: public boolean validateParameters() {
0197: return ValidationManager.validateParameters(this );
0198: }
0199:
0200: DataManager getDataManager() {
0201: return dataManager;
0202: }
0203:
0204: /**
0205: * Reload the XML configuration file.
0206: */
0207: public void reloadXMLConfigurationData() throws JWebAppException {
0208: try {
0209: getDataManager().reload();
0210: } catch (Exception e) {
0211: throw new JWebAppException(e);
0212: }
0213: }
0214:
0215: /**
0216: * Get the information associated with the current request.
0217: * @return a RequestData instance
0218: */
0219: public DataManager.RequestData getRequestData() {
0220: return requestData;
0221: }
0222:
0223: void setRequestData(DataManager.RequestData requestData) {
0224: this .requestData = requestData;
0225: }
0226:
0227: /**
0228: * Returns the last URL data key returned by a method from RequestHandler.
0229: * @return last URL data key string
0230: */
0231: public String getReturnedUrlKey() {
0232: return returnedUrlKey;
0233: }
0234:
0235: void setReturnedUrlKey(String urlDataKey) {
0236: this .returnedUrlKey = urlDataKey;
0237: }
0238:
0239: /**
0240: * Loads your object with request parameter data. "obj" is an object of any type
0241: * containing set methods. Any set method matching the name of a parameter will
0242: * be set with the request parameter value.
0243: *
0244: * @param obj an object with set methods
0245: *
0246: * @return object with set methods
0247: */
0248: public <T> T fillObjectFromRequest(T obj) throws JWebAppException {
0249: return fillObjectFromRequest(obj, true, false, null, false);
0250: }
0251:
0252: /**
0253: * Loads your object with request parameter data. "obj" is an object of any type
0254: * containing set methods. Any set method matching the name of a parameter will
0255: * be set with the request parameter value.
0256: *
0257: * @param obj an object with set methods
0258: * @param ignoreValueNames ignore the value names in the set
0259: * @param setNulls set or ignore null values
0260: *
0261: * @return object with set methods
0262: */
0263: public <T> T fillObjectFromRequest(T obj,
0264: Set<String> ignoreValueNames, boolean setNulls)
0265: throws JWebAppException {
0266: return fillObjectFromRequest(obj, true, false,
0267: ignoreValueNames, setNulls);
0268: }
0269:
0270: /**
0271: * Loads your object with request parameter data. "obj" is an object of any type
0272: * containing set methods. Any set method matching the name of a parameter will
0273: * be set with the request parameter value.
0274: *
0275: * @param obj an object with set methods
0276: * @param fillPublicSetMethods fill the public set methods
0277: * @param fillPublicFields fill the public fields
0278: * @param ignoreValueNames ignore the value names in the set
0279: * @param setNulls set or ignore null values
0280: *
0281: * @return object with set methods
0282: */
0283: public <T> T fillObjectFromRequest(T obj,
0284: boolean fillPublicSetMethods, boolean fillPublicFields,
0285: Set<String> ignoreValueNames, boolean setNulls)
0286: throws JWebAppException {
0287: try {
0288: ObjectFiller.fillObject(new GetHandler() {
0289: public Object get(String key, Class objectClass) {
0290: return getParameter(key, true);
0291: }
0292: }, obj, fillPublicSetMethods, fillPublicFields,
0293: ignoreValueNames, setNulls);
0294:
0295: return obj;
0296: } catch (Exception e) {
0297: throw new JWebAppException(e);
0298: }
0299: }
0300:
0301: /**
0302: * Return the servlets context.
0303: * @return an instance of ServletContext
0304: */
0305: public ServletContext getServletContext() {
0306: return servletContext;
0307: }
0308:
0309: /**
0310: * Return the servlet request.
0311: * @return an instance of HttpServletRequest
0312: */
0313: public HttpServletRequest getServletRequest() {
0314: return servletRequest;
0315: }
0316:
0317: /**
0318: * Return the servlet response.
0319: * @return an instance of HttpServletResponse
0320: */
0321: public HttpServletResponse getServletResponse() {
0322: return servletResponse;
0323: }
0324:
0325: /**
0326: * Log a message via ServletContext.log().
0327: *
0328: * @param message to log
0329: */
0330: public void log(String message) {
0331: servletContext.log(message);
0332: }
0333:
0334: /**
0335: * Log a message via ServletContext.log().
0336: *
0337: * @param message to log
0338: * @param t instance to log
0339: */
0340: public void log(String message, Throwable t) {
0341: servletContext.log(message, t);
0342: }
0343:
0344: /**
0345: * Checks if the current user has permission.
0346: * @param roles the the current user belongs to
0347: * @return true if the user has permission, false otherwise
0348: */
0349: public boolean hasPermission(Set<String> roles) {
0350: if (roles == null || roles.size() == 0)
0351: return true;
0352:
0353: if (getRemoteUserInformation() == null
0354: && getRemoteUser() == null)
0355: return false;
0356:
0357: Iterator<String> it = roles.iterator();
0358:
0359: while (it.hasNext()) {
0360: if (isUserInRole(it.next()))
0361: return true;
0362: }
0363:
0364: return false;
0365: }
0366:
0367: /**
0368: * Returns the remote user Id.
0369: * @return the remote user Id
0370: */
0371: public String getRemoteUser() {
0372: String remoteUser = servletRequest.getRemoteUser();
0373:
0374: if (remoteUser != null)
0375: return remoteUser;
0376:
0377: return (String) getSessionAttribute("jwaRemoteUser");
0378: }
0379:
0380: /**
0381: * Set the remote users information.
0382: * @param userId the remote users Id
0383: * @param salutation the remote users salutation (Mr., Miss., Mrs., ...), may be null
0384: * @param firstName the remote users first name, may be null
0385: * @param lastName the remote users last name, may be null
0386: * @param roles the remote user belongs to
0387: */
0388: public void setRemoteUserInformation(String userId,
0389: String salutation, String firstName, String lastName,
0390: Set<String> roles) {
0391: setSessionAttribute("jwaRemoteUser", userId);
0392:
0393: setSessionAttribute("jwaRemoteUserInformation", new RemoteUser(
0394: userId, salutation, firstName, lastName, roles));
0395: }
0396:
0397: /**
0398: * Remove remote users information from the environment (logout).
0399: */
0400: public void invalidateRemoteUser() {
0401: servletRequest.getSession().invalidate();
0402: }
0403:
0404: /**
0405: * Returns an instance of RemoteUser, which contains information (user id, first name, last name, roles) about the remote user.
0406: * @return an instance of RemoteUser
0407: */
0408: public RemoteUser getRemoteUserInformation() {
0409: return (RemoteUser) getSessionAttribute("jwaRemoteUserInformation");
0410: }
0411:
0412: /**
0413: * Checks if the current user is in the given role.
0414: *
0415: * @param role checks if the user is in the role
0416: * @return true if the user is in the role, false otherwise
0417: */
0418: public boolean isUserInRole(String role) {
0419: RemoteUser remoteUser = getRemoteUserInformation();
0420:
0421: if (remoteUser != null && remoteUser.getRoles() != null)
0422: return remoteUser.getRoles().contains(role);
0423:
0424: return servletRequest.isUserInRole(role);
0425: }
0426:
0427: /**
0428: * Returns a hash table of all the request attributes.
0429: * @return an instance of Hashtable
0430: */
0431: public Hashtable getAttributeHash() {
0432: Enumeration e = servletRequest.getAttributeNames();
0433: Hashtable attributeHash = new Hashtable();
0434:
0435: while (e.hasMoreElements()) {
0436: String name = (String) e.nextElement();
0437: attributeHash.put(name, getAttribute(name));
0438: }
0439:
0440: return attributeHash;
0441: }
0442:
0443: /**
0444: * Prints the request attributes to the given PrintStream.
0445: * @param out the PrintStream object to print to
0446: */
0447: public void printAttributes(PrintStream out) {
0448: Enumeration e = servletRequest.getAttributeNames();
0449:
0450: while (e.hasMoreElements()) {
0451: String name = (String) e.nextElement();
0452: out.println(name + " = " + getAttribute(name));
0453: }
0454: }
0455:
0456: /**
0457: * Returns a hash table of all the request parameters. If the parameter
0458: * has multiple values, then the hash entry will contain an array of the values.
0459: * @return an instance of Hashtable
0460: */
0461: public Hashtable getParameterHash() {
0462: Enumeration e = getParameterNames();
0463: Hashtable parameterHash = new Hashtable();
0464:
0465: while (e.hasMoreElements()) {
0466: String name = (String) e.nextElement(), values[] = getParameterValues(name);
0467:
0468: if (values != null)
0469: if (values.length == 1)
0470: parameterHash.put(name, values[0]);
0471: else
0472: parameterHash.put(name, values);
0473: }
0474:
0475: return parameterHash;
0476: }
0477:
0478: /**
0479: * Prints the request parameters to the given PrintStream.
0480: * @param out the PrintStream object to print to
0481: */
0482: public void printParameters(PrintStream out) {
0483: Enumeration e = getParameterNames();
0484:
0485: while (e.hasMoreElements()) {
0486: String name = (String) e.nextElement(), values[] = getParameterValues(name);
0487:
0488: out.print(name + " = ");
0489:
0490: if (values != null)
0491: for (int i = 0; i < values.length; i++)
0492: out.print(values[i]);
0493:
0494: out.println();
0495: }
0496: }
0497:
0498: /**
0499: * Returns the request parameter associated with the given name.
0500: * @param parameter the hash table key associated with parameter
0501: * @return the parameter
0502: */
0503: public String getParameter(String parameter) {
0504: return getParameter(parameter, null, false);
0505: }
0506:
0507: /**
0508: * Returns the request parameter associated with the given name.
0509: *
0510: * @param parameter the hash table key associated with parameter
0511: * @param defaultValue return the default value if the param is empty or null
0512: *
0513: * @return the parameter
0514: */
0515: public String getParameter(String parameter, String defaultValue) {
0516: return getParameter(parameter, defaultValue, true);
0517: }
0518:
0519: /**
0520: * Returns the request parameter associated with the given name.
0521: * @param parameter the hash table key associated with parameter
0522: * @param emptyToNull return null instead of an empty value
0523: * @return the parameter
0524: */
0525: public String getParameter(String parameter, boolean emptyToNull) {
0526: return getParameter(parameter, null, emptyToNull);
0527: }
0528:
0529: /**
0530: * Returns the request parameter associated with the given name.
0531: * @param parameter the hash table key associated with parameter
0532: * @param defaultValue return the default value if the param is empty or null
0533: * @param emptyToNull return null instead of an empty value
0534: * @return the parameter
0535: */
0536: public String getParameter(String parameter, String defaultValue,
0537: boolean emptyToNull) {
0538: String value = null;
0539:
0540: if (isMultipartFormData())
0541: value = getMultipartFormParameter(parameter);
0542:
0543: if (value == null)
0544: value = servletRequest.getParameter(parameter);
0545:
0546: if (value == null || (value.length() == 0 && emptyToNull))
0547: if (defaultValue != null)
0548: return defaultValue;
0549: else
0550: return null;
0551:
0552: return value;
0553: }
0554:
0555: /**
0556: * Returns the request parameter names.
0557: * @return an enumerated list of the parameter names
0558: */
0559: public Enumeration getParameterNames() {
0560: Vector nameVector = new Vector();
0561:
0562: if (isMultipartFormData()) {
0563: Hashtable hash = getMultipartFormDataHashtable();
0564:
0565: if (hash != null)
0566: nameVector.addAll(hash.keySet());
0567: }
0568:
0569: Enumeration e = servletRequest.getParameterNames();
0570:
0571: while (e.hasMoreElements())
0572: nameVector.addElement(e.nextElement());
0573:
0574: return nameVector.elements();
0575: }
0576:
0577: /**
0578: * Returns the request parameter values associated with the given name.
0579: * @param parameter the hash table key associated with parameter
0580: * @return the parameter values
0581: */
0582: public String[] getParameterValues(String parameter) {
0583: String values[] = null;
0584:
0585: if (isMultipartFormData())
0586: return new String[] { getParameter(parameter) };
0587: else if (servletRequest != null)
0588: return servletRequest.getParameterValues(parameter);
0589:
0590: return null;
0591: }
0592:
0593: /**
0594: * Returns the request attribute associated with the given name.
0595: * @param itemName the hash table key associated with the attribute
0596: * @return the attribute
0597: */
0598: public <T> T getAttribute(String itemName) {
0599: if (servletRequest != null)
0600: return (T) servletRequest.getAttribute(itemName);
0601:
0602: return null;
0603: }
0604:
0605: /**
0606: * Returns the request attribute associated with the given name.
0607: * @param itemName the hash table key associated with the attribute
0608: * @param defaultValue if the attribute does not exist, return the default value.
0609: * @return the attribute
0610: */
0611: public <T> T getAttribute(String itemName, T defaultValue) {
0612: T obj = null;
0613:
0614: if (servletRequest != null)
0615: obj = (T) servletRequest.getAttribute(itemName);
0616:
0617: if (obj != null)
0618: return obj;
0619:
0620: return defaultValue;
0621: }
0622:
0623: /**
0624: * Anything set with setAttribute() is available to page authors and is the best way to pass objects on to the view.
0625: * @param itemName the attribute name/key
0626: * @param item is the Object to be stored in the request for later access during request processing
0627: */
0628: public void setAttribute(String itemName, Object item) {
0629: if (servletRequest != null)
0630: servletRequest.setAttribute(itemName, item);
0631: }
0632:
0633: /**
0634: * Removes an attribute from the request.
0635: * @param itemName the attribute name/key
0636: */
0637: public void removeAttribute(String itemName) {
0638: if (servletRequest != null)
0639: servletRequest.removeAttribute(itemName);
0640: }
0641:
0642: /**
0643: * Returns a session attribute. This is the way to keep user oriented information between requests.
0644: * @param itemName the hash key associated with the stored object.
0645: * @return the stored object
0646: */
0647: public <T> T getSessionAttribute(String itemName) {
0648: if (servletRequest != null)
0649: return (T) servletRequest.getSession().getAttribute(
0650: itemName);
0651:
0652: return null;
0653: }
0654:
0655: /**
0656: * Returns a session attribute. This is the way to keep user oriented information between requests.
0657: * @param itemName the hash key associated with the stored object.
0658: * @param defaultValue if the attribute does not exist, return the default value.
0659: * @return the stored object
0660: */
0661: public <T> T getSessionAttribute(String itemName, T defaultValue) {
0662: T obj = null;
0663:
0664: if (servletRequest != null)
0665: obj = (T) servletRequest.getSession()
0666: .getAttribute(itemName);
0667:
0668: if (obj != null)
0669: return obj;
0670:
0671: return defaultValue;
0672: }
0673:
0674: /**
0675: * Sets a session attribute. This is the way to keep user oriented information between requests.
0676: * @param itemName the hash key associated with the stored object.
0677: * @param item the object to store
0678: */
0679: public void setSessionAttribute(String itemName, Object item) {
0680: if (servletRequest != null)
0681: servletRequest.getSession().setAttribute(itemName, item);
0682: }
0683:
0684: /**
0685: * Removes a session attribute.
0686: * @param itemName the hash key associated with the stored object.
0687: */
0688: public void removeSessionAttribute(String itemName) {
0689: if (servletRequest != null)
0690: servletRequest.getSession().removeAttribute(itemName);
0691: }
0692:
0693: /**
0694: * Returns the last exception set with setException().
0695: * @return the last exception set with setException().
0696: */
0697: public Exception getException() {
0698: return (Exception) getAttribute("jwaException");
0699: }
0700:
0701: /**
0702: * Sets an exception and makes it available to the view via "jwaException".
0703: *
0704: * @param exception any valid instance of Exception or a subclass.
0705: */
0706: public void setException(Exception exception) {
0707: setAttribute("jwaException", exception);
0708: }
0709:
0710: /**
0711: * Returns the set error code.
0712: * @return the error code
0713: */
0714: public Integer getErrorCode() {
0715: Integer val = (Integer) getAttribute("jwaErrorCode");
0716:
0717: return val != null ? val : new Integer(0);
0718: }
0719:
0720: /**
0721: * Returns the set error message.
0722: * @return the error message
0723: */
0724: public String getErrorMessage() {
0725: String str = (String) getAttribute("jwaErrorMessage");
0726:
0727: return str != null ? str : "";
0728: }
0729:
0730: /**
0731: * Set the error message. This is the method for passing error information back to the user.
0732: * @param errorMessage the error message
0733: */
0734: public void setErrorMessage(String errorMessage) {
0735: setErrorMessage(0, errorMessage);
0736: }
0737:
0738: /**
0739: * Set the error code and the error message. This is the method for passing error information back to the user.
0740: * @param errorCode the error code
0741: * @param errorMessage the error message
0742: */
0743: public void setErrorMessage(int errorCode, String errorMessage) {
0744: setErrorMessage(errorCode, errorMessage, true);
0745: }
0746:
0747: /**
0748: * Set the error code and the error message. This is the method for passing error information back to the user.
0749: * @param errorCode the error code
0750: * @param errorMessage the error message
0751: * @param overwrite Overwrite the current message
0752: */
0753: public void setErrorMessage(int errorCode, String errorMessage,
0754: boolean overwrite) {
0755: setAttribute("jwaErrorCode", new Integer(errorCode));
0756:
0757: if (overwrite)
0758: setAttribute("jwaErrorMessage", errorMessage);
0759: else {
0760: String msg = getErrorMessage();
0761:
0762: if (msg != null && msg.length() > 0)
0763: msg += "<br>\n";
0764:
0765: setAttribute("jwaErrorMessage", msg + errorMessage);
0766: }
0767: }
0768:
0769: /**
0770: * Returns the set warning code.
0771: * @return the warning code
0772: */
0773: public Integer getWarningCode() {
0774: Integer val = (Integer) getAttribute("jwaWarningCode");
0775:
0776: return val != null ? val : new Integer(0);
0777: }
0778:
0779: /**
0780: * Returns the set warning message.
0781: * @return the warning message
0782: */
0783: public String getWarningMessage() {
0784: String str = (String) getAttribute("jwaWarningMessage");
0785:
0786: return str != null ? str : "";
0787: }
0788:
0789: /**
0790: * Set the warning message. This is the method for passing warning information back to the user.
0791: * @param warningMessage the warning message
0792: */
0793: public void setWarningMessage(String warningMessage) {
0794: setWarningMessage(0, warningMessage);
0795: }
0796:
0797: /**
0798: * Set the warning code and the warning message. This is the method for passing warning information back to the user.
0799: * @param warningCode the warning code
0800: * @param warningMessage the warning message
0801: */
0802: public void setWarningMessage(int warningCode, String warningMessage) {
0803: setWarningMessage(warningCode, warningMessage, true);
0804: }
0805:
0806: /**
0807: * Set the warning code and the warning message. This is the method for passing warning information back to the user.
0808: * @param warningCode the warning code
0809: * @param warningMessage the warning message
0810: * @param overwrite Overwrite the current message
0811: */
0812: public void setWarningMessage(int warningCode,
0813: String warningMessage, boolean overwrite) {
0814: setAttribute("jwaWarningCode", new Integer(warningCode));
0815:
0816: if (overwrite)
0817: setAttribute("jwaWarningMessage", warningMessage);
0818: else {
0819: String msg = getWarningMessage();
0820:
0821: if (msg != null && msg.length() > 0)
0822: msg += "<br>\n";
0823:
0824: setAttribute("jwaWarningMessage", msg + warningMessage);
0825: }
0826: }
0827:
0828: /**
0829: * Returns the set application code.
0830: * @return the application code
0831: */
0832: public Integer getApplicationCode() {
0833: Integer val = (Integer) getAttribute("jwaApplicationCode");
0834:
0835: return val != null ? val : new Integer(0);
0836: }
0837:
0838: /**
0839: * Returns the set application message.
0840: * @return the application message
0841: */
0842: public String getApplicationMessage() {
0843: String str = (String) getAttribute("jwaApplicationMessage");
0844:
0845: return str != null ? str : "";
0846: }
0847:
0848: /**
0849: * Set the application message. This is the method for passing application related information back to the user.
0850: * @param applicationMessage the application message
0851: */
0852: public void setApplicationMessage(String applicationMessage) {
0853: setApplicationMessage(0, applicationMessage);
0854: }
0855:
0856: /**
0857: * Set the application code and the application message. This is the method for passing application related information back to the user.
0858: * @param applicationCode the application code
0859: * @param applicationMessage the application message
0860: */
0861: public void setApplicationMessage(int applicationCode,
0862: String applicationMessage) {
0863: setApplicationMessage(applicationCode, applicationMessage, true);
0864: }
0865:
0866: /**
0867: * Set the application code and the application message. This is the method for passing application related information back to the user.
0868: * @param applicationCode the application code
0869: * @param applicationMessage the application message
0870: * @param overwrite Overwrite the current message
0871: */
0872: public void setApplicationMessage(int applicationCode,
0873: String applicationMessage, boolean overwrite) {
0874: setAttribute("jwaApplicationCode", new Integer(applicationCode));
0875:
0876: if (overwrite)
0877: setAttribute("jwaApplicationMessage", applicationMessage);
0878: else {
0879: String msg = getApplicationMessage();
0880:
0881: if (msg != null && msg.length() > 0)
0882: msg += "<br>\n";
0883:
0884: setAttribute("jwaApplicationMessage", msg
0885: + applicationMessage);
0886: }
0887: }
0888:
0889: String resolveForwardReferences(UrlData urlData)
0890: throws JWebAppException {
0891: if (urlData != null) {
0892: String url = urlData.getUrl();
0893:
0894: while (url.indexOf("${") != -1) {
0895: if (url.indexOf('}') == -1)
0896: throw new JWebAppException(
0897: "URL syntax error: URL id="
0898: + urlData.getId() + ", url=" + url);
0899:
0900: urlData = dataManager.getUrlData(url.substring(url
0901: .indexOf("${") + 2, url.indexOf("}")));
0902:
0903: url = url.substring(0, url.indexOf("${"))
0904: + resolveForwardReferences(urlData)
0905: + url.substring(url.indexOf("}") + 1);
0906: }
0907:
0908: return url;
0909: }
0910:
0911: return null;
0912: }
0913:
0914: String getBuiltUri(UrlData urlData, boolean includeServletPath)
0915: throws JWebAppException {
0916: String forwardUri = resolveForwardReferences(urlData), returnUri = "";
0917:
0918: try {
0919: returnUri += getServletRequest().getContextPath();
0920:
0921: if (includeServletPath
0922: && getServletRequest().getPathInfo() != null)
0923: returnUri += getServletRequest().getServletPath();
0924:
0925: if (forwardUri.charAt(0) != '/')
0926: returnUri += "/";
0927: } catch (Exception e) {
0928: throw new JWebAppException(e);
0929: }
0930:
0931: returnUri += forwardUri;
0932:
0933: return returnUri;
0934: }
0935:
0936: public String getAbsoluteUri(String path, boolean includeServletPath)
0937: throws JWebAppException {
0938: try {
0939: return getBuiltUri(new UrlData(null, null, path),
0940: includeServletPath);
0941: } catch (Exception e) {
0942: throw new RuntimeException(e);
0943: }
0944: }
0945:
0946: public String getAbsoluteUri(String path) throws JWebAppException {
0947: return getAbsoluteUri(path, true);
0948: }
0949:
0950: String getBuiltUrl(UrlData urlData, boolean fullUrl,
0951: boolean includeServletPath, boolean rewrite)
0952: throws JWebAppException {
0953: String requestProtocol = getServletRequest().getScheme(), protocol = urlData
0954: .getProtocol() != null ? urlData.getProtocol()
0955: : requestProtocol;
0956: String forwardUrl = resolveForwardReferences(urlData), returnUrl = "";
0957:
0958: try {
0959: URI uri = new URI(forwardUrl);
0960:
0961: if (fullUrl && forwardUrl != null && protocol != null
0962: && uri.getScheme() == null) {
0963: returnUrl = protocol
0964: + "://"
0965: + (useDomainName == null ? getServletRequest()
0966: .getServerName() : useDomainName);
0967:
0968: int port = getServletRequest().getServerPort();
0969:
0970: if (port != 80 && port != 443)
0971: returnUrl += ":" + port;
0972:
0973: if (forwardUrl.charAt(0) != '/') {
0974: returnUrl += getServletRequest().getContextPath();
0975:
0976: if (includeServletPath
0977: && getServletRequest().getPathInfo() != null)
0978: returnUrl += getServletRequest()
0979: .getServletPath();
0980: }
0981:
0982: if (forwardUrl.charAt(0) != '/')
0983: returnUrl += "/";
0984: }
0985: } catch (Exception e) {
0986: throw new JWebAppException(e);
0987: }
0988:
0989: returnUrl += forwardUrl;
0990:
0991: if (rewrite)
0992: if (urlData.isRewrite())
0993: if (urlData.isRedirect())
0994: returnUrl = getServletResponse().encodeRedirectURL(
0995: returnUrl);
0996: else
0997: returnUrl = getServletResponse().encodeURL(
0998: returnUrl);
0999:
1000: return returnUrl;
1001: }
1002:
1003: public String getAbsoluteUrl(String contextRelativePath) {
1004: return getAbsoluteUrl(contextRelativePath, false);
1005: }
1006:
1007: public String getAbsoluteUrl(String contextRelativePath,
1008: boolean rewrite) {
1009: return getAbsoluteUrl(contextRelativePath, getServletRequest()
1010: .getScheme(), true, rewrite);
1011: }
1012:
1013: public String getAbsoluteUrl(String contextRelativePath,
1014: boolean includeServletPath, boolean rewrite) {
1015: return getAbsoluteUrl(contextRelativePath, getServletRequest()
1016: .getScheme(), includeServletPath, rewrite);
1017: }
1018:
1019: public String getAbsoluteUrl(String contextRelativePath,
1020: String protocol, boolean includeServletPath, boolean rewrite) {
1021: try {
1022: return getBuiltUrl(new UrlData(null, protocol,
1023: contextRelativePath), true, includeServletPath,
1024: rewrite);
1025: } catch (Exception e) {
1026: throw new RuntimeException(e);
1027: }
1028: }
1029:
1030: public String getUrl(String key) {
1031: return getUrl(key, false, false);
1032: }
1033:
1034: public String getUrl(String key, boolean fullUrl, boolean rewrite) {
1035: return (String) urlDataWrapper.get(key, fullUrl, rewrite);
1036: }
1037:
1038: public String getMessage(String key) {
1039: return dataManager.getMessage(key);
1040: }
1041:
1042: UrlDataWrapper getUrlDataWrapper() {
1043: return urlDataWrapper;
1044: }
1045:
1046: class UrlDataWrapper implements Map {
1047: public void clear() {
1048: }
1049:
1050: public boolean containsKey(Object obj) {
1051: return dataManager.getUrlDataHash().containsKey(obj);
1052: }
1053:
1054: public boolean containsValue(Object obj) {
1055: return dataManager.getUrlDataHash().containsValue(obj);
1056: }
1057:
1058: public java.util.Set entrySet() {
1059: return dataManager.getUrlDataHash().entrySet();
1060: }
1061:
1062: public boolean isEmpty() {
1063: return dataManager.getUrlDataHash().isEmpty();
1064: }
1065:
1066: public Set keySet() {
1067: return dataManager.getUrlDataHash().keySet();
1068: }
1069:
1070: public Object put(Object obj, Object obj1) {
1071: return null;
1072: }
1073:
1074: public void putAll(Map map) {
1075: }
1076:
1077: public Object remove(Object obj) {
1078: return null;
1079: }
1080:
1081: public int size() {
1082: return dataManager.getUrlDataHash().size();
1083: }
1084:
1085: public java.util.Collection values() {
1086: return dataManager.getUrlDataHash().values();
1087: }
1088:
1089: public Object get(Object obj) {
1090: return get(obj, true, urlRewriting);
1091: }
1092:
1093: public Object get(Object obj, boolean fullUrl, boolean rewrite) {
1094: UrlData urlData = dataManager.getUrlData((String) obj);
1095:
1096: if (urlData == null) {
1097: log("URL data (defined with jwaUrl, forward, redirect) not found for key "
1098: + (String) obj);
1099:
1100: return null;
1101: }
1102:
1103: try {
1104: return getBuiltUrl(urlData, fullUrl, true, rewrite);
1105: } catch (Exception e) {
1106: throw new RuntimeException(e);
1107: }
1108: }
1109: }
1110:
1111: /**
1112: * Returns an instance of MultipartFormData, which contains all the information
1113: * and abilities needed for dealing with multipart form data.
1114: * @param parameter the parameter of interest
1115: * @return an instance of MultipartFormData
1116: */
1117: public MultipartFormData getMultipartFormData(String parameter) {
1118: if (multipartFormDataHash == null)
1119: loadMultipartFormData();
1120:
1121: return (MultipartFormData) multipartFormDataHash.get(parameter);
1122: }
1123:
1124: /**
1125: * Returns returns the string data associated with the form data defined by parameter.
1126: * @param parameter the parameter of interest
1127: * @return a string containing the form data
1128: */
1129: public String getMultipartFormParameter(String parameter) {
1130: MultipartFormData formData = getMultipartFormData(parameter);
1131:
1132: if (formData != null && formData.isFormField())
1133: return formData.getString();
1134:
1135: return null;
1136: }
1137:
1138: /**
1139: * Returns a vector of MultipartFormData objects representing the form data.
1140: * @return a vector of MultipartFormData objects
1141: */
1142: public Vector getMultipartFormDataVector() {
1143: if (multipartFormDataVector == null)
1144: loadMultipartFormData();
1145:
1146: return multipartFormDataVector;
1147: }
1148:
1149: /**
1150: * Returns a Hashtable of MultipartFormData objects representing the form data
1151: * that are keyed by parameter Id.
1152: * @return a Hashtable of MultipartFormData objects
1153: */
1154: public Hashtable getMultipartFormDataHashtable() {
1155: if (multipartFormDataHash == null)
1156: loadMultipartFormData();
1157:
1158: return multipartFormDataHash;
1159: }
1160:
1161: public boolean isMultipartFormData() {
1162: String contentType = getServletRequest().getContentType();
1163:
1164: return multipartFormDataHash != null
1165: || (contentType != null && contentType.toLowerCase()
1166: .startsWith("multipart"));
1167: }
1168:
1169: /**
1170: * Loads the multipart form data. Uses the defaults of 102400 for file
1171: * threshold and "/WEB-INF/secure_uploads" for the file directory.
1172: */
1173: public void loadMultipartFormData() {
1174: File file = new File(getServletContext().getRealPath(
1175: "/WEB-INF/secure_uploads"));
1176:
1177: if (!file.exists())
1178: file.mkdirs();
1179:
1180: loadMultipartFormData(102400, file);
1181: }
1182:
1183: /**
1184: * Loads the multipart form data and allows definition of file size threshold
1185: * and temp file repository for uploads. The file size threshold defines whether uploaded files will
1186: * be stored in memory (equal or less than threshold) or on disk (greater than threshold).
1187: * @param sizeThreshold the size value at which files will be written to disk
1188: * @param tempRepository the file directory to write the files to
1189: */
1190: public void loadMultipartFormData(int sizeThreshold,
1191: File tempRepository) {
1192: if (isMultipartFormData())
1193: try {
1194: ServletFileUpload fileUpload = new ServletFileUpload(
1195: new DiskFileItemFactory(sizeThreshold,
1196: tempRepository));
1197: List fileList = fileUpload
1198: .parseRequest(getServletRequest());
1199:
1200: Iterator i = fileList.iterator();
1201:
1202: multipartFormDataVector = new Vector();
1203: multipartFormDataHash = new Hashtable();
1204:
1205: while (i.hasNext()) {
1206: MultipartFormData formData = new MultipartFormData(
1207: (DiskFileItem) i.next());
1208:
1209: multipartFormDataVector.addElement(formData);
1210: multipartFormDataHash.put(formData.getFieldName(),
1211: formData);
1212: }
1213: } catch (Exception e) {
1214: log("Could not parse multi part form data");
1215: log(e.toString(), e);
1216: }
1217: }
1218:
1219: /**
1220: * Class representing a multipart form element and methods to manipulate
1221: * and retreive form element data.
1222: */
1223: public static class MultipartFormData {
1224: DiskFileItem fileItem;
1225:
1226: MultipartFormData(DiskFileItem fileItem) {
1227: this .fileItem = fileItem;
1228: }
1229:
1230: /**
1231: * Returns the character set definition.
1232: * @return a String
1233: */
1234: public String getCharSet() {
1235: return fileItem.getCharSet();
1236: }
1237:
1238: /**
1239: * delete the multipart uploaded file from memory or disk.
1240: */
1241: public void delete() {
1242: fileItem.delete();
1243: }
1244:
1245: /**
1246: * Returns the content type.
1247: * @return a String
1248: */
1249: public String getContentType() {
1250: return fileItem.getContentType();
1251: }
1252:
1253: /**
1254: * Returns the field name as defined in the HTML form element.
1255: * @return a String
1256: */
1257: public String getFieldName() {
1258: return fileItem.getFieldName();
1259: }
1260:
1261: /**
1262: * Returns the multipart form elements value in bytes. Suitable for small file uploads.
1263: * @return an array of bytes
1264: */
1265: public byte[] getBytes() {
1266: return fileItem.get();
1267: }
1268:
1269: /**
1270: * The name of the file selected by the user for upload (see HTML <input type="file" ...>).
1271: * @return a String
1272: */
1273: public String getName() {
1274: return fileItem.getName();
1275: }
1276:
1277: /**
1278: * Returns the size of the data value.
1279: * @return a long
1280: */
1281: public long getSize() {
1282: return fileItem.getSize();
1283: }
1284:
1285: /**
1286: * Returns an InputStream that can be used to read the uploaded file.
1287: * @return an instance of InputStream
1288: */
1289: public InputStream getInputStream() throws JWebAppException {
1290: try {
1291: return fileItem.getInputStream();
1292: } catch (Exception e) {
1293: throw new JWebAppException(e);
1294: }
1295: }
1296:
1297: //public OutputStream getOutputStream() { return fileItem.getOutputStream(); }
1298:
1299: /**
1300: * Returns the data value as a string.
1301: * @return a String
1302: */
1303: public String getString() {
1304: return fileItem.getString();
1305: }
1306:
1307: /**
1308: * Returns the data value as a string.
1309: * @param encodingType the encoding type for the string
1310: * @return a String
1311: */
1312: public String getString(String encodingType)
1313: throws JWebAppException {
1314: try {
1315: return fileItem.getString(encodingType);
1316: } catch (Exception e) {
1317: throw new JWebAppException(e);
1318: }
1319: }
1320:
1321: /**
1322: * Returns true if the multipart form data element is a simple form value.
1323: * @return true if the multipart form data element is a simple form value, false otherwise
1324: */
1325: public boolean isFormField() {
1326: return fileItem.isFormField();
1327: }
1328:
1329: /**
1330: * Returns true if the uploaded file is stored in memory.
1331: * @return true if the uploaded file is stored in memory, false if stored on disk
1332: */
1333: public boolean isInMemory() {
1334: return fileItem.isInMemory();
1335: }
1336:
1337: /**
1338: * Write the uploaded file to a new location.
1339: * @param file the new files location
1340: */
1341: public void write(String file) throws JWebAppException {
1342: try {
1343: write(new File(file));
1344: } catch (Exception e) {
1345: throw new JWebAppException(e);
1346: }
1347: }
1348:
1349: /**
1350: * Write the uploaded file to a new location.
1351: * @param file the new files location
1352: */
1353: public void write(File file) throws JWebAppException {
1354: try {
1355: fileItem.write(file);
1356: } catch (Exception e) {
1357: throw new JWebAppException(e);
1358: }
1359: }
1360: }
1361: }
|