Example usage for javax.servlet.http HttpServletRequest getServerPort

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

Introduction

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

Prototype

public int getServerPort();

Source Link

Document

Returns the port number to which the request was sent.

Usage

From source file:cn.vlabs.duckling.vwb.VWBDriverServlet.java

private String buildURL(URLParser info, HttpServletRequest request) {
    boolean isHttp;
    StringBuffer buff = new StringBuffer();
    buff.append(request.getScheme() + "://");
    isHttp = "http".equalsIgnoreCase(request.getScheme());

    buff.append(request.getServerName());
    if (isHttp) {
        if (request.getServerPort() != 80)
            buff.append(":" + request.getServerPort());
    } else if (request.getServerPort() != 443) {
        buff.append(":" + request.getServerPort());
    }/*from w  w w  .  ja  v  a2  s  .com*/

    buff.append(info.getURI());
    if (request.getQueryString() != null) {
        buff.append("?" + request.getQueryString());
    }
    return buff.toString();
}

From source file:gov.nih.nci.cabig.caaers.web.admin.InvestigatorImporter.java

public void save(ImportCommand command, HttpServletRequest request) {
    List<DomainObjectImportOutcome<Investigator>> importableInvestigators = command
            .getImportableInvestigators();
    for (DomainObjectImportOutcome<Investigator> importOutcome : importableInvestigators) {
        try {/*ww w  . j a  v a2  s  .  c om*/
            investigatorRepository.save(importOutcome.getImportedDomainObject(),
                    ResetPasswordController.getURL(request.getScheme(), request.getServerName(),
                            request.getServerPort(), request.getContextPath()));
        } catch (MailException mEx) {
            logger.warn("Exception while sending email to Investigator", mEx);
        }
    }
    //   CAAERS-4461
    if (CollectionUtils.isNotEmpty(importableInvestigators))
        getEventFactory().publishEntityModifiedEvent(new LocalInvestigator(), true);
}

From source file:com.portfolio.security.LTIv2Servlet.java

private String getServiceURL(HttpServletRequest request) {
    String scheme = request.getScheme(); // http
    String serverName = request.getServerName(); // localhost
    int serverPort = request.getServerPort(); // 80
    String contextPath = request.getContextPath(); // /imsblis
    String servletPath = request.getServletPath(); // /ltitest
    String url = scheme + "://" + serverName + ":" + serverPort + contextPath + servletPath + "/";
    return url;//from   w w  w.  java  2  s  .com
}

From source file:gov.nih.nci.cabig.caaers.web.admin.ResearchStaffImporter.java

public void save(ImportCommand command, HttpServletRequest request) {
    List<DomainObjectImportOutcome<ResearchStaff>> importableResearchStaff = command
            .getImportableResearchStaff();
    for (DomainObjectImportOutcome<ResearchStaff> importOutcome : importableResearchStaff) {
        try {//  ww  w .  j  a v  a 2  s.com
            researchStaffRepository.save(importOutcome.getImportedDomainObject(),
                    ResetPasswordController.getURL(request.getScheme(), request.getServerName(),
                            request.getServerPort(), request.getContextPath()));
        } catch (MailException mEx) {
            logger.warn("Exception wile sending email to ResearchStaff", mEx);
        }
    }

    //   CAAERS-4461
    if (CollectionUtils.isNotEmpty(importableResearchStaff))
        getEventFactory().publishEntityModifiedEvent(new LocalResearchStaff(), true);
}

