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:com.sixt.service.framework.jetty.RpcReadException.java

public String toJson(HttpServletRequest req) {
    JsonObject obj = new JsonObject();

    Enumeration<String> h = req.getHeaderNames();
    while (h.hasMoreElements()) {
        String hKey = h.nextElement();
        String hValue = req.getHeader(hKey);
        obj.addProperty("request_header_" + hKey, hValue);
    }//from w  w w .j  av a 2 s  .c om

    obj.addProperty("exception_message", this.getMessage());
    obj.addProperty("request_query_string", req.getQueryString());
    obj.addProperty("request_url", req.getRequestURL().toString());
    obj.addProperty("request_remote_addr", req.getRemoteAddr());
    obj.addProperty("request_remote_port", req.getRemotePort());
    obj.addProperty("request_remote_host", req.getRemoteHost());
    obj.addProperty("request_remote_user", req.getRemoteUser());

    String readBody = "success";
    // read the whole remaining body and put the joined base64 encoded message into the json object
    try {
        byte[] ba = IOUtils.toByteArray(this.in);
        byte[] combined;
        if ((ba != null) && (this.incomplete != null)) {
            combined = new byte[ba.length + this.incomplete.length];
            System.arraycopy(incomplete, 0, combined, 0, this.incomplete.length);
            System.arraycopy(ba, 0, combined, this.incomplete.length, ba.length);
            obj.addProperty("request_body", Base64.getEncoder().encodeToString(combined));
        } else if (ba != null) {
            combined = ba;
        } else if (this.incomplete != null) {
            combined = this.incomplete;
        } else {
            readBody = "body is empty";
        }
    } catch (Exception ex) {
        readBody = String.format("failed because: %s", ex.getCause());
    }
    obj.addProperty("read_body", readBody);

    return obj.toString();
}

From source file:org.n52.v3d.terrainserver.profileservice.ProfileServlet.java

private void logGetGraphInfo(String pTmpName, VgElevationGrid pTerrain, VgLineString pDefLine,
        T3dTimeList pTimeProt, HttpServletRequest pRequest, String pOutputInfo) {
    try {/*from  w  ww.j av  a2s  .com*/
        PrintWriter lDat = new PrintWriter(new FileWriter(mWorkingDirectory + "/" + pTmpName + ".log"));

        // Berarbeitungszeit und weitere Infos protokollieren:
        lDat.println("REMOTE HOST: " + pRequest.getRemoteHost());
        lDat.println("REMOTE ADDRESS: " + pRequest.getRemoteAddr());
        //lDat.println("REMOTE USER: " + pRequest.getRemoteUser());
        lDat.println("QUERY STRING: " + pRequest.getQueryString());
        lDat.println("SESSION-ID: " + pRequest.getRequestedSessionId());
        lDat.println("DEFLINE: " + pDefLine);
        lDat.println("BBOX: " + pTerrain.getGeometry().envelope());
        lDat.println("BBOX-SIZE: " + pTerrain.getGeometry().envelope().areaXY());
        lDat.println("CELLSIZE: " + ((GmSimple2dGridGeometry) pTerrain.getGeometry()).getDeltaX()); // quidist.
        lDat.println("OUTPUT FORMAT: " + pOutputInfo);
        lDat.println("PROCESSING_TIMES [msec]: ");
        String[] lTimeProtStr = pTimeProt.protocol();
        for (int i = 0; i < lTimeProtStr.length; i++)
            lDat.println(lTimeProtStr[i]);

        lDat.close();
    } catch (IOException e) {
        throw new T3dException(e.getMessage());
    }
}

From source file:org.n52.v3d.terrainserver.profileservice.ProfileServlet.java

