Example usage for javax.servlet.http HttpServletRequest getRemoteAddr

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

Introduction

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

Prototype

public String getRemoteAddr();

Source Link

Document

Returns the Internet Protocol (IP) address of the client or last proxy that sent the request.

Usage

From source file:io.resthelper.RestHelperController.java

@ExceptionHandler(NotAllowIpException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public void accessDeniedException(HttpServletRequest request, NotAllowIpException e) {
    String remoteAddr = request.getHeader("X-Real-IP");
    remoteAddr = (remoteAddr != null) ? remoteAddr : request.getRemoteAddr();

    LOGGER.warn("Access Deny Ip : {}", remoteAddr);
}

From source file:de.eorganization.crawler.server.servlets.JSONImportServlet.java

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

    try {//  ww  w . j  ava2  s  . c om

        resp.setContentType("text/plain");

        InputStream stream = req.getInputStream();

        log.info("Got Upload " + req.getContentType() + " (" + req.getContentLength() + " bytes) from "
                + req.getRemoteAddr());

        String amiId = req.getHeader("AMI-ID");
        log.info("Got AMI ID:" + amiId);
        String repository = req.getHeader("REPO");
        log.info("Got REPO:" + repository);
        if (amiId == null || repository == null || "".equals(amiId) || "".equals(repository)) {
            log.severe("AMI ID and REPO HTTP Header required.");
            return;
        }

        // Gson gson = new Gson();
        // log.info("Parsed Gson " + gson.fromJson(new
        // InputStreamReader(stream), JsonObject.class));

        String jsonString = IOUtils.toString(stream);
        log.info("Got JSON String "
                + jsonString.substring(0, jsonString.length() > 128 ? 128 : jsonString.length() - 1));
        JSONObject json = new JSONObject();
        try {
            json = new JSONObject(jsonString);
            log.fine("Parsed Json " + json);
            log.finer("Json has keys: " + json.names());
        } catch (JSONException e) {
            log.severe("No JSON sent or wrong format.");
            return;
        }

        JSONObject software = json.optJSONObject("software");
        if (software != null) {
            log.finer("Software JSON " + software);

            JSONArray softwareNames = software.names();
            log.finer("Key Array JSON " + softwareNames);
            for (int i = 0; i < softwareNames.length(); i++) {
                log.fine("software " + softwareNames.getString(i) + " with version "
                        + software.getJSONObject(softwareNames.getString(i)).getString("version"));

                Map<String, String> softAttributes = new HashMap<String, String>();
                JSONArray softwareAttributes = software.getJSONObject(softwareNames.getString(i)).names();
                for (int j = 0; j < softwareAttributes.length(); j++)
                    softAttributes.put(softwareAttributes.getString(j),
                            software.getJSONObject(softwareNames.getString(i))
                                    .getString(softwareAttributes.getString(j)));

                Software soft = AmiManager.saveSoftware(amiId, repository, softwareNames.getString(i),
                        software.getJSONObject(softwareNames.getString(i)).getString("version"),
                        softAttributes);
                if (soft != null) {
                    log.fine("Saved/restored software " + soft);
                    // soft.getAttributes().putAll(softAttributes);
                    // AmiManager.updateSoftware(soft);
                    // log.fine("Saved object " + soft);
                } else
                    log.severe("Not able to save software information for given Ami Id " + amiId + "!");

            }
            List<String> names = new ArrayList<String>();
            for (int i = 0; i < softwareNames.length(); i++)
                names.add(softwareNames.getString(i));
            AmiManager.updateSoftwareNames(names);
            log.info("Saved " + softwareNames.length() + " software objects");

        }

        JSONObject languages = json.optJSONObject("languages");
        if (languages != null) {
            log.finer("Languages JSON " + languages);

            JSONArray languagesNames = languages.names();
            log.finer("Key Array JSON " + languagesNames);
            for (int i = 0; i < languagesNames.length(); i++) {
                log.fine("languages " + languagesNames.getString(i) + " with version "
                        + languages.getJSONObject(languagesNames.getString(i)).getString("version"));

                Map<String, String> langAttributes = new HashMap<String, String>();
                JSONArray languageAttributes = languages.getJSONObject(languagesNames.getString(i)).names();
                for (int j = 0; j < languageAttributes.length(); j++)
                    langAttributes.put(languageAttributes.getString(j),
                            languages.getJSONObject(languagesNames.getString(i))
                                    .getString(languageAttributes.getString(j)));

                Language lang = AmiManager.saveLanguage(amiId, repository, languagesNames.getString(i),
                        languages.getJSONObject(languagesNames.getString(i)).getString("version"),
                        langAttributes);
                if (lang != null) {
                    log.fine("Saved/restored programming language " + lang);
                    lang.getAttributes().putAll(langAttributes);
                    AmiManager.updateLanguage(lang);
                    log.fine("Saved object " + lang);
                } else
                    log.severe("Not able to save programming language information for given Ami Id " + amiId
                            + "!");

            }
            log.info("Saved " + languagesNames.length() + " programming language objects");
        }

        resp.getWriter().println(
                "Saving software packages and programming languages for " + amiId + " (" + repository + ").");

    } catch (JSONException e) {
        log.severe("Error while parsing JSON upload" + e.getMessage() + ", trace: " + e.getStackTrace());
        log.throwing(JSONImportServlet.class.getName(), "doPost", e);
        e.printStackTrace();

    } catch (Exception ex) {
        log.severe("Unexpected error" + ex.getMessage() + ", trace: " + ex.getStackTrace());
        log.throwing(JSONImportServlet.class.getName(), "doPost", ex);
        ex.printStackTrace();
    }

    // log.info("returning to referer " + req.getHeader("referer"));
    // resp.sendRedirect(req.getHeader("referer") != null &&
    // !"".equals(req.getHeader("referer")) ? req.getHeader("referer") :
    // "localhost:8088");
}

