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:siddur.solidtrust.image.ImageController.java

@RequestMapping(value = "/api/images")
public @ResponseBody DeferredResult<Object> findCarImages(final @RequestParam("id") String id,
        HttpServletRequest request) {
    final String ip = request.getRemoteHost();
    final String username = request.getAttribute(SolidtrustConstants.CLIENT_ID) + "";
    final int port = request.getLocalPort();
    final String address = request.getLocalAddr();

    final DeferredResult<Object> result = new DeferredResult<>(2000L, "no data");
    log4j.info("Id=" + id + " ,Remaining: " + suspendedImageRequests.remainingCapacity());
    try {//from w  w  w  .j a  va 2 s  . com
        suspendedImageRequests.add(result);
    } catch (Exception e1) {
        result.setResult("Image service is overload");
        return result;
    }
    result.onCompletion(new Runnable() {

        @Override
        public void run() {
            suspendedImageRequests.remove(result);
        }
    });

    new Thread(new Runnable() {

        @Override
        public void run() {
            AccessItem ai = new AccessItem();
            ai.setIp(ip);
            ai.setUsername(username);
            ai.setService(Product.IMAGES.getId());
            ai.setRequest(id);

            ImageProduct ip = null;
            try {
                ip = findImagesByLicensePlate(id);
            } catch (Exception e) {
                ai.setStatus(-1);
                log4j.error(e.getMessage(), e);
                ai.setResponse(e.getMessage());
                free.save(ai);
                return;
            }

            if (ip == null) {
                ai.setStatus(-1);
                ai.setResponse("Not found:" + id);
                free.save(ai);
                return;
            }

            ai.setResponse(ip.getId() + "");
            free.save(ai);

            ImageProduct resp = addPrefix(port, address, ip);
            result.setResult(resp);

        }
    }).start();

    return result;
}

From source file:org.apache.hadoop.hdfs.qjournal.server.GetJournalEditServlet.java

private boolean checkRequestorOrSendError(Configuration conf, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    if (UserGroupInformation.isSecurityEnabled() && !isValidRequestor(request, conf)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Only Namenode and another JournalNode may access this servlet");
        LOG.warn("Received non-NN/JN request for edits from " + request.getRemoteHost());
        return false;
    }/*from  ww  w .j a v  a 2 s  . c om*/
    return true;
}

From source file:fr.paris.lutece.plugins.mylutece.modules.openid.authentication.OpenIDAuthentication.java

/**
 * processing the authentication response
 * @param request The HTTP request/*from   w w w .j av  a 2  s  .  co m*/
 * @return The URL depending of the result
 */
