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:com.alfaariss.oa.ManagerServlet.java

/**
 * Handles requests send by the system manager.
 * /*from www .ja v a  2s.  co m*/
 * The following requests are supported at this moment:
 * <ul>
 * <li>do=restart</li>
 * <li>do=stop</li>
 * <li>do=start</li>
 * </ul>
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@Override
public void service(HttpServletRequest oRequest, HttpServletResponse oResponse)
        throws ServletException, IOException {
    try {
        Properties pConfig = cloneConfigurationFromRequest(oRequest);
        String sDo = oRequest.getParameter("do");
        if (sDo == null) //No 'do' paramater
        {
            String sGet = oRequest.getParameter("get");
            if (sGet == null) //No 'get' and no 'do' paramater
            {
                _logger.error("Invalid request sent from IP: " + oRequest.getRemoteAddr());
                oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } else {
                StringBuffer sbWarning = new StringBuffer("Invalid request with name: ");
                sbWarning.append(sGet);
                sbWarning.append(", sent from IP: ");
                sbWarning.append(oRequest.getRemoteAddr());
                _logger.error(sbWarning.toString());
                oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            }

        } else if (sDo.equals("restart")) {
            _logger.info("Performing restart request sent from IP: " + oRequest.getRemoteAddr());
            _oEngineLauncher.restart(pConfig);
        } else if (sDo.equals("stop")) {
            _logger.info("Performing stop request sent from IP: " + oRequest.getRemoteAddr());
            _oEngineLauncher.stop();
        } else if (sDo.equals("start")) {
            _logger.info("Performing start request sent from IP: " + oRequest.getRemoteAddr());
            _oEngineLauncher.start(pConfig);
        } else {
            StringBuffer sbWarning = new StringBuffer("Invalid request with name: ");
            sbWarning.append(sDo);
            sbWarning.append(", sent from IP: ");
            sbWarning.append(oRequest.getRemoteAddr());
            _logger.error(sbWarning.toString());
            oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }

        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_OK);
    } catch (OAException e) {
        _logger.error("Error processing request", e);

        _logger.debug("try stopping the server");
        _oEngineLauncher.stop();

        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        _logger.fatal("Internal error", e);

        _logger.debug("try stopping the server");
        _oEngineLauncher.stop();

        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:jipdbs.web.processors.ContactProcessor.java

@Override
public String doProcess(ResolverContext context) throws ProcessorException {

    if (context.isPost()) {
        HttpServletRequest req = context.getRequest();
        String mail = req.getParameter("m");
        String text = req.getParameter("text");

        if (StringUtils.isEmpty(mail) || StringUtils.isEmpty(text)) {
            Flash.error(req, MessageResource.getMessage("fields_required"));
            return null;
        }/*from   w ww.j a v  a 2 s .c  o  m*/

        if (!Validator.isValidEmail(mail)) {
            Flash.error(req, MessageResource.getMessage("invalid_email"));
            return null;
        }

        IDDBService app = (IDDBService) context.getServletContext().getAttribute("jipdbs");

        if (!app.isRecaptchaValid(req.getRemoteAddr(), req.getParameter("recaptcha_challenge_field"),
                req.getParameter("recaptcha_response_field"))) {
            Flash.error(req, MessageResource.getMessage("invalid_captcha"));
            return null;

        }
        Principal user = req.getUserPrincipal();
        app.sendAdminMail(user != null ? user.getName() : null, mail, text);
        Flash.ok(req, MessageResource.getMessage("mail_sent"));
    }
    return null;
}

From source file:br.org.indt.ndg.servlets.DownloadClient.java

private TransactionLogVO createTransactionLogVO(HttpServletRequest request) {
    TransactionLogVO t = new TransactionLogVO();
    t.setTransmissionMode(TransactionLogVO.MODE_HTTP);
    t.setAddress(request.getRemoteAddr());
    t.setTransactionType(TransactionLogVO.TYPE_RECEIVE_SURVEY);
    t.setUser(request.getParameter("user"));

    return t;//from w  ww  .  j av  a2s. c  o  m
}

From source file:net.webpasswordsafe.server.webservice.rest.PasswordController.java

@RequestMapping(value = "/passwords/{passwordId}", method = RequestMethod.GET)
public ModelAndView getPassword(@PathVariable("passwordId") String passwordId, HttpServletRequest request,
        @RequestHeader(Constants.REST_AUTHN_USERNAME) String authnUsername,
        @RequestHeader(Constants.REST_AUTHN_PASSWORD) String authnPassword,
        @RequestHeader(Constants.REST_AUTHN_TOTP) String authnTOTP) {
    boolean isSuccess = false;
    String message = "";
    Map<String, String> passwordMap = new HashMap<String, String>();
    try {/*from   ww  w .j  a  va  2s  . c om*/
        ServerSessionUtil.setIP(request.getRemoteAddr());
        AuthenticationStatus authStatus = loginService.login(authnUsername,
                Utils.buildCredentials(authnPassword, authnTOTP));
        if (AuthenticationStatus.SUCCESS == authStatus) {
            Password password = passwordService.getPassword(Long.valueOf(passwordId));
            if (password != null) {
                passwordMap.put("id", String.valueOf(password.getId()));
                passwordMap.put("title", password.getName());
                passwordMap.put("username", password.getUsername());
                passwordMap.put("notes", password.getNotes());
                passwordMap.put("tags", password.getTagsAsString());
                passwordMap.put("active", password.isActive() ? "Y" : "N");
                isSuccess = true;
            } else {
                message = "Password not found";
            }
        } else {
            message = "Invalid authentication";
        }
        loginService.logout();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        isSuccess = false;
        message = e.getMessage();
    }
    return createModelAndView(isSuccess, message, "password", passwordMap);
}

From source file:net.webpasswordsafe.server.webservice.rest.PasswordController.java

@RequestMapping(value = "/passwords", method = RequestMethod.GET)
public ModelAndView getPasswordList(@RequestParam(value = "query", required = false) String query,
        HttpServletRequest request, @RequestHeader(Constants.REST_AUTHN_USERNAME) String authnUsername,
        @RequestHeader(Constants.REST_AUTHN_PASSWORD) String authnPassword,
        @RequestHeader(Constants.REST_AUTHN_TOTP) String authnTOTP) {
    boolean isSuccess = false;
    String message = "";
    List<Map<String, String>> passwordList = new ArrayList<Map<String, String>>();
    try {/*w ww .  j  av a  2  s  .c om*/
        ServerSessionUtil.setIP(request.getRemoteAddr());
        AuthenticationStatus authStatus = loginService.login(authnUsername,
                Utils.buildCredentials(authnPassword, authnTOTP));
        if (AuthenticationStatus.SUCCESS == authStatus) {
            List<Password> results = passwordService.searchPassword(query, true, new HashSet<Tag>(), Match.AND);
            for (Password password : results) {
                Map<String, String> passwordMap = new HashMap<String, String>();
                passwordMap.put("id", String.valueOf(password.getId()));
                passwordMap.put("title", password.getName());
                passwordMap.put("username", password.getUsername());
                passwordMap.put("notes", password.getNotes());
                passwordMap.put("tags", password.getTagsAsString());
                passwordList.add(passwordMap);
            }
            isSuccess = true;
        } else {
            message = "Invalid authentication";
        }
        loginService.logout();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        isSuccess = false;
        message = e.getMessage();
    }
    return createModelAndView(isSuccess, message, "passwordList", passwordList);
}

From source file:com.hypersocket.auth.json.AuthenticatedController.java

AuthenticationState createAuthenticationState(String scheme, HttpServletRequest request,
        HttpServletResponse response) throws AccessDeniedException, UnsupportedEncodingException {

    Map<String, Object> environment = new HashMap<String, Object>();
    for (BrowserEnvironment env : BrowserEnvironment.values()) {
        if (request.getHeader(env.toString()) != null) {
            environment.put(env.toString(), request.getHeader(env.toString()));
        }//from w w  w  .  j a  v  a 2s.co  m
    }

    AuthenticationState state = authenticationService.createAuthenticationState(scheme, request.getRemoteAddr(),
            environment, sessionUtils.getLocale(request));

    Enumeration<?> names = request.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        state.addParameter(name, URLDecoder.decode(request.getParameter(name), "UTF-8"));
    }

    request.getSession().setAttribute(AUTHENTICATION_STATE_KEY, state);
    return state;
}