private void logGetElevationInfo(String pTmpName, VgElevationGrid pTerrain, VgPoint pPoint,
        T3dTimeList pTimeProt, HttpServletRequest pRequest, String pOutputInfo) {
    try {/*from w  w  w  .  j  a  v  a  2s.c o  m*/
        PrintWriter lDat = new PrintWriter(new FileWriter(mWorkingDirectory + "/" + pTmpName + ".log"));

        // Berarbeitungszeit und weitere Infos protokollieren:
        lDat.println("REMOTE HOST: " + pRequest.getRemoteHost());
        lDat.println("REMOTE ADDRESS: " + pRequest.getRemoteAddr());
        //lDat.println("REMOTE USER: " + pRequest.getRemoteUser());
        lDat.println("QUERY STRING: " + pRequest.getQueryString());
        lDat.println("SESSION-ID: " + pRequest.getRequestedSessionId());
        lDat.println("POINT: " + pPoint);
        lDat.println("BBOX: " + pTerrain.getGeometry().envelope());
        lDat.println("BBOX-SIZE: " + pTerrain.getGeometry().envelope().areaXY());
        lDat.println("CELLSIZE: " + ((GmSimple2dGridGeometry) pTerrain.getGeometry()).getDeltaX()); // quidist.
        lDat.println("OUTPUT FORMAT: " + pOutputInfo);
        lDat.println("PROCESSING_TIMES [msec]: ");
        String[] lTimeProtStr = pTimeProt.protocol();
        for (int i = 0; i < lTimeProtStr.length; i++)
            lDat.println(lTimeProtStr[i]);

        lDat.close();
    } catch (IOException e) {
        throw new T3dException(e.getMessage());
    }
}

From source file:siddur.solidtrust.image.ImageController.java

@RequestMapping(value = "/api/images1")
public @ResponseBody Object findCarImages1(final @RequestParam("id") String id, HttpServletRequest request) {
    final int port = request.getLocalPort();
    final String address = request.getLocalAddr();

    String username = request.getAttribute(SolidtrustConstants.CLIENT_ID) + "";
    AccessItem ai = new AccessItem();
    ai.setIp(request.getRemoteHost());
    ai.setUsername(username);//  w  ww.j  a  va 2 s  . co  m
    ai.setService(Product.IMAGES.getId());
    ai.setRequest(id);

    ImageProduct ip = null;
    try {
        ip = findImagesByLicensePlate(id, false);
        ai.setResponse(ip.getImage1());
    } catch (Exception e) {
    }

    if (ip == null) {
        ai.setStatus(-1);
        free.save(ai);
        return "no data";
    }
    free.save(ai);

    String portStr = port == 80 ? "" : ":" + port;
    String prex = "http://" + address + portStr + "/solidtrust/images/";
    ImageProduct resp = new ImageProduct();
    resp.setArrangement(ip.getArrangement());
    resp.setBrand(ip.getBrand());
    resp.setType(ip.getType());
    resp.setBuildYear(ip.getBuildYear());
    if (ip.getImage1() != null) {
        resp.setImage1(prex + ip.getImage1());
    }
    if (ip.getImage2() != null) {
        resp.setImage2(prex + ip.getImage2());
    }
    if (ip.getImage3() != null) {
        resp.setImage3(prex + ip.getImage3());
    }
    if (ip.getImage4() != null) {
        resp.setImage4(prex + ip.getImage4());
    }
    return resp;
}

From source file:com.github.dactiv.fear.user.web.AccountController.java

/**
 * ??//from  w ww .  ja  va 2 s.  c  o  m
 *
 * @param entity  map
 * @param request http servlet request
 *
 * @return ??:WEB-INF/page/index.ftl
 *
 * @throws Exception
 */
@RequestMapping(value = "registration", method = { RequestMethod.GET, RequestMethod.POST })
public String registration(@RequestParam Map<String, Object> entity, HttpServletRequest request)
        throws Exception {

    if (request.getMethod().equals(HttpMethod.GET.name())) {
        return "registration";
    } else {

        accountService.registration(entity);

        String username = entity.get("username").toString();
        String password = entity.get("password").toString();
        SecurityUtils.getSubject()
                .login(new UsernamePasswordToken(username, password, request.getRemoteHost()));
        return "redirect:/account/user-profile";
    }
}

