Example usage for javax.servlet.http HttpServletRequest getRemoteHost

List of usage examples for javax.servlet.http HttpServletRequest getRemoteHost

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRemoteHost.

Prototype

public String getRemoteHost();

Source Link

Document

Returns the fully qualified name of the client or the last proxy that sent the request.

Usage

From source file:org.jumpmind.symmetric.web.SymmetricServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ServerSymmetricEngine engine = findEngine(req);
    MDC.put("engineName", engine != null ? engine.getEngineName() : "?");
    if (engine == null) {
        boolean nodesBeingCreated = ServletUtils.getSymmetricEngineHolder(getServletContext())
                .areEnginesStarting();//  w w  w  . j  av  a2s  .c om
        if (nodesBeingCreated) {
            log.info(
                    "The client node request is being rejected because the server node does not exist yet.  There are nodes being initialized.  It might be that the node is not ready or that the database is unavailable.  Please be patient.  The request was {} from the host {} with an ip address of {}.  The query string was: {}",
                    new Object[] { ServletUtils.normalizeRequestUri(req), req.getRemoteHost(),
                            req.getRemoteAddr(), req.getQueryString() });
        } else {
            log.error(
                    "The client node request is being rejected because the server node does not exist.  Please check that the engine.name exists in the url.  It should be of the pattern http://host:port/sync/{engine.name}/{action}.  If it does not, then check the sync.url of this node or the registration.url of the client making the request.  The request was {} from the host {} with an ip address of {}.  The query string was: {}",
                    new Object[] { ServletUtils.normalizeRequestUri(req), req.getRemoteHost(),
                            req.getRemoteAddr(), req.getQueryString() });
        }
        ServletUtils.sendError(res, WebConstants.SC_SERVICE_UNAVAILABLE);

    } else if (engine.isStarted()) {
        IUriHandler handler = findMatchingHandler(engine, req);
        if (handler != null) {
            List<IInterceptor> beforeInterceptors = handler.getInterceptors();
            List<IInterceptor> afterInterceptors = null;
            try {
                if (beforeInterceptors != null) {
                    afterInterceptors = new ArrayList<IInterceptor>(beforeInterceptors.size());
                    for (IInterceptor interceptor : beforeInterceptors) {
                        if (interceptor.before(req, res)) {
                            afterInterceptors.add(interceptor);
                        } else {
                            return;
                        }
                    }
                }
                handler.handle(req, res);
            } catch (Exception e) {
                logException(req, e, !(e instanceof IOException && StringUtils.isNotBlank(e.getMessage())));
                if (!res.isCommitted()) {
                    ServletUtils.sendError(res, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }
            } finally {
                if (afterInterceptors != null) {
                    for (IInterceptor interceptor : afterInterceptors) {
                        interceptor.after(req, res);
                    }
                }
            }
        } else {
            log.error(
                    "The request path of the url is not supported.  The request was {} from the host {} with an ip address of {}.  The query string was: {}",
                    new Object[] { ServletUtils.normalizeRequestUri(req), req.getRemoteHost(),
                            req.getRemoteAddr(), req.getQueryString() });
            ServletUtils.sendError(res, HttpServletResponse.SC_BAD_REQUEST);
        }
    } else if (engine.isStarting()) {
        log.info(
                "The client node request is being rejected because the server node is currently starting.  Please be patient.  The request was {} from the host {} with an ip address of {} will not be processed.  The query string was: {}",
                new Object[] { ServletUtils.normalizeRequestUri(req), req.getRemoteHost(), req.getRemoteAddr(),
                        req.getQueryString() });
        ServletUtils.sendError(res, WebConstants.SC_SERVICE_UNAVAILABLE);
    } else if (!engine.isStarted() && !engine.isConfigured()) {
        log.info(
                "The client node request is being rejected because the server node was not started because it is not configured properly. The request {} from the host {} with an ip address of {} will not be processed.  The query string was: {}",
                new Object[] { ServletUtils.normalizeRequestUri(req), req.getRemoteHost(), req.getRemoteAddr(),
                        req.getQueryString() });
        ServletUtils.sendError(res, WebConstants.SC_SERVICE_UNAVAILABLE);
    } else {
        log.debug(
                "The client node request is being rejected because the server node is not started. The request {} from the host {} with an ip address of {} will not be processed.  The query string was: {}",
                new Object[] { ServletUtils.normalizeRequestUri(req), req.getRemoteHost(), req.getRemoteAddr(),
                        req.getQueryString() });
        ServletUtils.sendError(res, WebConstants.SC_SERVICE_UNAVAILABLE);
    }

}

