List of usage examples for javax.servlet ServletRequest getProtocol
public String getProtocol();
From source file:org.rhq.enterprise.gui.legacy.util.RequestUtils.java
/** * When you really really want to defeat a browser's cache, expire the content and set the no-cache header * * @param expire set <i>true</i> to have the content expire immediately *///from ww w.j a va 2s .c om public static void bustaCache(ServletRequest request, ServletResponse response, boolean expire) { if (!(response instanceof HttpServletResponse)) { return; } HttpServletResponse res = (HttpServletResponse) response; if (request.getProtocol().equalsIgnoreCase("HTTP/1.0")) { res.setHeader("Pragma", "no-cache"); } else if (request.getProtocol().equalsIgnoreCase("HTTP/1.1")) { res.setHeader("Cache-Control", "no-cache"); } if (expire) { Date now = new Date(); res.setDateHeader("Date", now.getTime()); res.setDateHeader("Expires", now.getTime() + 1000); } }
From source file:org.hyperic.hq.ui.util.RequestUtils.java
/** * When you really really want to defeat a browser's cache, expire the content and set the * no-cache header/*from ww w . j a v a 2 s . com*/ * @param expire set <i>true</i> to have the content expire immediately */ public static void bustaCache(ServletRequest request, ServletResponse response, boolean expire) { if (!(response instanceof HttpServletResponse)) return; HttpServletResponse res = (HttpServletResponse) response; if (request.getProtocol().equalsIgnoreCase("HTTP/1.0")) { res.setHeader("Pragma", "no-cache"); } else if (request.getProtocol().equalsIgnoreCase("HTTP/1.1")) { res.setHeader("Cache-Control", "no-cache"); } if (expire) { Date now = new Date(); res.setDateHeader("Date", now.getTime()); res.setDateHeader("Expires", now.getTime() + 1000); } }
From source file:org.everit.jetty.server.ecm.tests.EchoRemoteInfoServlet.java
@Override public void service(final ServletRequest req, final ServletResponse res) throws ServletException, IOException { PrintWriter writer = res.getWriter(); JSONObject jsonObject = new JSONObject(); jsonObject.put("remoteAddr", req.getRemoteAddr()); jsonObject.put("remoteHost", req.getRemoteHost()); jsonObject.put("remotePort", req.getRemotePort()); jsonObject.put("serverName", req.getServerName()); jsonObject.put("serverPort", req.getServerPort()); jsonObject.put("protocol", req.getProtocol()); jsonObject.put("secure", req.isSecure()); writer.write(jsonObject.toString()); }
From source file:org.xwiki.wysiwyg.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 = Utils.getComponent((Type) 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]; String html = req.getParameter(parameterName); // Remove the syntax parameter from the request to avoid interference with further request processing. String syntax = mreq.removeParameter(parameterName + "_syntax"); if (html == null || syntax == null) { continue; }//w w w. ja va 2 s. c o m try { HTMLConverter converter = Utils.getComponent((Type) HTMLConverter.class); mreq.setParameter(parameterName, converter.fromHTML(html, 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()) { handleConversionErrors(errors, output, mreq, res); } else { chain.doFilter(mreq, res); } } else { chain.doFilter(req, res); } }
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:se.natusoft.osgi.aps.rpchttpextender.servlet.RPCServlet.java
/** * Catch our host and port information which as far as I can determine is only possible to get from a request. * * @param req/* ww w .ja v a 2 s.c o m*/ * @param resp * @throws ServletException * @throws IOException */ public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { if (this.rpcBaseUrl == null) { String protocol = req.getProtocol().split("/")[0].toLowerCase(); if (req.getServerName() != null) { this.serverHost = req.getServerName(); } else if (req.getLocalName() != null) { this.serverHost = req.getLocalName(); } if (this.serverHost.equals("localhost")) { this.serverHost = InetAddress.getLocalHost().getHostName(); } this.serverPort = req.getServerPort(); this.rpcBaseUrl = protocol + "://" + this.serverHost + ":" + this.serverPort + "/apsrpc/"; try { onServiceAvailable(this.discoveryServiceTracker.allocateService(), null); this.discoveryServiceTracker.releaseService(); } catch (Exception e) { } } super.service(req, resp); }
From source file:com.mirth.connect.connectors.http.HttpReceiver.java
private ConstraintSecurityHandler createSecurityHandler(Handler handler) throws Exception { final Authenticator authenticator = authenticatorProvider.getAuthenticator(); final String authMethod; switch (authProps.getAuthType()) { case BASIC:/* w w w. j a v a 2 s .co m*/ authMethod = Constraint.__BASIC_AUTH; break; case DIGEST: authMethod = Constraint.__DIGEST_AUTH; break; default: authMethod = "customauth"; } Constraint constraint = new Constraint(); constraint.setName(authMethod); constraint.setRoles(new String[] { "user" }); constraint.setAuthenticate(true); ConstraintMapping constraintMapping = new ConstraintMapping(); constraintMapping.setConstraint(constraint); constraintMapping.setPathSpec("/*"); ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); securityHandler.setAuthenticator(new org.eclipse.jetty.security.Authenticator() { @Override public void setConfiguration(AuthConfiguration configuration) { } @Override public String getAuthMethod() { return authMethod; } @Override public void prepareRequest(ServletRequest request) { } @Override public Authentication validateRequest(final ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String remoteAddress = StringUtils.trimToEmpty(request.getRemoteAddr()); int remotePort = request.getRemotePort(); String localAddress = StringUtils.trimToEmpty(request.getLocalAddr()); int localPort = request.getLocalPort(); String protocol = StringUtils.trimToEmpty(request.getProtocol()); String method = StringUtils.trimToEmpty(request.getMethod()); String requestURI = StringUtils.trimToEmpty(request.getRequestURI()); Map<String, List<String>> headers = HttpMessageConverter.convertFieldEnumerationToMap(request); Map<String, List<String>> queryParameters = new LinkedHashMap<String, List<String>>(); for (Entry<String, String[]> entry : req.getParameterMap().entrySet()) { queryParameters.put(entry.getKey(), Arrays.asList(entry.getValue())); } EntityProvider entityProvider = new EntityProvider() { @Override public byte[] getEntity() throws IOException { byte[] entity = (byte[]) req.getAttribute(ATTRIBUTE_NAME); if (entity == null) { entity = IOUtils.toByteArray(req.getInputStream()); req.setAttribute(ATTRIBUTE_NAME, entity); } return entity; } }; RequestInfo requestInfo = new RequestInfo(remoteAddress, remotePort, localAddress, localPort, protocol, method, requestURI, headers, queryParameters, entityProvider, configuration.getRequestInformation(request)); try { AuthenticationResult result = authenticator.authenticate(requestInfo); for (Entry<String, List<String>> entry : result.getResponseHeaders().entrySet()) { if (StringUtils.isNotBlank(entry.getKey()) && entry.getValue() != null) { for (int i = 0; i < entry.getValue().size(); i++) { if (i == 0) { response.setHeader(entry.getKey(), entry.getValue().get(i)); } else { response.addHeader(entry.getKey(), entry.getValue().get(i)); } } } } switch (result.getStatus()) { case CHALLENGED: response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return org.eclipse.jetty.server.Authentication.SEND_CONTINUE; case SUCCESS: Principal userPrincipal = new KnownUser(StringUtils.trimToEmpty(result.getUsername()), null); Subject subject = new Subject(); subject.getPrincipals().add(userPrincipal); return new UserAuthentication(getAuthMethod(), new DefaultUserIdentity(subject, userPrincipal, new String[] { "user" })); case FAILURE: default: response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return org.eclipse.jetty.server.Authentication.SEND_FAILURE; } } catch (Throwable t) { logger.error("Error in HTTP authentication for " + connectorProperties.getName() + " (" + connectorProperties.getName() + " \"Source\" on channel " + getChannelId() + ").", t); eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), null, ErrorEventType.DESTINATION_CONNECTOR, "Source", connectorProperties.getName(), "Error in HTTP authentication for " + connectorProperties.getName(), t)); throw new ServerAuthException(t); } } @Override public boolean secureResponse(ServletRequest request, ServletResponse response, boolean mandatory, User validatedUser) throws ServerAuthException { return true; } }); securityHandler.addConstraintMapping(constraintMapping); securityHandler.setHandler(handler); return securityHandler; }
From source file:org.soaplab.clients.spinet.filters.RequestDumperFilter.java
/** * Time the processing that is performed by all subsequent filters in the * current filter stack, including the ultimately invoked servlet. * * @param request The servlet request we are processing * @param result The servlet response we are creating * @param chain The filter chain we are processing * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs *///from w ww . j av a2s . c o m public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return; // Render the generic servlet request properties StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); writer.println("Request Received at " + (new Timestamp(System.currentTimeMillis()))); writer.println(" characterEncoding=" + request.getCharacterEncoding()); writer.println(" contentLength=" + request.getContentLength()); writer.println(" contentType=" + request.getContentType()); writer.println(" locale=" + request.getLocale()); writer.print(" locales="); Enumeration locales = request.getLocales(); boolean first = true; while (locales.hasMoreElements()) { Locale locale = (Locale) locales.nextElement(); if (first) first = false; else writer.print(", "); writer.print(locale.toString()); } writer.println(); Enumeration names = request.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); writer.print(" parameter=" + name + "="); String values[] = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (i > 0) writer.print(", "); writer.print(values[i]); } writer.println(); } writer.println(" protocol=" + request.getProtocol()); writer.println(" remoteAddr=" + request.getRemoteAddr()); writer.println(" remoteHost=" + request.getRemoteHost()); writer.println(" scheme=" + request.getScheme()); writer.println(" serverName=" + request.getServerName()); writer.println(" serverPort=" + request.getServerPort()); writer.println(" isSecure=" + request.isSecure()); // Render the HTTP servlet request properties if (request instanceof HttpServletRequest) { writer.println("---------------------------------------------"); HttpServletRequest hrequest = (HttpServletRequest) request; writer.println(" contextPath=" + hrequest.getContextPath()); Cookie cookies[] = hrequest.getCookies(); if (cookies == null) cookies = new Cookie[0]; for (int i = 0; i < cookies.length; i++) { writer.println(" cookie=" + cookies[i].getName() + "=" + cookies[i].getValue()); } names = hrequest.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = hrequest.getHeader(name); writer.println(" header=" + name + "=" + value); } writer.println(" method=" + hrequest.getMethod()); writer.println(" pathInfo=" + hrequest.getPathInfo()); writer.println(" queryString=" + hrequest.getQueryString()); writer.println(" remoteUser=" + hrequest.getRemoteUser()); writer.println("requestedSessionId=" + hrequest.getRequestedSessionId()); writer.println(" requestURI=" + hrequest.getRequestURI()); writer.println(" servletPath=" + hrequest.getServletPath()); } writer.println("============================================="); // Log the resulting string writer.flush(); filterConfig.getServletContext().log(sw.getBuffer().toString()); log.info(sw.getBuffer().toString()); // Pass control on to the next filter chain.doFilter(request, response); }
From source file:org.zilverline.web.RequestDumperFilter.java
/** * Time the processing that is performed by all subsequent filters in the current filter stack, including the ultimately invoked * servlet./*from w w w. j a v a2 s. com*/ * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param chain The filter chain we are processing * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (filterConfig == null) { return; } log.debug("Request Received at " + (new Timestamp(System.currentTimeMillis()))); log.debug(" characterEncoding=" + request.getCharacterEncoding()); log.debug(" contentLength=" + request.getContentLength()); log.debug(" contentType=" + request.getContentType()); log.debug(" locale=" + request.getLocale()); Enumeration locales = request.getLocales(); StringBuffer localesBuffer = new StringBuffer(" locales="); boolean first = true; while (locales.hasMoreElements()) { Locale locale = (Locale) locales.nextElement(); if (first) { first = false; } else { localesBuffer.append(", "); } localesBuffer.append(locale.toString()); } log.debug(localesBuffer); Enumeration names = request.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); StringBuffer paramsBuffer = new StringBuffer(); paramsBuffer.append(" parameter=" + name + "="); String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (i > 0) { paramsBuffer.append(", "); } paramsBuffer.append(values[i]); } log.debug(paramsBuffer); } log.debug(" protocol=" + request.getProtocol()); log.debug(" remoteAddr=" + request.getRemoteAddr()); log.debug(" remoteHost=" + request.getRemoteHost()); log.debug(" scheme=" + request.getScheme()); log.debug(" serverName=" + request.getServerName()); log.debug(" serverPort=" + request.getServerPort()); log.debug(" isSecure=" + request.isSecure()); // Render the HTTP servlet request properties if (request instanceof HttpServletRequest) { log.debug("---------------------------------------------"); HttpServletRequest hrequest = (HttpServletRequest) request; log.debug(" contextPath=" + hrequest.getContextPath()); Cookie[] cookies = hrequest.getCookies(); if (cookies == null) { cookies = new Cookie[0]; } for (int i = 0; i < cookies.length; i++) { log.debug(" cookie=" + cookies[i].getName() + "=" + cookies[i].getValue()); } names = hrequest.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = hrequest.getHeader(name); log.debug(" header=" + name + "=" + value); } log.debug(" method=" + hrequest.getMethod()); log.debug(" pathInfo=" + hrequest.getPathInfo()); log.debug(" queryString=" + hrequest.getQueryString()); log.debug(" remoteUser=" + hrequest.getRemoteUser()); log.debug("requestedSessionId=" + hrequest.getRequestedSessionId()); log.debug(" requestURI=" + hrequest.getRequestURI()); log.debug(" servletPath=" + hrequest.getServletPath()); } log.debug("============================================="); // Pass control on to the next filter chain.doFilter(request, response); }
From source file:edu.vt.middleware.servlet.filter.RequestDumperFilter.java
/** {@inheritDoc} */ @SuppressWarnings(value = "unchecked") public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (this.config == null) { return;/*w w w .j a v a 2 s . co m*/ } // Just pass through to next filter if we're not at TRACE level if (!logger.isTraceEnabled()) { chain.doFilter(request, response); return; } // Create a variable to hold the (possibly different) request // passed to downstream filters ServletRequest downstreamRequest = request; // Render the generic servlet request properties final StringWriter sw = new StringWriter(); final PrintWriter writer = new PrintWriter(sw); writer.println("Dumping request..."); writer.println("-----------------------------------------------------"); writer.println("REQUEST received " + Calendar.getInstance().getTime()); writer.println(" characterEncoding=" + request.getCharacterEncoding()); writer.println(" contentLength=" + request.getContentLength()); writer.println(" contentType=" + request.getContentType()); writer.println(" locale=" + request.getLocale()); writer.print(" locales="); final Enumeration<Locale> locales = request.getLocales(); for (int i = 0; locales.hasMoreElements(); i++) { if (i > 0) { writer.print(", "); } writer.print(locales.nextElement()); } writer.println(); final Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { final String name = paramNames.nextElement(); writer.print(" parameter=" + name + "="); final String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (i > 0) { writer.print(", "); } writer.print(values[i]); } writer.println(); } writer.println(" protocol=" + request.getProtocol()); writer.println(" remoteAddr=" + request.getRemoteAddr()); writer.println(" remoteHost=" + request.getRemoteHost()); writer.println(" scheme=" + request.getScheme()); writer.println(" serverName=" + request.getServerName()); writer.println(" serverPort=" + request.getServerPort()); writer.println(" isSecure=" + request.isSecure()); // Render the HTTP servlet request properties if (request instanceof HttpServletRequest) { final HttpServletRequest hrequest = (HttpServletRequest) request; writer.println(" contextPath=" + hrequest.getContextPath()); Cookie[] cookies = hrequest.getCookies(); if (cookies == null) { cookies = new Cookie[0]; } for (int i = 0; i < cookies.length; i++) { writer.println(" cookie=" + cookies[i].getName() + "=" + cookies[i].getValue()); } final Enumeration<String> headerNames = hrequest.getHeaderNames(); while (headerNames.hasMoreElements()) { final String name = headerNames.nextElement(); final String value = hrequest.getHeader(name); writer.println(" header=" + name + "=" + value); } writer.println(" method=" + hrequest.getMethod()); writer.println(" pathInfo=" + hrequest.getPathInfo()); writer.println(" queryString=" + hrequest.getQueryString()); writer.println(" remoteUser=" + hrequest.getRemoteUser()); writer.println("requestedSessionId=" + hrequest.getRequestedSessionId()); writer.println(" requestURI=" + hrequest.getRequestURI()); writer.println(" servletPath=" + hrequest.getServletPath()); // Create a wrapped request that contains the request body // and that we will pass to downstream filters final ByteArrayRequestWrapper wrappedRequest = new ByteArrayRequestWrapper(hrequest); downstreamRequest = wrappedRequest; writer.println(wrappedRequest.getRequestBodyAsString()); } writer.println("-----------------------------------------------------"); // Log the resulting string writer.flush(); logger.trace(sw.getBuffer().toString()); // Pass control on to the next filter chain.doFilter(downstreamRequest, response); }