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:org.dataconservancy.dcs.lineage.http.support.RequestUtil.java

/**
 * Determine the port number that the client targeted with their {@code request}.  If {@code considerHostHeader} is
 * {@code true}, and a HTTP {@code Host} header is present, the value of the port in the header will be used as the
 * port number. If the header is not present, or if {@code considerHostHeader} is {@code false}, the port number
 * will be determined using {@link javax.servlet.http.HttpServletRequest#getRemotePort()}
 * (if {@code considerRemotePort} is {@code true}) followed by {@link javax.servlet.http.HttpServletRequest#getLocalPort()}
 * (if {@code considerLocalPort} is {@code true}).
 *
 * @param request the request/*w  ww  .j a  va  2s  .com*/
 * @return the port number targeted by the {@code request}
 */
private int determinePort(HttpServletRequest request) {

    int portNumber = -1;

    // If there is a 'Host' header with the request, and if
    // we are supposed to consider it when determining the port,
    // then use it.

    // This is the best way to go, because the client is indicating
    // what host and port they targeted
    final String hostHeader = request.getHeader(HOST_HEADER);
    if (considerHostHeader && hostHeader != null && hostHeader.trim().length() != 0) {
        String temp = parseHostHeader(hostHeader)[1];
        if (temp != null) {
            portNumber = Integer.parseInt(temp);
        }
    }

    // Either the 'Host' header wasn't considered, or parsing it failed for some reason.

    if (portNumber == -1 && considerRemotePort) {
        portNumber = request.getRemotePort();
    }

    if (portNumber == -1 && considerLocalPort) {
        portNumber = request.getLocalPort();
    }

    return portNumber;
}

From source file:cn.bc.web.util.DebugUtils.java

public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) {
    @SuppressWarnings("rawtypes")
    Enumeration e;//from  w w  w  .  j av a2s .c  om
    String name;
    StringBuffer html = new StringBuffer();

    //session
    HttpSession session = request.getSession();
    html.append("<div><b>session:</b></div><ul>");
    html.append(createLI("Id", session.getId()));
    html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString()));
    html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString()));

    //session:attributes
    e = session.getAttributeNames();
    html.append("<li>attributes:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, String.valueOf(session.getAttribute(name))));
    }
    html.append("</ul></li>\r\n");
    html.append("</ul>\r\n");

    //request
    html.append("<div><b>request:</b></div><ul>");
    html.append(createLI("URL", request.getRequestURL().toString()));
    html.append(createLI("QueryString", request.getQueryString()));
    html.append(createLI("Method", request.getMethod()));
    html.append(createLI("CharacterEncoding", request.getCharacterEncoding()));
    html.append(createLI("ContentType", request.getContentType()));
    html.append(createLI("Protocol", request.getProtocol()));
    html.append(createLI("RemoteAddr", request.getRemoteAddr()));
    html.append(createLI("RemoteHost", request.getRemoteHost()));
    html.append(createLI("RemotePort", request.getRemotePort() + ""));
    html.append(createLI("RemoteUser", request.getRemoteUser()));
    html.append(createLI("ServerName", request.getServerName()));
    html.append(createLI("ServletPath", request.getServletPath()));
    html.append(createLI("ServerPort", request.getServerPort() + ""));
    html.append(createLI("Scheme", request.getScheme()));
    html.append(createLI("LocalAddr", request.getLocalAddr()));
    html.append(createLI("LocalName", request.getLocalName()));
    html.append(createLI("LocalPort", request.getLocalPort() + ""));
    html.append(createLI("Locale", request.getLocale().toString()));

    //request:headers
    e = request.getHeaderNames();
    html.append("<li>Headers:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getHeader(name)));
    }
    html.append("</ul></li>\r\n");

    //request:parameters
    e = request.getParameterNames();
    html.append("<li>Parameters:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getParameter(name)));
    }
    html.append("</ul></li>\r\n");

    html.append("</ul>\r\n");

    //response
    html.append("<div><b>response:</b></div><ul>");
    html.append(createLI("CharacterEncoding", response.getCharacterEncoding()));
    html.append(createLI("ContentType", response.getContentType()));
    html.append(createLI("BufferSize", response.getBufferSize() + ""));
    html.append(createLI("Locale", response.getLocale().toString()));
    html.append("<ul>\r\n");
    return html;
}