From source file:es.agrega.soporte.http.BrowserDetector.java

/**
 * Process the HttpServletRequest for client information.
 * Prosecute to the fullest extent possible ;-)
 *
 * @param request An HttpRequest used to gather client information.
 *//*from ww w. ja v  a 2  s .  c o m*/
public void setRequest(HttpServletRequest request) {
    // because different containers/web-servers use diffent naming conventions,
    // we need to be extra careful fetching this headers
    String tempUAS = HttpUtils.findHeader(request, "USER_AGENT");
    if (tempUAS != null) {
        this.setUserAgentString(tempUAS);
    }

    // get values from request headers
    clientIP = request.getRemoteAddr();
    clientHost = request.getRemoteHost();
    String acceptEncoding = HttpUtils.findHeader(request, "ACCEPT_ENCODING");
    if (acceptEncoding != null && acceptEncoding.indexOf("gzip") != -1) {
        gzipOK = true;
    }

    // acceptMIME: parse ACCEPT and place into ARRAYLIST
    String[] acceptArray = StringUtils.split(HttpUtils.findHeader(request, "ACCEPT"), ",");
    acceptMIME = java.util.Arrays.asList(acceptArray);

    String protocol = request.getProtocol();
    if (protocol != null && protocol.indexOf("/") != -1) {
        int slashLoc = protocol.indexOf("/");
        protocolType = protocol.substring(0, slashLoc);
        try {
            protocolVersion = Float.valueOf(protocol.substring(slashLoc + 1)).floatValue();
        } catch (Exception e) { // if there was an error getting protocolVersion, set to -1
            protocolVersion = (float) -1.0;
        }
        if ("HTTP".equals(protocolType) && protocolVersion > 1.0)
            keepAliveOK = true;

    }
}

From source file:org.apereo.services.persondir.support.web.RequestAttributeSourceFilter.java

/**
 * Add other properties from the request to the attributes map.
 *
 * @param httpServletRequest Http Servlet Request
 * @param attributes Map of attributes to add additional attributes to from the Http Request
 *//*from   www. j av  a 2s . c o m*/
protected void addRequestProperties(final HttpServletRequest httpServletRequest,
        final Map<String, List<Object>> attributes) {
    if (this.remoteUserAttribute != null) {
        final String remoteUser = httpServletRequest.getRemoteUser();
        attributes.put(this.remoteUserAttribute, list(remoteUser));
    }
    if (this.remoteAddrAttribute != null) {
        final String remoteAddr = httpServletRequest.getRemoteAddr();
        attributes.put(this.remoteAddrAttribute, list(remoteAddr));
    }
    if (this.remoteHostAttribute != null) {
        final String remoteHost = httpServletRequest.getRemoteHost();
        attributes.put(this.remoteHostAttribute, list(remoteHost));
    }
    if (this.serverNameAttribute != null) {
        final String serverName = httpServletRequest.getServerName();
        attributes.put(this.serverNameAttribute, list(serverName));
    }
    if (this.serverPortAttribute != null) {
        final int serverPort = httpServletRequest.getServerPort();
        attributes.put(this.serverPortAttribute, list(serverPort));
    }
}

From source file:org.gss_project.gss.server.rest.UserHandler.java

/**
 * Handle POST requests in the users namespace.
 *
  * @param req The servlet request we are processing
  * @param resp The servlet response we are processing
  * @throws IOException if an input/output error occurs
 *//*from  ww w . j  av  a  2s.  c  om*/
void postUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {
        final User user = getUser(req);
        User owner = getOwner(req);
        if (!owner.equals(user))
            throw new InsufficientPermissionsException("User " + user.getUsername()
                    + " does not have permission to modify " + owner.getUsername());
        boolean hasResetWebDAVParam = req.getParameterMap().containsKey(RESET_WEBDAV_PARAMETER);
        if (hasResetWebDAVParam) {
            String newPassword = new TransactionHelper<String>().tryExecute(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return getService().resetWebDAVPassword(user.getId());
                }
            });

            // Set the cookie again to send new value
            Cookie cookie = new Cookie(Login.WEBDAV_COOKIE, newPassword);
            cookie.setMaxAge(-1);
            String domain = req.getRemoteHost();
            String path = req.getContextPath();
            cookie.setDomain(domain);
            cookie.setPath(path);
            resp.addCookie(cookie);
        }
        // Workaround for IE's broken caching behavior.
        resp.setHeader("Expires", "-1");
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (RpcException e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, e.getMessage());
    } catch (Exception e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.tightblog.rendering.processors.CommentProcessor.java

WeblogEntryComment createCommentFromRequest(HttpServletRequest request, WeblogPageRequest pageRequest,
        HTMLSanitizer.Level sanitizerLevel) {

    /*// ww w.j a v a 2  s  .c o m
     * Convert request parameters into a WeblogEntryComment object.  Params used:
     *   name - comment author
     *   email - comment email
     *   url - comment referring url
     *   content - comment contents
     *   notify - if commenter wants to receive notifications
     */
    WeblogEntryComment comment = new WeblogEntryComment();
    comment.setNotify(request.getParameter("notify") != null);
    comment.setName(Utilities.removeHTML(request.getParameter("name")));
    comment.setEmail(Utilities.removeHTML(request.getParameter("email")));
    comment.setWeblogEntry(pageRequest.getWeblogEntry());
    comment.setRemoteHost(request.getRemoteHost());
    comment.setPostTime(Instant.now());
    comment.setBlogger(pageRequest.getBlogger());

    String previewCheck = request.getParameter("preview");
    comment.setPreview(previewCheck != null && !"false".equalsIgnoreCase(previewCheck));

    // Validate url
    comment.setUrl(Utilities.removeHTML(request.getParameter("url")));
    String urlCheck = comment.getUrl();
    if (StringUtils.isNotBlank(urlCheck)) {
        urlCheck = urlCheck.trim().toLowerCase();
        if (!urlCheck.startsWith("http://") && !urlCheck.startsWith("https://")) {
            urlCheck = "http://" + urlCheck;
        }
        comment.setUrl(urlCheck);
    }

    // Validate content
    String rawComment = request.getParameter("content");

    if (StringUtils.isNotBlank(rawComment)) {
        comment.setContent(StringUtils.left(rawComment, 2000));

        Whitelist commentHTMLWhitelist = sanitizerLevel.getWhitelist();

        // Need to insert paragraph breaks in case commenter didn't do so.
        String commentTemp = Utilities.insertLineBreaksIfMissing(comment.getContent());

        // Remove HTML tags outside those permitted by the TightBlog admin
        comment.setContent(Jsoup.clean(commentTemp, commentHTMLWhitelist));
    }

    return comment;
}

From source file:org.openiam.webadmin.role.RoleDetailController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {

    RoleDetailCommand roleCommand = (RoleDetailCommand) command;

    String userId = (String) request.getSession().getAttribute("userId");
    String domainId = (String) request.getSession().getAttribute("domainid");
    String login = (String) request.getSession().getAttribute("login");

    Role role = roleCommand.getRole();
    prepareObject(role);// w  w w.ja v  a2s .c  om

    String btn = request.getParameter("btn");

    if (btn != null && btn.equalsIgnoreCase("Delete")) {
        Response resp = roleDataService.removeRole(role.getId().getServiceId(), role.getId().getRoleId());

        auditHelper.addLog("DELETE", domainId, login, "WEBCONSOLE", userId, "0", "ROLE",
                role.getId().getRoleId(), null, "SUCCESS", null, null, null, null, null,
                role.getId().getServiceId() + "-" + role.getId().getRoleId(), request.getRemoteHost());

        return new ModelAndView(new RedirectView(redirectView, true));

    }

    if (roleDataService.getRole(role.getId().getServiceId(), role.getId().getRoleId()) != null) {
        // update
        roleDataService.updateRole(role);

        if (roleCommand.getMode().equalsIgnoreCase("NEW")) {
            auditHelper.addLog("CREATE", domainId, login, "WEBCONSOLE", userId, "0", "ROLE",
                    role.getId().getRoleId(), null, "SUCCESS", null, null, null, null, null,
                    role.getId().getServiceId() + "-" + role.getId().getRoleId(), request.getRemoteHost());
        } else {

            auditHelper.addLog("MODIFY", domainId, login, "WEBCONSOLE", userId, "0", "ROLE",
                    role.getId().getRoleId(), null, "SUCCESS", null, null, null, null, null,
                    role.getId().getServiceId() + "-" + role.getId().getRoleId(), request.getRemoteHost());
        }
    } else {
        // new
        role.setCreateDate(new Date(System.currentTimeMillis()));
        role.setCreatedBy(userId);
        roleDataService.addRole(role);

        auditHelper.addLog("CREATE", domainId, login, "WEBCONSOLE", userId, "0", "ROLE",
                role.getId().getRoleId(), null, "SUCCESS", null, null, null, null, null,
                role.getId().getServiceId() + "-" + role.getId().getRoleId(), request.getRemoteHost());

    }

    request.getSession().removeAttribute("roleid");
    request.getSession().removeAttribute("domainid");

    return new ModelAndView(new RedirectView(redirectView, true));

}

From source file:com.iwancool.dsm.service.impl.AbstractBaseService.java

/**
 * ?IP?/*from  ww  w  .  j av a 2s . c o  m*/
 * 
 * @author long
 * @create 2014-4-16 ?6:05:46
 * @since
 * @param request
 * @return
 */
protected String getRequestIPAddress(HttpServletRequest request) {
    String remoteIp = request.getHeader("x-forwarded-for");
    if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
        remoteIp = request.getHeader("X-Real-IP");
    }
    if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
        remoteIp = request.getHeader("Proxy-Client-IP");
    }
    if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
        remoteIp = request.getHeader("WL-Proxy-Client-IP");
    }
    if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
        remoteIp = request.getHeader("HTTP_CLIENT_IP");
    }
    if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
        remoteIp = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
        remoteIp = request.getRemoteAddr();
    }
    if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
        remoteIp = request.getRemoteHost();
    }
    return remoteIp;
}