From source file:com.vangent.hieos.logbrowser.servlets.AuthenticationServlet.java

/**
 * //from  w  w  w.  j av a 2 s  . c o m
 *  Entry point of the servlet
 */
public void doPost(HttpServletRequest req, HttpServletResponse res) {
    res.setContentType("text/xml");
    HttpSession session = req.getSession(true);
    String passwordInput = req.getParameter("password");
    String newPassword = req.getParameter("chgPassword");
    String getIsAdmin = req.getParameter("isAdmin");
    String logout = req.getParameter("logout");
    String ipFrom = req.getRemoteAddr();
    String company = null;
    try {
        InetAddress address = InetAddress.getByName(ipFrom);
        if (address instanceof Inet6Address) {
            if (address.isLoopbackAddress()) {
                ipFrom = "127.0.0.1";
            } else {
                ipFrom = "null";
            }
        }
    } catch (UnknownHostException e) {
    }

    if (ipFrom != null && !ipFrom.equals("null")) {
        Log log = new Log();
        try {
            PreparedStatement selectCompanyName = null;
            Connection con = log.getConnection();
            selectCompanyName = con.prepareStatement("SELECT company_name,email FROM ip where ip = ? ; ");
            selectCompanyName.setString(1, ipFrom);
            ResultSet result = selectCompanyName.executeQuery();
            if (result.next()) {
                company = result.getString(1).replaceAll("'", "&quot;");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (LoggerException e) {
            e.printStackTrace();
        } finally {
            try {
                log.closeConnection();
            } catch (LoggerException ex) {
                Logger.getLogger(AuthenticationServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    String pageNumber = (String) session.getAttribute("page");
    String numberResultsByPage = (String) session.getAttribute("numberResultsByPage");
    session.setAttribute("isAdmin", true); // BHT (HACK).

    // DISABLED (BHT)
    // readFile();
    if (passwordInput != null) {
        try {
            if (passwordRead.equals(passwordInput)) {
                session.setAttribute("isAdmin", true);
                if (newPassword != null) {
                    FileWriter fstream;
                    try {
                        fstream = new FileWriter(passwordFile);
                        BufferedWriter out = new BufferedWriter(fstream);
                        out.write(newPassword);
                        out.close();
                        res.getWriter()
                                .write("<response isChanged='true' isAuthenticated='true' page ='" + pageNumber
                                        + "' numberResultByPage='" + numberResultsByPage + "'></response>");

                    } catch (IOException e) {
                        try {
                            res.getWriter().write("<response isChanged='false' page ='" + pageNumber
                                    + "' numberResultByPage='" + numberResultsByPage + "' ip='" + ipFrom + "' +"
                                    + " company='" + company + "' > " + e.getMessage() + "</response>");
                        } catch (IOException e1) {
                        }
                    }

                } else {
                    res.getWriter().write("<response isAuthenticated='true' page ='" + pageNumber
                            + "' numberResultByPage='" + numberResultsByPage + "'></response>");
                }
            } else {
                res.getWriter().write("<response isAuthenticated='false' ip='" + ipFrom + "' page ='"
                        + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>");
            }
        } catch (Exception e) {
        }
    } else if (getIsAdmin != null && getIsAdmin.equals("get")) {
        try {
            Boolean isAuthenticated = (Boolean) session.getAttribute("isAdmin");
            String sysType = (String) session.getAttribute("systemType");

            if (sysType == null) {
                sysType = "new";
            }

            if (isAuthenticated != null && isAuthenticated.booleanValue()) {
                res.getWriter().write("<response isAuthenticated='true' systemType='" + sysType + "' page ='"
                        + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>");
                /*} else if (authorizedIPs.contains(ipFrom)) {
                res.getWriter().write(
                "<response isAuthenticated='true'" + " page ='" + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>");
                session.setAttribute("isAdmin", true);
                }*/
            } else {
                res.getWriter()
                        .write("<response isAuthenticated='false' ip='" + ipFrom + "' systemType ='" + sysType
                                + "' company    ='" + company + "' page       ='" + pageNumber
                                + "' numberResultByPage='" + numberResultsByPage + "'></response>");
            }
        } catch (IOException e) {
        }
    } else if (logout != null && logout.equals("yes")) {
        session.invalidate();
        try {
            res.getWriter().write("<response/>");
        } catch (IOException e) {
        }
    }
}

From source file:com.xhsoft.framework.common.filter.SessionUpcFilter.java

public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = ((HttpServletRequest) req);
    HttpSession session = (request).getSession();
    //UserInfo user=(UserInfo)session.getAttribute(SessionCons.CURRENT_ACCOUNT);

    try {/*  w w w  .  j a v  a2  s.c o  m*/
        /*if(user!=null){
          LoginUtil.setLoginUser(request, user);
        }*/

        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Pragma", "No-cache");
        httpResponse.setHeader("Cache-Control", "no-cache");
        httpResponse.setDateHeader("Expires", 0);
        chain.doFilter(request, response);
    } catch (IOException ex) {
        logger.error(request.getRemoteAddr() + " io error : " + ex);
    } catch (Exception de) {
        de.printStackTrace();
    }
    logger.debug("User Filter end!");
}

From source file:com.ebay.pulsar.analytics.resources.PulsarQueryResource.java

@POST
@Path("core")
@Consumes(MediaType.APPLICATION_JSON)//from www  .ja  va2s . c  om
@Produces(MediaType.APPLICATION_JSON)
public Response core(@Context HttpServletRequest request, CoreRequest req) {
    if (logger.isDebugEnabled()) {
        logger.debug("Core API called from IP: " + request.getRemoteAddr());
    }
    req.setNamespace(RequestNameSpace.core);
    boolean trace = request.getParameter("debug") == null ? false : true;
    return processRequest(req, trace);
}

From source file:com.funtl.framework.smoke.core.modules.version.service.VersionInfoService.java

/**
 * get remote ip/*from www  .  jav a2 s. c  o  m*/
 *
 * @param request
 * @return
 */
private String getIP(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
    }
    System.out.println("current ip: " + ip);
    return ip;
}