List of usage examples for javax.servlet.jsp PageContext getRequest
abstract public ServletRequest getRequest();
From source file:ar.com.zauber.commons.web.uri.UriJspFunctionsTest.java
/** Test que prueba si el pedido es en el mismo segmento ..*/ @Test// w w w .jav a 2 s .com @Ignore(value = "ahora que no se envia el request...") public final void buildUriWithContext() { setException(true); PageContext ctx = getPc(); HttpServletRequest req = getReq(); Mockito.when(req.getRequestURI()).thenReturn("/app/bin/nada"); Mockito.when(req.getContextPath()).thenReturn("/app/bin"); Assert.assertEquals("./abc", UriJspFunctions.buildVarArgs(ctx, "abc", ctx.getRequest())); Assert.assertEquals("./abc", UriJspFunctions.buildVarArgs(ctx, "/abc", ctx.getRequest())); Mockito.when(req.getRequestURI()).thenReturn("/app/bin/nada/par"); Mockito.when(req.getContextPath()).thenReturn("/app/bin"); Assert.assertEquals("../par/abc", UriJspFunctions.buildVarArgs(ctx, "/par/abc", ctx.getRequest())); }
From source file:com.silverpeas.tags.navigation.links.LinkGeneratorImpl.java
/** * Construction de l'url de l'item./* ww w . ja v a 2 s .c om*/ * @param pageContext * @param themetracker * @param node * @param idsTopicsRoots * @param pub * @param prefixId * @return * @throws RemoteException */ public String generateFullSemanticPath(PageContext pageContext, KmeliaTagUtil themetracker, NodeDetail node, String idsTopicsRoots, PublicationDetail pub, String prefixId) throws RemoteException { StringBuffer path = new StringBuffer(); path.append(((HttpServletRequest) pageContext.getRequest()).getContextPath()); path.append("/"); StringTokenizer nodes = new StringTokenizer(node.getPath(), "/"); boolean beginPath = false; while (nodes.hasMoreTokens()) { String nodeId = nodes.nextToken(); if (beginPath) { NodeDetail n = themetracker.getTopic(nodeId); path.append(tranformName(n.getName())); path.append("/"); } else { beginPath = isRootTopic(nodeId, idsTopicsRoots); } } path.append(tranformName(node.getName())); path.append("/"); if (pub != null) { path.append(tranformName(pub.getName())); path.append("/"); } if (prefixId != null) { path.append(prefixId); } path.append(node.getId()); return path.toString(); }
From source file:dk.netarkivet.common.webinterface.HTMLUtils.java
/** * Parses a integer request parameter and checks that it lies within a given interval. If it doesn't, forwards to an * error page and throws ForwardedToErrorPage. * * @param context The context this call happens in * @param param A parameter to parse./*w w w .j a v a 2 s . c o m*/ * @param minValue The minimum allowed value * @param maxValue The maximum allowed value * @return The value x parsed from the string, if minValue <= x <= maxValue * @throws ForwardedToErrorPage if the parameter doesn't exist, is not a parseable integer, or doesn't lie within * the limits. */ public static int parseAndCheckInteger(PageContext context, String param, int minValue, int maxValue) throws ForwardedToErrorPage { // Note that we may not want to be to strict here // as otherwise information could be lost. ArgumentNotValid.checkNotNull(context, "context"); ArgumentNotValid.checkNotNull(param, "param"); Locale loc = HTMLUtils.getLocaleObject(context); forwardOnEmptyParameter(context, param); int value; String paramValue = context.getRequest().getParameter(param); try { value = NumberFormat.getInstance(loc).parse(paramValue).intValue(); if (value < minValue || value > maxValue) { forwardWithErrorMessage(context, I18N, "errormsg;parameter.0.outside.range.1.to.2.3", param, paramValue, minValue, maxValue); throw new ForwardedToErrorPage("Parameter '" + param + "' should be between " + minValue + " and " + maxValue + " but is " + paramValue); } return value; } catch (ParseException e) { forwardWithErrorMessage(context, I18N, "errormsg;parameter.0.not.an.integer.1", param, paramValue); throw new ForwardedToErrorPage("Invalid value " + paramValue + " for integer parameter '" + param + "'", 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 www .j av a 2 s. c o 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:ar.com.zauber.commons.web.uri.UriJspFunctionsTest.java
/** Test de UriJsp sin cotexto*/ @Test//from www . j a v a 2 s . co m @Ignore(value = "ahora que no se envia el request...") public final void buildUriDefault() throws Exception { setException(true); PageContext ctx = getPc(); HttpServletRequest req = getReq(); Mockito.when(req.getRequestURI()).thenReturn("/123/abc/asd/asd"); Mockito.when(req.getContextPath()).thenReturn(StringUtils.EMPTY); Assert.assertEquals("../../../abc", UriJspFunctions.buildVarArgs(ctx, "abc", ctx.getRequest())); }
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 ww . ja va 2 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). 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/*w ww. ja 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 ww w .j ava 2 s . com*/ * @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.harvester.webinterface.TrapCreateOrUpdateAction.java
@Override protected void doAction(PageContext context, I18n i18n) { String name = null;/* ww w. j a va2s . c om*/ boolean isActive = true; String description = null; InputStream is = null; String id = null; String fileName = null; HttpServletRequest request = (HttpServletRequest) context.getRequest(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { HTMLUtils.forwardWithErrorMessage(context, i18n, e, "errormsg;crawlertrap.upload.error"); throw new ForwardedToErrorPage("Error on multipart post", e); } for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals(Constants.TRAP_NAME)) { name = item.getString(); } else if (item.getFieldName().equals(Constants.TRAP_IS_ACTIVE)) { isActive = Boolean.parseBoolean(item.getString()); } else if (item.getFieldName().equals(Constants.TRAP_DESCRIPTION)) { description = item.getString(); } else if (item.getFieldName().equals(Constants.TRAP_ID)) { id = item.getString(); } } else { try { fileName = item.getName(); is = item.getInputStream(); } catch (IOException e) { HTMLUtils.forwardWithErrorMessage(context, i18n, e, "errormsg;crawlertrap.upload.error"); throw new ForwardedToErrorPage("Error on multipart post", e); } } } GlobalCrawlerTrapListDAO dao = GlobalCrawlerTrapListDBDAO.getInstance(); if (id != null) { // update existing trap list int trapId = Integer.parseInt(id); GlobalCrawlerTrapList trap = dao.read(trapId); trap.setActive(isActive); trap.setDescription(description); trap.setName(name); if (fileName != null && !fileName.isEmpty()) { log.debug("Reading global crawler trap list from '" + fileName + "'"); try { trap.setTrapsFromInputStream(is, name); } catch (ArgumentNotValid argumentNotValid) { HTMLUtils.forwardWithErrorMessage(context, i18n, "errormsg;crawlertrap.regexp.error"); throw new ForwardedToErrorPage(argumentNotValid.getMessage()); } } dao.update(trap); } else { // create new trap list log.debug("Reading global crawler trap list from '" + fileName + "'"); GlobalCrawlerTrapList trap = new GlobalCrawlerTrapList(is, name, description, isActive); if (!dao.exists(name)) { dao.create(trap); } else { // crawlertrap named like this already exists. HTMLUtils.forwardWithErrorMessage(context, i18n, "errormsg;crawlertrap.0.exists.error", name); throw new ForwardedToErrorPage("Crawlertrap with name '" + name + "' exists already"); } } }
From source file:org.terasoluna.gfw.web.token.transaction.TransactionTokenTagTest.java
/** * TransactionToken is null/*from www .j av a 2 s .c o m*/ */ @Test public void testWriteTagContentTagWriter01() { // setup arguments TransactionTokenTag tag = new TransactionTokenTag(); PageContext pageContext = mock(PageContext.class); tag.setPageContext(pageContext); HttpServletRequest request = mock(HttpServletRequest.class); StringWriter sw = new StringWriter(); TagWriter tagWriter = new TagWriter(sw); // mock behavior when((HttpServletRequest) pageContext.getRequest()).thenReturn(request); when((TransactionToken) request.getAttribute(TransactionTokenInterceptor.NEXT_TOKEN_REQUEST_ATTRIBUTE_NAME)) .thenReturn(null); // run int result = 1; try { result = tag.writeTagContent(tagWriter); } catch (JspException e) { fail(); } // assert assertThat(sw.getBuffer().toString(), is("")); assertThat(result, is(0)); }