List of usage examples for javax.servlet.jsp PageContext getResponse
abstract public ServletResponse getResponse();
From source file:dk.netarkivet.archive.webinterface.BatchGUI.java
/** * Method for creating the batchjob overview page. Creates both the heading and the table for the batchjobs defined * in settings.// ww w. j a va2s. c o m * * @param context The context of the page. Contains the locale for the language package. * @throws ArgumentNotValid If the PageContext is null. * @throws IOException If it is not possible to write to the JspWriter. */ public static void getBatchOverviewPage(PageContext context) throws ArgumentNotValid, IOException { ArgumentNotValid.checkNotNull(context, "PageContext context"); JspWriter out = context.getOut(); // retrieve the jobs etc. String[] jobs = Settings.getAll(CommonSettings.BATCHJOBS_CLASS); Locale locale = context.getResponse().getLocale(); if (jobs.length == 0) { out.print("<h3>" + I18N.getString(locale, "batchpage;No.batchjobs.defined.in.settings", new Object[] {}) + "</h3>"); return; } // add header for batchjob selection table out.print("<table class=\"selection_table\" cols=\"4\">\n"); out.print(" <tr>\n"); out.print(" <th>" + I18N.getString(locale, "batchpage;Batchjob", new Object[] {}) + "</th>\n"); out.print(" <th>" + I18N.getString(locale, "batchpage;Last.run", new Object[] {}) + "</th>\n"); out.print(" <th>" + I18N.getString(locale, "batchpage;Output.file", new Object[] {}) + "</th>\n"); out.print(" <th>" + I18N.getString(locale, "batchpage;Error.file", new Object[] {}) + "</th>\n"); out.print(" </tr>\n"); for (int i = 0; i < jobs.length; i++) { out.print(" <tr Class=\"" + HTMLUtils.getRowClass(i) + "\">\n"); out.print(getOverviewTableEntry(jobs[i], locale)); out.print(" </tr>\n"); } out.print("</table>\n"); }
From source file:dk.netarkivet.archive.webinterface.BatchGUI.java
/** * Method for creating the page for a batchjob. It contains the following informations: * <p>/*from w w w.j a v a2 s .c o m*/ * <br/> * - Creates a line with the name of the batchjob.<br/> * - Write the description if the batchjob has a metadata resource annotation description of the batchjob class.<br/> * - The last run information, date and size of the error and output files. <br/> * - The arguments of the batchjob, with information if they have been defined in the resource annotations of the * class.<br/> * - Radio buttons for choosing the replica.<br/> * - Input box for regular expression for filenames to match.<br/> * - Execution button.<br/> * * @param context The context of the page. Must contains a class name of the batchjob. * @throws UnknownID If the class cannot be found. * @throws ArgumentNotValid If the context is null. * @throws IllegalState If the class is not an instance of FileBatchJob. * @throws ForwardedToErrorPage If the context does not contain the required information. * @throws IOFailure If there is problems with the JspWriter. */ @SuppressWarnings("rawtypes") public static void getPageForClass(PageContext context) throws UnknownID, ArgumentNotValid, IllegalState, ForwardedToErrorPage, IOFailure { ArgumentNotValid.checkNotNull(context, "PageContext context"); HTMLUtils.forwardOnEmptyParameter(context, Constants.BATCHJOB_PARAMETER); try { // Retrieve variables Locale locale = context.getResponse().getLocale(); ServletRequest request = context.getRequest(); String className = request.getParameter(Constants.BATCHJOB_PARAMETER); JspWriter out = context.getOut(); // retrieve the batch class and the constructor. Class c = getBatchClass(className); out.print(I18N.getString(locale, "batchpage;Name.of.batchjob", new Object[] {}) + ": <b>" + c.getName() + "</b><br/>\n"); out.print(getClassDescription(c, locale)); out.print(getPreviousRuns(c.getName(), locale)); // begin form out.println("<form method=\"post\" action=\"" + Constants.URL_BATCHJOB_EXECUTE + "?" + Constants.BATCHJOB_PARAMETER + "=" + className + "\">"); out.print(getHTMLarguments(c, locale)); out.print(getReplicaRadioButtons(locale)); out.print(getRegularExpressionInputBox(locale)); out.print(getSubmitButton(locale)); // end form out.print("</form>"); } catch (IOException e) { String errMsg = "Could not create page with batchjobs."; log.warn(errMsg, e); throw new IOFailure(errMsg, e); } }
From source file:dk.netarkivet.common.webinterface.HTMLUtils.java
/** * Forward to our standard error message page with an internationalized message. Note that this <em>doesn't</em> * throw ForwardedToErrorPage, it is the job of whoever calls this to do that if not within a JSP page (a JSP page * can just return immediately). The text involved must be HTML-escaped before passing to this method. * * @param context The context that the error happened in (the JSP-defined pageContext, typically) * @param i18n The i18n information//from w w w. j a va2s . co m * @param label An i18n label for the error. This label should begin with "errormsg;". * @param args Any extra args for i18n. These must be valid HTML. * @throws IOFailure If the forward fails. */ public static void forwardWithRawErrorMessage(PageContext context, I18n i18n, String label, Object... args) { // Note that we may not want to be to strict here // as otherwise information could be lost. ArgumentNotValid.checkNotNull(context, "context"); ArgumentNotValid.checkNotNull(I18N, "I18N"); ArgumentNotValid.checkNotNull(label, "label"); ArgumentNotValid.checkNotNull(args, "args"); String msg = i18n.getString(context.getResponse().getLocale(), label, args); context.getRequest().setAttribute("message", msg); RequestDispatcher rd = context.getServletContext().getRequestDispatcher("/message.jsp"); try { rd.forward(context.getRequest(), context.getResponse()); } catch (IOException e) { final String errormsg = "Failed to forward on error " + msg; log.warn(errormsg, e); throw new IOFailure(errormsg, e); } catch (ServletException e) { final String errormsg = "Failed to forward on error " + msg; log.warn(errormsg, e); throw new IOFailure(errormsg, e); } }
From source file:dk.netarkivet.common.webinterface.HTMLUtils.java
/** * Forward to our standard error message page with an internationalized message. Note that this <em>doesn't</em> * throw ForwardedToErrorPage, it is the job of whoever calls this to do that if not within a JSP page (a JSP page * can just return immediately). All text involved will be HTML-escaped. * * @param context The context that the error happened in (the JSP-defined pageContext, typically) * @param I18N The i18n information/*from w ww .j a v a 2 s. co m*/ * @param label An i18n label for the error. This label should begin with "errormsg;". * @param args Any extra args for i18n * @throws IOFailure If the forward fails */ public static void forwardWithErrorMessage(PageContext context, I18n I18N, String label, Object... args) { // Note that we may not want to be to strict here // as otherwise information could be lost. ArgumentNotValid.checkNotNull(context, "context"); ArgumentNotValid.checkNotNull(I18N, "I18N"); ArgumentNotValid.checkNotNull(label, "label"); ArgumentNotValid.checkNotNull(args, "args"); String msg = HTMLUtils.escapeHtmlValues(I18N.getString(context.getResponse().getLocale(), label, args)); context.getRequest().setAttribute("message", msg); RequestDispatcher rd = context.getServletContext().getRequestDispatcher("/message.jsp"); final String errormsg = "Failed to forward on error " + msg; try { rd.forward(context.getRequest(), context.getResponse()); } catch (IOException e) { log.warn(errormsg, e); throw new IOFailure(errormsg, e); } catch (ServletException e) { log.warn(errormsg, e); throw new IOFailure(errormsg, e); } }
From source file:dk.netarkivet.common.webinterface.HTMLUtils.java
/** * Forward to our standard error message page with an internationalized message, in case of exception. Note that * this <em>doesn't</em> throw ForwardedToErrorPage, it is the job of whoever calls this to do that if not within a * JSP page (a JSP page can just return immediately). All text involved will be HTML-escaped. * * @param context The context that the error happened in (the JSP-defined pageContext, typically) * @param i18n The i18n information/*from w w w .j a va 2 s. c om*/ * @param e The exception that is being handled. * @param label An i18n label for the error. This label should begin with "errormsg;". * @param args Any extra args for i18n * @throws IOFailure If the forward fails */ public static void forwardWithErrorMessage(PageContext context, I18n i18n, Throwable e, String label, Object... args) { // Note that we may not want to be to strict here // as otherwise information could be lost. ArgumentNotValid.checkNotNull(context, "context"); ArgumentNotValid.checkNotNull(I18N, "I18N"); ArgumentNotValid.checkNotNull(label, "label"); ArgumentNotValid.checkNotNull(args, "args"); String msg = HTMLUtils.escapeHtmlValues(i18n.getString(context.getResponse().getLocale(), label, args)); context.getRequest().setAttribute("message", msg + "\n" + e.getLocalizedMessage()); RequestDispatcher rd = context.getServletContext().getRequestDispatcher("/message.jsp"); final String errormsg = "Failed to forward on error " + msg; try { rd.forward(context.getRequest(), context.getResponse()); } catch (IOException e1) { log.warn(errormsg, e1); throw new IOFailure(errormsg, e1); } catch (ServletException e1) { log.warn(errormsg, e1); throw new IOFailure(errormsg, e1); } }
From source file:dk.netarkivet.archive.webinterface.BitpreserveFileState.java
/** * Processes a missingFiles request./*w w w .j a v a2s . c om*/ * <p> * Parameters of the form Constants.ADD_COMMAND=<bitarchive>##<filename> causes the file to be added to * that bitarchive, if it is missing. * <p> * Parameters of the form Constants.GET_INFO_COMMAND=<filename> causes checksums to be computed for the file * in all bitarchives and the information to be shown in the next update (notice that this information disappears * when the page is next reloaded). * * @param context the current JSP context. * @param res the result object. This is updated with result information, and expected to be printed to the * resulting page. * @return A map of info gathered for files as requested. * @throws ArgumentNotValid If the context or res is null. * @throws ForwardedToErrorPage if the commands have the wrong number of arguments. */ public static Map<String, PreservationState> processMissingRequest(PageContext context, StringBuilder res) throws ArgumentNotValid, ForwardedToErrorPage { ArgumentNotValid.checkNotNull(context, "PageContext context"); ArgumentNotValid.checkNotNull(res, "StringBuilder res"); Map<String, String[]> params = context.getRequest().getParameterMap(); HTMLUtils.forwardOnMissingParameter(context, Constants.BITARCHIVE_NAME_PARAM); String bitarchiveName = params.get(Constants.BITARCHIVE_NAME_PARAM)[0]; if (!Replica.isKnownReplicaName(bitarchiveName)) { List<String> names = new ArrayList<String>(); HTMLUtils.forwardOnIllegalParameter(context, Constants.BITARCHIVE_NAME_PARAM, StringUtils.conjoin(", ", names.toArray(Replica.getKnownNames()))); } ActiveBitPreservation preserve = ActiveBitPreservationFactory.getInstance(); Locale l = context.getResponse().getLocale(); if (params.containsKey(Constants.ADD_COMMAND)) { String[] adds = params.get(Constants.ADD_COMMAND); for (String s : adds) { String[] parts = s.split(Constants.STRING_FILENAME_SEPARATOR); checkArgs(context, parts, Constants.ADD_COMMAND, "bitarchive name", "filename"); final Replica ba = Replica.getReplicaFromName(parts[0]); final String filename = parts[1]; try { preserve.uploadMissingFiles(ba, filename); res.append(HTMLUtils.escapeHtmlValues( I18N.getString(l, "file.0.has.been.restored.in.replica.on.1", filename, ba.getName()))); res.append("<br/>"); } catch (Exception e) { res.append(I18N.getString(l, "errormsg;attempt.at.restoring.0.in.replica" + ".at.1.failed", filename, ba)); res.append("<br/>"); res.append(e.getMessage()); res.append("<br/>"); log.warn("Could not restore file '" + filename + "' in bitarchive '" + ba + "'", e); } } } // A map ([filename] -> [preservationstate]) to contain // preservationstates for all files retrieved from the // parameter Constants.GET_INFO_COMMAND. // This map is an empty map, if this parameter is undefined. Map<String, PreservationState> infoMap; // Do this at the end so that the info reflects the current state. if (params.containsKey(Constants.GET_INFO_COMMAND)) { String[] getInfos = params.get(Constants.GET_INFO_COMMAND); infoMap = preserve.getPreservationStateMap(getInfos); } else { infoMap = new HashMap<String, PreservationState>(); } return infoMap; }
From source file:com.ecyrd.jspwiki.filters.SpamFilter.java
/** * This method checks if the hash value is still valid, i.e. if it exists at all. This * can occur in two cases: either this is a spam bot which is not adaptive, or it is * someone who has been editing one page for too long, and their session has expired. * <p>//w ww . j a v a2s.c o m * This method puts a redirect to the http response field to page "SessionExpired" * and logs the incident in the spam log (it may or may not be spam, but it's rather likely * that it is). * * @param context The WikiContext * @param pageContext The JSP PageContext. * @return True, if hash is okay. False, if hash is not okay, and you need to redirect. * @throws IOException If redirection fails * @since 2.6 */ public static final boolean checkHash(WikiContext context, PageContext pageContext) throws IOException { String hashName = getHashFieldName((HttpServletRequest) pageContext.getRequest()); if (pageContext.getRequest().getParameter(hashName) == null) { if (pageContext.getAttribute(hashName) == null) { Change change = getChange(context, EditorManager.getEditedText(pageContext)); log(context, REJECT, "MissingHash", change.m_change); String redirect = context.getURL(WikiContext.VIEW, "SessionExpired"); ((HttpServletResponse) pageContext.getResponse()).sendRedirect(redirect); return false; } } return true; }
From source file:dk.netarkivet.archive.webinterface.BitpreserveFileState.java
/** * Extract the name of the replica (parameter Constants.BITARCHIVE_NAME_PARAM) and the type of update requested * (parameter Constants.UPDATE_TYPE_PARAM). The latter is set to to Constants.FIND_MISSING_FILES_OPTION if the * request is to update missing files, or to Constants.CHECKSUM_OPTION if the request is to update the checksum * information./*from w w w . j a va 2s . c om*/ * * @param context the current JSP context * @return an I18N string telling which type of update has just been initiated. * @throws ForwardedToErrorPage if an unknown bitarchive or update type is posted, or one of the two required * parameters are missing. * @throws ArgumentNotValid If the context is null. */ public static String processUpdateRequest(PageContext context) throws ArgumentNotValid, ForwardedToErrorPage { ArgumentNotValid.checkNotNull(context, "PageContext context"); ServletRequest request = context.getRequest(); String bitarchiveName = request.getParameter(Constants.BITARCHIVE_NAME_PARAM); if (bitarchiveName == null) { HTMLUtils.forwardWithErrorMessage(context, I18N, "errormsg;missing.parameter.0", Constants.BITARCHIVE_NAME_PARAM); throw new ForwardedToErrorPage("Parameter '" + Constants.BITARCHIVE_NAME_PARAM + "' not set"); } String updateTypeRequested = request.getParameter(Constants.UPDATE_TYPE_PARAM); if (updateTypeRequested == null) { HTMLUtils.forwardWithErrorMessage(context, I18N, "errormsg;missing.parameter.0", Constants.UPDATE_TYPE_PARAM); throw new ForwardedToErrorPage("Parameter '" + Constants.UPDATE_TYPE_PARAM + "' not set"); } if (!Replica.isKnownReplicaName(bitarchiveName)) { HTMLUtils.forwardWithErrorMessage(context, I18N, "errormsg;unknown.bitarchive.0", bitarchiveName); throw new ForwardedToErrorPage("Unknown replica: " + bitarchiveName); } Replica bitarchive = Replica.getReplicaFromName(bitarchiveName); Locale l = context.getResponse().getLocale(); String statusmessage = HTMLUtils.escapeHtmlValues( I18N.getString(l, "initiating;update.of.0.for.replica.1", updateTypeRequested, bitarchiveName)); if (updateTypeRequested.equalsIgnoreCase(Constants.FIND_MISSING_FILES_OPTION)) { // Start new thread for findmissing files action. new BitpreservationUpdateThread(bitarchive, BitpreservationUpdateType.FINDMISSING).start(); return statusmessage; } else if (updateTypeRequested.equalsIgnoreCase(Constants.CHECKSUM_OPTION)) { // Start new thread for finding corrupt files action. new BitpreservationUpdateThread(bitarchive, BitpreservationUpdateType.CHECKSUM).start(); return statusmessage; } else { HTMLUtils.forwardWithErrorMessage(context, I18N, "errormsg;unknown.filestatus.update.type.0", updateTypeRequested); throw new ForwardedToErrorPage("Unknown filestatus update type: " + bitarchiveName); } }
From source file:ar.com.zauber.commons.web.uri.assets.AssetsTest.java
/** test */ @Test/*from w w w. j ava 2s . c om*/ public final void testAssetsUriFactory() throws Exception { // Creado el servlet final XmlWebApplicationContext ctx = new XmlWebApplicationContext(); ctx.setConfigLocations(new String[] { "classpath:ar/com/zauber/commons/web/uri/assets/" + profile + "-assets-spring.xml", }); ctx.setServletContext(new MockServletContext()); ctx.refresh(); for (int i = 0; i < 2; i++) { // Armo el request final PageContext pageCtx = createPageContext(ctx); // <assets:javascript key="/_js/lib/jquery-1.4.2.js"/> JavascriptTag js = new JavascriptTag(); js.setPageContext(pageCtx); js.setKey("/_js/lib/jquery-1.4.2.js"); js.doStartTag(); js.doEndTag(); // <assets:javascript key="/_js/model/foo.js"/> js = new JavascriptTag(); js.setPageContext(pageCtx); js.setKey("/_js/model/foo.js"); js.setCharset("utf-8"); js.doStartTag(); js.doEndTag(); // <assets:css key="/stylesheet.css"/> final CssTag t = new CssTag(); t.setPageContext(pageCtx); t.setCharset("utf-8"); t.setKey("/stylesheet.css"); t.doStartTag(); t.doEndTag(); // <assets:css key="/stylesheet.css"/> final ImageTag image = new ImageTag(); image.setPageContext(pageCtx); image.setKey("/1.gif"); image.doStartTag(); image.doEndTag(); // <assets:print/> final PrintTag printTag = new PrintTag(); printTag.setPageContext(pageCtx); printTag.doStartTag(); printTag.doEndTag(); // Validaciones final MockHttpServletResponse response = (MockHttpServletResponse) pageCtx.getResponse(); final String result = new String(response.getContentAsByteArray(), "utf8"); final InputStream is = getClass().getResourceAsStream(profile + "-expected.txt"); try { Assert.assertEquals(IOUtils.toString(is), result); } finally { is.close(); } } }
From source file:org.apache.struts.taglib.TagUtils.java
/** * Compute a hyperlink URL based on the <code>forward</code>, * <code>href</code>, <code>action</code> or <code>page</code> parameter * that is not null. The returned URL will have already been passed to * <code>response.encodeURL()</code> for adding a session identifier. * * @param pageContext PageContext for the tag making this call * @param forward Logical forward name for which to look up the * context-relative URI (if specified) * @param href URL to be utilized unmodified (if specified) * @param page Module-relative page for which a URL should be * created (if specified) * @param action Logical action name for which to look up the * context-relative URI (if specified) * @param params Map of parameters to be dynamically included * (if any)//w w w .j ava 2 s . com * @param anchor Anchor to be dynamically included (if any) * @param redirect Is this URL for a <code>response.sendRedirect()</code>? * @param encodeSeparator This is only checked if redirect is set to * false (never encoded for a redirect). If true, * query string parameter separators are encoded * as >amp;, else & is used. * @param useLocalEncoding If set to true, urlencoding is done on the * bytes of character encoding from * ServletResponse#getCharacterEncoding. Use UTF-8 * otherwise. * @return URL with session identifier * @throws java.net.MalformedURLException if a URL cannot be created for * the specified parameters */ public String computeURLWithCharEncoding(PageContext pageContext, String forward, String href, String page, String action, String module, Map params, String anchor, boolean redirect, boolean encodeSeparator, boolean useLocalEncoding) throws MalformedURLException { String charEncoding = "UTF-8"; if (useLocalEncoding) { charEncoding = pageContext.getResponse().getCharacterEncoding(); } // TODO All the computeURL() methods need refactoring! // Validate that exactly one specifier was included int n = 0; if (forward != null) { n++; } if (href != null) { n++; } if (page != null) { n++; } if (action != null) { n++; } if (n != 1) { throw new MalformedURLException(messages.getMessage("computeURL.specifier")); } // Look up the module configuration for this request ModuleConfig moduleConfig = getModuleConfig(module, pageContext); // Calculate the appropriate URL StringBuffer url = new StringBuffer(); HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); if (forward != null) { ForwardConfig forwardConfig = moduleConfig.findForwardConfig(forward); if (forwardConfig == null) { throw new MalformedURLException(messages.getMessage("computeURL.forward", forward)); } // **** removed - see bug 37817 **** // if (forwardConfig.getRedirect()) { // redirect = true; // } if (forwardConfig.getPath().startsWith("/")) { url.append(request.getContextPath()); url.append(RequestUtils.forwardURL(request, forwardConfig, moduleConfig)); } else { url.append(forwardConfig.getPath()); } } else if (href != null) { url.append(href); } else if (action != null) { ActionServlet servlet = (ActionServlet) pageContext.getServletContext() .getAttribute(Globals.ACTION_SERVLET_KEY); String actionIdPath = RequestUtils.actionIdURL(action, moduleConfig, servlet); if (actionIdPath != null) { action = actionIdPath; url.append(request.getContextPath()); url.append(actionIdPath); } else { url.append(instance.getActionMappingURL(action, module, pageContext, false)); } } else /* if (page != null) */ { url.append(request.getContextPath()); url.append(this.pageURL(request, page, moduleConfig)); } // Add anchor if requested (replacing any existing anchor) if (anchor != null) { String temp = url.toString(); int hash = temp.indexOf('#'); if (hash >= 0) { url.setLength(hash); } url.append('#'); url.append(this.encodeURL(anchor, charEncoding)); } // Add dynamic parameters if requested if ((params != null) && (params.size() > 0)) { // Save any existing anchor String temp = url.toString(); int hash = temp.indexOf('#'); if (hash >= 0) { anchor = temp.substring(hash + 1); url.setLength(hash); temp = url.toString(); } else { anchor = null; } // Define the parameter separator String separator = null; if (redirect) { separator = "&"; } else if (encodeSeparator) { separator = "&"; } else { separator = "&"; } // Add the required request parameters boolean question = temp.indexOf('?') >= 0; Iterator keys = params.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); Object value = params.get(key); if (value == null) { if (!question) { url.append('?'); question = true; } else { url.append(separator); } url.append(this.encodeURL(key, charEncoding)); url.append('='); // Interpret null as "no value" } else if (value instanceof String) { if (!question) { url.append('?'); question = true; } else { url.append(separator); } url.append(this.encodeURL(key, charEncoding)); url.append('='); url.append(this.encodeURL((String) value, charEncoding)); } else if (value instanceof String[]) { String[] values = (String[]) value; for (int i = 0; i < values.length; i++) { if (!question) { url.append('?'); question = true; } else { url.append(separator); } url.append(this.encodeURL(key, charEncoding)); url.append('='); url.append(this.encodeURL(values[i], charEncoding)); } } else /* Convert other objects to a string */ { if (!question) { url.append('?'); question = true; } else { url.append(separator); } url.append(this.encodeURL(key, charEncoding)); url.append('='); url.append(this.encodeURL(value.toString(), charEncoding)); } } // Re-add the saved anchor (if any) if (anchor != null) { url.append('#'); url.append(this.encodeURL(anchor, charEncoding)); } } // Perform URL rewriting to include our session ID (if any) // but only if url is not an external URL if ((href == null) && (pageContext.getSession() != null)) { HttpServletResponse response = (HttpServletResponse) pageContext.getResponse(); if (redirect) { return (response.encodeRedirectURL(url.toString())); } return (response.encodeURL(url.toString())); } return (url.toString()); }