From source file:org.jutge.joc.porra.recaptcha.interceptor.ReCaptchaInterceptor.java

@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler) throws Exception {
    this.logger.info("ReCaptchaInterceptor.preHandle");
    final ReCaptchaConsumer annotation = ReCaptchaInterceptor.getReCaptchaConsumerAnnotation(handler);
    if (annotation != null) {
        final String recaptchaResponse = request.getParameter(ReCaptchaUtils.RECAPTCHA_RESPONSE_FIELD);
        final String recaptchaChallenge = request.getParameter(ReCaptchaUtils.RECAPTCHA_CHALLENGE_FIELD);
        final String remoteAddr = request.getRemoteAddr();
        final ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        final ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, recaptchaChallenge,
                recaptchaResponse);/*from   w  w w.ja v  a2s .  c om*/
        request.setAttribute(ReCaptchaUtils.RECAPTCHA_IS_VALID, reCaptchaResponse.isValid());
    }
    return true;
}

From source file:de.logicline.splash.controller.UserController.java

/**
 * user login with captcha verification/*from  w w  w . ja  va2  s  . c om*/
 * needs configured heroku connector add on
 * returns specific error if auth failed or config not don
 * 
 * @param userInput
 * @param request
 * @param response
 * @return
 */
@RequestMapping(value = "/user/clogin", method = RequestMethod.POST)
public @ResponseBody Map<String, String> userLoginWithCaptcha(@RequestBody Map<String, String> userInput,
        HttpServletRequest request, HttpServletResponse response) {

    String username = userInput.get("username");
    String password = userInput.get("password");
    String challenge = userInput.get("recaptcha_challenge_field");
    String uresponse = userInput.get("recaptcha_response_field");

    ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(request.getRemoteAddr(), challenge, uresponse);

    if (reCaptchaResponse.isValid()) {
        response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        return null;
    }

    UserEntity userEntityTmp = userService.getUserByName(username);

    if (userEntityTmp == null || BCrypt.checkpw(password, userEntityTmp.getPassword())) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
    }

    // TODO merge with normal login
    Map<String, String> responseMap = new HashMap<String, String>();
    String token = userEntityTmp.getToken();
    responseMap.put("token", token);
    responseMap.put("userId", String.valueOf(userEntityTmp.getUserId()));
    responseMap.put("role", userEntityTmp.getRole());

    ContactEntity contactEntity = userService.getContact(token);
    if (contactEntity != null) {
        responseMap.put("firstName", contactEntity.getFirstName());
        responseMap.put("lastName", contactEntity.getLastName());
    }

    return responseMap;
}

