List of usage examples for javax.servlet ServletRequest getServerPort
public int getServerPort();
From source file:org.beangle.security.web.auth.LoginUrlEntryPoint.java
/** * Performs the redirect (or forward) to the login form URL. *///from w w w. j a v a 2 s . co m public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String redirectUrl = null; if (serverSideRedirect) { String loginForm = determineUrlToUseForThisRequest(httpRequest, httpResponse, authException); logger.debug("Server side forward to: {}", loginForm); RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(loginForm); dispatcher.forward(request, response); return; } else { // redirect to login page. Use https if forceHttps true redirectUrl = determineUrlToUseForThisRequest(httpRequest, httpResponse, authException); } if (!("XMLHttpRequest".equals(httpRequest.getHeader("x-requested-with")) || StringUtils.isNotEmpty(httpRequest.getParameter("x-requested-with")))) { String backurl = new UrlBuilder(httpRequest.getContextPath()).scheme(request.getScheme()) .serverName(request.getServerName()).port(request.getServerPort()) .servletPath(httpRequest.getServletPath()).queryString(httpRequest.getQueryString()).buildUrl(); redirectUrl += "?backurl=" + URLEncoder.encode(backurl); } // httpRequest.getSession().setAttribute("backurl", backurl); // httpRequest.getSession().setAttribute("backurltime", System.currentTimeMillis()); RedirectUtils.sendRedirect(httpRequest, httpResponse, redirectUrl); }
From source file:net.sf.j2ep.RewriteFilter.java
/** * Rewrites the outgoing stream to make sure URLs and headers * are correct. The incoming request is first processed to * identify what resource we want to proxy. * /*www . ja va 2s. c o m*/ * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; HttpServletRequest httpRequest = (HttpServletRequest) request; //httpRequest.setCharacterEncoding("UTF-8"); //httpResponse.setCharacterEncoding("UTF-8"); if (response.isCommitted()) { log.info("Not proxying, already committed."); return; } else if (!(request instanceof HttpServletRequest)) { log.info("Request is not HttpRequest, will only handle HttpRequests."); return; } else if (!(response instanceof HttpServletResponse)) { log.info("Request is not HttpResponse, will only handle HttpResponses."); return; } else { Server server = serverChain.evaluate(httpRequest); if (server == null) { log.info("Could not find a rule for this request, will not do anything."); filterChain.doFilter(request, response); } else { httpRequest.setAttribute("proxyServer", server); String ownHostName = request.getServerName() + ":" + request.getServerPort(); UrlRewritingResponseWrapper wrappedResponse; wrappedResponse = new UrlRewritingResponseWrapper(httpResponse, server, ownHostName, httpRequest, serverChain); filterChain.doFilter(httpRequest, wrappedResponse); wrappedResponse.processStream(); } } }
From source file:org.jahia.services.content.JCRStoreProvider.java
public String getAbsoluteContextPath(ServletRequest request) { StringBuilder serverUrlBuffer = new StringBuilder(request.getScheme()); serverUrlBuffer.append("://"); serverUrlBuffer.append(request.getServerName()); if (request.getServerPort() != 80 && request.getServerPort() != 443) { serverUrlBuffer.append(":"); serverUrlBuffer.append(request.getServerPort()); }//from w w w . j a v a2 s . c o m return serverUrlBuffer.toString(); }
From source file:org.ambraproject.web.VirtualJournalContextFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { final Collection<String> virtualJournals = configuration.getList(CONF_VIRTUALJOURNALS_JOURNALS); String defaultJournal = configuration.getString(CONF_VIRTUALJOURNALS_DEFAULT); // need to do <rule> based processing String journalName = findMatchingVirtualJournal(configuration, (HttpServletRequest) request); if (journalName != null) { if (log.isTraceEnabled()) { log.trace("journal from rules: journal = \"" + journalName + "\""); }//from w w w.j a v a 2s.c o m } else { // was a simple config <default> specified? journalName = defaultJournal; if (log.isTraceEnabled()) { log.trace("journal from defaults: journal = \"" + journalName + "\""); } } // empty if default not set if (journalName == null) { journalName = ""; if (log.isTraceEnabled()) { log.trace("Default journal not set"); } } if (log.isDebugEnabled()) { log.debug("journal = \"" + journalName + "\" for " + ((HttpServletRequest) request).getRequestURL()); } // put virtualJournal context in the ServletRequest for webapp to use request.setAttribute(VirtualJournalContext.PUB_VIRTUALJOURNAL_CONTEXT, new VirtualJournalContext(journalName, defaultJournal, request.getScheme(), request.getServerPort(), request.getServerName(), ((HttpServletRequest) request).getContextPath(), virtualJournals)); /* * Establish a "Nested Diagnostic Context" for logging, e.g. prefix log entries w/journal name * http://logging.apache.org/log4j/docs/api/org/apache/log4j/NDC.html */ NDC.push(journalName); try { // continue the Filter chain ... filterChain.doFilter(request, response); } finally { // cleanup "Nested Diagnostic Context" for logging NDC.pop(); NDC.remove(); // TODO: appropriate place to cleanup for Thread? } }
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/*from ww w.j av a2s . co 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: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 w w . ja v a2 s .com*/ 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 . ja v a2 s. c o m * * @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;/*from ww w. j av a 2s . c o 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); }
From source file:com.evon.injectTemplate.InjectTemplateFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; StringWriter writer = new StringWriter(); BufferedResponseWrapper wrapper = new BufferedResponseWrapper((HttpServletResponse) response, writer); chain.doFilter(request, wrapper);//w ww . j a v a 2 s .c om String contentType = null; String uri = httpRequest.getRequestURI(); contentType = httpResponse.getContentType(); if (contentTypes.containsKey(uri)) { contentType = contentTypes.get(uri); } else if (contentType != null) { contentTypes.put(uri, contentType); } contentType = (contentType == null) ? "none" : contentType; String out = writer.getBuffer().toString(); boolean requestedURIIsTheTemplate = false; requestedURIIsTheTemplate = InjectUtils.isTemplate(uri); boolean contentTypeIsText = !wrapper.isBinary() && contentType != null && !contentType.equals("none"); if (requestedURIIsTheTemplate || !contentTypeIsText) { if (contentTypeIsText) { response.getWriter().print(out); } return; } if (!templateLodaded && !templateLodadedStarted) { loadTemplates(httpRequest); } TemplateBean template = getTemplatePathByURI(uri); if (template == null) { response.getWriter().print(out); return; } String key = null; if (template.cache.equals("SESSION")) { String cookiesNames = getCookieHashs(httpRequest); key = template.path + cookiesNames; } else if (template.cache.equals("ON")) { key = template.path; } if (!templates.containsKey("/" + template.path)) { throw new ServletException("Template [" + template.path + "] not founded"); } boolean needRefresh = template.refreshInSeconds > 0 && ((System.currentTimeMillis() - template.lastUpdate) / 1000) > template.refreshInSeconds; boolean replaceTemplate = template.cache.equals("OFF") || !htmlContents.containsKey(key) || needRefresh; /* pra investigar erro de nulo, boolean notExist = key==null || !htmlContents.containsKey(key); * if(!notExist) { notExist=!notExist; //throw new ServletException("content not exist"); } */ if (replaceTemplate) { if (needRefresh) { template.lastUpdate = System.currentTimeMillis(); } try { loadContentTemplate(template, request.getServerName(), request.getServerPort(), request.getProtocol().contains("HTTPS"), httpRequest); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } HTMLInfoBean templateHTML = templates.get("/" + template.path); String contentTemplate = htmlContents.get(key).getContent(); IDocument docOut = HTMLParser.parse(out); for (String selector : templateHTML.getSelectors()) { IElements elements = docOut.select(selector); if (elements.size() == 0) { System.out.println("WARNING: Selector [" + selector + "] in template [" + templateHTML.getUri() + "] not founded in [" + httpRequest.getRequestURI() + "]"); continue; } if (elements.size() != 1) { System.out.println( "WARNING: Selector get many elements. Choosed the first to URI: " + templateHTML.getUri()); } IElement element = elements.get(0); String innerHTML = element.html(); contentTemplate = contentTemplate.replace("<INJECT selector='" + selector + "'/>", innerHTML); } response.getWriter().print(contentTemplate); }
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) {/* w w w. j ava 2 s .c o 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; }