From source file:org.openiam.webadmin.res.ResourceDetailController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {

    log.debug("onSubmit called");

    ResourceDetailCommand resCommand = (ResourceDetailCommand) command;
    ManagedSys sys;//from ww w .j av  a2s . c o m

    String userId = (String) request.getSession().getAttribute("userId");
    String domainId = (String) request.getSession().getAttribute("domainid");
    String login = (String) request.getSession().getAttribute("login");

    String btn = request.getParameter("btn");

    if (btn != null && btn.equalsIgnoreCase("Delete")) {
        Resource res = resCommand.getResource();
        resourceDataService.removeResource(res.getResourceId());

        auditHelper.addLog("DELETE", domainId, login, "WEBCONSOLE", userId, "0", "RESOURCE",
                res.getResourceId(), null, "SUCCESS", null, null, null, null, null, res.getName(),
                request.getRemoteHost());

        return new ModelAndView(new RedirectView("resourcelist.cnt", true));

    }

    Resource res = resCommand.getResource();

    if (resCommand.getResource().getResourceId() == null
            || resCommand.getResource().getResourceId().length() == 0) {
        // new
        log.info("Creating new resource..");

        res.setResourceId(null);
        Set<ResourceProp> propSet = resCommand.getResourceProp();

        Set<ResourceProp> newPropSet = new HashSet<ResourceProp>();

        if (propSet != null) {
            for (ResourceProp rp : propSet) {
                rp.setResourcePropId(null);
                rp.setResourceId(null);
                newPropSet.add(rp);
            }
        }
        res.setResourceProps(newPropSet);

        res = resourceDataService.addResource(res);

        auditHelper.addLog("CREATE", domainId, login, "WEBCONSOLE", userId, "0", "RESOURCE",
                res.getResourceId(), null, "SUCCESS", null, null, null, null, null, res.getName(),
                request.getRemoteHost());

    } else {
        // existing record
        res.setResourceProps(resCommand.getResourceProp());

        resourceDataService.updateResource(res);

        auditHelper.addLog("MODIFY", domainId, login, "WEBCONSOLE", userId, "0", "RESOURCE",
                res.getResourceId(), null, "SUCCESS", null, null, null, null, null, res.getName(),
                request.getRemoteHost());

    }
    // create a link with the managed sys object
    if (res != null) {
        String managedSysId = res.getManagedSysId();
        if (managedSysId != null && managedSysId.length() > 0) {
            ManagedSys mSys = managedSysClient.getManagedSys(managedSysId);
            mSys.setPswd(mSys.getDecryptPassword());
            mSys.setResourceId(res.getResourceId());

            log.info("Password=" + mSys.getPswd());

            managedSysClient.updateManagedSystem(mSys);

        }

    }
    /*
            
    http://localhost:8080/webconsole/resourceDetail.cnt?resId=101&menugrp=SECURITY_RES
     log.info("refreshing attr list for resourceId=" + resId);
    String view = redirectView + "&menuid=RESAPPROVER&menugrp=SECURITY_RES&objId=" + resId;
    log.info("redirecting to=" + view);
            
    return new ModelAndView(new RedirectView(view, true));
     */

    String view = redirectView + "&menugrp=SECURITY_RES&resId=" + res.getResourceId();

    return new ModelAndView(new RedirectView(view, true));

}