From source file:com.m2a.struts.M2AFormBase.java

/**
  * If bean is set to mutable, calls <code>resetSessionLocale</code>
  * and <code>setRemoteAddr</code>.
  */*  ww  w.  j  av a2 s . c  o  m*/
  * Subclasses resetting their own fields should observe the mutable
  * state (<code>if (isMutable()) ...</code>).
  *
  * @param mapping The mapping used to select this instance
  * @param request The servlet request we are processing
  */
public void reset(ActionMapping mapping, HttpServletRequest request) {

    if (isMutable()) {

        resetSessionLocale(request);
        setRemoteAddr(request.getRemoteAddr());
    }

}

From source file:cn.bc.web.util.DebugUtils.java

public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) {
    @SuppressWarnings("rawtypes")
    Enumeration e;//from   w w w.  j a  va 2 s  .co m
    String name;
    StringBuffer html = new StringBuffer();

    //session
    HttpSession session = request.getSession();
    html.append("<div><b>session:</b></div><ul>");
    html.append(createLI("Id", session.getId()));
    html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString()));
    html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString()));

    //session:attributes
    e = session.getAttributeNames();
    html.append("<li>attributes:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, String.valueOf(session.getAttribute(name))));
    }
    html.append("</ul></li>\r\n");
    html.append("</ul>\r\n");

    //request
    html.append("<div><b>request:</b></div><ul>");
    html.append(createLI("URL", request.getRequestURL().toString()));
    html.append(createLI("QueryString", request.getQueryString()));
    html.append(createLI("Method", request.getMethod()));
    html.append(createLI("CharacterEncoding", request.getCharacterEncoding()));
    html.append(createLI("ContentType", request.getContentType()));
    html.append(createLI("Protocol", request.getProtocol()));
    html.append(createLI("RemoteAddr", request.getRemoteAddr()));
    html.append(createLI("RemoteHost", request.getRemoteHost()));
    html.append(createLI("RemotePort", request.getRemotePort() + ""));
    html.append(createLI("RemoteUser", request.getRemoteUser()));
    html.append(createLI("ServerName", request.getServerName()));
    html.append(createLI("ServletPath", request.getServletPath()));
    html.append(createLI("ServerPort", request.getServerPort() + ""));
    html.append(createLI("Scheme", request.getScheme()));
    html.append(createLI("LocalAddr", request.getLocalAddr()));
    html.append(createLI("LocalName", request.getLocalName()));
    html.append(createLI("LocalPort", request.getLocalPort() + ""));
    html.append(createLI("Locale", request.getLocale().toString()));

    //request:headers
    e = request.getHeaderNames();
    html.append("<li>Headers:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getHeader(name)));
    }
    html.append("</ul></li>\r\n");

    //request:parameters
    e = request.getParameterNames();
    html.append("<li>Parameters:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getParameter(name)));
    }
    html.append("</ul></li>\r\n");

    html.append("</ul>\r\n");

    //response
    html.append("<div><b>response:</b></div><ul>");
    html.append(createLI("CharacterEncoding", response.getCharacterEncoding()));
    html.append(createLI("ContentType", response.getContentType()));
    html.append(createLI("BufferSize", response.getBufferSize() + ""));
    html.append(createLI("Locale", response.getLocale().toString()));
    html.append("<ul>\r\n");
    return html;
}

