List of usage examples for javax.servlet ServletRequest getParameter
public String getParameter(String name);
String
, or null
if the parameter does not exist. From source file:co.kuali.coeus.sys.impl.persistence.SchemaSpyFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final UserSession session = getGlobalVariableService().getUserSession() != null ? getGlobalVariableService().getUserSession() : (UserSession) ((HttpServletRequest) request).getSession() .getAttribute(KRADConstants.USER_SESSION_KEY); if (session == null || !getPermissionService().isAuthorizedByTemplate(session.getPrincipalId(), KRADConstants.KRAD_NAMESPACE, KimConstants.PermissionTemplateNames.OPEN_VIEW, Collections.singletonMap(KimConstants.AttributeConstants.VIEW_ID, KIM_SCHEMA_SPY_VIEW_ID), Collections.<String, String>emptyMap())) { HttpUtils.disableCache((HttpServletResponse) response); ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN); return;/* ww w .j a v a 2 s . c om*/ } if (!getConfigurationService().getPropertyValueAsBoolean(SCHEMA_SPY_CONFIG_PARAM)) { HttpUtils.disableCache((HttpServletResponse) response); response.getWriter().write("SchemaSpy has been disabled."); return; } synchronized (initialized) { if (REFRESH_TRUE.equals(request.getParameter(REFRESH_PARAM)) && initialized.get()) { Executors.newSingleThreadExecutor().execute(refreshSchemaSpy); } if (!initialized.get()) { HttpUtils.disableCache((HttpServletResponse) response); response.getWriter().write("Please wait. SchemaSpy is still processing."); return; } } chain.doFilter(request, response); }
From source file:org.apache.catalina.valves.ExtendedAccessLogValve.java
/** * Get app specific data.//from w w w . j ava 2 s . c o m * @param fieldInfo The field to decode * @param request Where we will pull the data from. * @return The appropriate value */ private String getAppSpecific(FieldInfo fieldInfo, Request request) { ServletRequest sr = request.getRequest(); HttpServletRequest hsr = null; if (sr instanceof HttpServletRequest) hsr = (HttpServletRequest) sr; switch (fieldInfo.xType) { case FieldInfo.X_PARAMETER: return wrap(urlEncode(sr.getParameter(fieldInfo.value))); case FieldInfo.X_REQUEST: return wrap(sr.getAttribute(fieldInfo.value)); case FieldInfo.X_SESSION: HttpSession session = null; if (hsr != null) { session = hsr.getSession(false); if (session != null) return wrap(session.getAttribute(fieldInfo.value)); } break; case FieldInfo.X_COOKIE: Cookie[] c = hsr.getCookies(); for (int i = 0; c != null && i < c.length; i++) { if (fieldInfo.value.equals(c[i].getName())) { return wrap(c[i].getValue()); } } case FieldInfo.X_APP: return wrap(request.getContext().getServletContext().getAttribute(fieldInfo.value)); case FieldInfo.X_SERVLET_REQUEST: if (fieldInfo.location == FieldInfo.X_LOC_AUTHTYPE) { return wrap(hsr.getAuthType()); } else if (fieldInfo.location == FieldInfo.X_LOC_REMOTEUSER) { return wrap(hsr.getRemoteUser()); } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONID) { return wrap(hsr.getRequestedSessionId()); } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDFROMCOOKIE) { return wrap("" + hsr.isRequestedSessionIdFromCookie()); } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDVALID) { return wrap("" + hsr.isRequestedSessionIdValid()); } else if (fieldInfo.location == FieldInfo.X_LOC_CONTENTLENGTH) { return wrap("" + hsr.getContentLength()); } else if (fieldInfo.location == FieldInfo.X_LOC_CHARACTERENCODING) { return wrap(hsr.getCharacterEncoding()); } else if (fieldInfo.location == FieldInfo.X_LOC_LOCALE) { return wrap(hsr.getLocale()); } else if (fieldInfo.location == FieldInfo.X_LOC_PROTOCOL) { return wrap(hsr.getProtocol()); } else if (fieldInfo.location == FieldInfo.X_LOC_SCHEME) { return wrap(hsr.getScheme()); } else if (fieldInfo.location == FieldInfo.X_LOC_SECURE) { return wrap("" + hsr.isSecure()); } break; default: ; } return "-"; }
From source file:filters.ActionValidationFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String requPath = httpServletRequest.getServletPath(); /*//from w w w. jav a 2 s .c om * ignore resource files (CSS, JPEG/PNG, JavaScript) ... */ if (requPath.startsWith(STATIC_RESOURCES) || requPath.startsWith(API)) { chain.doFilter(request, response); return; } /* * This filter makes only sense, if user is logged in. */ User user = AuthenticationUtils.getUser(); if (user != null && user.getName() != null) { /* * get sessions credential storage variable */ String storedCredential = (String) request.getAttribute(REQUEST_ATTRIB_CREDENTIAL); /* * if null, create new one */ if (storedCredential == null) { storedCredential = getNewCredential(user, httpServletRequest.getSession()); request.setAttribute(REQUEST_ATTRIB_CREDENTIAL, storedCredential); } log.debug("credential for " + user.getName() + " = " + storedCredential); /* * get credential from request parameter * * FIXME: This does not work with multipart-requests! Thus, on such * requests we must otherwise send the ckey. */ String requestCredential = request.getParameter(REQUEST_PARAM_CREDENTIAL); /* * check and propagate correctness */ request.setAttribute(REQUEST_ATTRIB_VALID_CREDENTIAL, storedCredential.equals(requestCredential)); } // Pass control on to the next filter chain.doFilter(request, response); }
From source file:de.appsolve.padelcampus.filter.AdminFilter.java
/** * @param request//from w w w.java 2 s.c om * @param response * @param chain * @throws java.io.IOException * @throws javax.servlet.ServletException * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; Player player = sessionUtil.getUser(httpRequest); if (player == null) { sessionUtil.setLoginRedirectPath(httpRequest, httpRequest.getRequestURI()); httpResponse.sendRedirect(httpResponse.encodeRedirectURL("/login")); return; } Set<Privilege> privileges = sessionUtil.getPrivileges(httpRequest); String pathInfo = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length()); for (Privilege privilege : privileges) { if (privilege.getPathPattern().matcher(pathInfo).matches()) { chain.doFilter(request, response); if (!StringUtils.isEmpty(httpRequest.getMethod()) && httpRequest.getMethod().equalsIgnoreCase("POST")) { LOG.info(String.format("AUDIT: %s executed %s %s", player, httpRequest.getMethod(), httpRequest.getRequestURI())); Enumeration<String> parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String paramName = parameterNames.nextElement(); String paramValue = request.getParameter(paramName); LOG.info(String.format("%s: %s", paramName, paramValue)); } } return; } } httpResponse.sendError(HttpStatus.SC_FORBIDDEN); } else { chain.doFilter(request, response); } }
From source file:com.netspective.sparx.navigate.NavigationPage.java
/** * Checks to see if the current page is valid or not. Currently, the validity of a page is only determined * by required request parameters and permissions. * * @param nc current navigation context//w ww .ja va 2s . c o m * * @return True if all required request parameters are available */ public boolean isValid(NavigationContext nc) { List reqParams = getRequireRequestParams(); if (reqParams.size() > 0) { ServletRequest request = nc.getRequest(); for (int i = 0; i < reqParams.size(); i++) { String name = (String) reqParams.get(i); if (request.getParameter(name) == null) { nc.setMissingRequiredReqParam(name); return false; } } } if (permissions != null) { AuthenticatedUser user = nc.getAuthenticatedUser(); if (user == null) { nc.setMissingRequiredPermissions(permissions); return false; } try { if (!user.hasAnyPermission(nc.getAccessControlListsManager(), permissions)) { nc.setMissingRequiredPermissions(permissions); return false; } } catch (PermissionNotFoundException e) { getLog().error(e); nc.setMissingRequiredPermissions(permissions); return false; } } return true; }
From source file:org.opencms.jsp.CmsJspTagTemplate.java
/** * Internal action method.<p>/*from w w w. j av a 2 s . co m*/ * * @param element the selected element * @param elementlist list the list of elements to check * @param checkall flag to indicate that all elements should be checked * @param checknone flag to indicate that the check is done for nonexisting elements * @param req the current request * @return boolean <code>true</code> if this element should be inclued, <code>false</code> * otherwise */ public static boolean templateTagAction(String element, String elementlist, boolean checkall, boolean checknone, ServletRequest req) { if (elementlist != null) { CmsFlexController controller = CmsFlexController.getController(req); String filename = controller.getCmsObject().getRequestContext().getUri(); I_CmsXmlDocument content = null; try { content = CmsXmlPageFactory.unmarshal(controller.getCmsObject(), filename, req); } catch (CmsException e) { LOG.error(Messages.get().getBundle().key(Messages.ERR_XML_DOCUMENT_UNMARSHAL_1, filename), e); } if (content != null) { String absolutePath = controller.getCmsObject().getSitePath(content.getFile()); // check the elements in the elementlist, if the check fails don't render the element String[] elements = CmsStringUtil.splitAsArray(elementlist, ','); boolean found = false; for (int i = 0; i < elements.length; i++) { String el = elements[i].trim(); List<Locale> locales = content.getLocales(el); Locale locale = null; if ((locales != null) && (locales.size() != 0)) { locale = OpenCms.getLocaleManager().getBestMatchingLocale( controller.getCmsObject().getRequestContext().getLocale(), OpenCms.getLocaleManager().getDefaultLocales(controller.getCmsObject(), absolutePath), locales); } if ((locale != null) && content.hasValue(el, locale) && content.isEnabled(el, locale)) { found = true; if (!checkall) { // found at least an element that is available break; } } else { if (checkall) { // found at least an element that is not available return false; } } } if (!found && !checknone) { // no element found while checking for existing elements return false; } else if (found && checknone) { // element found while checking for nonexisting elements return false; } } } // otherwise, check if an element was defined and if its equal to the desired element String param = req.getParameter(I_CmsResourceLoader.PARAMETER_ELEMENT); return ((element == null) || (param == null) || (param.equals(element))); }
From source file:org.xwiki.wysiwyg.server.filter.ConversionFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // Take the list of request parameters that require HTML conversion. String[] parametersRequiringHTMLConversion = req.getParameterValues(REQUIRES_HTML_CONVERSION); if (parametersRequiringHTMLConversion != null) { MutableServletRequestFactory mreqFactory = (MutableServletRequestFactory) Utils .getComponent(MutableServletRequestFactory.class, req.getProtocol()); // Wrap the current request in order to be able to change request parameters. MutableServletRequest mreq = mreqFactory.newInstance(req); // Remove the list of request parameters that require HTML conversion to avoid recurrency. mreq.removeParameter(REQUIRES_HTML_CONVERSION); // Try to convert each parameter from the list and save caught exceptions. Map<String, Throwable> errors = new HashMap<String, Throwable>(); // Save also the output to prevent loosing data in case of conversion exceptions. Map<String, String> output = new HashMap<String, String>(); for (int i = 0; i < parametersRequiringHTMLConversion.length; i++) { String parameterName = parametersRequiringHTMLConversion[i]; if (StringUtils.isEmpty(parameterName)) { continue; }/*from w w w . jav a 2s . c om*/ // Remove the syntax parameter from the request to avoid interference with further request processing. String syntax = mreq.removeParameter(parameterName + "_syntax"); try { HTMLConverter converter = Utils.getComponent(HTMLConverter.class); mreq.setParameter(parameterName, converter.fromHTML(req.getParameter(parameterName), syntax)); } catch (Exception e) { LOGGER.error(e.getLocalizedMessage(), e); errors.put(parameterName, e); } // If the conversion fails the output contains the value before the conversion. output.put(parameterName, mreq.getParameter(parameterName)); } if (!errors.isEmpty()) { // In case of a conversion exception we have to redirect the request back and provide a key to access // the exception and the value before the conversion from the session. // Redirect to the error page specified on the request. String redirectURL = mreq.getParameter("xerror"); if (redirectURL == null) { // Redirect to the referrer page. redirectURL = mreq.getReferer(); } // Extract the query string. String queryString = StringUtils.substringAfterLast(redirectURL, String.valueOf('?')); // Remove the query string. redirectURL = StringUtils.substringBeforeLast(redirectURL, String.valueOf('?')); // Remove the previous key from the query string. We have to do this since this might not be the first // time the conversion fails for this redirect URL. queryString = queryString.replaceAll("key=.*&?", ""); if (queryString.length() > 0 && !queryString.endsWith(String.valueOf('&'))) { queryString += '&'; } // Save the output and the caught exceptions on the session. queryString += "key=" + save(mreq, output, errors); mreq.sendRedirect(res, redirectURL + '?' + queryString); } else { chain.doFilter(mreq, res); } } else { chain.doFilter(req, res); } }
From source file:com.google.zxing.web.DecodeServlet.java
private static void processImage(BufferedImage image, ServletRequest request, HttpServletResponse response) throws IOException, ServletException { LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); Collection<Result> results = Lists.newArrayListWithCapacity(1); try {//from w w w . ja v a2s. c o m Reader reader = new MultiFormatReader(); ReaderException savedException = null; try { // Look for multiple barcodes MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader); Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS); if (theResults != null) { results.addAll(Arrays.asList(theResults)); } } catch (ReaderException re) { savedException = re; } if (results.isEmpty()) { try { // Look for pure barcode Result theResult = reader.decode(bitmap, HINTS_PURE); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Look for normal barcode in photo Result theResult = reader.decode(bitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Try again with other binarizer BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source)); Result theResult = reader.decode(hybridBitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { handleException(savedException, response); return; } } catch (RuntimeException re) { // Call out unexpected errors in the log clearly log.log(Level.WARNING, "Unexpected exception from library", re); throw new ServletException(re); } String fullParameter = request.getParameter("full"); boolean minimalOutput = fullParameter != null && !Boolean.parseBoolean(fullParameter); if (minimalOutput) { response.setContentType(MediaType.PLAIN_TEXT_UTF_8.toString()); response.setCharacterEncoding(StandardCharsets.UTF_8.name()); try (Writer out = new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8)) { for (Result result : results) { out.write(result.getText()); out.write('\n'); } } } else { request.setAttribute("results", results); request.getRequestDispatcher("decoderesult.jspx").forward(request, response); } }
From source file:com.ecyrd.jspwiki.WikiEngine.java
/** * This is a safe version of the Servlet.Request.getParameter() routine. * Unfortunately, the default version always assumes that the incoming * character set is ISO-8859-1, even though it was something else. * This means that we need to make a new string using the correct * encoding./*w ww . java2 s .c om*/ * <P> * For more information, see: * <A HREF="http://www.jguru.com/faq/view.jsp?EID=137049">JGuru FAQ</A>. * <P> * Incidentally, this is almost the same as encodeName(), below. * I am not yet entirely sure if it's safe to merge the code. * * @param request The servlet request * @param name The parameter name to get. * @return The parameter value or null * @since 1.5.3 * @deprecated JSPWiki now requires servlet API 2.3, which has a better * way of dealing with this stuff. This will be removed in * the near future. */ public String safeGetParameter(ServletRequest request, String name) { try { String res = request.getParameter(name); if (res != null) { res = new String(res.getBytes("ISO-8859-1"), getContentEncoding()); } return res; } catch (UnsupportedEncodingException e) { log.fatal("Unsupported encoding", e); return ""; } }
From source file:eu.freme.broker.tools.internationalization.EInternationalizationFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (!(req instanceof HttpServletRequest) || !(res instanceof HttpServletResponse)) { chain.doFilter(req, res);/* w w w.j av a2 s.c om*/ return; } HttpServletRequest httpRequest = (HttpServletRequest) req; HttpServletResponse httpResponse = (HttpServletResponse) res; if (httpRequest.getMethod().equals("OPTIONS")) { chain.doFilter(req, res); return; } String uri = httpRequest.getRequestURI(); for (Pattern pattern : endpointBlacklistRegex) { if (pattern.matcher(uri).matches()) { chain.doFilter(req, res); return; } } String informat = getInformat(httpRequest); String outformat = getOutformat(httpRequest); if (outformat != null && (informat == null || !outformat.equals(informat))) { Exception exception = new BadRequestException("Can only convert to outformat \"" + outformat + "\" when informat is also \"" + outformat + "\""); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } if (outformat != null && !outputFormats.contains(outformat)) { Exception exception = new BadRequestException("\"" + outformat + "\" is not a valid output format"); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } if (informat == null) { chain.doFilter(req, res); return; } boolean roundtripping = false; if (outformat != null) { roundtripping = true; logger.debug("convert from " + informat + " to " + outformat); } else { logger.debug("convert input from " + informat + " to nif"); } // do conversion of informat to nif // create BodySwappingServletRequest String inputQueryString = req.getParameter("input"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (InputStream requestInputStream = inputQueryString == null ? /* * read * data * from * request * body */req.getInputStream() : /* * read data from query string input * parameter */new ReaderInputStream(new StringReader(inputQueryString), "UTF-8")) { // copy request content to buffer IOUtils.copy(requestInputStream, baos); } // create request wrapper that converts the body of the request from the // original format to turtle Reader nif; byte[] baosData = baos.toByteArray(); if (baosData.length == 0) { Exception exception = new BadRequestException("No input data found in request."); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } ByteArrayInputStream bais = new ByteArrayInputStream(baosData); try { nif = eInternationalizationApi.convertToTurtle(bais, informat.toLowerCase()); } catch (ConversionException e) { logger.error("Error", e); throw new InternalServerErrorException("Conversion from \"" + informat + "\" to NIF failed"); } BodySwappingServletRequest bssr = new BodySwappingServletRequest((HttpServletRequest) req, nif, roundtripping); if (!roundtripping) { chain.doFilter(bssr, res); return; } ConversionHttpServletResponseWrapper dummyResponse; try { dummyResponse = new ConversionHttpServletResponseWrapper(httpResponse, eInternationalizationApi, new ByteArrayInputStream(baosData), informat, outformat); chain.doFilter(bssr, dummyResponse); ServletOutputStream sos = httpResponse.getOutputStream(); byte[] data = dummyResponse.writeBackToClient(); httpResponse.setContentLength(data.length); sos.write(data); sos.flush(); sos.close(); } catch (ConversionException e) { e.printStackTrace(); // exceptionHandlerService.writeExceptionToResponse((HttpServletResponse)res,new // InternalServerErrorException()); } }