List of usage examples for javax.servlet.http HttpServletRequest getRemoteHost
public String getRemoteHost();
From source file:org.apache.hadoop.gateway.AuditLoggingTest.java
@Test /**/*from w w w. j ava 2 s . c o m*/ * Empty filter chain. Two events with same correlation ID are expected: * * action=access request_type=uri outcome=unavailable * action=access request_type=uri outcome=success message=Response status: 404 */ public void testNoFiltersAudit() throws ServletException, IOException { FilterConfig config = EasyMock.createNiceMock(FilterConfig.class); EasyMock.replay(config); HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class); ServletContext context = EasyMock.createNiceMock(ServletContext.class); GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class); EasyMock.expect(request.getMethod()).andReturn(METHOD).anyTimes(); EasyMock.expect(request.getPathInfo()).andReturn(PATH).anyTimes(); EasyMock.expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes(); EasyMock.expect(request.getRemoteAddr()).andReturn(ADDRESS).anyTimes(); EasyMock.expect(request.getRemoteHost()).andReturn(HOST).anyTimes(); EasyMock.expect(request.getServletContext()).andReturn(context).anyTimes(); EasyMock.expect(context.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE)).andReturn(gatewayConfig) .anyTimes(); EasyMock.expect(gatewayConfig.getHeaderNameForRemoteAddress()).andReturn("Custom-Forwarded-For").anyTimes(); EasyMock.replay(request); EasyMock.replay(context); EasyMock.replay(gatewayConfig); HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class); EasyMock.replay(response); FilterChain chain = EasyMock.createNiceMock(FilterChain.class); EasyMock.replay(chain); GatewayFilter gateway = new GatewayFilter(); gateway.init(config); gateway.doFilter(request, response, chain); gateway.destroy(); assertThat(CollectAppender.queue.size(), is(1)); Iterator<LoggingEvent> iterator = CollectAppender.queue.iterator(); LoggingEvent accessEvent = iterator.next(); verifyAuditEvent(accessEvent, CONTEXT_PATH + PATH, ResourceType.URI, Action.ACCESS, ActionOutcome.UNAVAILABLE, null, "Request method: GET"); }
From source file:org.apache.hadoop.gateway.AuditLoggingTest.java
@Test /**/*from w ww. j a v a 2 s.c o m*/ * One NoOp filter in chain. Single audit event with same with specified request URI is expected: * * action=access request_type=uri outcome=unavailable */ public void testNoopFilter() throws ServletException, IOException, URISyntaxException { FilterConfig config = EasyMock.createNiceMock(FilterConfig.class); EasyMock.replay(config); HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class); ServletContext context = EasyMock.createNiceMock(ServletContext.class); GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class); EasyMock.expect(request.getMethod()).andReturn(METHOD).anyTimes(); EasyMock.expect(request.getPathInfo()).andReturn(PATH).anyTimes(); EasyMock.expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes(); EasyMock.expect(request.getRemoteAddr()).andReturn(ADDRESS).anyTimes(); EasyMock.expect(request.getRemoteHost()).andReturn(HOST).anyTimes(); EasyMock.expect(request.getServletContext()).andReturn(context).anyTimes(); EasyMock.expect(context.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE)).andReturn(gatewayConfig) .anyTimes(); EasyMock.expect(gatewayConfig.getHeaderNameForRemoteAddress()).andReturn("Custom-Forwarded-For").anyTimes(); EasyMock.replay(request); EasyMock.replay(context); EasyMock.replay(gatewayConfig); HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class); EasyMock.replay(response); FilterChain chain = EasyMock.createNiceMock(FilterChain.class); EasyMock.replay(chain); Filter filter = EasyMock.createNiceMock(Filter.class); EasyMock.replay(filter); GatewayFilter gateway = new GatewayFilter(); gateway.addFilter("path", "filter", filter, null, null); gateway.init(config); gateway.doFilter(request, response, chain); gateway.destroy(); assertThat(CollectAppender.queue.size(), is(1)); Iterator<LoggingEvent> iterator = CollectAppender.queue.iterator(); LoggingEvent accessEvent = iterator.next(); verifyAuditEvent(accessEvent, CONTEXT_PATH + PATH, ResourceType.URI, Action.ACCESS, ActionOutcome.UNAVAILABLE, null, "Request method: GET"); }
From source file:org.paxle.gui.impl.HttpAuthManager.java
public User httpAuth(final HttpServletRequest request, String httpAuthHeader) throws UnsupportedEncodingException { if (httpAuthHeader == null || httpAuthHeader.length() <= "Basic ".length()) { return null; }// ww w . j a v a 2s . c om // base64 decode and get username + password byte[] authBytes = Base64.decodeBase64(httpAuthHeader.substring("Basic ".length()).getBytes("UTF-8")); httpAuthHeader = new String(authBytes, "UTF-8"); String[] authData = httpAuthHeader.split(":"); if (authData.length == 0) { logger.info(String.format("[%s] No user-authentication data found to access '%s'.", request.getRemoteHost(), request.getRequestURI())); return null; } // extracting username + password String userName = authData[0]; String password = authData.length == 1 ? "" : authData[1]; return authenticatedAs(request, userName, password); }
From source file:org.hoteia.qalingo.core.web.handler.security.ExtSimpleUrlAuthenticationSuccessHandler.java
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { try {/* w w w . jav a 2 s. c o m*/ final RequestData requestData = requestUtil.getRequestData(request); // CUSTOMER Customer customer = customerService.getCustomerByLoginOrEmail(authentication.getName()); // Persit the new CustomerConnectionLog CustomerConnectionLog customerConnectionLog = new CustomerConnectionLog(); customerConnectionLog.setCustomerId(customer.getId()); customerConnectionLog.setLoginDate(new Date()); customerConnectionLog.setAppCode(Constants.APP_NAME_FO_MCOMMERCE_CODE); customerConnectionLog.setHost(request.getRemoteHost()); customerConnectionLog.setAddress(requestUtil.getRemoteAddr(request)); customer.getConnectionLogs().add(customerConnectionLog); customerConnectionLogService.saveOrUpdateCustomerConnectionLog(customerConnectionLog); requestUtil.updateCurrentCustomer(request, customer); // UPDATE CART WITH THE CUSTOMER INFORMATIONS webManagementService.updateCart(requestData, customer); setUseReferer(false); String url = requestUtil.getCurrentRequestUrlNotSecurity(request); String lastUrl = requestUtil.getCurrentRequestUrlNotSecurity(request); // SANITY CHECK if (StringUtils.isNotEmpty(lastUrl) && (lastUrl.contains("cart") || lastUrl.contains("checkout"))) { url = urlService.generateUrl(FoUrls.CART_DELIVERY, requestUtil.getRequestData(request)); } else { url = urlService.generateUrl(FoUrls.PERSONAL_DETAILS, requestUtil.getRequestData(request)); } setDefaultTargetUrl(url); redirectStrategy.sendRedirect(request, response, url); } catch (Exception e) { logger.error("", e); } }
From source file:nl.opengeogroep.filesetsync.server.stripes.RequestLoggerActionBean.java
@After(stages = LifecycleStage.ActionBeanResolution) public void setMDCHeaders() { MDC.clear();//from w w w .j a v a 2 s.co m HttpServletRequest r = context.getRequest(); String forwardedFor = r.getHeader("X-Forwarded-For"); MDC.put("request.remoteAddr", forwardedFor != null ? forwardedFor : r.getRemoteAddr()); String s = context.getServletContext().getInitParameter("logHeaders"); if (StringUtils.isNotBlank(s)) { for (String header : s.split(",")) { log.debug(String.format("header %s: %s", header, r.getHeader(header))); MDC.put("request.header." + header.toLowerCase(), r.getHeader(header)); } } StringBuffer url = r.getRequestURL(); if (r.getQueryString() != null) { url.append("?"); url.append(r.getQueryString()); } if (log.isTraceEnabled()) { String remoteHost = r.getRemoteHost(); if (!remoteHost.equals(r.getRemoteAddr())) { log.trace("remote host: " + r.getRemoteHost()); } } }
From source file:org.jumpmind.symmetric.web.PullUriHandler.java
public void handleWithCompression(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { // request has the "other" nodes info String nodeId = ServletUtils.getParameter(req, WebConstants.NODE_ID); log.debug("Pull request received from {}", nodeId); if (StringUtils.isBlank(nodeId)) { ServletUtils.sendError(res, HttpServletResponse.SC_BAD_REQUEST, "Node must be specified"); return;/*w w w .ja v a 2 s . c o m*/ } ChannelMap map = new ChannelMap(); map.addSuspendChannels(req.getHeader(WebConstants.SUSPENDED_CHANNELS)); map.addIgnoreChannels(req.getHeader(WebConstants.IGNORED_CHANNELS)); // pull out headers and pass to pull() method pull(nodeId, req.getRemoteHost(), req.getRemoteAddr(), res.getOutputStream(), req.getHeader(WebConstants.HEADER_ACCEPT_CHARSET), map); log.debug("Done with Pull request from {}", nodeId); }
From source file:org.ligoj.app.http.security.CaptchaFilter.java
@Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpServletRequest = (HttpServletRequest) request; final HttpSession session = httpServletRequest.getSession(false); final Captcha captcha = session == null ? null : (Captcha) session.getAttribute(Captcha.NAME); if (captcha == null) { // No session -> no CAPTCHA to match log.info("No configured for this session"); fail(response, "session", "null"); } else {//from w w w .ja v a2 s.c om session.removeAttribute(Captcha.NAME); if (captcha.isCorrect(StringUtils.trimToEmpty(httpServletRequest.getHeader(CAPTCHA_HEADER)))) { chain.doFilter(request, response); } else { // CAPTCHA does not match -> the CAPTCHA must be regenerated. log.info("Invalid captcha received from {} '{}' instead of {}", httpServletRequest.getRemoteHost(), request.getParameter(CAPTCHA_HEADER), captcha.getAnswer()); fail(response, CAPTCHA_HEADER, "invalid"); } } }
From source file:net.voidfunction.rm.common.FileServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().setMaxInactiveInterval(120); response.setHeader("Date", HTTPUtils.getServerTime(0)); // Parse the filename and the ID out of the URL String[] urlParts = request.getRequestURI().substring(1).split("/"); if (urlParts.length < 2) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return;//from w w w. ja va2 s . c o m } String fileID = urlParts[1]; String fileName = ""; if (urlParts.length > 2) fileName = urlParts[2]; String logOut = "File " + fileID + " (" + fileName + ") requested by " + request.getRemoteHost() + " [Result: "; RMFile file = node.getFileRepository().getFileById(fileID); if (file == null) { // File with given ID not found - no redirect for you. logOut += "Not found]"; node.getLog().info(logOut); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().write("<b>404 Not Found</b><br/>Could not find a file with ID " + fileID); return; } boolean workerDL = (fileName.equals("Worker-Download")); if (workerDL) logOut += " (Worker Download) "; // Let the download listener know, if any, but don't count worker downloads if (dlListener != null && !workerDL) dlListener.fileDownloaded(file); String redirURL = null; if (locator != null) redirURL = (String) request.getSession().getAttribute("fileURL-" + fileID); if (redirURL == null && locator != null) redirURL = locator.locateURL(fileID, fileName); if (redirURL != null) { node.getLog().debug("Found redirect URL: " + redirURL); request.getSession().setAttribute("fileURL-" + fileID, redirURL); // Redirect to the new URL logOut += "Redirect]"; node.getLog().info(logOut); response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); response.setHeader("Location", redirURL); } else { // We have to try to find it ourselves logOut += "Found locally]"; node.getLog().info(logOut); // Caching magic - we can safely assume the file won't change String etag = Hex.encodeHexString(file.getHash()); response.setHeader("ETag", etag); String ifModifiedSince = request.getHeader("If-Modified-Since"); String ifNoneMatch = request.getHeader("If-None-Match"); boolean etagMatch = (ifNoneMatch != null) && (ifNoneMatch.equals(etag)); if (ifModifiedSince != null || etagMatch) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("Last-Modified", ifModifiedSince); } else { // Send the HTTP response and file data response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Expires", HTTPUtils.getServerTime(3600)); response.setHeader("Cache-Control", "max-age=3600"); response.setContentType(file.getMimetype()); response.setHeader("Content-Length", String.valueOf(file.getSize())); // Stream the file data to the output stream using Apache IOUtils InputStream fileIn = node.getFileRepository().getFileData(fileID); IOUtils.copyLarge(fileIn, response.getOutputStream()); } } }
From source file:cms.service.app.ServiceController.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HashMap<String, String> userdata; AccessToken access = null;/* w w w . jav a2s .c om*/ AccessToken regaccess = null; RequestDispatcher rd; String strNextPage = null; boolean isvalidtoken = false; boolean subscription = false; String reguser = "registration"; String regpassword = "reg$56*123"; String baseurl = request.getRequestURL().toString().split("/service")[0]; String remotehost = request.getRemoteHost(); String remoteaddress = request.getRemoteAddr(); String username = request.getParameter("username"); String password = request.getParameter("password"); String useraction = request.getParameter("useraction"); String adminuser = request.getParameter("adminuser"); String usertoken = request.getParameter("usertoken"); String servicekey = request.getParameter("servicekey"); String amount = request.getParameter("amount"); String objid = request.getParameter("refobjid"); String description = request.getParameter("description"); String leadactions = "campaign whitepapers contactus training"; String sendreference = request.getParameter("sendreference"); ; Date date = new Date(); //set remote address request.setCharacterEncoding("UTF-8"); /*if(custom!=null&&!custom.equals("")){ custom="dan@softlean.com#-1624640437#127.0.0.1"; item_name="xyx"; item_number="899"; } subscription=(custom!=null&&!custom.equals(""))?true:false; logger.info(date.toString()+":-subscription="+subscription+" custom="+custom); if(subscription){ custret=custom.split("-"); if(custret.length==6) username=custret[3]; usertoken=custret[4]; tu.updatePayment(custret); } */ //first verify remote client whether the request is from same client if (!tu.isEmptyValue(servicekey)) { try { String val = new String(Base64Util.decode(servicekey.getBytes())); logger.info("servicekey=" + val); if (!tu.isEmptyValue(val)) { String[] items = val.split(CONST.IPSEPERATOR); if (items.length >= 2) { username = items[0]; password = items[1]; } if (items.length == 3) { useraction = items[2]; if (useraction.equalsIgnoreCase("campaign") && tu.isEmptyValue(sendreference)) { sendreference = "2"; } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //logger.info("\n"+date.toString()+":-username="+username+ " password="+password+" useraction="+useraction); if (CONST.GENERATE_LOG) { logger.info("\n" + date.toString() + ":-URI=" + request.getRequestURI()); logger.info("\n" + date.toString() + ":-Request Remote address=" + remoteaddress + " Remote Host=" + remotehost); } //Identify the current page as login page if (!tu.isEmptyValue(username) && !tu.isEmptyValue(password)) { //Do not check license for hosting solution access = m_service.verifyLogin(username, password, remoteaddress); } else { regaccess = m_service.verifyLogin(reguser, regpassword, remoteaddress); } if (access != null && tu.isEmptyValue(useraction)) { logger.info("\n" + date.toString() + " Loged in User:=" + username + " " + ":-Assigned Token=" + access.getToken() + ":-Assigned Modules=" + access.getModules()); //access token is appended with Client IP in the indexpage strNextPage = "/src/index.jsp?username=" + username + "&firstname=" + access.getFirstname() + "&usertoken=" + access.getToken() + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR + username + "&baseurl=" + baseurl + "&modules=" + access.getModules(); } else if (access != null && !tu.isEmptyValue(useraction) && leadactions.toLowerCase().contains(useraction.toLowerCase())) { strNextPage = "/src/campaign/" + useraction + ".jsp?username=" + username + "&firstname=" + access.getFirstname() + "&usertoken=" + access.getToken() + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR + username + "&baseurl=" + baseurl + "&campaignid=" + objid + "&sendreference=" + sendreference; //logger.info("\n"+date.toString()+"strNextPage:="+strNextPage); //}else if(access!=null && !tu.isEmptyValue(useraction) && useraction.equalsIgnoreCase("whitepapers")){ //strNextPage="/src/campaign/white_paper.jsp?username="+username+"&firstname="+access.getFirstname()+"&usertoken="+access.getToken()+CONST.IPSEPERATOR+remoteaddress+CONST.IPSEPERATOR+username+"&baseurl=" // +baseurl+"&campaignid="+objid; //logger.info("\n"+date.toString()+"strNextPage:="+strNextPage); } else if (subscription) { userdata = m_service.verifyUserToken(usertoken); isvalidtoken = usertoken != null && !usertoken.equals("") && userdata != null; if (isvalidtoken) { strNextPage = "/src/index.jsp?username=" + username + "&usertoken=" + usertoken + "&baseurl=" + baseurl; } } else if (!tu.isEmptyValue(useraction) && useraction.equalsIgnoreCase("missingpassword")) { strNextPage = "/src/password.jsp?token=" + regaccess.getToken() + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR + reguser + "&baseurl=" + baseurl; } else if (!tu.isEmptyValue(useraction) && useraction.equalsIgnoreCase("demoregistration")) { strNextPage = "/src/demologin.jsp?token=" + regaccess.getToken() + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR + reguser + "&baseurl=" + baseurl; } else if (!tu.isEmptyValue(adminuser) && adminuser.equals("sa")) { strNextPage = "/src/admin.jsp?token=" + regaccess.getToken() + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR + reguser + "&baseurl=" + baseurl; } else if (!tu.isEmptyValue(amount) && !tu.isEmptyValue(objid)) { userdata = m_service.verifyUserToken(usertoken); if (userdata != null && !userdata.isEmpty()) { strNextPage = "/src/java_sim/payment.jsp?email=" + username + "&objid=" + objid + "&amount=" + amount + "&description=" + description; } } else if (regaccess != null) { strNextPage = "/src/login.jsp?token=" + regaccess.getToken() + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR + reguser + "&baseurl=" + baseurl; } else { strNextPage = "/src/error.jsp?token=null" + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR + reguser + "&baseurl=" + baseurl; } if (CONST.GENERATE_LOG) { logger.info("\n" + date.toString() + ":-Mapped Filename : " + strNextPage); } if (!strNextPage.equals("")) { rd = m_autoContext.getRequestDispatcher(strNextPage); // Forward the request to the target page try { if (rd != null) { rd.forward(request, response); } } catch (Exception e) { logger.info("ControllerServlet.doPost(): error in rd.forward"); e.printStackTrace(); } } else { // This should be logged. logger.info("Next Page is null"); super.doPost(request, response); } }
From source file:org.apache.hadoop.fs.webdav.WebdavServlet.java
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("/--------------------------------------------------"); log.debug(request.getMethod() + " " + request.getRequestURL().toString()); log.info(request.getMethod() + " " + request.getRequestURL().toString()); log.info(request.getMethod() + " " + request.getRequestURI().toString()); log.info(" RemoteHost: " + request.getRemoteHost()); log.info("| ATTRIBUTES: "); Enumeration e1 = request.getAttributeNames(); while (e1.hasMoreElements()) { String name = (String) e1.nextElement(); log.info("|| " + name + ": "); }//from ww w . ja v a 2 s . co m log.info("| PARAMETERS: "); Enumeration e2 = request.getParameterNames(); while (e2.hasMoreElements()) { String name = (String) e2.nextElement(); log.info("|| " + name + ": "); } log.info("HEADERS: "); Enumeration e6 = request.getHeaderNames(); while (e6.hasMoreElements()) { String name = (String) e6.nextElement(); log.info("-- " + name + ": " + request.getHeader(name)); } log.info("RemoteUser: " + request.getRemoteUser()); log.info("AuthType: " + request.getAuthType()); currentUserName = request.getRemoteUser(); String roles = ""; if (currentUserRoles != null) { for (String roleName : currentUserRoles) { roles += roleName + ", "; } if (roles.length() > 2) { roles = roles.substring(0, roles.length() - 2); } } log.debug("Roles: " + roles); try { super.service(request, response); } catch (Exception e) { if (e.getCause() instanceof AccessControlException) { log.info("EXCEPTION: Can't access to resource. You don't have permissions."); MultiStatusResponse msr = new MultiStatusResponse(request.getRequestURL().toString(), 401, "Can't access to resource. You don't have permissions."); MultiStatus ms = new MultiStatus(); ms.addResponse(msr); WebdavResponse webdavResponse = new WebdavResponseImpl(response); webdavResponse.sendMultiStatus(ms); } else new WebdavResponseImpl(response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } log.info("\\--------------------------------------------------"); }