public String verifyResponse(HttpServletRequest request) {
    String strReturnUrl = getMessageUrl(request, MESSAGE_KEY_AUTHENTICATION_FAILED);

    _logger.debug(
            "Provider callback - host : " + request.getRemoteHost() + " - IP : " + request.getRemoteAddr());

    OpenIDUser user = null;

    try {
        // extract the parameters from the authentication response
        // (which comes in as a HTTP request from the OpenID provider)
        ParameterList response = new ParameterList(request.getParameterMap());

        // retrieve the previously stored discovery information
        DiscoveryInformation discovered = (DiscoveryInformation) request.getSession()
                .getAttribute("openid-disc");

        // extract the receiving URL from the HTTP request
        StringBuffer receivingURL = request.getRequestURL();
        String queryString = request.getQueryString();

        if ((queryString != null) && (queryString.length() > 0)) {
            receivingURL.append("?").append(request.getQueryString());
        }

        // verify the response; ConsumerManager needs to be the same
        // (static) instance used to place the authentication request
        VerificationResult verification = _manager.verify(receivingURL.toString(), response, discovered);

        // examine the verification result and extract the verified identifier
        Identifier verified = verification.getVerifiedId();
        _logger.debug("Authentication verification  : " + verified);

        if (verified != null) {
            user = new OpenIDUser(verified.getIdentifier(), this);

            AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();

            if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
                _logger.debug("Authentication successfull - identifier : " + verified.getIdentifier());

                FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);

                for (String strKey : (Set<String>) fetchResp.getAttributes().keySet()) {
                    _logger.debug(
                            "Attribute " + strKey + " - value : " + fetchResp.getAttributes().get(strKey));
                }

                String strFirstName = (String) fetchResp.getAttributes().get(ATTRIBUTE_FIRST_NAME);
                String strLastName = (String) fetchResp.getAttributes().get(ATTRIBUTE_LAST_NAME);
                List emails = fetchResp.getAttributeValues(ATTRIBUTE_EMAIL);
                String email = (String) emails.get(0);

                user.setUserInfo(LuteceUser.NAME_GIVEN, strFirstName);
                user.setUserInfo(LuteceUser.NAME_FAMILY, strLastName);
                user.setUserInfo(LuteceUser.BUSINESS_INFO_ONLINE_EMAIL, email);
            }

            SecurityService.getInstance().registerUser(request, user);

            strReturnUrl = AppPathService.getBaseUrl(request) + AppPathService.getPortalUrl(); // success
        }
    } catch (OpenIDException e) {
        _logger.error("OpenId Error in provider response : " + e.getMessage(), e);
    }

    return strReturnUrl;
}

From source file:com.qualogy.qafe.web.upload.DatagridUploadServlet.java

@SuppressWarnings("unchecked")
private void writeUploadInfo(HttpServletRequest request) {
    writeLog("Document Upload!");

    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        Object name = headerNames.nextElement();
        if (name != null) {
            writeLog("Header - " + name + " : " + request.getHeader((String) name));
        }// w  w  w.  j av a2s.c  om
    }

    writeLog("ServletRemoteAddr: " + request.getRemoteAddr());
    writeLog("Remote Host: " + request.getRemoteHost());
    writeLog("Remote User: " + request.getRemoteUser());
    writeLog("Protocol: " + request.getProtocol());
    writeLog("Server Name: " + request.getServerName());
    writeLog("Server Port: " + request.getServerPort());
    writeLog("Request URL: " + request.getRequestURL());

}

From source file:de.mpg.escidoc.services.pidcache.web.MainServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logger.info("POST request");

    if (req.getParameter("url") == null) {
        logger.warn("URL parameter failed.");
        resp.sendError(HttpServletResponse.SC_NO_CONTENT, "URL parameter failed.");
    }//from w  ww.  java2 s .c  om
    try {

        if (!authenticate(req, resp)) {
            logger.warn("Unauthorized request from " + req.getRemoteHost());
            return;
        }

        PidCacheService cacheService = new PidCacheService();
        String xmlOutput = null;

        if (logger.isDebugEnabled()) {
            logger.info("request pathInfo <" + req.getPathInfo() + ">");
        }
        if (GwdgPidService.GWDG_PIDSERVICE_CREATE.equals(req.getPathInfo())) {
            xmlOutput = cacheService.create(req.getParameter("url"));
        } else if (GwdgPidService.GWDG_PIDSERVICE_EDIT.equals(req.getPathInfo())) {
            if (req.getParameter("pid") == null) {
                resp.sendError(HttpServletResponse.SC_NO_CONTENT, "PID parameter failed.");
            }
            xmlOutput = cacheService.update(req.getParameter("pid"), req.getParameter("url"));
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, req.getPathInfo());
        }

        resp.encodeRedirectURL(cacheService.getLocation());
        resp.addHeader("Location", cacheService.getLocation());
        resp.getWriter().append(xmlOutput);
    } catch (Exception e) {
        throw new ServletException("Error processing request", e);
    }
}

From source file:io.kamax.mxisd.controller.identity.v1.SessionRestController.java