From source file:org.exist.management.client.JMXServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Verify if request is from localhost or if user has specific servlet/container managed role.
    if (isFromLocalHost(request)) {
        // Localhost is always authorized to access
        LOG.debug("Local access granted");

    } else if (hasSecretToken(request, getToken())) {
        // Correct token is provided
        LOG.debug("Correct token provided by " + request.getRemoteHost());

    } else {//from ww w  . j a  va  2s. c  om
        // Check if user is already authorized, e.g. via MONEX allow user too
        response.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Access allowed for localhost, or when correct token has been provided.");
        return;
    }

    // Perform actual writing of data
    writeXmlData(request, response);
}

From source file:edu.uiowa.icts.authentication.AuthHandle.java

/** {@inheritDoc} */
@Override/* ww w  . j a va  2s  .  c om*/
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication auth)
        throws IOException, ServletException {

    log.debug("successfully authenticated " + String.valueOf(auth.getPrincipal()));

    if (req.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION") != null) {
        req.getSession().removeAttribute("SPRING_SECURITY_LAST_EXCEPTION");
    }

    for (GrantedAuthority ga : auth.getAuthorities()) {
        log.debug(ga.getAuthority());
    }

    HttpSession session = req.getSession();
    String username = req.getParameter("j_username");
    session.setAttribute("username", username);

    AuditLogger.info(session.getId(), username, "logged in from", req.getRemoteHost());

    target.onAuthenticationSuccess(req, res, auth);

}

From source file:seava.j4e.web.controller.session.SessionController.java

/**
 * Pack extra information about login into a ThreadLocal to be passed to the
 * authentication-provider service/*www. j  ava2  s.  co  m*/
 * 
 * @param clientCode
 * @param language
 * @param request
 */
private void prepareLoginParamsHolder(String clientCode, String language, HttpServletRequest request) {

    ILoginParams lp = this.getApplicationContext().getBean(ILoginParams.class);

    String ip = request.getHeader("X-Forwarded-For");
    if (ip != null && !"".equals(ip)) {
        ip = ip.substring(0, ip.indexOf(","));
    } else {
        ip = request.getRemoteAddr();
    }

    lp.setRemoteIp(ip);
    lp.setUserAgent(request.getHeader("User-Agent"));
    lp.setRemoteHost(request.getRemoteHost());
    lp.setLanguage(language);
    lp.setClientCode(clientCode);
    LoginParamsHolder.params.set(lp);

}

From source file:energy.usef.core.endpoint.ReceiverEndpoint.java

/**
 * Sends a client message to a queue./*from ww  w. j  ava  2  s  .  c om*/
 *
 * @param messageText message
 * @param request {@link HttpServletRequest}
 * @return status
 */
@POST
@Path("/receiveMessage")
@Consumes(TEXT_XML)
public Response receiveMessage(String messageText, @Context HttpServletRequest request) {
    try {
        // verify that the signed message has not been received yet.
        incomingMessageVerificationService.checkSignedMessageHash(DigestUtils.sha256(messageText));

        // transform the text/xml to a SignedMessage message
        SignedMessage signedMessage = XMLUtil.xmlToMessage(messageText, SignedMessage.class,
                config.getBooleanProperty(ConfigParam.VALIDATE_INCOMING_XML).booleanValue());

        // Get original senders IP-address, both directly and from the proxy('s).
        String addresslist = request.getRemoteAddr() + "," + request.getRemoteHost();
        String address = request.getHeader("X-Forwarded-For");
        if (address != null) {
            addresslist += "," + address;
        }

        // check if the sender is allowed to send messages to this endpoint
        messageFilterService.filterMessage(signedMessage.getSenderDomain(), addresslist);

        // verify sender by trying to unsing message
        String unsignedContent = verifyMessage(signedMessage);
        LOGGER_CONFIDENTIAL.debug("Received msg: {} ", unsignedContent);

        Message message = (Message) XMLUtil.xmlToMessage(unsignedContent,
                config.getBooleanProperty(ConfigParam.VALIDATE_INCOMING_XML).booleanValue());

        incomingMessageVerificationService.validateMessageId(message.getMessageMetadata().getMessageID());
        incomingMessageVerificationService
                .validateMessageValidUntil(message.getMessageMetadata().getValidUntil());

        // Check if the metadata is correct and the participant exists
        incomingMessageVerificationService.validateSender(signedMessage, message);

        jmsService.sendMessageToInQueue(unsignedContent);

        return Response.status(OK)
                .entity("Correctly received msg " + unsignedContent + " and set in to the IN queue").build();

    } catch (BusinessException e) {
        LOGGER.warn(e.getMessage(), e);
        return createBusinessErrorResponse(e);
    } catch (TechnicalException e) {
        LOGGER.error(e.getMessage(), e);
        return createErrorResponse(e.getMessage());
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return createErrorResponse("Unknown server problem occurred.");
    }
}