From source file:org.daxplore.presenter.server.servlets.PresenterBrowserServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    try {//from w w  w  .j a v a  2 s .c o  m
        if (welcomeTemplate == null) {
            try {
                welcomeTemplate = IOUtils
                        .toString(getServletContext().getResourceAsStream("/templates/welcome.html"));
            } catch (IOException e) {
                throw new InternalServerException("Failed to load the welcome template", e);
            }
        }

        String baseurl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();

        String[] arguments = { baseurl };

        String responseHTML = MessageFormat.format(welcomeTemplate, (Object[]) arguments);

        response.setContentType("text/html; charset=UTF-8");
        try (Writer writer = response.getWriter()) {
            writer.write(responseHTML);
        } catch (IOException e) {
            throw new InternalServerException("Failed to display presenter servlet", e);
        }
    } catch (InternalServerException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Unexpected exception: " + e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.sun.syndication.propono.atom.server.impl.FileBasedAtomHandler.java

/**
 * Contruct handler for one request, using specified file storage directory.
 * @param req       Request to be handled.
 * @param uploaddir File storage upload dir.
 *///  w w  w .  j a v a  2s  .co  m
public FileBasedAtomHandler(HttpServletRequest req, String uploaddir) {
    log.debug("ctor");

    userName = authenticateBASIC(req);

    atomProtocolURL = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
            + req.getContextPath() + req.getServletPath();

    contextURI = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
            + req.getContextPath();

    try {
        service = new FileBasedAtomService(userName, uploaddir, contextURI, req.getContextPath(),
                req.getServletPath());
    } catch (Throwable t) {
        throw new RuntimeException("ERROR creating FileBasedAtomService", t);
    }
}

From source file:com.ucap.uccc.cmis.impl.webservices.CmisWebServicesServlet.java

private UrlBuilder compileBaseUrl(HttpServletRequest request, HttpServletResponse response) {
    UrlBuilder result;//w  ww  . j a  v  a  2  s  . com

    String baseUrl = (String) request.getAttribute(Dispatcher.BASE_URL_ATTRIBUTE);
    if (baseUrl != null) {
        result = new UrlBuilder(baseUrl);
    } else {
        result = new UrlBuilder(request.getScheme(), request.getServerName(), request.getServerPort(), null);
        result.addPath(request.getContextPath());
        result.addPath(request.getServletPath());
    }

    return result;
}

From source file:com.google.step2.example.consumer.servlet.LoginServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    log.info("Login Servlet Post");

    // posted means they're sending us an OpenID4
    StringBuffer realmBuf = new StringBuffer(req.getScheme()).append("://").append(req.getServerName());

    if ((req.getScheme().equalsIgnoreCase("http") && req.getServerPort() != 80)
            || (req.getScheme().equalsIgnoreCase("https") && req.getServerPort() != 443)) {
        realmBuf.append(":").append(req.getServerPort());
    }//ww  w . j  a  v a2s .  com

    String realm = realmBuf.toString();
    String returnToUrl = new StringBuffer(realm).append(req.getContextPath()).append(REDIRECT_PATH).toString();

    // this is magic - normally this would also fall out of the discovery:
    OAuthAccessor accessor = null;

    // Fetch an unauthorized OAuth request token to test authorizing
    if (YES_STRING.equals(req.getParameter("oauth"))) {
        try {
            accessor = providerStore.getOAuthAccessor("google");
            accessor = oauthConsumerUtil.getRequestToken(accessor);

            // TODO(sweis): Put this string contstant somewhere that makes sense
            String oauthTestEndpoint = (String) accessor.getProperty("oauthTestEndpoint");
            if (oauthTestEndpoint != null) {
                realm = oauthTestEndpoint;
                returnToUrl = oauthTestEndpoint;
            }
        } catch (ProviderInfoNotFoundException e) {
            throw new ServletException(e);
        } catch (OAuthException e) {
            throw new ServletException(e);
        } catch (URISyntaxException e) {
            throw new ServletException(e);
        }
    }

    // we assume that the user typed an identifier for an IdP, not for a user
    IdpIdentifier openId = new IdpIdentifier(req.getParameter("openid"));

    AuthRequestHelper helper = consumerHelper.getAuthRequestHelper(openId, returnToUrl.toString());

    helper.requestUxIcon(true);

    if (accessor != null) {
        log.debug("Requesting OAuth scope : " + (String) accessor.getProperty("scope"));
        helper.requestOauthAuthorization(accessor.consumer.consumerKey, (String) accessor.getProperty("scope"));
    }

    if (YES_STRING.equals(req.getParameter("email"))) {
        log.debug("Requesting AX email");
        helper.requestAxAttribute(Step2.AxSchema.EMAIL, true);
    }

    if (YES_STRING.equals(req.getParameter("country"))) {
        log.debug("Requesting AX country");
        helper.requestAxAttribute(Step2.AxSchema.COUNTRY, true);
    }

    if (YES_STRING.equals(req.getParameter("language"))) {
        log.debug("Requesting AX country");
        helper.requestAxAttribute(Step2.AxSchema.LANGUAGE, true);
    }

    if (YES_STRING.equals(req.getParameter("firstName"))) {
        log.debug("Requesting AX country");
        helper.requestAxAttribute(Step2.AxSchema.FIRST_NAME, true);
    }

    if (YES_STRING.equals(req.getParameter("lastName"))) {
        log.debug("Requesting AX country");
        helper.requestAxAttribute(Step2.AxSchema.LAST_NAME, true);
    }

    HttpSession session = req.getSession();
    AuthRequest authReq = null;
    try {
        authReq = helper.generateRequest();
        authReq.setRealm(realm);

        // add PAPE, if requested
        if (YES_STRING.equals(req.getParameter("reauth"))) {
            log.debug("Requesting PAPE reauth");
            PapeRequest pape = PapeRequest.createPapeRequest();
            pape.setMaxAuthAge(1);
            authReq.addExtension(pape);
        }

        session.setAttribute("discovered", helper.getDiscoveryInformation());
    } catch (DiscoveryException e) {
        StringBuffer errorMessage = new StringBuffer("Could not discover OpenID endpoint.");
        errorMessage.append("\n\n").append("Check if URL is valid: ");
        errorMessage.append(openId).append("\n\n");
        errorMessage.append("Stack Trace:\n");
        for (StackTraceElement s : e.getStackTrace()) {
            errorMessage.append(s.toString()).append('\n');
        }
        resp.sendError(400, errorMessage.toString());
        return;
    } catch (MessageException e) {
        throw new ServletException(e);
    } catch (ConsumerException e) {
        throw new ServletException(e);
    }
    if (YES_STRING.equals(req.getParameter("usePost"))) {
        // using POST
        req.setAttribute("message", authReq);
        RequestDispatcher d = req.getRequestDispatcher("/WEB-INF/formredirection.jsp");
        d.forward(req, resp);
    } else {
        // using GET
        resp.sendRedirect(authReq.getDestinationUrl(true));
    }
}