From source file:com.nec.harvest.controller.SonekihController.java

/**
 * Load given department current page// www .ja  v  a  2  s  . co  m
 * 
 * @param request
 *            HttpServletRequest
 * @param processingGroup
 *            Current processing group menu
 * @param selectedDepartment
 *            Given department
 * @param model
 *            Model interchange between client and server
 */
private void loadDepartmentPage(HttpServletRequest request, String processingGroup, String selectedDepartment,
        String processingDepartment, Model model) {
    if (StringUtils.isEmpty(processingGroup) || StringUtils.isEmpty(selectedDepartment)) {
        model.addAttribute("page", null);
        model.addAttribute("manualLoad", false);
    }

    UriComponents uriComponent = UriComponentsBuilder
            .fromUriString(
                    request.getContextPath() + "/{proNo}/pagination/paging/{orglevel}/{deptCode}/{index}")
            .build();
    URI uri = uriComponent.expand(processingGroup, selectedDepartment, processingDepartment, 0).encode()
            .toUri();

    try {
        HttpClient client = HttpClientBuilder.create().build();
        HttpHost host = new HttpHost(request.getServerName(), request.getLocalPort(), request.getScheme());
        HttpGet get = new HttpGet(uri);
        HttpResponse response = client.execute(host, get);

        // Get the content
        String htmlPage = read(response.getEntity().getContent());

        // 
        model.addAttribute("page", htmlPage);
        model.addAttribute("manualLoad", true);
        model.addAttribute("unitDept", selectedDepartment);
        model.addAttribute("deptCode", processingDepartment);
    } catch (IOException ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:com.timesheet.controller.TimeSheetController.java

@RequestMapping(value = "/adduser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("user") User user, HttpSession session, HttpServletRequest request) {
    User currentUser = (User) session.getAttribute("user");
    String password = utils.pwdGenerator();

    user.setCompany(currentUser.getCompany());
    user.setPassword(password);// w  w w . j  a  v a  2  s.  c o  m

    userService.addUser(user);

    //login link
    String srverName = request.getServerName();
    System.out.println(" @@@@@@@@@@@@@@@@@@@@@@ Email server :" + srverName);
    srverName = srverName.substring(srverName.indexOf(":") + 1);
    System.out.println(" @@@@@@@@@@@@@@@@@@@@@@ Email server11 :" + srverName);

    //Send confirmation email
    String to = user.getEmail();
    String subject = "You are invited to join time sheet for " + currentUser.getCompany().getName();
    String body = "Your login information : Email " + user.getEmail() + "<br/> Password : " + password;
    body += "<br/><br/> Please <a href='http://" + srverName + ":" + request.getLocalPort()
            + request.getContextPath() + "/index' > Login </a> and reset your password as soon as possible";

    try {
        emailService.sendMail(to, subject, body);
    } catch (MessagingException ex) {
        Logger.getLogger(TimeSheetController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "redirect:/user-home";
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same content POST
 * data (JSON, XML, etc.) as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are
 *                               configuring to send a standard POST request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
 *//*from   w  ww . j av a2s.  c om*/
private void handleContentPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException, ServletException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = httpServletRequest.getReader();
    for (;;) {
        String line = reader.readLine();
        if (line == null)
            break;
        content.append(line);
    }

    String contentType = httpServletRequest.getContentType();
    String postContent = content.toString();

    if (contentType.startsWith("text/x-gwt-rpc")) {
        String clientHost = httpServletRequest.getLocalName();
        if (clientHost.equals("127.0.0.1")) {
            clientHost = "localhost";
        }

        int clientPort = httpServletRequest.getLocalPort();
        String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : "");
        String serverUrl = stringProxyHost + ((intProxyPort != 80) ? ":" + intProxyPort : "")
                + httpServletRequest.getServletPath();
        //debug("Replacing client (" + clientUrl + ") with server (" + serverUrl + ")");
        postContent = postContent.replace(clientUrl, serverUrl);
    }

    String encoding = httpServletRequest.getCharacterEncoding();
    debug("POST Content Type: " + contentType + " Encoding: " + encoding, "Content: " + postContent);
    StringRequestEntity entity;
    try {
        entity = new StringRequestEntity(postContent, contentType, encoding);
    } catch (UnsupportedEncodingException e) {
        throw new ServletException(e);
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestEntity(entity);
}

From source file:org.sipfoundry.voicemail.MediaServlet.java

public void doIt(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ValidUsers validUsers = (ValidUsers) request.getAttribute(SipxIvrServletHandler.VALID_USERS_ATTR);
    MailboxManager mailboxManager = (MailboxManager) request
            .getAttribute(SipxIvrServletHandler.MAILBOX_MANAGER);
    SipxIvrConfiguration ivrConfig = (SipxIvrConfiguration) request
            .getAttribute(SipxIvrServletHandler.IVR_CONFIG_ATTR);
    String method = request.getMethod().toUpperCase();

    String pathInfo = request.getPathInfo();
    String[] subDirs = pathInfo.split("/");
    if (subDirs.length < 3) {
        response.sendError(404); // path not found
        return;//  w ww. j a va  2  s  .  c  o  m
    }

    // The first element is empty (the leading slash)
    // The second element is the mailbox
    String mailboxString = subDirs[1];
    // The third element is the "context" (either mwi, message)
    String dir = subDirs[2];
    String messageId = subDirs[3];

    User user = validUsers.getUser(mailboxString);
    // only superadmin and mailbox owner can access this service
    // TODO allow all admin user to access it
    if (user != null && ServletUtil.isForbidden(request, user.getUserName(), request.getLocalPort(),
            ivrConfig.getHttpPort())) {
        response.sendError(403); // Send 403 Forbidden
        return;
    }

    if (user != null) {
        if (method.equals(METHOD_GET)) {
            VmMessage message = mailboxManager.getVmMessage(user.getUserName(), messageId, true);
            File audioFile = message.getAudioFile();
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + audioFile.getName() + "\"");

            OutputStream responseOutputStream = null;
            InputStream stream = null;
            try {
                responseOutputStream = response.getOutputStream();
                stream = new FileInputStream(audioFile);
                IOUtils.copy(stream, responseOutputStream);
            } finally {
                IOUtils.closeQuietly(stream);
                IOUtils.closeQuietly(responseOutputStream);
                message.cleanup();
            }
        } else {
            response.sendError(405);
        }
    }

}

From source file:com.zimbra.cs.dav.service.DavServlet.java

private RequestType getAllowedRequestType(HttpServletRequest req) {
    if (!super.isRequestOnAllowedPort(req))
        return RequestType.none;
    Server server = null;//  w  ww . java2 s  . co  m
    try {
        server = Provisioning.getInstance().getLocalServer();
    } catch (Exception e) {
        return RequestType.none;
    }
    boolean allowPassword = server.getBooleanAttr(Provisioning.A_zimbraCalendarCalDavClearTextPasswordEnabled,
            true);
    int sslPort = server.getIntAttr(Provisioning.A_zimbraMailSSLPort, 443);
    int mailPort = server.getIntAttr(Provisioning.A_zimbraMailPort, 80);
    int incomingPort = req.getLocalPort();
    if (incomingPort == sslPort)
        return RequestType.both;
    else if (incomingPort == mailPort && allowPassword)
        return RequestType.both;
    else
        return RequestType.authtoken;
}

From source file:com.iLabs.spice.handler.LoginHandler.java

public String loginAction() throws IOException, ClassNotFoundException, SQLException {
    String result = "failure";
    try {//w w  w  .j  a va 2s  .co  m
        java.util.Date date = new java.util.Date();
        System.out.println("The Start Time (1): " + new Timestamp(date.getTime()));

        ProfileBean ownerProfile = (ProfileBean) getSessionScope().get("ownerProfile");
        ProfileBean currentProfile = (ProfileBean) getSessionScope().get("currentProfile");
        if (ownerProfile == null) {
            ownerProfile = new ProfileBean();
        }
        if (currentProfile == null) {
            currentProfile = new ProfileBean();
        }

        IPerson person = (IPerson) ServiceLocator.getService("PersonSvc");
        UserAuth authPerson = person.authenticateUser(currentProfile.getUserAuth().getUserName(),
                currentProfile.getUserAuth().getUserPassword());

        //This condition checks if the authPerson returned from authentication service is null or not.
        //If the user who enters the site is an authenticated user, the user's info and his friends info is stored in 
        //currentProfile as well as ownerProfile bean.
        if (authPerson != null && authPerson.getUserName() != null) {
            //Save the QoS Level of the user (Platinum, Gold or Silver)
            qoslevel = currentProfile.getUserAuth().getProfile().getProfileURL();

            ClientResource clientResource = new ClientResource("http://192.168.1.41:8180/sessions");

            Session session = new Session();

            ConnectionParty owner = new ConnectionParty();
            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance()
                    .getExternalContext().getRequest();
            owner.setIp(request.getHeader("X-Forwarded-For"));
            owner.setPort(request.getRemotePort());
            System.out.println("Client address: " + request.getRemoteAddr());
            System.out.println("Client port: " + request.getRemotePort());
            if (qoslevel.equalsIgnoreCase("GOLD")) {
                owner.setSip_uri("sip:alice@openepc.test");
                session.setApplicationId("surveillance");
            } else {
                if (qoslevel.equalsIgnoreCase("Silver")) {
                    owner.setSip_uri("sip:bob@openepc.test");
                    session.setApplicationId("IMS");
                } else {
                    owner.setSip_uri("sip:charlie@openepc.test");
                    session.setApplicationId("YouTube");
                }
            }
            System.out.println("REQUEST  " + request.getRemoteAddr() + request.getRemoteHost()
                    + request.getLocalPort() + request.getRequestURI());
            System.out.println(request.getHeader("X-Forwarded-For"));
            ConnectionParty otherParty = new ConnectionParty();
            otherParty.setIp("192.168.1.41");
            otherParty.setPort(8080);
            otherParty.setSip_uri("");

            session.setSessionOwner(owner);
            session.setSessionOtherParty(otherParty);

            ServiceInfo serviceInfo = new ServiceInfo();
            //serviceInfo.setServiceId("Webcamstream");
            setBandwidthAndPriority(serviceInfo, qoslevel);
            serviceInfo.setMediaType(MediaType.DATA);
            serviceInfo.setLifeTime(6000);

            session.setServiceInfo(serviceInfo);

            Representation response = clientResource.post(session);
            String resp = response.getText();
            SI.setSessionID(resp.substring(70, 125));
            System.out.println("200 OK RESPONSE IS: " + resp);
            String s = SI.getSessionID();
            System.out.println("SESSION ID IS: " + s);

            UserFriends userFriends = person.getFriends(authPerson.getUserId());
            ownerProfile.setUserAuth(authPerson);
            ownerProfile.setUserFriends(userFriends);
            currentProfile.setUserAuth(authPerson);
            currentProfile.setUserFriends(userFriends);
            getSessionScope().put("ownerProfile", ownerProfile);
            getSessionScope().put("currentProfile", currentProfile);

            DatabaseConnector r = new DatabaseConnector();
            r.Write(s, authPerson.getUserId());
            //authPerson.getProfile().setProfileURL(s);
            System.out.println("User " + authPerson.getProfile().getFirstName() + " "
                    + authPerson.getProfile().getProfileURL());

            System.out.println("The Start Time (3): " + new Timestamp(date.getTime()));
            result = "success";
        } else { // if user is not an authenticate user, then error message is generated.
            FacesMessage message = new FacesMessage("Please Check Username and password");
            FacesContext.getCurrentInstance().addMessage("login:user_password", message);
        }

    } catch (SysException e) {
        e.printStackTrace();
    }
    return result;

}

From source file:org.nunux.poc.portal.ProxyServlet.java

/**
 * Sets up the given {@link PostMethod} to send the same content POST data
 * (JSON, XML, etc.) as was sent in the given {@link HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 * configuring to send a standard POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains
 * the POST data to be sent via the {@link PostMethod}
 *//*from   w  w w. j  a  v  a  2s.c o  m*/
private void handleContentPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException, ServletException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = httpServletRequest.getReader();
    for (;;) {
        String line = reader.readLine();
        if (line == null) {
            break;
        }
        content.append(line);
    }

    String contentType = httpServletRequest.getContentType();
    String postContent = content.toString();

    if (contentType.startsWith("text/x-gwt-rpc")) {
        String clientHost = httpServletRequest.getLocalName();
        if (clientHost.equals("127.0.0.1")) {
            clientHost = "localhost";
        }

        int clientPort = httpServletRequest.getLocalPort();
        String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : "");
        String serverUrl = stringProxyHost + ((intProxyPort != 80) ? ":" + intProxyPort : "")
                + httpServletRequest.getServletPath();
        //debug("Replacing client (" + clientUrl + ") with server (" + serverUrl + ")");
        postContent = postContent.replace(clientUrl, serverUrl);
    }

    String encoding = httpServletRequest.getCharacterEncoding();
    debug("POST Content Type: " + contentType + " Encoding: " + encoding, "Content: " + postContent);
    StringRequestEntity entity;
    try {
        entity = new StringRequestEntity(postContent, contentType, encoding);
    } catch (UnsupportedEncodingException e) {
        throw new ServletException(e);
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestEntity(entity);
}

From source file:io.hops.hopsworks.api.jupyter.JupyterService.java

@GET
@Path("/running")
@Produces(MediaType.APPLICATION_JSON)/*from   w ww. j  a  v  a2  s.co  m*/
@AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST })
public Response isRunning(@Context SecurityContext sc, @Context HttpServletRequest req)
        throws ServiceException {

    String hdfsUser = getHdfsUser(sc);
    JupyterProject jp = jupyterFacade.findByUser(hdfsUser);
    if (jp == null) {
        throw new ServiceException(RESTCodes.ServiceErrorCode.JUPYTER_SERVERS_NOT_FOUND, Level.FINE);
    }
    // Check to make sure the jupyter notebook server is running
    boolean running = jupyterProcessFacade.pingServerJupyterUser(jp.getPid());
    // if the notebook is not running but we have a database entry for it,
    // we should remove the DB entry (and restart the notebook server).
    if (!running) {
        jupyterFacade.removeNotebookServer(hdfsUser);
        throw new ServiceException(RESTCodes.ServiceErrorCode.JUPYTER_SERVERS_NOT_RUNNING, Level.FINE);
    }
    String externalIp = Ip.getHost(req.getRequestURL().toString());
    settings.setHopsworksExternalIp(externalIp);
    Integer port = req.getLocalPort();
    String endpoint = externalIp + ":" + port;
    if (endpoint.compareToIgnoreCase(jp.getHostIp()) != 0) {
        // update the host_ip to whatever the client saw as the remote host:port
        jp.setHostIp(endpoint);
        jupyterFacade.update(jp);
    }

    return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(jp).build();
}