From source file:org.apache.synapse.commons.throttle.module.handler.ThrottleHandler.java

/**
 * processing through the throttle//from  w w  w  . jav  a 2 s .c o  m
 * 1) concurrent throttling
 * 2) access rate based throttling - domain or ip
 *
 * @param throttle       The Throttle object - holds all configuration and state data
 *                       of the throttle
 * @param messageContext The MessageContext , that holds all data per message basis
 * @throws AxisFault         Throws when access must deny for caller
 * @throws ThrottleException    ThrottleException
 */
public void process(Throttle throttle, MessageContext messageContext) throws ThrottleException, AxisFault {

    String throttleId = throttle.getId();
    ConfigurationContext cc = messageContext.getConfigurationContext();

    // acquiring  cache manager.
    Cache<String, ConcurrentAccessController> cache;
    CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager(THROTTLING_CACHE_MANAGER);
    if (cacheManager != null) {
        cache = cacheManager.getCache(THROTTLING_CACHE);
    } else {
        cache = Caching.getCacheManager().getCache(THROTTLING_CACHE);
    }
    if (log.isDebugEnabled()) {
        log.debug("created throttling cache : " + cache);
    }
    // Get the concurrent access controller
    ConcurrentAccessController cac;
    String key = null;
    key = ThrottleConstants.THROTTLE_PROPERTY_PREFIX + throttleId + ThrottleConstants.CAC_SUFFIX;
    cac = cache.get(key);

    // check for concurrent access
    boolean canAccess = doConcurrentThrottling(cac, messageContext);

    if (canAccess) {
        // if the concurrent access is success then
        // do the access rate based throttling

        if (messageContext.getFLOW() == MessageContext.IN_FLOW) {
            //gets the remote caller domain name
            String domain = null;
            HttpServletRequest request = (HttpServletRequest) messageContext
                    .getPropertyNonReplicable(HTTPConstants.MC_HTTP_SERVLETREQUEST);
            if (request != null) {
                domain = request.getRemoteHost();
            }

            // Domain name based throttling
            //check whether a configuration has been defined for this domain name or not
            String callerId = null;
            if (domain != null) {
                //loads the ThrottleContext
                ThrottleContext throttleCtxt = throttle
                        .getThrottleContext(ThrottleConstants.DOMAIN_BASED_THROTTLE_KEY);
                if (throttleCtxt != null) {
                    //Loads the ThrottleConfiguration
                    ThrottleConfiguration throttleConfig = throttleCtxt.getThrottleConfiguration();
                    if (throttleConfig != null) {
                        //check for configuration for this caller
                        callerId = throttleConfig.getConfigurationKeyOfCaller(domain);
                        if (callerId != null) {
                            // If this is a clustered env.
                            throttleCtxt.setThrottleId(throttleId);
                            AccessInformation infor = accessRateController.canAccess(throttleCtxt, callerId,
                                    ThrottleConstants.DOMAIN_BASE);
                            StatCollector.collect(infor, domain, ThrottleConstants.DOMAIN_BASE);

                            //check for the permission for access
                            if (!infor.isAccessAllowed()) {

                                //In the case of both of concurrency throttling and
                                //rate based throttling have enabled ,
                                //if the access rate less than maximum concurrent access ,
                                //then it is possible to occur death situation.To avoid that reset,
                                //if the access has denied by rate based throttling
                                if (cac != null) {
                                    cac.incrementAndGet();
                                    cache.put(key, cac);
                                    if (debugOn) {
                                        log.debug("Added the state of ConcurrentAccessController "
                                                + "to cache with key : " + key);
                                    }
                                }
                                throw new AxisFault(" Access deny for a " + "caller with Domain " + domain + " "
                                        + " : Reason : " + infor.getFaultReason());
                            }
                        } else {
                            if (debugOn) {
                                log.debug("Could not find the Throttle Context for domain-Based "
                                        + "Throttling for domain name " + domain + " Throttling for this "
                                        + "domain name may not be configured from policy");
                            }
                        }
                    }
                }
            } else {
                if (debugOn) {
                    log.debug("Could not find the domain of the caller - IP-based throttling may occur");
                }
            }

            //IP based throttling - Only if there is no configuration for caller domain name

            if (callerId == null) {
                String ip = (String) messageContext.getProperty(MessageContext.REMOTE_ADDR);
                if (ip != null) {
                    // loads IP based throttle context
                    ThrottleContext context = throttle
                            .getThrottleContext(ThrottleConstants.IP_BASED_THROTTLE_KEY);
                    if (context != null) {
                        //Loads the ThrottleConfiguration
                        ThrottleConfiguration config = context.getThrottleConfiguration();
                        if (config != null) {
                            // check for configuration for this ip
                            callerId = config.getConfigurationKeyOfCaller(ip);
                            if (callerId != null) {
                                context.setThrottleId(throttleId);
                                AccessInformation infor = accessRateController.canAccess(context, callerId,
                                        ThrottleConstants.IP_BASE);
                                // check for the permission for access
                                StatCollector.collect(infor, ip, ThrottleConstants.IP_BASE);
                                if (!infor.isAccessAllowed()) {

                                    //In the case of both of concurrency throttling and
                                    //rate based throttling have enabled ,
                                    //if the access rate less than maximum concurrent access ,
                                    //then it is possible to occur death situation.To avoid that reset,
                                    //if the access has denied by rate based throttling
                                    if (cac != null) {
                                        cac.incrementAndGet();
                                        // set back if this is a clustered env
                                        cache.put(key, cac);
                                        if (debugOn) {
                                            log.debug("Added the state of ConcurrentAccessController "
                                                    + "to cache with key : " + key);
                                        }
                                    }
                                    throw new AxisFault(" Access deny for a " + "caller with IP " + ip + " "
                                            + " : Reason : " + infor.getFaultReason());
                                }
                            }
                        }
                    } else {
                        if (debugOn) {
                            log.debug("Could not find the throttle Context for IP-Based throttling");
                        }
                    }
                } else {
                    if (debugOn) {
                        log.debug(
                                "Could not find the IP address of the caller " + "- throttling will not occur");
                    }
                }
            }
        }
        // all the replication functionality of the access rate based throttling handles by itself
        // just replicate the current state of ConcurrentAccessController
        if (cac != null) {
            cache.put(key, cac);
            if (debugOn) {
                log.debug("Added the state of ConcurrentAccessController " + "to cache with key : " + key);
            }
        }

        //finally engage rolebased access throttling if available
        doRoleBasedAccessThrottling(throttle, messageContext);
    } else {
        //replicate the current state of ConcurrentAccessController
        if (cac != null) {
            cache.put(key, cac);
            if (debugOn) {
                log.debug("Added the state of ConcurrentAccessController " + "to cache with key : " + key);
            }
        }
        throw new AxisFault(
                "Access has currently been denied since " + " maximum concurrent access have exceeded");
    }

}