Example usage for javax.servlet.http HttpServletRequest getLocalAddr

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

Introduction

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

Prototype

public String getLocalAddr();

Source Link

Document

Returns the Internet Protocol (IP) address of the interface on which the request was received.

Usage

From source file:com.jd.survey.web.settings.SectorsController.java

@Secured({ "ROLE_ADMIN" })
@RequestMapping(params = "create", produces = "text/html")
public String createSector(Principal principal, Model uiModel, HttpServletRequest httpServletRequest) {
    log.info("createForm(): handles param form");
    try {//from w w  w  .j  a v  a2s.c om
        User user = userService.user_findByLogin(principal.getName());
        if (!user.isAdmin()) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }
        Sector sector = new Sector();
        populateEditForm(uiModel, sector, user);
        return "admin/sectors/create";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.jd.survey.web.settings.SectorsController.java

@Secured({ "ROLE_ADMIN" })
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@RequestParam(value = "_proceed", required = false) String proceed, @Valid Sector sector,
        BindingResult bindingResult, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("update(): handles PUT");
    try {//from  w  w w .ja v  a  2  s  .c om
        User user = userService.user_findByLogin(principal.getName());

        if (!user.isAdmin()) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        if (proceed != null) {
            if (bindingResult.hasErrors()) {
                populateEditForm(uiModel, sector, user);
                return "admin/sectors/update";
            }

            if (surveySettingsService.dataset_findByName(sector.getName()) != null && !surveySettingsService
                    .dataset_findByName(sector.getName()).getId().equals(sector.getId())) {
                bindingResult.rejectValue("name", "field_unique");
                populateEditForm(uiModel, sector, user);
                return "admin/sectors/update";
            }
            uiModel.asMap().clear();
            sector = surveySettingsService.sector_merge(sector);
            return "redirect:/admin/sectors/"
                    + encodeUrlPathSegment(sector.getId().toString(), httpServletRequest);
        } else {
            return "redirect:/admin/sectors";
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.jd.survey.web.settings.SectorsController.java

@Secured({ "ROLE_ADMIN" })
@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String createPost(@RequestParam(value = "_proceed", required = false) String proceed,
        @Valid Sector sector, BindingResult bindingResult, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("create(): handles " + RequestMethod.POST.toString());
    try {/*  w w  w. j a  va2  s.c  om*/
        User user = userService.user_findByLogin(principal.getName());
        if (!user.isAdmin()) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        if (proceed != null) {
            if (bindingResult.hasErrors()) {
                populateEditForm(uiModel, sector, user);
                return "admin/sectors/create";
            }

            if (surveySettingsService.dataset_findByName(sector.getName()) != null && !surveySettingsService
                    .dataset_findByName(sector.getName()).getId().equals(sector.getId())) {
                bindingResult.rejectValue("name", "field_unique");
                populateEditForm(uiModel, sector, user);
                return "admin/sectors/update";
            }

            uiModel.asMap().clear();
            sector = surveySettingsService.sector_merge(sector);
            return "redirect:/admin/sectors/"
                    + encodeUrlPathSegment(sector.getId().toString(), httpServletRequest);
        } else {
            return "redirect:/admin/sectors";
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }

}

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);/*from   www.j  a va2 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:com.jd.survey.web.settings.SurveyDefinitionPageController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "create", produces = "text/html")
public String createGet(@PathVariable("id") Long surveyDefinitionId, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    try {//from w  w  w . j  a v a2s .  co m
        User user = userService.user_findByLogin(principal.getName());
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId);
        SurveyDefinitionPage surveyDefinitionPage = new SurveyDefinitionPage(surveyDefinition);
        populateEditForm(uiModel, surveyDefinitionPage, user);
        return "settings/surveyDefinitionPages/create";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:nz.co.fortytwo.signalk.processor.UploadProcessor.java

@Override
public void process(Exchange exchange) throws Exception {

    logger.debug("UploadProcessor starts");
    HttpServletRequest request = exchange.getIn(HttpMessage.class).getRequest();
    logger.debug("Session = " + request.getSession().getId());
    HttpSession session = request.getSession();
    if (logger.isDebugEnabled()) {

        logger.debug("Request = " + exchange.getIn().getHeader(Exchange.HTTP_SERVLET_REQUEST).getClass());
        logger.debug("Session = " + session.getId());
    }/*from   w w w  . j  a v a  2s  .  c o m*/

    if (session.getId() != null) {

        String remoteAddress = request.getRemoteAddr();
        String localAddress = request.getLocalAddr();
        if (Util.sameNetwork(localAddress, remoteAddress)) {
            exchange.getIn().setHeader(SignalKConstants.MSG_TYPE, SignalKConstants.INTERNAL_IP);
        } else {
            exchange.getIn().setHeader(SignalKConstants.MSG_TYPE, SignalKConstants.EXTERNAL_IP);
        }
        if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("POST")) {
            processUpload(exchange);
        }
    } else {
        exchange.getIn().setHeader("Location", SignalKConstants.SIGNALK_AUTH);
        exchange.getIn().setBody("Authentication Required");
    }
}

From source file:com.sonymobile.jenkins.plugins.kerberossso.KerberosSSOFilter.java

/**
 * Filters every request made to the server to determine and set authentication of the user.
 * 1. Find out if the user is already authenticated (by checking the securityContext).
 * 2. Otherwise, authenticate the user from his Kerberos ticket and,
 * 3. Set him as authenticated by setting a new securityContext.
 * During the negotiation process used by Spnego, none of the filters after this one in the chain
 * will be allowed to execute./*ww  w  . j a v a2s  . c  o m*/
 *
 * @param request the Servlet request to serve
 * @param response the Servlet response to serve
 * @param chain the filter chain determining which filter will execute after ours.
 * @throws IOException if redirection goes wrong or if another filter in the chain fails.
 * @throws ServletException if the authentication fails.
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if ((!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse))
            || containsBypassHeader(request)) {
        chain.doFilter(request, response);
        return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String userContentPath = httpRequest.getContextPath() + "/userContent";

    if (httpRequest.getRequestURI().startsWith(userContentPath)) {
        chain.doFilter(request, response);
        return;
    }

    SpnegoHttpServletResponse spnegoHttpResponse = new SpnegoHttpServletResponse(
            (HttpServletResponse) response);

    if (PluginImpl.getInstance().isRedirectEnabled()
            && !httpRequest.getLocalAddr().equals(httpRequest.getRemoteAddr())) {
        // If Local and Remote address is the same, the user is Localhost and shouldn't be redirected.

        String requestedDomain = new URL(httpRequest.getRequestURL().toString()).getHost();
        String requestedURL = httpRequest.getRequestURL().toString();
        if (!requestedDomain.toLowerCase().contains(PluginImpl.getInstance().getRedirect().toLowerCase())) {

            String redirect = requestedURL.replaceFirst(requestedDomain,
                    requestedDomain + "." + PluginImpl.getInstance().getRedirect());
            spnegoHttpResponse.sendRedirect(redirect);
        }
    }

    // A user is "always" authenticated by Jenkins as anonymous when not authenticated in any other way.
    if (SecurityContextHolder.getContext().getAuthentication() == null
            || !SecurityContextHolder.getContext().getAuthentication().isAuthenticated()
            || Functions.isAnonymous()) {
        Functions.advertiseHeaders((HttpServletResponse) response); //Adds headers for CLI

        Principal principal;

        try {
            principal = authenticator.authenticate(httpRequest, spnegoHttpResponse);
        } catch (LoginException e) {
            logger.log(Level.WARNING, "Failed to fetch spnegoPrincipal name for user");
            chain.doFilter(request, spnegoHttpResponse);
            return;
        }

        // Expecting negotiation
        if (principal == null) {
            return;
        }

        String principalName = principal.getName();

        if (principalName.contains("@")) {
            principalName = principalName.substring(0, principalName.indexOf("@"));
        }

        try {
            SecurityRealm realm = Jenkins.getInstance().getSecurityRealm();
            UserDetails userDetails = realm.loadUserByUsername(principalName);
            Authentication authToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
                    userDetails.getPassword(), userDetails.getAuthorities());

            ACL.impersonate(authToken);
            if (Jenkins.getVersion().isNewerThan(new VersionNumber("1.568"))) {
                try {
                    Method fireLoggedIn = SecurityListener.class.getMethod("fireLoggedIn", String.class);
                    fireLoggedIn.invoke(null, userDetails.getUsername());
                } catch (Exception e) {
                    logger.log(Level.WARNING, "Failed to invoke fireLoggedIn method", e);
                }
            }
            logger.log(Level.FINE, "Authenticated user {0}", userDetails.getUsername());
        } catch (UsernameNotFoundException e) {
            logger.log(Level.WARNING, "Username {0} not registered by Jenkins", principalName);
        } catch (NullPointerException e) {
            logger.log(Level.WARNING, "User authentication failed");
            e.printStackTrace();
        } catch (DataAccessException e) {
            logger.log(Level.WARNING, "No access to user database");
            e.printStackTrace();
        }
    }

    chain.doFilter(request, response);
}