From source file:com.nirima.jenkins.webdav.impl.methods.MethodBase.java

public void init(HttpServletRequest request, HttpServletResponse response, IDavContext ctx, IDavRepo repo,
        String root) {/*from  ww  w.  j  a  v  a  2  s  . c om*/
    m_request = request;
    m_response = response;
    m_ctx = ctx;
    m_repo = repo;

    // TODO : what if it is https
    m_baseUrl = "http://" + request.getServerName();
    if (request.getServerPort() != 80)
        m_baseUrl += ":" + request.getServerPort();

    m_baseUrl += request.getContextPath() + request.getServletPath();

    // Path is the path into the repo we have requested

    // Root will be something like /config, so add to the base url
    m_baseUrl += root;

    // PathInfo will also be /config/woo, but we ignore the 1st part

    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        pathInfo = request.getServletPath();
    }

    m_path = request.getContextPath() + pathInfo;
    if (m_path == null) {
        m_path = "/";
    } else {
        m_path = m_path.substring(root.length());
    }

    s_logger.info(request.getMethod() + " " + m_baseUrl + " Called with path " + m_path);
}

From source file:cz.fi.muni.xkremser.editor.server.AuthenticationServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession(true);
    String url = (String) session.getAttribute(HttpCookies.TARGET_URL);
    String root = (URLS.LOCALHOST() ? "http://" : "https://") + req.getServerName() + (URLS.LOCALHOST()
            ? (req.getServerPort() == 80 || req.getServerPort() == 443 ? "" : (":" + req.getServerPort()))
            : "") + URLS.ROOT() + (URLS.LOCALHOST() ? "?gwt.codesvr=127.0.0.1:9997" : "");
    String authHeader = req.getHeader("Authorization");
    if (authHeader != null) {
        String decodedHeader = decode(req, authHeader);
        String pass = configuration.getHttpBasicPass();
        if (pass == null || "".equals(pass.trim()) || pass.length() < 4) {
            requrireAuthentication(resp);
        }//from   w  w w. j a va  2 s  .c o  m
        if (decodedHeader.equals(ALLOWED_PREFIX + pass)) {
            session.setAttribute(HttpCookies.TARGET_URL, null);
            session.setAttribute(HttpCookies.SESSION_ID_KEY,
                    "https://www.google.com/profiles/109255519115168093543");
            session.setAttribute(HttpCookies.NAME_KEY, "admin");
            session.setAttribute(HttpCookies.ADMIN, HttpCookies.ADMIN_YES);
            ACCESS_LOGGER.info("LOG IN: [" + FORMATTER.format(new Date()) + "] User "
                    + decodedHeader.substring(0, decodedHeader.indexOf(":")) + " with openID BASIC_AUTH and IP "
                    + req.getRemoteAddr());
            URLS.redirect(resp, url == null ? root : url);
            return;
        } else {
            requrireAuthentication(resp);
            return;
        }
    }
    session.setAttribute(HttpCookies.TARGET_URL, null);
    String token = req.getParameter("token");

    String appID = configuration.getOpenIDApiKey();
    String openIdurl = configuration.getOpenIDApiURL();
    RPX rpx = new RPX(appID, openIdurl);
    Element e = null;
    try {
        e = rpx.authInfo(token);
    } catch (ConnectionException connEx) {
        requrireAuthentication(resp);
        return;
    }
    String idXPath = "//identifier";
    String nameXPath = "//displayName";
    XPathFactory xpfactory = XPathFactory.newInstance();
    XPath xpath = xpfactory.newXPath();
    String identifier = null;
    String name = null;
    try {
        XPathExpression expr1 = xpath.compile(idXPath);
        XPathExpression expr2 = xpath.compile(nameXPath);
        NodeList nodes1 = (NodeList) expr1.evaluate(e.getOwnerDocument(), XPathConstants.NODESET);
        NodeList nodes2 = (NodeList) expr2.evaluate(e.getOwnerDocument(), XPathConstants.NODESET);
        Element el = null;
        if (nodes1.getLength() != 0) {
            el = (Element) nodes1.item(0);
        }
        if (el != null) {
            identifier = el.getTextContent();
        }
        if (nodes2.getLength() != 0) {
            el = (Element) nodes2.item(0);
        }
        if (el != null) {
            name = el.getTextContent();
        }
    } catch (XPathExpressionException e1) {
        e1.printStackTrace();
    }
    if (identifier != null && !"".equals(identifier)) {
        ACCESS_LOGGER.info("LOG IN: [" + FORMATTER.format(new Date()) + "] User " + name + " with openID "
                + identifier + " and IP " + req.getRemoteAddr());
        int userStatus = UserDAO.UNKNOWN;
        try {
            userStatus = userDAO.isSupported(identifier);
        } catch (DatabaseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        switch (userStatus) {
        case UserDAO.UNKNOWN:
            // TODO handle DB error (inform user)
            break;
        case UserDAO.USER:
            // HttpCookies.setCookie(req, resp, HttpCookies.SESSION_ID_KEY,
            // identifier);
            session.setAttribute(HttpCookies.SESSION_ID_KEY, identifier);
            session.setAttribute(HttpCookies.NAME_KEY, name);
            URLS.redirect(resp, url == null ? root : url);
            break;
        case UserDAO.ADMIN:
            // HttpCookies.setCookie(req, resp, HttpCookies.SESSION_ID_KEY,
            // identifier);
            // HttpCookies.setCookie(req, resp, HttpCookies.ADMIN,
            // HttpCookies.ADMIN_YES);
            session.setAttribute(HttpCookies.SESSION_ID_KEY, identifier);
            session.setAttribute(HttpCookies.NAME_KEY, name);
            session.setAttribute(HttpCookies.ADMIN, HttpCookies.ADMIN_YES);
            URLS.redirect(resp, url == null ? root : url);
            break;
        case UserDAO.NOT_PRESENT:
        default:
            session.setAttribute(HttpCookies.UNKNOWN_ID_KEY, identifier);
            session.setAttribute(HttpCookies.NAME_KEY, name);
            URLS.redirect(resp, root + URLS.INFO_PAGE);
            break;
        }
    } else {
        URLS.redirect(resp, root + (URLS.LOCALHOST() ? URLS.LOGIN_LOCAL_PAGE : URLS.LOGIN_PAGE));
    }

    // System.out.println("ID:" + identifier);

    // if user is supported redirect to homepage else show him a page that he
    // has to be added to system first by admin

}