List of usage examples for javax.servlet.http HttpServletRequest getAttributeNames
public Enumeration<String> getAttributeNames();
Enumeration
containing the names of the attributes available to this request. From source file:org.apache.tapestry.engine.TagSupportService.java
public void service(IEngineServiceView engine, IRequestCycle cycle, ResponseOutputStream output) throws ServletException, IOException { RequestContext context = cycle.getRequestContext(); HttpServletRequest request = context.getRequest(); String serviceName = getAttribute(request, Tapestry.TAG_SUPPORT_SERVICE_ATTRIBUTE); Object raw = request.getAttribute(Tapestry.TAG_SUPPORT_PARAMETERS_ATTRIBUTE); Object[] parameters = null;//w ww . j a v a 2s . c o m try { parameters = (Object[]) raw; } catch (ClassCastException ex) { throw new ServletException(Tapestry.format("TagSupportService.attribute-not-array", Tapestry.TAG_SUPPORT_PARAMETERS_ATTRIBUTE, Tapestry.getClassName(raw.getClass()))); } IEngineService service = cycle.getEngine().getService(serviceName); ILink link = service.getLink(cycle, null, parameters); String URI = link.getURL(); if (LOG.isDebugEnabled()) { LOG.debug("Request servlet path = " + request.getServletPath()); Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); LOG.debug("Request parameter " + name + " = " + request.getParameter(name)); } e = request.getAttributeNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); LOG.debug("Request attribute " + name + " = " + request.getAttribute(name)); } LOG.debug("Result URI: " + URI); } HttpServletResponse response = context.getResponse(); PrintWriter servletWriter = response.getWriter(); IMarkupWriter writer = new HTMLWriter(servletWriter); writer.print(URI); writer.flush(); }
From source file:org.dspace.submit.step.UploadStep.java
/** * Process the upload of a new file!/*from w w w .j av a2 s .c om*/ * * @param context * The relevant DSpace Context. * @param request * Servlet's HTTP request object. * @param response * Servlet's HTTP response object. * @param subInfo * submission info object * @return Status or error flag which will be processed by * UI-related code! (if STATUS_COMPLETE or 0 is returned, * no errors occurred!) * @throws ServletException * A general exception a servlet can throw when it encounters difficulty. * @throws IOException * A general class of exceptions produced by failed or interrupted I/O operations. * @throws SQLException * An exception that provides information on a database access error or other errors. * @throws AuthorizeException * Exception indicating the current user of the context does not have permission * to perform a particular action. */ public int processUploadFile(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) throws ServletException, IOException, SQLException, AuthorizeException { boolean formatKnown = true; boolean fileOK = false; BitstreamFormat bf = null; Bitstream b = null; //NOTE: File should already be uploaded. //Manakin does this automatically via Cocoon. //For JSP-UI, the SubmissionController.uploadFiles() does the actual upload Enumeration attNames = request.getAttributeNames(); //loop through our request attributes while (attNames.hasMoreElements()) { String attr = (String) attNames.nextElement(); //if this ends with "-path", this attribute //represents a newly uploaded file if (attr.endsWith("-path")) { //strip off the -path to get the actual parameter //that the file was uploaded as String param = attr.replace("-path", ""); // Load the file's path and input stream and description String filePath = (String) request.getAttribute(param + "-path"); InputStream fileInputStream = (InputStream) request.getAttribute(param + "-inputstream"); //attempt to get description from attribute first, then direct from a parameter String fileDescription = (String) request.getAttribute(param + "-description"); if (fileDescription == null || fileDescription.length() == 0) { fileDescription = request.getParameter("description"); } // if information wasn't passed by User Interface, we had a problem // with the upload if (filePath == null || fileInputStream == null) { return STATUS_UPLOAD_ERROR; } if (subInfo == null) { // In any event, if we don't have the submission info, the request // was malformed return STATUS_INTEGRITY_ERROR; } // Create the bitstream Item item = subInfo.getSubmissionItem().getItem(); // do we already have a bundle? List<Bundle> bundles = itemService.getBundles(item, "ORIGINAL"); if (bundles.size() < 1) { // set bundle's name to ORIGINAL b = itemService.createSingleBitstream(context, fileInputStream, item, "ORIGINAL"); } else { // we have a bundle already, just add bitstream b = bitstreamService.create(context, bundles.get(0), fileInputStream); } // Strip all but the last filename. It would be nice // to know which OS the file came from. String noPath = filePath; while (noPath.indexOf('/') > -1) { noPath = noPath.substring(noPath.indexOf('/') + 1); } while (noPath.indexOf('\\') > -1) { noPath = noPath.substring(noPath.indexOf('\\') + 1); } b.setName(context, noPath); b.setSource(context, filePath); b.setDescription(context, fileDescription); // Identify the format bf = bitstreamFormatService.guessFormat(context, b); b.setFormat(context, bf); // Update to DB bitstreamService.update(context, b); itemService.update(context, item); if ((bf != null) && (bf.isInternal())) { log.warn("Attempt to upload file format marked as internal system use only"); backoutBitstream(context, subInfo, b, item); return STATUS_UPLOAD_ERROR; } // Check for virus if (configurationService.getBooleanProperty("submission-curation.virus-scan")) { Curator curator = new Curator(); curator.addTask("vscan").curate(context, item); int status = curator.getStatus("vscan"); if (status == Curator.CURATE_ERROR) { backoutBitstream(context, subInfo, b, item); return STATUS_VIRUS_CHECKER_UNAVAILABLE; } else if (status == Curator.CURATE_FAIL) { backoutBitstream(context, subInfo, b, item); return STATUS_CONTAINS_VIRUS; } } // If we got this far then everything is more or less ok. context.dispatchEvents(); // save this bitstream to the submission info, as the // bitstream we're currently working with subInfo.setBitstream(b); //if format was not identified if (bf == null) { return STATUS_UNKNOWN_FORMAT; } } //end if attribute ends with "-path" } //end while return STATUS_COMPLETE; }
From source file:elw.web.ErrController.java
@RequestMapping(value = "*") public ModelAndView do_handle(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final String url = (String) req.getAttribute("javax.servlet.error.request_uri"); final Integer statusCode = (Integer) req.getAttribute("javax.servlet.error.status_code"); if (statusCode != null && 404 == statusCode && ignoredUris.contains(url)) { resp.sendError(410, "ignored"); return null; }//from w w w.j a va 2 s .c o m try { final String message = (String) req.getAttribute("javax.servlet.error.message"); final Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception"); final String eventId = Long.toString(System.currentTimeMillis(), 36); final StringWriter logDest = new StringWriter(); final PrintWriter logOut = new PrintWriter(logDest); final HttpSession session = req.getSession(false); logOut.println( "web error: eventId=" + eventId + " status=" + statusCode + " message='" + message + "'"); logOut.println("url: " + url); logOut.print("attributes: "); final Enumeration reqAttrNames = req.getAttributeNames(); while (reqAttrNames.hasMoreElements()) { final String aName = (String) reqAttrNames.nextElement(); if (!aName.startsWith("javax.servlet") && !aName.startsWith("org.springframework")) { logOut.print(aName + "=" + String.valueOf(req.getAttribute(aName)) + " "); } } logOut.println(); if (session != null) { logOut.println("session id: " + session.getId()); logOut.print("session: "); final Enumeration sessAttrNames = session.getAttributeNames(); while (sessAttrNames.hasMoreElements()) { final String aName = (String) sessAttrNames.nextElement(); if (!aName.startsWith("javax.servlet") && !aName.startsWith("org.springframework")) { logOut.print(aName + "=" + String.valueOf(session.getAttribute(aName)) + " "); } } logOut.println(); } log.error(logDest.toString(), throwable); final PrintWriter out = resp.getWriter(); out.print("<html><title>HTTP status " + statusCode + " : " + message + "</title>" + "<body><h3>HTTP status " + statusCode + " : " + message + "</h3>" + "Sorry for inconvenience and thanks for finding just another bug out there.<br/>" + "For the time being, you may log out, log in and then try the operation once again.<br/><br/>" + "Event reference id: <b>" + eventId + "</b>." + "</body></html>"); } catch (Throwable t) { log.error("failed on reporting error", t); } return null; }
From source file:org.bibsonomy.webapp.util.spring.controller.MinimalisticControllerSpringWrapper.java
/** * instantiates, initializes and runs the MinimalisticController * //from w w w .j a v a2 s .c o m * @see org.springframework.web.servlet.mvc.AbstractController#handleRequestInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @SuppressWarnings("unchecked") @Override protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception { ((RequestLogic) getApplicationContext().getBean("requestLogic")).setRequest(request); // hack but thats springs fault ((ResponseLogic) getApplicationContext().getBean("responseLogic")).setResponse(response); // hack but thats springs fault final MinimalisticController<T> controller = (MinimalisticController<T>) getApplicationContext() .getBean(controllerBeanName); /** * Controller is put into request. * * FIXME: is this still neccessary? * * SuppressValidation retrieves controller from request again! */ request.setAttribute(CONTROLLER_ATTR_NAME, controller); /* * DEBUG: log request attributes */ if (log.isDebugEnabled()) { final Enumeration<?> e = request.getAttributeNames(); while (e.hasMoreElements()) { log.debug(e.nextElement().toString()); } } final T command = controller.instantiateCommand(); /* * put context into command * * TODO: in the future this is hopefully no longer needed, since the wrapper * only exists to transfer request attributes into the command. */ command.setContext((RequestWrapperContext) request.getAttribute(RequestWrapperContext.class.getName())); /* * set validator for this instance */ if (controller instanceof ValidationAwareController<?>) { this.setValidator(((ValidationAwareController<T>) controller).getValidator()); } /* * bind request attributes to command */ final ServletRequestDataBinder binder = bindAndValidate(request, command); final BindException errors = new BindException(binder.getBindingResult()); if (controller instanceof ErrorAware) { ((ErrorAware) controller).setErrors(errors); } View view; /* * define error view */ if (controller instanceof AjaxController) { view = Views.AJAX_ERRORS; } else { view = Views.ERROR; } try { view = controller.workOn(command); } catch (final MalformedURLSchemeException malformed) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); errors.reject("error.http.notFound", malformed.getMessage()); log.warn("Could not complete controller (invalid URL scheme) : " + malformed.getMessage()); } catch (final AccessDeniedException ad) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); errors.reject(ad.getMessage()); log.warn("Could not complete controller (AccessDeniedException), occured in: " + ad.getStackTrace()[0] + ", msg is: " + ad.getMessage()); } catch (final ServiceUnavailableException e) { response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); response.setHeader("Retry-After", Long.toString(e.getRetryAfter())); errors.reject(e.getMessage(), new Object[] { e.getRetryAfter() }, "Service unavailable"); /* * this exception is only thrown in UserLoginController * if desired, add some logging there. Otherwise, our error logs get * cluttered.(dbe) */ // log.warn("Could not complete controller (Service unavailable): " + e.getMessage()); } catch (final ResourceMovedException e) { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", urlGenerator.getPostUrl(e.getResourceType(), e.getNewIntraHash(), e.getUserName())); } catch (final ResourceNotFoundException e) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); errors.reject("error.post.notfound", e.getMessage()); // FIXME: it would be better, to show the specific 404 view } catch (final org.springframework.security.access.AccessDeniedException ex) { /* * we rethrow the exception here in order that Spring Security can * handle the exception (saving request and redirecting to the login * page (if user is not logged in) or to the access denied page) */ throw ex; } catch (final Exception ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); errors.reject("error.internal", new Object[] { ex }, "Internal Server Error: " + ex.getMessage()); log.error("Could not complete controller (general exception) for request /" + request.getRequestURI() + "?" + request.getQueryString() + " with referer " + request.getHeader("Referer"), ex); } log.debug("Exception catching block passed, putting comand+errors into model."); final Map<String, Object> model = new HashMap<String, Object>(); model.put(getCommandName(), command); /* * put errors into model */ model.putAll(errors.getModel()); log.debug("Returning model and view."); /** * If the view is already a Spring view, use it directly. * The primal reason for the this workaround is, that Spring's RedirctView * automatically appends the model parameters to each redirected URL. This * can only be avoided by calling setExposeModelAttributes(false) on the * RedirectView. Hence, we must directly create a redirect view instead of * using a "redirect:..." URL. */ if (org.springframework.web.servlet.View.class.isAssignableFrom(view.getClass())) { return new ModelAndView((org.springframework.web.servlet.View) view, model); } return new ModelAndView(view.getName(), model); }
From source file:org.dspace.submit.step.UploadWithEmbargoStep.java
/** * Process the upload of a new file!/*from w ww. j a va 2s.com*/ * * @param context * current DSpace context * @param request * current servlet request object * @param response * current servlet response object * @param subInfo * submission info object * * @return Status or error flag which will be processed by * UI-related code! (if STATUS_COMPLETE or 0 is returned, * no errors occurred!) */ protected int processUploadFile(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) throws ServletException, IOException, SQLException, AuthorizeException { boolean formatKnown = true; boolean fileOK = false; BitstreamFormat bf = null; Bitstream b = null; //NOTE: File should already be uploaded. //Manakin does this automatically via Cocoon. //For JSP-UI, the SubmissionController.uploadFiles() does the actual upload Enumeration attNames = request.getAttributeNames(); //loop through our request attributes while (attNames.hasMoreElements()) { String attr = (String) attNames.nextElement(); //if this ends with "-path", this attribute //represents a newly uploaded file if (attr.endsWith("-path")) { //strip off the -path to get the actual parameter //that the file was uploaded as String param = attr.replace("-path", ""); // Load the file's path and input stream and description String filePath = (String) request.getAttribute(param + "-path"); InputStream fileInputStream = (InputStream) request.getAttribute(param + "-inputstream"); //attempt to get description from attribute first, then direct from a parameter String fileDescription = (String) request.getAttribute(param + "-description"); if (fileDescription == null || fileDescription.length() == 0) { request.getParameter("description"); } // if information wasn't passed by User Interface, we had a problem // with the upload if (filePath == null || fileInputStream == null) { return STATUS_UPLOAD_ERROR; } if (subInfo == null) { // In any event, if we don't have the submission info, the request // was malformed return STATUS_INTEGRITY_ERROR; } // Create the bitstream Item item = subInfo.getSubmissionItem().getItem(); // do we already have a bundle? Bundle[] bundles = item.getBundles("ORIGINAL"); if (bundles.length < 1) { // set bundle's name to ORIGINAL b = item.createSingleBitstream(fileInputStream, "ORIGINAL"); } else { // we have a bundle already, just add bitstream b = bundles[0].createBitstream(fileInputStream); } // Strip all but the last filename. It would be nice // to know which OS the file came from. String noPath = filePath; while (noPath.indexOf('/') > -1) { noPath = noPath.substring(noPath.indexOf('/') + 1); } while (noPath.indexOf('\\') > -1) { noPath = noPath.substring(noPath.indexOf('\\') + 1); } b.setName(noPath); b.setSource(filePath); b.setDescription(fileDescription); // Identify the format bf = FormatIdentifier.guessFormat(context, b); b.setFormat(bf); // Update to DB b.update(); item.update(); processAccessFields(context, request, subInfo, b); // commit all changes to database context.commit(); if ((bf != null) && (bf.isInternal())) { log.warn("Attempt to upload file format marked as internal system use only"); backoutBitstream(subInfo, b, item); return STATUS_UPLOAD_ERROR; } // Check for virus if (ConfigurationManager.getBooleanProperty("submission-curation", "virus-scan")) { Curator curator = new Curator(); curator.addTask("vscan").curate(item); int status = curator.getStatus("vscan"); if (status == Curator.CURATE_ERROR) { backoutBitstream(subInfo, b, item); return STATUS_VIRUS_CHECKER_UNAVAILABLE; } else if (status == Curator.CURATE_FAIL) { backoutBitstream(subInfo, b, item); return STATUS_CONTAINS_VIRUS; } } // If we got this far then everything is more or less ok. // Comment - not sure if this is the right place for a commit here // but I'm not brave enough to remove it - Robin. context.commit(); // save this bitstream to the submission info, as the // bitstream we're currently working with subInfo.setBitstream(b); //if format was not identified if (bf == null) { return STATUS_UNKNOWN_FORMAT; } } //end if attribute ends with "-path" } //end while return STATUS_COMPLETE; }
From source file:com.cws.esolutions.security.filters.SSLEnforcementFilter.java
public void doFilter(final ServletRequest sRequest, final ServletResponse sResponse, final FilterChain filterChain) throws ServletException, IOException { final String methodName = SSLEnforcementFilter.CNAME + "#doFilter(final ServletRequest req, final servletResponse res, final FilterChain filterChain) throws ServletException, IOException"; if (DEBUG) {//from w w w . ja v a 2 s . co m DEBUGGER.debug(methodName); DEBUGGER.debug("ServletRequest: {}", sRequest); DEBUGGER.debug("ServletResponse: {}", sResponse); DEBUGGER.debug("FilterChain: {}", filterChain); } final HttpServletRequest hRequest = (HttpServletRequest) sRequest; final HttpServletResponse hResponse = (HttpServletResponse) sResponse; if (DEBUG) { final HttpSession hSession = hRequest.getSession(); DEBUGGER.debug("HttpServletRequest: {}", hRequest); DEBUGGER.debug("HttpServletResponse: {}", hResponse); DEBUGGER.debug("HttpSession: {}", hSession); DEBUGGER.debug("Dumping session content:"); Enumeration<?> sessionEnumeration = hSession.getAttributeNames(); while (sessionEnumeration.hasMoreElements()) { String element = (String) sessionEnumeration.nextElement(); Object value = hSession.getAttribute(element); DEBUGGER.debug("Attribute: {}; Value: {}", element, value); } DEBUGGER.debug("Dumping request content:"); Enumeration<?> requestEnumeration = hRequest.getAttributeNames(); while (requestEnumeration.hasMoreElements()) { String element = (String) requestEnumeration.nextElement(); Object value = hRequest.getAttribute(element); DEBUGGER.debug("Attribute: {}; Value: {}", element, value); } DEBUGGER.debug("Dumping request parameters:"); Enumeration<?> paramsEnumeration = hRequest.getParameterNames(); while (paramsEnumeration.hasMoreElements()) { String element = (String) paramsEnumeration.nextElement(); Object value = hRequest.getParameter(element); DEBUGGER.debug("Parameter: {}; Value: {}", element, value); } } if (SSLEnforcementFilter.LOCALHOST.contains(sRequest.getServerName())) { if (DEBUG) { DEBUGGER.debug("Local request. Breaking out..."); } filterChain.doFilter(sRequest, sResponse); return; } if ((this.ignoreHosts != null) && (this.ignoreHosts.length != 0)) { if (Arrays.asList(this.ignoreHosts).contains("ALL")) { if (DEBUG) { DEBUGGER.debug("ALL URIs are ignored. Breaking ..."); } filterChain.doFilter(sRequest, sResponse); return; } for (String host : this.ignoreHosts) { String requestHost = host.trim(); if (DEBUG) { DEBUGGER.debug(host); DEBUGGER.debug(requestHost); } if (StringUtils.equals(requestHost, sRequest.getServerName().trim())) { if (DEBUG) { DEBUGGER.debug("Host found in ignore list. Not processing request!"); } filterChain.doFilter(sRequest, sResponse); return; } } } if ((this.ignoreURIs != null) && (this.ignoreURIs.length != 0)) { if (Arrays.asList(this.ignoreURIs).contains("ALL")) { if (DEBUG) { DEBUGGER.debug("ALL URIs are ignored. Breaking ..."); } filterChain.doFilter(sRequest, sResponse); return; } // no hosts in ignore list for (String uri : this.ignoreURIs) { String requestURI = uri.trim(); if (DEBUG) { DEBUGGER.debug(uri); DEBUGGER.debug(requestURI); } if (StringUtils.equals(requestURI, hRequest.getRequestURI().trim())) { if (DEBUG) { DEBUGGER.debug("URI found in ignore list. Not processing request!"); } filterChain.doFilter(sRequest, sResponse); return; } } } if (hRequest.isSecure()) { // Request came in on a secure channel or // the HTTP:DECRYPTED header is true // do nothing if (DEBUG) { DEBUGGER.debug("Filter not applied to request - already secured. No action taken."); } filterChain.doFilter(sRequest, sResponse); return; } // secure it StringBuilder redirectURL = new StringBuilder().append(SSLEnforcementFilter.SECURE_URL_PREFIX) .append(sRequest.getServerName()) .append((sRequest.getServerPort() != SSLEnforcementFilter.SECURE_URL_PORT) ? ":" + sRequest.getServerPort() : null) .append(hRequest.getRequestURI()); if (StringUtils.isNotBlank(hRequest.getQueryString())) { redirectURL.append("?" + hRequest.getQueryString()); } if (DEBUG) { DEBUGGER.debug("redirectURL: {}", redirectURL); } hResponse.sendRedirect(URLEncoder.encode(redirectURL.toString(), systemConfig.getEncoding())); return; }
From source file:com.sg.rest.filters.LoggerFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { LOGGER.error(NON_HTTP_REQUEST + System.lineSeparator() + request.getInputStream().toString()); throw new RuntimeException(EXPECTING_AN_HTTP_REQUEST); }// www. j a v a 2 s .c o m HttpServletRequest httpRequest = (HttpServletRequest) request; StringBuilder sb = new StringBuilder(); //General header sb.append(System.lineSeparator()); sb.append(INCOMING_REQUEST); //Request url sb.append(System.lineSeparator()); sb.append(REQUEST_URL); sb.append(httpRequest.getRequestURL()); //Method sb.append(System.lineSeparator()); sb.append(METHOD); sb.append(httpRequest.getMethod()); //Parameters if (httpRequest.getParameterNames().hasMoreElements()) { sb.append(System.lineSeparator()); sb.append(PARAMETERS); Enumeration enParams = httpRequest.getParameterNames(); while (enParams.hasMoreElements()) { sb.append(System.lineSeparator()); String paramName = (String) enParams.nextElement(); sb.append(paramName); sb.append(" : "); sb.append(httpRequest.getParameter(paramName)); } } //Attributes if (httpRequest.getAttributeNames().hasMoreElements()) { sb.append(System.lineSeparator()); sb.append(ATTRIBUTES); Enumeration enAttribs = httpRequest.getAttributeNames(); while (enAttribs.hasMoreElements()) { sb.append(System.lineSeparator()); String attribName = (String) enAttribs.nextElement(); sb.append(attribName); sb.append(" : "); sb.append(httpRequest.getAttribute(attribName)); } } //Headers if (httpRequest.getHeaderNames().hasMoreElements()) { sb.append(System.lineSeparator()); sb.append(HEADERS); Enumeration enHeaders = httpRequest.getHeaderNames(); while (enHeaders.hasMoreElements()) { sb.append(System.lineSeparator()); String headerName = (String) enHeaders.nextElement(); sb.append(headerName); sb.append(" : "); sb.append(httpRequest.getHeader(headerName)); } } //AuthType if (httpRequest.getAuthType() != null && !httpRequest.getAuthType().isEmpty()) { sb.append(System.lineSeparator()); sb.append(AUTH_TYPE); sb.append(httpRequest.getAuthType()); } //Cookies if (httpRequest.getCookies() != null && httpRequest.getCookies().length > 0) { sb.append(System.lineSeparator()); sb.append(COOKIES); for (Cookie cookie : httpRequest.getCookies()) { sb.append(System.lineSeparator()); sb.append(cookie.getName()); sb.append(" : "); sb.append(cookie.getValue()); } } //RemoteAddr if (httpRequest.getRemoteAddr() != null && !httpRequest.getRemoteAddr().isEmpty()) { sb.append(System.lineSeparator()); sb.append(REMOTE_ADDR); sb.append(httpRequest.getRemoteAddr()); } //RemoteHost if (httpRequest.getRemoteHost() != null && !httpRequest.getRemoteHost().isEmpty()) { sb.append(System.lineSeparator()); sb.append(REMOTE_HOST); sb.append(httpRequest.getRemoteHost()); } //User principal if (httpRequest.getUserPrincipal() != null) { if (httpRequest.getUserPrincipal().getName() != null && !httpRequest.getUserPrincipal().getName().isEmpty()) { sb.append(System.lineSeparator()); sb.append(PRINCIPAL); sb.append(httpRequest.getUserPrincipal().getName()); } } //Body ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest( (HttpServletRequest) request); String body = IOUtils.toString(wrappedRequest.getReader()); if (body != null && !body.isEmpty()) { sb.append(System.lineSeparator()); sb.append(BODY); sb.append(System.lineSeparator()); sb.append(body); } wrappedRequest.resetInputStream(); LOGGER.info(sb.toString()); chain.doFilter(wrappedRequest, response); }
From source file:org.sakaiproject.sdata.tool.SnoopHandler.java
/** * @param request//from ww w.j a v a 2 s. co m */ private void snoopRequest(HttpServletRequest request) { StringBuilder sb = new StringBuilder("SData Request :").append(request); sb.append("\n\tRequest Path :").append(request.getPathInfo()); sb.append("\n\tMethod :").append(request.getMethod()); for (Enumeration<?> hnames = request.getHeaderNames(); hnames.hasMoreElements();) { String name = (String) hnames.nextElement(); sb.append("\n\tHeader :").append(name).append("=[").append(request.getHeader(name)).append("]"); } for (Enumeration<?> hnames = request.getParameterNames(); hnames.hasMoreElements();) { String name = (String) hnames.nextElement(); sb.append("\n\tParameter :").append(name).append("=[").append(request.getParameter(name)).append("]"); } if (request.getCookies() != null) { for (Cookie c : request.getCookies()) { sb.append("\n\tCookie:"); sb.append("name[").append(c.getName()); sb.append("]path[").append(c.getPath()); sb.append("]value[").append(c.getValue()); } } sb.append("]"); for (Enumeration<?> hnames = request.getAttributeNames(); hnames.hasMoreElements();) { String name = (String) hnames.nextElement(); sb.append("\n\tAttribute :").append(name).append("=[").append(request.getAttribute(name)).append("]"); } HttpSession session = request.getSession(); sb.append("\n\tUser :").append(request.getRemoteUser()); if (session != null) { sb.append("\n\tSession ID :").append(session.getId()); for (Enumeration<?> hnames = session.getAttributeNames(); hnames.hasMoreElements();) { String name = (String) hnames.nextElement(); sb.append("\n\tSession Attribute :").append(name).append("=[").append(session.getAttribute(name)) .append("]"); } } else { sb.append("\n\tNo Session"); } LOG.info(sb.toString()); }
From source file:org.impalaframework.extension.mvc.util.RequestModelHelper.java
/** * /*w w w . ja v a 2 s. c om*/ * @param logger * @param request */ public static void maybeDebugRequest(Log logger, HttpServletRequest request) { if (logger.isDebugEnabled()) { logger.debug("#####################################################################################"); logger.debug("---------------------------- Request details ---------------------------------------"); logger.debug("Request context path: " + request.getContextPath()); logger.debug("Request path info: " + request.getPathInfo()); logger.debug("Request path translated: " + request.getPathTranslated()); logger.debug("Request query string: " + request.getQueryString()); logger.debug("Request servlet path: " + request.getServletPath()); logger.debug("Request request URI: " + request.getRequestURI()); logger.debug("Request request URL: " + request.getRequestURL()); logger.debug("Request session ID: " + request.getRequestedSessionId()); logger.debug("------------------------------------------------ "); logger.debug("Parameters ------------------------------------- "); final Enumeration<String> parameterNames = request.getParameterNames(); Map<String, String> parameters = new TreeMap<String, String>(); while (parameterNames.hasMoreElements()) { String name = parameterNames.nextElement(); String value = request.getParameter(name); final String lowerCase = name.toLowerCase(); if (lowerCase.contains("password") || lowerCase.contains("cardnumber")) { value = "HIDDEN"; } parameters.put(name, value); } //now output final Set<String> parameterKeys = parameters.keySet(); for (String key : parameterKeys) { logger.debug(key + ": " + parameters.get(key)); } logger.debug("------------------------------------------------ "); Map<String, Object> attributes = new TreeMap<String, Object>(); logger.debug("Attributes ------------------------------------- "); final Enumeration<String> attributeNames = request.getAttributeNames(); while (attributeNames.hasMoreElements()) { String name = attributeNames.nextElement(); Object value = request.getAttribute(name); final String lowerCase = name.toLowerCase(); if (lowerCase.contains("password") || lowerCase.contains("cardnumber")) { value = "HIDDEN"; } attributes.put(name, value); } //now output final Set<String> keys = attributes.keySet(); for (String name : keys) { Object value = attributes.get(name); logger.debug(name + ": " + (value != null ? value.toString() : value)); } logger.debug("------------------------------------------------ "); logger.debug("#####################################################################################"); } else { if (logger.isInfoEnabled()) { logger.info( "#####################################################################################"); logger.info("Request query string: " + request.getQueryString()); logger.info("Request request URI: " + request.getRequestURI()); logger.info( "#####################################################################################"); } } }
From source file:org.gbif.portal.webservices.rest.Dispatcher.java
/** * Generate a cleaned parameters map from a get request, including any attributes (from URL rewriting) * // w ww . j a v a2s .c om * @param request * @return parameters map * @throws GbifWebServiceException */ protected Map<String, Object> processGet(HttpServletRequest request) throws GbifWebServiceException { Map<String, Object> kvps = new HashMap<String, Object>(); Enumeration enumeration = request.getParameterNames(); // Place the first value in the map under its own name (since in general // most parameters are processed as singletons, but if there are more // than one values, also insert the array under the name "<name>_array". if (enumeration != null) { Map parameterMap = request.getParameterMap(); while (enumeration.hasMoreElements()) { String name = (String) enumeration.nextElement(); String[] values = (String[]) parameterMap.get(name); kvps.put(name.toLowerCase(), values[0]); if (values.length > 1) { kvps.put(name + ARRAY_SUFFIX, values); } } } enumeration = request.getAttributeNames(); if (enumeration != null) { while (enumeration.hasMoreElements()) { String name = (String) enumeration.nextElement(); Object value = request.getAttribute(name); if (value instanceof String) { kvps.put(name.toLowerCase(), (String) value); } } } String url = request.getRequestURL().toString(); String servletPath = request.getServletPath(); String urlBase = url.substring(0, url.indexOf(servletPath)); kvps.put("portalroot", urlBase); kvps.put("wsroot", urlBase + servletPath); log.debug("Parameter map: " + kvps.toString()); return kvps; }