From source file:com.jd.survey.web.settings.SurveyDefinitionPageController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
public String delete(@PathVariable("id") Long id, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("delete(): id=" + id);
    try {/* w  ww  .  j  av  a 2  s.  c  o  m*/
        User user = userService.user_findByLogin(principal.getName());
        if (!securityService.userIsAuthorizedToManageSurvey(id, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        SurveyDefinitionPage surveyDefinitionPage = surveySettingsService.surveyDefinitionPage_findById(id);
        surveySettingsService.surveyDefinitionPage_remove(surveyDefinitionPage);
        uiModel.asMap().clear();
        return "redirect:/settings/surveyDefinitions/" + encodeUrlPathSegment(
                surveyDefinitionPage.getSurveyDefinition().getId().toString(), httpServletRequest);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

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 ww  . j  ava2  s  . c o  m
        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:com.jd.survey.web.reports.ReportController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "spss", produces = "text/html")
public void surveySPSSExport(@PathVariable("id") Long surveyDefinitionId, Principal principal,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {
    try {/*  w w  w  .  jav a2  s.co m*/
        User user = userService.user_findByLogin(principal.getName());
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            response.sendRedirect("../accessDenied");
            //throw new AccessDeniedException("Unauthorized access attempt");
        }

        String metadataFileName = "survey" + surveyDefinitionId + ".sps";
        String dataFileName = "survey" + surveyDefinitionId + ".dat";

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zipfile = new ZipOutputStream(baos);

        //metadata    
        zipfile.putNextEntry(new ZipEntry(metadataFileName));
        zipfile.write(sPSSHelperService.getSurveyDefinitionSPSSMetadata(surveyDefinitionId, dataFileName));
        //data
        zipfile.putNextEntry(new ZipEntry(dataFileName));
        zipfile.write(sPSSHelperService.getSurveyDefinitionSPSSData(surveyDefinitionId));
        zipfile.close();

        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "inline;filename=survey" + surveyDefinitionId + "_spss.zip");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        //servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8"));
        servletOutputStream.write(baos.toByteArray());
        servletOutputStream.flush();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}