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:org.apache.openaz.xacml.rest.XACMLRest.java

/**
 * Helper routine to dump the HTTP servlet request being serviced. Primarily for debugging.
 *
 * @param request - Servlet request (from a POST/GET/PUT/etc.)
 *//*  www.jav  a  2  s. c  o  m*/
public static void dumpRequest(HttpServletRequest request) {
    if (logger.isDebugEnabled()) {
        // special-case for receiving heartbeat - don't need to repeatedly output all of the information
        // in multiple lines
        if (request.getMethod().equals("GET") && "hb".equals(request.getParameter("type"))) {
            logger.debug("GET type=hb : heartbeat received");
            return;
        }
        logger.debug(request.getMethod() + ":" + request.getRemoteAddr() + " " + request.getRemoteHost() + " "
                + request.getRemotePort());
        logger.debug(request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort());
        Enumeration<String> en = request.getHeaderNames();
        logger.debug("Headers:");
        while (en.hasMoreElements()) {
            String element = en.nextElement();
            Enumeration<String> values = request.getHeaders(element);
            while (values.hasMoreElements()) {
                String value = values.nextElement();
                logger.debug(element + ":" + value);
            }
        }
        logger.debug("Attributes:");
        en = request.getAttributeNames();
        while (en.hasMoreElements()) {
            String element = en.nextElement();
            logger.debug(element + ":" + request.getAttribute(element));
        }
        logger.debug("ContextPath: " + request.getContextPath());
        if (request.getMethod().equals("PUT") || request.getMethod().equals("POST")) {
            // POST and PUT are allowed to have parameters in the content, but in our usage the parameters
            // are always in the Query string.
            // More importantly, there are cases where the POST and PUT content is NOT parameters (e.g. it
            // might contain a Policy file).
            // Unfortunately the request.getParameterMap method reads the content to see if there are any
            // parameters,
            // and once the content is read it cannot be read again.
            // Thus for PUT and POST we must avoid reading the content here so that the main code can read
            // it.
            logger.debug("Query String:" + request.getQueryString());
            try {
                if (request.getInputStream() == null) {
                    logger.debug("Content: No content inputStream");
                } else {
                    logger.debug("Content available: " + request.getInputStream().available());
                }
            } catch (Exception e) {
                logger.debug("Content: inputStream exception: " + e.getMessage() + ";  (May not be relevant)");
            }
        } else {
            logger.debug("Parameters:");
            Map<String, String[]> params = request.getParameterMap();
            Set<String> keys = params.keySet();
            for (String key : keys) {
                String[] values = params.get(key);
                logger.debug(key + "(" + values.length + "): " + (values.length > 0 ? values[0] : ""));
            }
        }
        logger.debug("Request URL:" + request.getRequestURL());
    }
}

From source file:org.easyrec.util.core.Web.java

/**
 * This method trims a http-request with the given parameter. e.g. request:
 * /myServlet?id=1&desc=hallo --> trimRequest(request, "id") -->
 * /myServlet?desc=hallo/*from  w ww  .  j a v a2 s.c  om*/
 *
 * @param request   HttpServletRequest
 * @param parameter String
 * @return String
 */
@SuppressWarnings({ "unchecked", "UnusedDeclaration" })
public static String trimRequest(HttpServletRequest request, String parameter) {

    String query = "";
    if (!Strings.isNullOrEmpty(parameter) && request.getParameterMap() != null) {
        for (final Object o : request.getParameterMap().entrySet()) {
            Entry<String, String[]> m = (Entry<String, String[]>) o;
            if (!parameter.equals(m.getKey())) {
                query += m.getKey() + "=" + m.getValue()[0] + "&";
            }
        }

        return request.getScheme() + "://" + request.getLocalAddr() + ":" + request.getLocalPort()
                + request.getContextPath() + request.getServletPath() + "?" + Text.removeLast(query);
    } else
        return null;
}

From source file:org.wso2.carbon.identity.application.authenticator.iwa.servlet.IWAServlet.java

/**
 * Returns true if HTTP request is from the same host (localhost).
 *
 * @param req servlet request/*www .  j  a  v a 2 s  .  c o  m*/
 * @return true if HTTP request is from the same host (localhost)
 */
private boolean isLocalhost(final HttpServletRequest req) {
    return StringUtils.equals(req.getLocalAddr(), (req.getRemoteAddr()));
}

From source file:org.openmrs.module.kenyaemr.SystemMonitorController.java

/**
 * Checks if incoming request for system monitoring data should be allowed
 * @param request the request//from  w w w.j  av  a  2s  .  c o  m
 * @return true if request should be allowed
 */
protected boolean checkAccess(HttpServletRequest request) {
    // For now just check that request is local
    return OpenmrsUtil.nullSafeEquals(request.getRemoteAddr(), request.getLocalAddr());
}

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

@GET
@Produces({ MediaType.TEXT_HTML })
@Path("/welcome")
public Response welcome(@Context HttpServletRequest http, @PathParam("taille") Integer taille) {
    Map<String, Object> map = new HashMap<>();
    map.put("ip", http.getLocalAddr() + ":" + http.getLocalPort());
    return Response.ok(new Viewable("/welcome", map)).build();
}

