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.mashupmedia.controller.remote.RemoteLibraryController.java

@RequestMapping(value = "/connect/{libraryType}/{uniqueName}", method = RequestMethod.GET)
public ModelAndView handleConnectRemoteLibrary(HttpServletRequest request, @PathVariable String libraryType,
        @PathVariable String uniqueName, Model model) throws IOException {

    Library remoteLibrary = getRemoteLibrary(uniqueName, request, false);
    if (remoteLibrary == null) {
        logger.info("Unable to connect to remote library, unknown host: " + request.getRemoteHost());
        return null;
    }//w  w  w .ja va 2 s .  c  o m

    File file = FileHelper.getLibraryXmlFile(remoteLibrary.getId());
    final String xml = FileUtils.readFileToString(file, Encoding.UTF8.getEncodingString());

    ModelAndView modelAndView = new ModelAndView(new View() {

        @Override
        public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
                throws Exception {
            response.setContentType(getContentType());
            response.getWriter().print(xml);
        }

        @Override
        public String getContentType() {
            return WebContentType.XML.getContentType();
        }
    });

    return modelAndView;
}

From source file:org.apache.nifi.toolkit.tls.service.server.TlsCertificateAuthorityServiceHandler.java

private void writeResponse(ObjectMapper objectMapper, HttpServletRequest request, HttpServletResponse response,
        TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse, int responseCode) throws IOException {
    if (logger.isInfoEnabled()) {
        logger.info(new StringBuilder("Returning code:").append(responseCode).append(" payload ")
                .append(objectMapper.writeValueAsString(tlsCertificateAuthorityResponse)).append(" to ")
                .append(request.getRemoteHost()).toString());
    }/*from  w w w  .j a  v  a2  s.co m*/
    if (responseCode == Response.SC_OK) {
        objectMapper.writeValue(response.getWriter(), tlsCertificateAuthorityResponse);
        response.setStatus(responseCode);
    } else {
        response.setStatus(responseCode);
        response.setContentType("application/json");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        objectMapper.writeValue(response.getWriter(), tlsCertificateAuthorityResponse);
    }
}

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

@RequestMapping(value = "/api/images2")
public @ResponseBody Object findCarImages(final String brand, final String model, final String build,
        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();
    AccessItem ai = new AccessItem();
    ai.setIp(ip);//www.  j ava  2  s  . c o  m
    ai.setUsername(username);
    ai.setService(Product.IMAGES2.getId());
    ai.setRequest("Brand=" + brand + ", Model=" + model + ", Build=" + build);

    log4j.info("Brand=" + brand + ", Model=" + model + ", Build=" + build + " ,Remaining: "
            + suspendedImageRequests.remainingCapacity());
    try {
        ImageProduct imageProduct = netCarService.search(brand, model, build);
        ai.setResponse(imageProduct.getImage1());
        free.save(ai);
        return addPrefix(port, address, imageProduct);
    } catch (Exception e) {
        log4j.error(e.getMessage(), e);
        ai.setResponse(e.getMessage());
        free.save(ai);
    }
    return "no data";
}

From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLoginmodule.java

public Map<String, String> matchHeaders(HttpServletRequest request, String[] headers)
        throws HeaderMismatchException {
    Map<String, String> headerMap = new HashMap<String, String>();
    for (String header : headers) {
        String headerValue = request.getHeader(header);
        if (headerValue != null) {
            headerMap.put(header, headerValue);
        } else// w  w  w  . j a v  a2  s  . c  o  m
            log.warn("An Unauthorized attempt has been made to access the protected resource from host "
                    + request.getRemoteHost());
    }
    return headerMap;
}

From source file:org.mashupmedia.controller.remote.RemoteLibraryController.java

@RequestMapping(value = "/album-art/{uniqueName}/{imageTypeValue}/{songId}", method = { RequestMethod.GET,
        RequestMethod.HEAD })//from w  w w  .j  ava2s  .c om
