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:ru.mystamps.web.support.spring.security.AuthenticationFailureListener.java

@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
    HttpServletRequest request = getRequest();
    if (request == null) {
        LOG.warn("Can't get http request object");
        return;/*w w  w. j a  v a 2s .c o  m*/
    }

    // TODO: log more info (login for example) (#59)
    // TODO: sanitize all user's values (#60)
    String method = request.getMethod();
    String page = request.getRequestURI();
    String ip = request.getRemoteAddr();
    String referer = request.getHeader("referer");
    String agent = request.getHeader("user-agent");
    Date date = new Date(event.getTimestamp());

    siteService.logAboutFailedAuthentication(page, method, null, ip, referer, agent, date);
}

From source file:org.basinmc.irc.bridge.github.TeamCityHandler.java

/**
 * {@inheritDoc}/*from w  w w. java2 s  . c  o  m*/
 */
@Override
public void handle(@Nonnull String target, @Nonnull Request baseRequest, @Nonnull HttpServletRequest request,
        @Nonnull HttpServletResponse response) throws IOException, ServletException {
    if (!target.startsWith("/build")) {
        return;
    }

    if (this.serverAddress != null && !this.serverAddress.isEmpty()
            && !this.serverAddress.equals(request.getRemoteAddr())) {
        logger.info("Access denied to build webhook from " + request.getRemoteAddr());

        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        baseRequest.setHandled(true);
        return;
    }

    JsonNode data;

    try (InputStream inputStream = request.getInputStream()) {
        data = reader.readTree(inputStream).get("build");
    }

    switch (target) {
    default:
        return;
    case "/build/started":
        this.bridge.sendMessage(String.format(MESSAGE_START, data.get("buildFullName").asText(),
                data.get("agentName").asText(), data.get("buildStatusUrl").asText()));
        break;
    case "/build/success":
        this.bridge.sendMessage(String.format(MESSAGE_SUCCESS, data.get("buildFullName").asText(),
                data.get("buildStatusUrl").asText()));
        break;
    case "/build/failure":
        this.bridge.sendMessage(String.format(MESSAGE_FAILURE, data.get("buildFullName").asText(),
                data.get("buildStatusUrl").asText()));
        break;
    }

    logger.info("Handled build webhook from " + request.getRemoteAddr());
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    baseRequest.setHandled(true);
}

From source file:com.wso2telco.stepbasedsequencehandler.MIFEStepBasedSequenceHandler.java

/**
 * Retrive ip address.//from   w w w . j a  v a 2 s.co m
 *
 * @param request the request
 * @return the string
 */
public String retriveIPAddress(HttpServletRequest request) {

    String ipAddress = null;
    try {
        ipAddress = request.getHeader("X-FORWARDED-FOR");
    } catch (Exception e) {
    }

    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }

    return ipAddress;
}

From source file:de.zib.vold.userInterface.RESTController.java

@ModelAttribute("clientIpAddress")
public String populateClientIpAddress(HttpServletRequest request) {
    return request.getRemoteAddr();
}

From source file:UploadDownloadFile.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);/*from   w  w w .ja  v  a  2 s  .  c om*/
    String filePath;
    final String clientip = request.getRemoteAddr().replace(":", "_");
    filePath = "/Users/" + currentuser + "/GlassFish_Server/glassfish/domains/domain1/tmpfiles/Uploaded/"
            + clientip + "/";
    System.out.println("filePath = " + filePath);
    // filePath = "/Users/jhovarie/Desktop/webuploaded/";
    File f = new File(filePath);
    if (!f.exists()) {
        f.mkdirs();
    }

    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    //factory.setRepository(new File("c:\\temp"));
    factory.setRepository(new File(filePath));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<a href='" + currenthost + "/UploadDownloadFile/index.html'><< BACK <<</a><br/>");
        String fileName = "";
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>");
            }
        }

        out.println("Target Location = " + filePath);
        out.write(
                "<br/><a href=\"UploadDownloadFile?fileName=" + fileName + "\">Download " + fileName + "</a>");
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println("Error in Process " + ex);
    }
}

From source file:com.wso2telco.gsma.handlers.MIFEStepBasedSequenceHandler.java

/**
 * Retrieve ip address.//from w  ww  . j  a  v a  2  s.  co m
 *
 * @param request the request
 * @return the string
 */
private String retrieveIPAddress(HttpServletRequest request) {
    String header = request.getHeader(HEADER_X_FORWARDED_FOR);
    String ipAddress = header != null ? header : request.getRemoteAddr();
    return ipAddress;
}

From source file:fr.scc.elo.controller.EloController.java

@GET
@Produces({ MediaType.TEXT_HTML })
@Path("/match/manage/{taille}/winners/{w}/loosers/{l}/score/{s}/type/{t}/create/{c}")
public void saveMatchAndRestart(@Context HttpServletRequest http, @Context HttpServletResponse redirect,
        @BeanParam MatchRequest request, @PathParam("taille") Integer taille) throws IOException {
    Map<String, Object> map = getMatchMap(http, taille);
    try {/*from  w  w  w .  j  av  a2s . c  o m*/
        if (connectionService.acceptIPUpdate(http.getRemoteAddr())) {
            MatchResponse response = eloManager.manageMatch(StringUtils.lowerCase(request.getWinnerList()),
                    StringUtils.lowerCase(request.getLooserList()), request.getScore(), request.getTypeMatch(),
                    request.getCreatePlayers());
            map.put("status", response.getPlayersUpdated().size() + " players updated");
        } else {
            map.put("status", "Not allowed to save match");
        }
    } catch (Exception e) {
        map.put("status", e.getMessage());
    }
    redirect.sendRedirect("/rest/v1/elo/match/manage/" + taille);
}