From source file:stroom.proxy.repo.StroomStreamProcessor.java

public void processRequestHeader(final HttpServletRequest httpServletRequest) {
    String guid = globalMetaMap.get(StroomHeaderArguments.GUID);

    // Allocate a GUID if we have not got one.
    if (guid == null) {
        guid = UUID.randomUUID().toString();
        globalMetaMap.put(StroomHeaderArguments.GUID, guid);

        // Only allocate RemoteXxx details if the GUID has not been
        // allocated.

        // Allocate remote address if not set.
        if (StringUtils.hasText(httpServletRequest.getRemoteAddr())) {
            globalMetaMap.put(StroomHeaderArguments.REMOTE_ADDRESS, httpServletRequest.getRemoteAddr());
        }// www. j  a v a2  s  .c om

        // Save the time the data was received.
        globalMetaMap.put(StroomHeaderArguments.RECEIVED_TIME, DateUtil.createNormalDateTimeString());

        // Allocate remote address if not set.
        if (StringUtils.hasText(httpServletRequest.getRemoteHost())) {
            globalMetaMap.put(StroomHeaderArguments.REMOTE_HOST, httpServletRequest.getRemoteHost());
        }

        if (httpServletRequest.getAttribute(CertificateUtil.SERVLET_CERT_ARG) != null) {
            // Here we pull out the SSL client certificate and check that it
            // is OK based on the settings of the group the feed belongs to.
            try {
                final Object[] certs = (Object[]) httpServletRequest
                        .getAttribute(CertificateUtil.SERVLET_CERT_ARG);

                final X509Certificate cert = CertificateUtil.extractCertificate(certs);
                final String dn = CertificateUtil.extractDNFromCertificate(cert);
                final Long expiryDate = CertificateUtil.extractExpiryDateFromCertificate(cert);
                if (expiryDate != null) {
                    globalMetaMap.put(StroomHeaderArguments.REMOTE_CERT_EXPIRY,
                            DateUtil.createNormalDateTimeString(expiryDate));
                }

                globalMetaMap.put(StroomHeaderArguments.REMOTE_DN, dn);
            } catch (final Exception ex) {
                LOGGER.error("doPost() - Failed to extract certificate", ex);
            }
        }
    }

}

From source file:stroom.util.zip.StroomStreamProcessor.java

public void processRequestHeader(final HttpServletRequest httpServletRequest) {
    String guid = globalHeaderMap.get(StroomHeaderArguments.GUID);

    // Allocate a GUID if we have not got one.
    if (guid == null) {
        guid = UUID.randomUUID().toString();
        globalHeaderMap.put(StroomHeaderArguments.GUID, guid);

        // Only allocate RemoteXxx details if the GUID has not been
        // allocated.

        // Allocate remote address if not set.
        if (StringUtils.hasText(httpServletRequest.getRemoteAddr())) {
            globalHeaderMap.put(StroomHeaderArguments.REMOTE_ADDRESS, httpServletRequest.getRemoteAddr());
        }//from   w w w .j a  v  a  2s  .co  m

        // Save the time the data was received.
        globalHeaderMap.put(StroomHeaderArguments.RECEIVED_TIME, DateUtil.createNormalDateTimeString());

        // Allocate remote address if not set.
        if (StringUtils.hasText(httpServletRequest.getRemoteHost())) {
            globalHeaderMap.put(StroomHeaderArguments.REMOTE_HOST, httpServletRequest.getRemoteHost());
        }

        if (httpServletRequest.getAttribute(CertificateUtil.SERVLET_CERT_ARG) != null) {
            // Here we pull out the SSL client certificate and check that it
            // is OK based on the settings of the group the feed belongs to.
            try {
                final Object[] certs = (Object[]) httpServletRequest
                        .getAttribute(CertificateUtil.SERVLET_CERT_ARG);

                final X509Certificate cert = CertificateUtil.extractCertificate(certs);
                final String dn = CertificateUtil.extractDNFromCertificate(cert);
                final Long expiryDate = CertificateUtil.extractExpiryDateFromCertificate(cert);
                if (expiryDate != null) {
                    globalHeaderMap.put(StroomHeaderArguments.REMOTE_CERT_EXPIRY,
                            DateUtil.createNormalDateTimeString(expiryDate));
                }

                globalHeaderMap.put(StroomHeaderArguments.REMOTE_DN, dn);
            } catch (final Exception ex) {
                LOGGER.error("doPost() - Failed to extract certificate", ex);
            }
        }
    }

}