Example usage for javax.servlet.http HttpServletRequest getLocalPort

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

Introduction

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

Prototype

public int getLocalPort();

Source Link

Document

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

Usage

From source file:com.zimbra.cs.servlet.ZimbraServlet.java

protected boolean isAdminRequest(HttpServletRequest req) throws ServiceException {
    int adminPort = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, -1);
    if (req.getLocalPort() == adminPort) {
        //can still be in offline server where port=adminPort
        int mailPort = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraMailPort,
                -1);/*from  w w w .  j  a  v  a 2  s .  co m*/
        if (mailPort == adminPort) //we are in offline, so check cookie
            return getAdminAuthTokenFromCookie(req) != null;
        else
            return true;
    }
    return false;
}

From source file:com.rsginer.spring.controllers.RestaurantesController.java

@RequestMapping(value = { "/upload-file" }, method = RequestMethod.POST, produces = "application/json")
public void uploadFile(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @RequestParam("file") MultipartFile file) {
    try {/*  w  w  w . ja  va2 s.c o m*/
        String rutaRelativa = "/uploads";
        String rutaAbsoluta = httpServletRequest.getServletContext().getVirtualServerName();
        String jsonSalida = jsonTransformer
                .toJson("http://" + rutaAbsoluta + ":" + httpServletRequest.getLocalPort()
                        + httpServletRequest.getContextPath() + "/uploads/" + file.getOriginalFilename());
        if (!file.isEmpty()) {
            int res = fileSaveService.saveFile(file, httpServletRequest);
            if (res == 200) {
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                httpServletResponse.setContentType("application/json; charset=UTF-8");
                try {
                    httpServletResponse.getWriter().println(jsonSalida);
                } catch (IOException ex) {
                    Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else {
            httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    } catch (BussinessException ex) {
        List<BussinessMessage> bussinessMessages = ex.getBussinessMessages();
        String jsonSalida = jsonTransformer.toJson(bussinessMessages);
        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }
    } catch (Exception ex) {
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            ex.printStackTrace(httpServletResponse.getWriter());
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }

    }

}

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);//w w  w.j av a  2  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:org.sakaiproject.nakamura.messagebucket.UntrustedMessageBucketServiceImpl.java

public String getBucketUrl(HttpServletRequest request, String context) throws MessageBucketException {
    String[] trackingCookies = clusterService.getRequestTrackingCookie(request);
    if (trackingCookies != null) {
        for (String trackingCookie : trackingCookies) {
            ClusterUser clusterUser = clusterService.getUser(trackingCookie);
            if (clusterUser != null) {
                String token = getToken(clusterUser.getUser(), context);
                return MessageFormat.format(urlPattern, request.getScheme(), request.getLocalName(),
                        String.valueOf(request.getLocalPort()), token, token.substring(0, 1),
                        token.substring(0, 2), clusterUser.getServerId(), request.getRemoteUser());
            }// w w  w  .  ja v a2s. c  om
        }
    }
    throw new MessageBucketException("No Cluster tracking is available");
}

From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

private void initializeServlet2point4Properties(HttpServletRequest servletRequest) {
    ServletContext context = servletRequest.getSession().getServletContext();
    if (context.getMajorVersion() > 1 && context.getMinorVersion() > 3) {
        remotePort = servletRequest.getRemotePort();
        localName = servletRequest.getLocalName();
        localAddr = servletRequest.getLocalAddr();
        localPort = servletRequest.getLocalPort();
    }/*w w w  . ja v a  2s. c o  m*/
}

From source file:org.eclipse.orion.internal.server.hosting.HostedStatusDecorator.java

/**
 * Adds status field to a representation of a site configuration.
 * @param siteConfigJson The JSONObject representing a single site configuration.
 * @param user The user making the request.
 * @param resource The original request passed to the decorator.
 *//*  ww w .  ja v  a  2s . co m*/
private void addStatus(HttpServletRequest req, JSONObject siteConfigJson, UserInfo user, URI resource)
        throws JSONException {
    String id = siteConfigJson.getString(ProtocolConstants.KEY_ID);
    SiteInfo siteConfiguration = SiteInfo.getSite(user, id);
    if (siteConfiguration == null)
        return;
    IHostedSite site = HostingActivator.getDefault().getHostingService().get(siteConfiguration, user);
    JSONObject hostingStatus = new JSONObject();
    if (site != null) {
        hostingStatus.put(SiteConfigurationConstants.KEY_HOSTING_STATUS_STATUS, "started"); //$NON-NLS-1$
        String portSuffix = ":" + req.getLocalPort(); //$NON-NLS-1$
        // Whatever scheme was used to access the resource, assume it's used for the sites too
        // Hosted site also shares same contextPath 
        String hostedUrl = req.getScheme() + "://" + site.getHost() + portSuffix + req.getContextPath(); //$NON-NLS-1$
        hostingStatus.put(SiteConfigurationConstants.KEY_HOSTING_STATUS_URL, hostedUrl);
    } else {
        hostingStatus.put(SiteConfigurationConstants.KEY_HOSTING_STATUS_STATUS, "stopped"); //$NON-NLS-1$
    }
    siteConfigJson.put(SiteConfigurationConstants.KEY_HOSTING_STATUS, hostingStatus);
}

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 {// w w  w.  jav a 2  s.com
        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:de.highbyte_le.weberknecht.request.taglibs.SiteBaseLinkTag.java

protected String getBaseUrl() throws JspException {

    if (!(pageContext.getRequest() instanceof HttpServletRequest))
        throw new JspException("unable to get a HttpServletRequest");

    StringBuilder baseUrl = new StringBuilder();

    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

    try {/*from  w  ww . j a  v a 2  s. c  om*/
        ContextConfig conf = new ContextConfig();
        baseUrl.append(conf.getValue("webapp_base_url"));

        if (baseUrl.charAt(baseUrl.length() - 1) != '/')
            baseUrl.append("/");
    } catch (NamingException e) {
        logger.error("getTokenUrl() - naming exception while fetching webapp_base_url: " + e.getMessage()); //$NON-NLS-1$

        logger.warn("automatically generating base URL");
        String contextPath = request.getContextPath();
        String localHost = request.getLocalName();
        int localPort = request.getLocalPort();

        if (baseUrl.length() > 0) //just to be sure
            baseUrl = new StringBuilder();

        baseUrl.append("http://").append(localHost).append(":").append(localPort + contextPath).append("/");
    }

    return baseUrl.toString();
}

From source file:net.fenyo.mail4hotspot.web.BrowserServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    // debug informations
    log.debug("doGet");
    log.debug("context path: " + request.getContextPath());
    log.debug("character encoding: " + request.getCharacterEncoding());
    log.debug("content length: " + request.getContentLength());
    log.debug("content type: " + request.getContentType());
    log.debug("local addr: " + request.getLocalAddr());
    log.debug("local name: " + request.getLocalName());
    log.debug("local port: " + request.getLocalPort());
    log.debug("method: " + request.getMethod());
    log.debug("path info: " + request.getPathInfo());
    log.debug("path translated: " + request.getPathTranslated());
    log.debug("protocol: " + request.getProtocol());
    log.debug("query string: " + request.getQueryString());
    log.debug("requested session id: " + request.getRequestedSessionId());
    log.debug("Host header: " + request.getServerName());
    log.debug("servlet path: " + request.getServletPath());
    log.debug("request URI: " + request.getRequestURI());
    @SuppressWarnings("unchecked")
    final Enumeration<String> header_names = request.getHeaderNames();
    while (header_names.hasMoreElements()) {
        final String header_name = header_names.nextElement();
        log.debug("header name: " + header_name);
        @SuppressWarnings("unchecked")
        final Enumeration<String> header_values = request.getHeaders(header_name);
        while (header_values.hasMoreElements())
            log.debug("  " + header_name + " => " + header_values.nextElement());
    }/*from ww  w .  ja v a  2 s  .c  o m*/
    if (request.getCookies() != null)
        for (Cookie cookie : request.getCookies()) {
            log.debug("cookie:");
            log.debug("cookie comment: " + cookie.getComment());
            log.debug("cookie domain: " + cookie.getDomain());
            log.debug("cookie max age: " + cookie.getMaxAge());
            log.debug("cookie name: " + cookie.getName());
            log.debug("cookie path: " + cookie.getPath());
            log.debug("cookie value: " + cookie.getValue());
            log.debug("cookie version: " + cookie.getVersion());
            log.debug("cookie secure: " + cookie.getSecure());
        }
    @SuppressWarnings("unchecked")
    final Enumeration<String> parameter_names = request.getParameterNames();
    while (parameter_names.hasMoreElements()) {
        final String parameter_name = parameter_names.nextElement();
        log.debug("parameter name: " + parameter_name);
        final String[] parameter_values = request.getParameterValues(parameter_name);
        for (final String parameter_value : parameter_values)
            log.debug("  " + parameter_name + " => " + parameter_value);
    }

    // parse request

    String target_scheme = null;
    String target_host;
    int target_port;

    // request.getPathInfo() is url decoded
    final String[] path_info_parts = request.getPathInfo().split("/");
    if (path_info_parts.length >= 2)
        target_scheme = path_info_parts[1];
    if (path_info_parts.length >= 3) {
        target_host = path_info_parts[2];
        try {
            if (path_info_parts.length >= 4)
                target_port = new Integer(path_info_parts[3]);
            else
                target_port = 80;
        } catch (final NumberFormatException ex) {
            log.warn(ex);
            target_port = 80;
        }
    } else {
        target_scheme = "http";
        target_host = "www.google.com";
        target_port = 80;
    }

    log.debug("remote URL: " + target_scheme + "://" + target_host + ":" + target_port);

    // create forwarding request

    final URL target_url = new URL(target_scheme + "://" + target_host + ":" + target_port);
    final HttpURLConnection target_connection = (HttpURLConnection) target_url.openConnection();

    // be transparent for accept-language headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_languages = request.getHeaders("accept-language");
    while (accepted_languages.hasMoreElements())
        target_connection.setRequestProperty("Accept-Language", accepted_languages.nextElement());

    // be transparent for accepted headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_content = request.getHeaders("accept");
    while (accepted_content.hasMoreElements())
        target_connection.setRequestProperty("Accept", accepted_content.nextElement());

}