From source file:service.FileUploadSvc.java

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)// w w  w .  j a  va  2 s.com
@Path("/multipleFiles")
public String uploadFile(@Context HttpServletRequest request) {

    String actualPath = servletContext.getRealPath("");
    String serverPath = "http://" + request.getLocalAddr() + ":" + request.getLocalPort()
            + request.getContextPath();

    String responseStatus = SUCCESS_RESPONSE;
    String candidateName = null;

    String fileLocation = "";
    fileLocation = actualPath + File.separator + "uploads";
    System.out.println(fileLocation);
    //checks whether there is a file upload request or not
    if (ServletFileUpload.isMultipartContent(request)) {
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload fileUpload = new ServletFileUpload(factory);
        try {
            /*
             * parseRequest returns a list of FileItem
             * but in old (pre-java5) style
             */
            final List items = fileUpload.parseRequest(request);

            if (items != null) {
                final Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    final FileItem item = (FileItem) iter.next();
                    String itemName = item.getName();
                    if (itemName != null) {
                        itemName = FilenameUtils.getName(itemName);
                    }
                    final String fieldName = item.getFieldName();
                    final String fieldValue = item.getString();
                    System.out.println("File: " + itemName);
                    if (item.isFormField()) {
                        candidateName = fieldValue;
                        System.out.println("Field Name: " + fieldName + ", Field Value: " + fieldValue);
                        System.out.println("Candidate Name: " + candidateName);
                    } else {
                        final File savedFile = new File(fileLocation + File.separator + itemName);
                        System.out.println("Saving the file: " + savedFile.getName());
                        item.write(savedFile);
                    }

                }
            }
        } catch (Exception e) {
            responseStatus = Utils.constructFailed("upload", false, e.getLocalizedMessage());
        }
    }

    return responseStatus;
}

From source file:org.carewebframework.ui.userheader.UserHeader.java

/**
 * @see org.carewebframework.api.context.IContextEvent#committed()
 *//*from w ww .  ja  v a 2  s.com*/
@Override
public void committed() {
    IUser user = UserContext.getActiveUser();

    if (log.isDebugEnabled()) {
        log.debug("user: " + user);
    }

    if (currentUser != null && currentUser.equals(user)) {
        return;
    }

    currentUser = user;
    String text = user == null ? "" : user.getFullName();

    if (user != null && user.getSecurityDomain() != null) {
        text += "@" + user.getSecurityDomain().getName();
    }

    HttpServletRequest request = FrameworkWebSupport.getHttpServletRequest();
    String info = StringUtils.trimToEmpty((request == null ? "" : request.getLocalAddr()) + " " + dbRegion);
    userHeader.setValue(text + (info.isEmpty() ? "" : " (" + info + ")"));
    password.setVisible(SecurityUtil.getSecurityService().canChangePassword());
    Clients.resize(root);
}

From source file:com.ecsteam.cloudlaunch.controller.RestServices.java

@RequestMapping("/statistics")
public ApplicationStatistics statistics(HttpServletRequest request) throws IOException {
    ApplicationStatistics statistics = statisticsProvider.getCurrentStatistics();

    statistics.setHost(request.getLocalAddr());
    statistics.setPort(request.getLocalPort());

    return statistics;
}

From source file:com.flipkart.phantom.runtime.impl.jetty.filter.ServletTraceFilter.java

/**
 * Submits the service request endpoint data
 * @param request the service request//www  .j a v  a 2 s . co m
 */
private void submitEndpoint(HttpServletRequest request) {
    if (!endPointSubmitter.endPointSubmitted()) {
        String contextPath = request.getContextPath();
        String localAddr = request.getLocalAddr();
        int localPort = request.getLocalPort();
        endPointSubmitter.submit(localAddr, localPort, contextPath);
        LOGGER.debug("Setting endpoint: addr: {}, port: {}, contextpath: " + contextPath, localAddr, localPort);
    }
}

From source file:org.taverna.server.master.identity.WorkflowInternalAuthProvider.java

/**
 * Check that the authentication request is actually valid for the given
 * user record.// w ww . j av a 2s . c o m
 * 
 * @param userRecord
 *            as retrieved from the
 *            {@link #retrieveUser(String, UsernamePasswordAuthenticationToken)}
 *            or <code>UserCache</code>
 * @param principal
 *            the principal that is trying to authenticate (and that we're
 *            trying to bind)
 * @param credentials
 *            the credentials (e.g., password) presented by the principal
 * 
 * @throws AuthenticationException
 *             AuthenticationException if the credentials could not be
 *             validated (generally a <code>BadCredentialsException</code>,
 *             an <code>AuthenticationServiceException</code>)
 * @throws Exception
 *             If something goes wrong. Will be logged and converted to a
 *             generic AuthenticationException.
 */
protected void additionalAuthenticationChecks(UserDetails userRecord, @Nonnull Object principal,
        @Nonnull Object credentials) throws Exception {
    @Nonnull
    HttpServletRequest req = ((ServletRequestAttributes) currentRequestAttributes()).getRequest();

    // Are we coming from a "local" address?
    if (!req.getLocalAddr().equals(req.getRemoteAddr()) && !authorizedAddresses.contains(req.getRemoteAddr())) {
        if (logDecisions)
            log.info("attempt to use workflow magic token from untrusted address:" + " token="
                    + userRecord.getUsername() + ", address=" + req.getRemoteAddr());
        throw new BadCredentialsException("bad login token");
    }

    // Does the password match?
    if (!credentials.equals(userRecord.getPassword())) {
        if (logDecisions)
            log.info("workflow magic token is untrusted due to password mismatch:" + " wanted="
                    + userRecord.getPassword() + ", got=" + credentials);
        throw new BadCredentialsException("bad login token");
    }

    if (logDecisions)
        log.info("granted role " + SELF + " to user " + userRecord.getUsername());
}