List of usage examples for javax.servlet.http HttpServletRequest getRemoteHost
public String getRemoteHost();
From source file:com.liferay.portal.action.LoginAction.java
protected void sendPassword(HttpServletRequest req) throws Exception { String emailAddress = ParamUtil.getString(req, "emailAddress"); String remoteAddr = req.getRemoteAddr(); String remoteHost = req.getRemoteHost(); String userAgent = req.getHeader(HttpHeaders.USER_AGENT); UserLocalServiceUtil.sendPassword(PortalUtil.getCompanyId(req), emailAddress, remoteAddr, remoteHost, userAgent);//from w w w.ja va 2s . c om SessionMessages.add(req, "request_processed", emailAddress); }
From source file:org.opencastproject.capture.admin.endpoint.CaptureAgentStateRestService.java
@POST @Produces(MediaType.TEXT_HTML)//from w w w. j av a 2s . c o m @Path("agents/{name}") // Todo: Capture agent may send an optional FormParam containing it's configured address. // If this exists don't use request.getRemoteHost() for the URL @RestQuery(name = "setAgentState", description = "Set the status of a given capture agent", pathParameters = { @RestParameter(name = "name", description = "The name of a given capture agent", isRequired = true, type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(description = "The address of a given capture agent", isRequired = true, name = "address", type = Type.STRING), @RestParameter(description = "The state of the capture agent", isRequired = true, name = "state", type = Type.STRING) }, reponses = { @RestResponse(description = "{agentName} set to {state}", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "{state} is empty or not known", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "The agent {agentName} does not exist", responseCode = HttpServletResponse.SC_NOT_FOUND), @RestResponse(description = "If no capture agent state service is available", responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE) }, returnDescription = "") public Response setAgentState(@Context HttpServletRequest request, @FormParam("address") String address, @PathParam("name") String agentName, @FormParam("state") String state) throws NotFoundException { if (service == null) return Response.serverError().status(Response.Status.SERVICE_UNAVAILABLE).build(); if (StringUtils.isBlank(state) || !AgentState.KNOWN_STATES.contains(state)) { logger.debug("'{}' is not a valid state", state); return Response.status(javax.ws.rs.core.Response.Status.BAD_REQUEST).build(); } if (StringUtils.isEmpty(address)) address = request.getRemoteHost(); logger.debug("Agents URL: {}", address); boolean agentStateUpdated = service.setAgentState(agentName, state); boolean agentUrlUpdated = service.setAgentUrl(agentName, address); if (!agentStateUpdated && !agentUrlUpdated) { logger.debug("{}'s state '{}' and url '{}' has not changed, nothing has been updated", new String[] { agentName, state, address }); return Response.ok().build(); } logger.debug("{}'s state successfully set to {}", agentName, state); return Response.ok(agentName + " set to " + state).build(); }
From source file:uk.co.channele.itres.Documents.java
public void doGet(HttpServletRequest rqst, HttpServletResponse resp) throws ServletException, IOException { RequestDispatcher handler;//from w w w. j ava2s. c o m IdentityBean userId; NewsBean newsBean; synchronized (this) { HttpSession session = rqst.getSession(false); if (session != null) { userId = (IdentityBean) session.getAttribute("userIdentity"); if (userId.isRegistered()) { if (session.getAttribute("newsBean") == null) { newsBean = new NewsBean(); session.setAttribute("newsBean", newsBean); } else { newsBean = (NewsBean) session.getAttribute("newsBean"); } newsBean.setUserId(userId.getUserName()); newsBean.setRemoteHost(rqst.getRemoteHost()); newsBean.setEditable(true); handler = context.getRequestDispatcher("/notices.jsp"); } else { handler = context.getRequestDispatcher("/register.jsp"); } } else { handler = context.getRequestDispatcher("/index.jsp"); } handler.include(rqst, resp); } // end sync }
From source file:cn.bc.web.util.WebUtils.java
/** * ??:[0]-IP?,[1]-??,[2]-User Agent,[3]-mac * //from w w w .j a va2 s . c o m * @param request * @return */ public static String[] getClient(HttpServletRequest request) { String[] client = new String[] { null, null, null, null }; // User Agent? client[2] = request.getHeader("User-Agent"); // ?????X-Forwarded-For?Ip,?unknownIPIP String key = "X-Forwarded-For"; String clientIp = request.getHeader(key); if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) { key = "Proxy-Client-IP"; clientIp = request.getHeader(key); } if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) { key = "WL-Proxy-Client-IP"; // Weblogic?IP clientIp = request.getHeader(key); } if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) { key = "RemoteAddr"; clientIp = request.getRemoteAddr();// ??ip? } client[0] = clientIp; if (trace) {// name+ip??+mac logger.info("start traceClientMachine...:clientIp=" + clientIp); if ("127.0.0.1".equals(clientIp) || "localhost".equals(clientIp)) { // ?() client[1] = clientIp + "|" + key; logger.info("skip traceClientMachine because local machine"); } else { client[1] = request.getRemoteHost();// ???ip????(?) try { // ?mac? client[3] = WebUtils.getMac(clientIp); client[1] = key + "|" + client[3]; } catch (Exception e) { logger.info(e.getMessage(), e); client[1] = "notrace:" + key; client[3] = "notrace:"; } } logger.info("finished traceClientMachine"); } else { client[1] = clientIp + "|" + key; client[3] = "notrace:"; } return client; }
From source file:com.netspective.sparx.security.HttpLoginManager.java
protected void registerLogin(HttpServletValueContext hsvc, MutableAuthenticatedUser user) { user.registerLogin(hsvc);/*from w ww. j a v a 2 s . co m*/ activeUsers.add(user); HttpServletRequest req = hsvc.getHttpRequest(); if (log.isInfoEnabled()) { String userId = user.getUserId().toString(); StringBuffer info = new StringBuffer(); info.append("login"); info.append(MONITOR_ENTRY_FIELD_SEPARATOR); info.append(userId); info.append(MONITOR_ENTRY_FIELD_SEPARATOR); info.append(req.getRemoteUser()); info.append(MONITOR_ENTRY_FIELD_SEPARATOR); info.append(req.getRemoteHost()); info.append(MONITOR_ENTRY_FIELD_SEPARATOR); info.append(req.getRemoteAddr()); info.append(MONITOR_ENTRY_FIELD_SEPARATOR); BitSet perms = user.getUserPermissions(); info.append(perms != null ? user.getUserPermissions().toString() : "{}"); info.append(MONITOR_ENTRY_FIELD_SEPARATOR); String[] roles = user.getUserRoleNames(); if (roles != null) { for (int r = 0; r < roles.length; r++) { if (r > 0) info.append(MONITOR_ENTRY_FIELD_SEPARATOR); info.append(roles[r]); } } log.info(info); } if (log.isDebugEnabled()) { String userId = user.getUserId().toString(); log.debug("User '" + userId + "' (" + user.getUserName() + ") is now authenticated for Session ID '" + req.getSession().getId() + "'"); BitSet perms = user.getUserPermissions(); if (perms != null) log.debug("User '" + userId + "' has permissions " + user.getUserPermissions().toString()); else log.debug("User '" + userId + " has no permissions."); String[] roles = user.getUserRoleNames(); if (roles != null) { for (int r = 0; r < roles.length; r++) log.debug("User '" + userId + "' has role " + roles[r]); } else log.debug("User '" + userId + " has no roles."); } hsvc.getProject().broadcastActivity(new HttpLoginActivity(hsvc.getProject(), hsvc)); }
From source file:com.voa.weixin.filter.AuthorFilter.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String signature = request.getParameter("signature");// ?? String timestamp = request.getParameter("timestamp");// String nonce = request.getParameter("nonce");// ? String echostr = request.getParameter("echostr");// ? try {/*from ww w.ja v a 2 s . c om*/ logger.debug("signatrue : " + signature); logger.debug("timestamp : " + timestamp); boolean checked = WeixinUtils.checkAuthentication(signature, timestamp, nonce, echostr, token); if (checked) { String requestStr = IOUtils.toString(request.getInputStream(), "UTF-8"); logger.debug("requestStr : " + requestStr); SessionManager.getInstance().buildSession(requestStr, response); } else { logger.warn("host:" + request.getRemoteHost() + " request content cant't checked."); } } catch (Exception e) { e.printStackTrace(); e.printStackTrace(LogUtil.getErrorStream(logger)); } }
From source file:org.apache.lucene.gdata.servlet.handler.AuthenticationHandler.java
/** * @see org.apache.lucene.gdata.servlet.handler.GDataRequestHandler#processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */// www. j ava 2s. c om @SuppressWarnings("unused") public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String serviceName = request.getParameter(AuthenticationController.SERVICE_PARAMETER); if (LOG.isInfoEnabled()) { String application = request.getParameter(AuthenticationController.APPLICATION_PARAMETER); LOG.info("Authentication request for service: " + serviceName + "; Application name: " + application); } if (!this.registry.isServiceRegistered(serviceName)) throw new AuthenticationException("requested Service " + serviceName + "is not registered"); String password = request.getParameter(AuthenticationController.PASSWORD_PARAMETER); String accountName = request.getParameter(AuthenticationController.ACCOUNT_PARAMETER); String clientIp = request.getRemoteHost(); GDataAccount account = getAccount(accountName); if (account == null || !account.getPassword().equals(password)) throw new AuthenticationException("Account is null or password does not match"); String token = this.controller.authenticatAccount(account, clientIp); sendToken(response, token); if (LOG.isInfoEnabled()) { LOG.info("Account authenticated -- " + account); } } catch (AuthenticationException e) { LOG.error("BadAuthentication -- " + e.getMessage(), e); sendError(response, GDataResponse.FORBIDDEN, "BadAuthentication"); } catch (Exception e) { LOG.error("Unexpected Exception -- SERVERERROR -- " + e.getMessage(), e); sendError(response, GDataResponse.SERVER_ERROR, "Service not available"); } }
From source file:org.apache.hadoop.hdfs.server.namenode.GetImageServlet.java
@SuppressWarnings("unchecked") public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { Map<String, String[]> pmap = request.getParameterMap(); try {//from www. j a va2s. com ServletContext context = getServletContext(); final FSImage nnImage = (FSImage) context.getAttribute("name.system.image"); final TransferFsImage ff = new TransferFsImage(pmap, request, response); final Configuration conf = (Configuration) getServletContext().getAttribute(JspHelper.CURRENT_CONF); if (UserGroupInformation.isSecurityEnabled() && !isValidRequestor(request.getRemoteUser(), conf)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Only Namenode and Secondary Namenode may access this servlet"); LOG.warn("Received non-NN/SNN request for image or edits from " + request.getRemoteHost()); return; } UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { if (ff.getImage()) { // send fsImage TransferFsImage.getFileServer(response.getOutputStream(), nnImage.getFsImageName()); } else if (ff.getEdit()) { // send edits TransferFsImage.getFileServer(response.getOutputStream(), nnImage.getFsEditName()); } else if (ff.putImage()) { // issue a HTTP get request to download the new fsimage nnImage.validateCheckpointUpload(ff.getToken()); reloginIfNecessary().doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { TransferFsImage.getFileClient(ff.getInfoServer(), "getimage=1", nnImage.getFsImageNameCheckpoint()); return null; } }); nnImage.checkpointUploadDone(); } return null; } // We may have lost our ticket since the last time we tried to open // an http connection, so log in just in case. private UserGroupInformation reloginIfNecessary() throws IOException { // This method is only called on the NN, therefore it is safe to // use these key values. return UserGroupInformation.loginUserFromKeytabAndReturnUGI( SecurityUtil.getServerPrincipal(conf.get(DFS_NAMENODE_KRB_HTTPS_USER_NAME_KEY), NameNode.getAddress(conf).getHostName()), conf.get(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY)); } }); } catch (Exception ie) { String errMsg = "GetImage failed. " + StringUtils.stringifyException(ie); response.sendError(HttpServletResponse.SC_GONE, errMsg); throw new IOException(errMsg); } finally { response.getOutputStream().close(); } }
From source file:org.sparkbit.jsonrpc.SparkBitServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { try {/*from ww w.j a va2s . co m*/ long requestID = ++counter; log.info("----------------------------------------------------"); log.info("*** Request # " + requestID + " RECEIVED"); final StopWatch stopwatch = new StopWatch(); stopwatch.start(); InputStream is = req.getInputStream(); OutputStream os = resp.getOutputStream(); resp.addHeader("Content-Type", "application/json"); // This will deserialize the request and invoke // our ContactServiceImpl code based on the method and params // specified in the request. The result, including any // RpcException (if thrown), will be serialized to the OutputStream // server.call(serializer, is, os); log.info("remote host = " + req.getRemoteHost()); log.info("request URL = " + req.getRequestURL().toString()); // log.info("session ID = " + req.getRequestedSessionId()); // We use a modified version of the above call so that we can filter 'stop' for localhost mycall(req.getRemoteHost(), server, serializer, is, os); is.close(); os.close(); stopwatch.stop(); log.info("*** Request # " + requestID + " FINISHED - processing time = " + stopwatch); } catch (Exception e) { throw new ServletException(e); } }
From source file:gov.nist.appvet.servlet.AppVetServlet.java
private AppInfo createAppInfo(String userName, String sessionId, FileItem fileItem, String clientIpAddress, HttpServletRequest request) { String appId = generateAppid(); AppInfo appInfo = new AppInfo(appId, true); appInfo.userName = userName;/* ww w . j av a2 s .co m*/ appInfo.sessionId = sessionId; appInfo.fileItem = fileItem; appInfo.fileName = FileUtil.getNormalizedFileName(fileItem.getName()); InetAddress addr; try { addr = InetAddress.getByName(request.getRemoteHost()); } catch (UnknownHostException e) { log.error(e.getMessage()); return null; } appInfo.clientHost = addr.getCanonicalHostName(); // Set temporary icon until icon is extracted from app final String sourceIconPath = AppVetProperties.APP_IMAGES + "/default.png"; appInfo.log.debug("Source icon: " + sourceIconPath); final String destIconPath = AppVetProperties.APP_IMAGES + "/" + appInfo.appId + ".png"; FileUtil.copyFile(sourceIconPath, destIconPath); return appInfo; }