@RequestMapping(value = "/validate/{medium}/requestToken")
String init(HttpServletRequest request, HttpServletResponse response, @PathVariable String medium)
        throws IOException {
    log.info("Request {}: {}", request.getMethod(), request.getRequestURL(), request.getQueryString());
    if (ThreePidMedium.Email.is(medium)) {
        SessionEmailTokenRequestJson req = parser.parse(request, SessionEmailTokenRequestJson.class);
        return gson.toJson(
                new Sid(mgr.create(request.getRemoteHost(), new ThreePid(req.getMedium(), req.getValue()),
                        req.getSecret(), req.getAttempt(), req.getNextLink())));
    }//  w  w  w .j  a va  2  s .co  m

    if (ThreePidMedium.PhoneNumber.is(medium)) {
        SessionPhoneTokenRequestJson req = parser.parse(request, SessionPhoneTokenRequestJson.class);
        ThreePid threepid = new ThreePid(req.getMedium(), req.getValue());

        String sessionId = mgr.create(request.getRemoteHost(), threepid, req.getSecret(), req.getAttempt(),
                req.getNextLink());

        JsonObject res = new JsonObject();
        res.addProperty("sid", sessionId);
        res.addProperty(threepid.getMedium(), threepid.getAddress());
        return gson.toJson(res);
    }

    JsonObject obj = new JsonObject();
    obj.addProperty("errcode", "M_INVALID_3PID_TYPE");
    obj.addProperty("error", medium + " is not supported as a 3PID type");
    response.setStatus(HttpStatus.SC_BAD_REQUEST);
    return gson.toJson(obj);
}

From source file:com.streamsets.pipeline.stage.origin.httpserver.PushHttpReceiver.java

protected Map<String, String> getCustomHeaderAttributes(HttpServletRequest req) {
    Map<String, String> customHeaderAttributes = new HashMap<>();
    customHeaderAttributes.put(PATH_HEADER, StringUtils.stripToEmpty(req.getServletPath()));
    customHeaderAttributes.put(QUERY_STRING_HEADER, StringUtils.stripToEmpty(req.getQueryString()));
    customHeaderAttributes.put(METHOD_HEADER, StringUtils.stripToEmpty(req.getMethod()));
    customHeaderAttributes.put(REMOTE_HOST, StringUtils.stripToEmpty(req.getRemoteHost()));
    Enumeration<String> headerNames = req.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            customHeaderAttributes.put(headerName, req.getHeader(headerName));
        }/*from   w  w w.  ja  v  a2s . c om*/
    }

    return customHeaderAttributes;
}

From source file:OpenProdocServ.Oper.java

/**
 * /*from  w ww. ja  v  a 2 s.com*/
 * @param Req
 * @param out
 * @throws Exception
 */
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception {
    String Order = Req.getParameter(DriverRemote.ORDER);
    String Param = Req.getParameter(DriverRemote.PARAM);
    if (PDLog.isDebug()) {
        PDLog.Debug("From:" + Req.getRemoteHost() + "/" + Req.getRemoteHost() + ":" + Req.getRemoteUser());
        PDLog.Debug("Order:" + Order);
        PDLog.Debug("Param:" + Param);
    }
    DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document XMLObjects = DB.parse(new ByteArrayInputStream(Param.getBytes("UTF-8")));
    if (Order.equals(DriverGeneric.S_LOGIN)) {
        NodeList OPDObjectList = XMLObjects.getElementsByTagName("U");
        Node OPDObject = OPDObjectList.item(0);
        String User = OPDObject.getTextContent();
        OPDObjectList = XMLObjects.getElementsByTagName("C");
        OPDObject = OPDObjectList.item(0);
        String Pass = OPDObject.getTextContent();
        DriverGeneric D = ProdocFW.getSession("PD", User, Pass);
        Req.getSession().setAttribute("PRODOC_SESS", D);
        Answer(Req, out, true, null, null);
        return;
    } else if (Order.equals(DriverGeneric.S_UNLOCK)) {
        getSessOPD(Req).UnLock();
        Req.getSession().setAttribute("PRODOC_SESS", null);
        Answer(Req, out, true, null, null);
        return;
    }
    DriverGeneric D = getSessOPD(Req);
    String Results = D.RemoteOrder(Order, XMLObjects);
    Answer(Req, out, Results);
    XMLObjects = null;
    DB.reset();
}

