List of usage examples for javax.servlet.http HttpServletRequest getRemoteHost
public String getRemoteHost();
From source file:br.com.siprot.framework.servlet.FacesServlet.java
public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException { HttpServletRequest httpRequest = ((HttpServletRequest) request); String pathInfo = httpRequest.getPathInfo(); // if it is a prefix mapping ... if (pathInfo != null && (pathInfo.startsWith("/WEB-INF") || pathInfo.startsWith("/META-INF"))) { StringBuffer buffer = new StringBuffer(); buffer.append(" Someone is trying to access a secure resource : ").append(pathInfo); buffer.append("\n remote address is ").append(httpRequest.getRemoteAddr()); buffer.append("\n remote host is ").append(httpRequest.getRemoteHost()); buffer.append("\n remote user is ").append(httpRequest.getRemoteUser()); buffer.append("\n request URI is ").append(httpRequest.getRequestURI()); log.warn(buffer.toString());//from w w w. jav a 2s .c o m // Why does RI return a 404 and not a 403, SC_FORBIDDEN ? ((HttpServletResponse) response).sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (log.isTraceEnabled()) log.trace("service begin"); FacesContext facesContext = _facesContextFactory.getFacesContext(_servletConfig.getServletContext(), request, response, _lifecycle); try { _lifecycle.execute(facesContext); _lifecycle.render(facesContext); } catch (Throwable e) { //bloco de tratamento para excecao tratada if (e instanceof FacesException) { try { ErrorHandler.handleException(facesContext, (Exception) e); _lifecycle.render(facesContext); } catch (Exception ex) { throw new ServletException(ex); } } //fim do bloco de tratamento else if (e instanceof IOException) { throw (IOException) e; } else if (e instanceof ServletException) { throw (ServletException) e; } else if (e.getMessage() != null) { throw new ServletException(e.getMessage(), e); } else { throw new ServletException(e); } } finally { facesContext.release(); } if (log.isTraceEnabled()) log.trace("service end"); }
From source file:net.sourceforge.vulcan.web.struts.actions.ToggleSchedulerAction.java
@Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { final String schedulerName = request.getParameter("schedulerName"); if (StringUtils.isBlank(schedulerName)) { throw new IllegalArgumentException("Missing request paraemeter 'schedulerName'"); }//w w w.j a v a2 s .c om final SchedulerConfigDto schedulerConfig = (SchedulerConfigDto) stateManager .getSchedulerConfig(schedulerName).copy(); final String action = schedulerConfig.isPaused() ? "unpause" : "pause"; final AuditEvent event = new AuditEvent(this, "audit.scheduler.toggle", BaseDispatchAction.getUsername(request), request.getRemoteHost(), action, "scheduler", schedulerName, null); eventHandler.reportEvent(event); auditLog.info(messageSource.getMessage(event.getKey(), event.getArgs(), Locale.getDefault())); schedulerConfig.setPaused(!schedulerConfig.isPaused()); stateManager.updateSchedulerConfig(schedulerName, schedulerConfig, false); return mapping.findForward("dashboard"); }
From source file:com.example.HoneycombFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { chain.doFilter(request, response); return;// ww w . j a va2s.c o m } HttpServletRequest req = (HttpServletRequest) request; long start = System.nanoTime(); try { chain.doFilter(request, response); } finally { long responseTimeNanos = System.nanoTime() - start; Event event = libhoney.newEvent(); event.addField("method", req.getMethod()); event.addField("path", req.getRequestURI()); event.addField("query", req.getQueryString()); Principal principal = req.getUserPrincipal(); if (principal != null) { event.addField("user", principal.getName()); } event.addField("host", req.getRemoteHost()); event.addField("responseTimeNanos", responseTimeNanos); try { event.send(); } catch (HoneyException e) { log.error(e.getMessage(), e); } } }
From source file:fr.hoteia.qalingo.web.handler.security.ExtSimpleUrlAuthenticationSuccessHandler.java
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { // Find the current customer Customer customer = customerService.getCustomerByLoginOrEmail(authentication.getName()); // Persit only the new CustomerConnectionLog CustomerConnectionLog customerConnectionLog = new CustomerConnectionLog(); customerConnectionLog.setCustomerId(customer.getId()); customerConnectionLog.setLoginDate(new Date()); customerConnectionLog.setApp(Constants.APP_NAME_FO_MCOMMERCE_CODE); customerConnectionLog.setHost(request.getRemoteHost()); customerConnectionLog.setAddress(request.getRemoteAddr()); customerConnectionLogService.saveOrUpdateCustomerConnectionLog(customerConnectionLog); try {//w w w.ja va2 s .c om // Update the Customer in Session customer.getConnectionLogs().add(customerConnectionLog); requestUtil.updateCurrentCustomer(request, customer); setUseReferer(false); String url = requestUtil.getCurrentRequestUrlNotSecurity(request); // SANITY CHECK if (StringUtils.isEmpty(url)) { url = urlService.generateUrl(FoUrls.HOME, requestUtil.getRequestData(request)); } else { String cartDetails = "cart-details.html"; if (url.contains(cartDetails)) { url = urlService.generateUrl(FoUrls.CART_DELIVERY, requestUtil.getRequestData(request)); } } setDefaultTargetUrl(url); redirectStrategy.sendRedirect(request, response, url); } catch (Exception e) { LOG.error("", e); } }
From source file:com.legstar.c2ws.servlet.C2wsProxy.java
/** {@inheritDoc} */ protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException { long startTime = System.currentTimeMillis(); /* Use correlation id received in http header. This allows logs on * this side to be easily correlated with the mainframe logs. */ String requestID = request.getHeader(CORRELATION_ID_HDR); if (LOG.isDebugEnabled()) { LOG.debug("Start proxy request " + requestID + " from client " + request.getRemoteHost()); }//from w ww. j a v a 2 s. co m /* Make sure this is a Mainframe LegStar request. */ if (!isSupportedContentType(request)) { throw new ServletException("Content type " + request.getContentType() + " is not supported"); } try { /* Get all the bytes from the request in a byte array */ int requestBytesLen = request.getContentLength(); byte[] requestBytes = new byte[requestBytesLen]; InputStream in = request.getInputStream(); int offset = 0; int n; do { n = in.read(requestBytes, offset, requestBytesLen - offset); } while (n != -1); if (LOG.isDebugEnabled()) { LOG.debug("Request data from host:"); traceData(requestID, requestBytes, LOG); } /* Call the proxy getting a byte array back */ byte[] replyBytes = getServiceProxy().invoke(requestID, requestBytes); if (LOG.isDebugEnabled()) { LOG.debug("Reply data to host:"); traceData(requestID, replyBytes, LOG); } /* Push the reply byte array into the http response */ response.setContentType(request.getContentType()); response.getOutputStream().write(replyBytes); } catch (IOException e) { throw (new ServletException(e)); } catch (ProxyInvokerException e) { throw (new ServletException(e)); } long endTime = System.currentTimeMillis(); if (LOG.isDebugEnabled()) { LOG.debug("End proxy request " + requestID + " from client " + request.getRemoteHost() + " serviced in " + (endTime - startTime) + " msecs"); } }
From source file:org.ejbca.ui.web.protocol.OCSPServlet.java
private void processOcspRequest(HttpServletRequest request, HttpServletResponse response, final HttpMethod httpMethod) throws ServletException { final String remoteAddress = request.getRemoteAddr(); final String remoteHost = request.getRemoteHost(); final StringBuffer requestUrl = request.getRequestURL(); final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), remoteAddress); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), remoteAddress);// w w w. ja v a 2 s.c om try { if (auditLogger.isEnabled()) { auditLogger.paramPut(PatternLogger.LOG_ID, Integer.valueOf(localTransactionId)); auditLogger.paramPut(PatternLogger.SESSION_ID, sessionID); auditLogger.paramPut(PatternLogger.CLIENT_IP, remoteAddress); } if (transactionLogger.isEnabled()) { transactionLogger.paramPut(PatternLogger.LOG_ID, Integer.valueOf(localTransactionId)); transactionLogger.paramPut(PatternLogger.SESSION_ID, sessionID); transactionLogger.paramPut(PatternLogger.CLIENT_IP, remoteAddress); } OCSPRespBuilder responseGenerator = new OCSPRespBuilder(); OcspResponseInformation ocspResponseInformation = null; try { byte[] requestBytes = checkAndGetRequestBytes(request, httpMethod); X509Certificate[] requestCertificates = (X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"); ocspResponseInformation = integratedOcspResponseGeneratorSession.getOcspResponse(requestBytes, requestCertificates, remoteAddress, remoteHost, requestUrl, auditLogger, transactionLogger); } catch (MalformedRequestException e) { if (transactionLogger.isEnabled()) { transactionLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME); } if (auditLogger.isEnabled()) { auditLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME); } String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); log.info(errMsg); if (log.isDebugEnabled()) { log.debug(errMsg, e); } // RFC 2560: responseBytes are not set on error. ocspResponseInformation = new OcspResponseInformation( responseGenerator.build(OCSPRespBuilder.MALFORMED_REQUEST, null), OcspConfiguration.getMaxAge(CertificateProfileConstants.CERTPROFILE_NO_PROFILE)); if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.MALFORMED_REQUEST); transactionLogger.writeln(); } if (auditLogger.isEnabled()) { auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.MALFORMED_REQUEST); } } catch (Throwable e) { // NOPMD, we really want to catch everything here to return internal error on unexpected errors if (transactionLogger.isEnabled()) { transactionLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); } if (auditLogger.isEnabled()) { auditLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); } final String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); log.info(errMsg); if (log.isDebugEnabled()) { log.debug(errMsg, e); } // RFC 2560: responseBytes are not set on error. ocspResponseInformation = new OcspResponseInformation( responseGenerator.build(OCSPRespBuilder.INTERNAL_ERROR, null), OcspConfiguration.getMaxAge(CertificateProfileConstants.CERTPROFILE_NO_PROFILE)); if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.INTERNAL_ERROR); transactionLogger.writeln(); } if (auditLogger.isEnabled()) { auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.INTERNAL_ERROR); } } byte[] ocspResponseBytes = ocspResponseInformation.getOcspResponse(); response.setContentType("application/ocsp-response"); response.setContentLength(ocspResponseBytes.length); if (HttpMethod.GET.equals(httpMethod)) { addRfc5019CacheHeaders(request, response, ocspResponseInformation); } else { if (log.isDebugEnabled()) { log.debug( "Will not add RFC 5019 cache headers: \"clients MUST use the GET method (to enable OCSP response caching)\""); } } response.getOutputStream().write(ocspResponseBytes); response.getOutputStream().flush(); } catch (Exception e) { log.error("", e); transactionLogger.flush(); auditLogger.flush(); } }
From source file:org.jolokia.http.AgentServlet.java
@SuppressWarnings({ "PMD.AvoidCatchingThrowable", "PMD.AvoidInstanceofChecksInCatchClause" }) private void handle(ServletRequestHandler pReqHandler, HttpServletRequest pReq, HttpServletResponse pResp) throws IOException { JSONAware json = null;/* w w w. ja v a 2 s.com*/ try { // Check access policy requestHandler.checkAccess(allowDnsReverseLookup ? pReq.getRemoteHost() : null, pReq.getRemoteAddr(), getOriginOrReferer(pReq)); // Remember the agent URL upon the first request. Needed for discovery updateAgentDetailsIfNeeded(pReq); // Dispatch for the proper HTTP request method json = handleSecurely(pReqHandler, pReq, pResp); } catch (Throwable exp) { json = requestHandler.handleThrowable( exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp); } finally { setCorsHeader(pReq, pResp); String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue()); String answer = json != null ? json.toJSONString() : requestHandler.handleThrowable(new Exception("Internal error while handling an exception")) .toJSONString(); if (callback != null) { // Send a JSONP response sendResponse(pResp, "text/javascript", callback + "(" + answer + ");"); } else { sendResponse(pResp, getMimeType(pReq), answer); } } }
From source file:com.redhat.rhn.frontend.servlets.DumpFilter.java
/** {@inheritDoc} */ public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (log.isDebugEnabled()) { // handle request HttpServletRequest request = (HttpServletRequest) req; log.debug("Entered doFilter() ==================================="); log.debug("AuthType: " + request.getAuthType()); log.debug("Method: " + request.getMethod()); log.debug("PathInfo: " + request.getPathInfo()); log.debug("Translated path: " + request.getPathTranslated()); log.debug("ContextPath: " + request.getContextPath()); log.debug("Query String: " + request.getQueryString()); log.debug("Remote User: " + request.getRemoteUser()); log.debug("Remote Host: " + request.getRemoteHost()); log.debug("Remote Addr: " + request.getRemoteAddr()); log.debug("SessionId: " + request.getRequestedSessionId()); log.debug("uri: " + request.getRequestURI()); log.debug("url: " + request.getRequestURL().toString()); log.debug("Servlet path: " + request.getServletPath()); log.debug("Server Name: " + request.getServerName()); log.debug("Server Port: " + request.getServerPort()); log.debug("RESPONSE encoding: " + resp.getCharacterEncoding()); log.debug("REQUEST encoding: " + request.getCharacterEncoding()); log.debug("JVM encoding: " + System.getProperty("file.encoding")); logSession(request.getSession()); logHeaders(request);// w ww . j a v a 2 s . c o m logCookies(request.getCookies()); logParameters(request); logAttributes(request); log.debug("Calling chain.doFilter() -----------------------------"); } chain.doFilter(req, resp); if (log.isDebugEnabled()) { log.debug("Returned from chain.doFilter() -----------------------"); log.debug("Handle Response, not much to print"); log.debug("Response: " + resp.toString()); log.debug("Leaving doFilter() ==================================="); } }
From source file:com.adito.security.actions.UpdatePrivateKeyPassphraseDispatchAction.java
private ActionForward cleanUpAndReturn(ActionMapping mapping, HttpServletRequest request, ActionForward af) { CoreUtil.removePageInterceptListener(request.getSession(), "updatePrivateKeyPassphrase"); /*//from ww w. ja v a 2 s .c o m * And update the user attributes and fire the logon event */ CoreServlet.getServlet() .fireCoreEvent(new CoreEvent(this, CoreEventConstants.LOGON, getSessionInfo(request).getCredentials(), getSessionInfo(request)) .addAttribute(CoreAttributeConstants.EVENT_ATTR_IP_ADDRESS, request.getRemoteAddr()) .addAttribute(CoreAttributeConstants.EVENT_ATTR_HOST, request.getRemoteHost())); return af; }