From source file:com.music.web.MusicController.java

@RequestMapping("/music/get/{id}")
public void getPiece(@PathVariable long id,
        @RequestParam(required = false, defaultValue = "false") boolean mobileApp,
        @RequestParam(required = false, defaultValue = "false") boolean download, OutputStream os,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    Long userId = null;//from   www  .  ja v  a 2  s  .co  m
    if (userContext.getUser() != null) {
        userId = userContext.getUser().getId();
    }
    if (download) {
        pieceService.incrementDownloads(id, false);
    } else {
        pieceService.storePlay(id, userId, request.getRemoteAddr(), mobileApp);
    }
    response.setHeader("Content-Disposition", "attachment; filename=\"" + id + ".mp3\"");
    setNotCacheable(response);
    response.setContentType("audio/mp3");
    InputStream is = pieceService.getPieceFile(id);
    IOUtils.copy(is, os);
}

From source file:UploadDownloadFile.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);/*from   ww  w.ja va 2s. c o  m*/
    System.out.println("--> doGet -->");
    String filePath;

    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("File Name can't be null or empty");
    }
    final String clientip = request.getRemoteAddr().replace(":", "_");
    filePath = "/Users/" + currentuser + "/GlassFish_Server/glassfish/domains/domain1/tmpfiles/Uploaded/"
            + clientip + "/";
    File file = new File(filePath + File.separator + fileName);

    System.out.println("download file = " + file);
    if (!file.exists()) {
        throw new ServletException("File doesn't exists on server.");
    }
    System.out.println("File location on server::" + file.getAbsolutePath());
    ServletContext ctx = getServletContext();
    InputStream fis = new FileInputStream(file);
    String mimeType = ctx.getMimeType(file.getAbsolutePath());
    response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
    response.setContentLength((int) file.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    ServletOutputStream os = response.getOutputStream();
    byte[] bufferData = new byte[1024];
    int read = 0;
    while ((read = fis.read(bufferData)) != -1) {
        os.write(bufferData, 0, read);
    }
    os.flush();
    os.close();
    fis.close();
    System.out.println("File downloaded at client successfully");
}

From source file:javax.faces.webapp.FacesServlet.java

public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {

    HttpServletRequest httpRequest = ((HttpServletRequest) request);
    String pathInfo = httpRequest.getPathInfo();

    // if it is a prefix mapping ...
    if (pathInfo != null && (pathInfo.startsWith("/WEB-INF") || pathInfo.startsWith("/META-INF"))) {
        StringBuffer buffer = new StringBuffer();

        buffer.append(" Someone is trying to access a secure resource : ").append(pathInfo);
        buffer.append("\n remote address is ").append(httpRequest.getRemoteAddr());
        buffer.append("\n remote host is ").append(httpRequest.getRemoteHost());
        buffer.append("\n remote user is ").append(httpRequest.getRemoteUser());
        buffer.append("\n request URI is ").append(httpRequest.getRequestURI());

        log.warn(buffer.toString());/* w w  w .j a v a  2s  . com*/

        // Why does RI return a 404 and not a 403, SC_FORBIDDEN ?

        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (log.isTraceEnabled())
        log.trace("service begin");
    FacesContext facesContext = _facesContextFactory.getFacesContext(_servletConfig.getServletContext(),
            request, response, _lifecycle);
    try {
        _lifecycle.execute(facesContext);
        _lifecycle.render(facesContext);
    } catch (Throwable e) {
        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof ServletException) {
            throw (ServletException) e;
        } else if (e.getMessage() != null) {
            throw new ServletException(e.getMessage(), e);
        } else {
            throw new ServletException(e);
        }
    } finally {
        facesContext.release();
    }
    if (log.isTraceEnabled())
        log.trace("service end");
}