From source file:org.jbia.admin.VoteServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//* w w w .ja va2  s. c  o m*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    /*
     * Get the system properties that contain the text to display and log:
     */
    String strDisplay = System.getProperty("jbia.display", "property jbia.display not found");
    String strLog = System.getProperty("jbia.log", "property jbia.log not found ");

    /*
     * Generate the display and log entry:
     */
    PrintWriter out = resp.getWriter();
    out.write("<html><body><h1>" + strDisplay + "</h1></body></html>");
    log.info(String.format(strLog, req.getRemoteHost()));
}

From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.TunnelServlet.java

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    monitor.fireOnRequest(request, response);
    if (response.isCommitted())
        return;//from   w w  w  . ja va2  s .c om

    ExtendedHttpMethod postMethod;

    // for this create ui server and port, properties.
    InetSocketAddress inetAddress = new InetSocketAddress(sslEndPoint, sslPort);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET"))
        postMethod = new ExtendedGetMethod();
    else
        postMethod = new ExtendedPostMethod();

    JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getRemoteHost());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setTargetURL(this.prot + inetAddress.getHostName());

    CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream());

    // copy headers
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hdr = (String) headerNames.nextElement();
        String lhdr = hdr.toLowerCase();

        if ("host".equals(lhdr)) {
            Enumeration<?> vals = httpRequest.getHeaders(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val.startsWith("127.0.0.1")) {
                    postMethod.addRequestHeader(hdr, sslEndPoint);
                }
            }
            continue;
        }

        Enumeration<?> vals = httpRequest.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                postMethod.addRequestHeader(hdr, val);
            }
        }

    }

    if (postMethod instanceof ExtendedPostMethod)
        ((ExtendedPostMethod) postMethod)
                .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType()));

    HostConfiguration hostConfiguration = new HostConfiguration();

    httpRequest.getProtocol();
    hostConfiguration.getParams().setParameter(SoapUIHostConfiguration.SOAPUI_SSL_CONFIG,
            settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPATH, "") + " "
                    + settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPASSWORD, ""));
    hostConfiguration.setHost(new URI(this.prot + sslEndPoint, true));

    hostConfiguration = ProxyUtils.initProxySettings(settings, httpState, hostConfiguration, prot + sslEndPoint,
            new DefaultPropertyExpansionContext(project));

    if (sslEndPoint.indexOf("/") < 0)
        postMethod.setPath("/");
    else
        postMethod.setPath(sslEndPoint.substring(sslEndPoint.indexOf("/"), sslEndPoint.length()));

    monitor.fireBeforeProxy(request, response, postMethod, hostConfiguration);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
        if (httpState == null)
            httpState = new HttpState();
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod, httpState);
    } else {
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod);
    }
    capturedData.stopCapture();

    capturedData.setRequest(capture.getCapturedData());
    capturedData.setRawResponseBody(postMethod.getResponseBody());
    capturedData.setResponseHeader(postMethod);
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), postMethod, capture));
    capturedData.setRawResponseData(
            getResponseToBytes(response.toString(), postMethod, capturedData.getRawResponseBody()));

    monitor.fireAfterProxy(request, response, postMethod, capturedData);

    StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
    // copy headers to response
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    for (String name : responseHeaders.keySet()) {
        for (String header : responseHeaders.get(name))
            httpResponse.addHeader(name, header);

    }

    IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream());

    postMethod.releaseConnection();

    synchronized (this) {
        monitor.addMessageExchange(capturedData);
    }

    capturedData = null;
}