From source file:org.wallride.service.AuthorizedUserDetailsService.java

@Transactional(readOnly = false)
@Override/* w  w  w .  ja  v a 2 s  .c o m*/
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    AuthorizedUser authorizedUser = (AuthorizedUser) authentication.getPrincipal();
    userRepository.updateLastLoginTime(authorizedUser.getId(), new Date());

    logger.info("\"{}\" logged in. IP: [{}]", authorizedUser.toString(), request.getRemoteAddr());

    super.onAuthenticationSuccess(request, response, authentication);
}

From source file:aiai.ai.launchpad.server.ServerController.java

@PostMapping("/rest-auth/srv")
public ExchangeData processRequestAuth(@RequestBody ExchangeData data, HttpServletRequest request) {
    log.debug("processRequestAnon(), globals.isSecureRestUrl: {}, data: {}", globals.isSecureRestUrl, data);
    return serverService.processRequest(data, request.getRemoteAddr());
}

From source file:com.mylab.TransmitMailBean.java

/**
 * Initializes the bean and sends or queues the mail.
 * @param context//from   w  w w  .ja  v  a 2  s .  com
 * @param request
 * @param response
 * @throws javax.servlet.jsp.JspException
 * @throws IOException 
 */
public void init(PageContext context, HttpServletRequest request, HttpServletResponse response) {
    try {

        remoteaddress = request.getRemoteAddr();

        jsp = new CmsJspXmlContentBean(context, request, response);

        GreetingcardConfigDao configDao = new OpenCmsGreetingcardConfigDao(jsp.getCmsObject());

        GreetingcardConfig config = null;

        try {
            config = configDao.readConfig();
        } catch (DataAccessException ex) {
        }

        cmsContext = new OpenCmsContext(jsp);

        CmsObject cms = jsp.getCmsObject();

        vfsService = new OpenCmsVFSService(jsp);

        //get the parameters from the request
        authorName = request.getParameter("author_name");
        authorMail = request.getParameter("author_address");
        receiverName = request.getParameter("receiver_name");
        receiverAddress = request.getParameter("receiver_address");
        subject = request.getParameter("subject");
        imagePath = request.getParameter("image_url");
        greetingcardTemplatePath = request.getParameter("greetingcard_fileName");
        transmitTime = request.getParameter("transmit_date");
        audiomessage = request.getParameter("audio_message");
        if ((audiomessage != null) && (audiomessage.length() > 0)) {
            if (audiomessage.contains("Letter-To-Hermione.mp3"))
                audiomessage = "";
            else {
                CmsShell cmdShell = new CmsShell("/usr/local/apache-tomcat-7.0.57/webapps/opencms/WEB-INF",
                        null, "opencms", "/bin/bash", null);
                file = new File("/home/jan/bin/opencmsshell.sh");
                try {
                    fileInputStream = new FileInputStream(file);
                    cmdShell.start(fileInputStream);
                    fileInputStream.close();
                    audiomessage = System.getProperty("audio_message");
                    System.clearProperty("audio_message");
                } catch (IOException ex) {
                }
            }
        }

        transmitDate = null;
        if (!"0".equals(transmitTime)) {
            transmitDate = new Date(Long.parseLong(transmitTime));
        }

        MailTransmission transmission = new OpenCmsMailTransmission(cms, config, new OpenCmsMailService());

        GreetingcardTemplateDao greetingcardTemplateDao = new OpenCmsGreetingcardTemplateDao(cms);

        // get url of the server for sending the url of the generated image

        String serverUrl = cmsContext.getServerPath(cmsContext.link(cmsContext.removeSiteRoot(imagePath)));
        //String serverUrl = GreetingCardHelper.getServerContextPath(request, jsp.link(cms.getRequestContext().removeSiteRoot(imagePath)));

        // construct the card
        Greetingcard card = new Greetingcard();
        card.setAuthorMail(authorMail);
        card.setAuthorName(authorName);
        card.setImagePath(imagePath);
        card.setReceiverMail(receiverAddress);
        card.setReceiverName(receiverName);
        card.setSubject(subject);
        card.setTransmitDate(transmitDate);
        card.setUrl(serverUrl);
        if ((audiomessage != null) && (audiomessage.length() > 0))
            card.setAudioPath("/greetingcards/.content/audiomessages/" + audiomessage);
        else
            card.setAudioPath("");

        // read the greetingcard template
        GreetingcardTemplate cardTemplate = greetingcardTemplateDao.readCard(greetingcardTemplatePath);

        // transform the content using MailTemplate
        // TODO this should be transformed using method parameters not constructor
        MailTemplate mailTemplate = new StringMailTemplate(cardTemplate.getMailText());
        card.setContent(mailTemplate.getContent(card));

        loginUser();

        // send the mail with the TransmitMail-class

        transmission.sendOrQueue(config, vfsService, card);

        logout();

        transmitted = true;

        count = getCounterManager().incrementCounter(counterKey + "_" + remoteaddress);

    } catch (MessagingException | DataAccessException e) {
        e.printStackTrace();
    } catch (CmsException e) {
        e.printStackTrace();
    } finally {
    }
}