public ModelAndView handleAlbumArt(HttpServletRequest request, @PathVariable String uniqueName,
        @PathVariable String imageTypeValue, @PathVariable Long songId, Model model) throws IOException {
    Library remoteLibrary = getRemoteLibrary(uniqueName, request, true);
    if (remoteLibrary == null) {
        logger.info("Unable to load album art, unknown host: " + request.getRemoteHost());
        return null;
    }

    logInAsSystemuser(request);

    ImageType imageType = ImageHelper.getImageType(imageTypeValue);
    StringBuilder servletPathBuilder = new StringBuilder(request.getServletPath());
    servletPathBuilder.append("/music/album-art");
    servletPathBuilder.append("/" + imageType.toString().toLowerCase());
    MediaItem mediaItem = mediaManager.getMediaItem(songId);
    if (mediaItem == null || !(mediaItem instanceof Song)) {
        return null;
    }
    Song song = (Song) mediaItem;
    Album album = song.getAlbum();
    long albumId = album.getId();

    servletPathBuilder.append("/" + albumId);
    return new ModelAndView("forward:" + servletPathBuilder.toString());
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUnidExtension.java

boolean checkAuthorization(HttpServletRequest request) {
    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
    if (certs == null) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoclientauth", request.getRemoteAddr(),
                request.getRemoteHost());
        m_log.error(errMsg);/*from  w ww .j a  va2s. c  o  m*/
        return false;
    }
    // The certificate of the entity is nr 0
    X509Certificate cert = certs[0];
    if (cert == null) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoclientauth", request.getRemoteAddr(),
                request.getRemoteHost());
        m_log.error(errMsg);
        return false;
    }
    // Check if the certificate is authorised to access the Fnr
    if (this.trustedCerts.contains(cert.getSerialNumber())) {
        // If we found in the hashmap the same key with issuer and serialnumber, we know we got it. 
        // Just verify it as well to be damn sure
        try {
            cert.verify(this.cacert.getPublicKey());
        } catch (Exception e) {
            String errMsg = intres.getLocalizedMessage("ocsp.errorverifycert");
            m_log.error(errMsg, e);
            return false;
        }
        // If verify was successful we know if was good!
        return true;
    }
    String errMsg = intres.getLocalizedMessage("ocsp.erroruntrustedclientauth", request.getRemoteAddr(),
            request.getRemoteHost());
    m_log.error(errMsg);
    return false;
}

From source file:com.evolveum.midpoint.gui.impl.util.ReportPeerQueryInterceptor.java

private boolean checkRequest(HttpServletRequest request, HttpServletResponse response, String operation) {

    String userAgent = request.getHeader("User-Agent");
    if (!ReportTypeUtil.HEADER_USERAGENT.equals(userAgent)) {
        LOGGER.debug("Invalid user-agent: {}", userAgent);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }//from  w  ww. j  a  v a  2s. c  om

    if (!nodeAuthenticator.authenticate(request.getRemoteHost(), request.getRemoteAddr(), operation)) {
        LOGGER.debug("Unknown node, host: {} ", request.getRemoteHost());
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }

    return true;
}

From source file:net.navasoft.madcoin.backend.services.controller.SessionController.java

/**
 * Signup.//from  w ww. ja  va 2  s  .co  m
 * 
 * @param request
 *            the request
 * @param fromSystem
 *            the from system
 * @param fromToken
 *            the from token
 * @param userAgent
 *            the user agent
 * @param signer
 *            the signer
 * @return the success response vo
 * @since 18/08/2014, 08:00:20 PM
 */
@RequestMapping(value = { newUser }, method = { RequestMethod.PUT, RequestMethod.POST })
@ResponseStatus(value = HttpStatus.OK)
public @ResponseBody SuccessResponseVO signup(HttpServletRequest request,
        @RequestHeader("X-Origin-OS") String fromSystem, @RequestHeader("X-Origin-Token") String fromToken,
        @RequestHeader("User-Agent") String userAgent,
        @RequestBody(required = true) AppSignupSuccessRequestVO signer) {
    String ipAddress = request.getRemoteAddr();
    System.out.println(request.getRemoteAddr() + "/" + request.getRemoteHost());
    signer.setIpAddress(ipAddress);
    signer.setGadget(userAgent);
    signer.setOs(fromSystem);
    signer.setSerial(fromToken);
    signer.setVersion(userAgent);
    return service.signUpUser(buildWrapper(signer));
}

From source file:de.mpg.mpdl.inge.pidcache.web.MainServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    logger.info("PID cache POST request");

    if (req.getParameter("url") == null) {
        resp.sendError(HttpServletResponse.SC_NO_CONTENT, "URL parameter failed.");
    }/*  w  w w .  j  a  v  a2  s . c o m*/
    try {

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

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

        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.setStatus(cacheService.getStatus());
        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:org.eclipse.gyrex.http.jetty.internal.app.ApplicationDelegateHandler.java

private void setupMdc(final Application application, final HttpServletRequest request) {
    // application specific information
    MDC.put(MDC_KEY_APPLICATION_ID, application.getId());
    MDC.put(MDC_KEY_CONTEXT_PATH, application.getContext().getContextPath().toString());

    // general request information
    MDC.put(MDC_KEY_REQUEST_REMOTE_HOST, request.getRemoteHost());
    MDC.put(MDC_KEY_REQUEST_REQUEST_URI, request.getRequestURI());
    final StringBuffer requestURL = request.getRequestURL();
    if (requestURL != null) {
        MDC.put(MDC_KEY_REQUEST_REQUEST_URL, requestURL.toString());
    }//from  w  ww. j  a v a2  s. c  om
    MDC.put(MDC_KEY_REQUEST_QUERY_STRING, request.getQueryString());
    MDC.put(MDC_KEY_REQUEST_USER_AGENT_MDC_KEY, request.getHeader("User-Agent"));
    MDC.put(MDC_KEY_REQUEST_X_FORWARDED_FOR, request.getHeader("X-Forwarded-For"));
}