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:com.viewer.controller.ViewerController.java

@RequestMapping(value = "/GetApplicationHost", method = RequestMethod.GET, headers = {
        "Content-type=application/json" })
@ResponseBody/*from  w w w. j av a  2  s.c o m*/
private String GetApplicationHost(@RequestBody HttpServletRequest request) {

    return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
}

From source file:com.sun.socialsite.web.filters.CustomizedPageCachingFilter.java

@Override
protected String calculateKey(final HttpServletRequest req) {

    StringBuffer sb;/*from   www.j ava  2s  . co  m*/
    String queryString = null;

    /*
     * We want our keys to be absolute URLs (with scheme, hostname, etc) so that
     * they'll line-up with what our URLStrategy uses (which makes it easier for
     * other code to invalidate cache entries when an entity is updated).
     */

    if (req.getAttribute("javax.servlet.include.request_uri") != null) {
        sb = new StringBuffer();
        sb.append(req.getMethod());
        sb.append("|");
        sb.append(req.getScheme()).append("://").append(req.getServerName());
        switch (req.getServerPort()) {
        case 80:
            if (req.getScheme().equalsIgnoreCase("http")) {
                break;
            }
        case 443:
            if (req.getScheme().equalsIgnoreCase("https")) {
                break;
            }
        default:
            sb.append(":").append(req.getServerPort());
        }
        sb.append((String) (req.getAttribute("javax.servlet.include.request_uri")));
        queryString = (String) (req.getAttribute("javax.servlet.include.query_string"));
    } else {
        sb = req.getRequestURL();
        queryString = req.getQueryString();
    }

    if (queryString != null) {
        sb.append("?").append(queryString);
    }

    String key = sb.toString();
    log.trace("key=" + key);

    return key;
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarLoginHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFSecuritySecUserObj resetUser,
        ICFSecurityClusterObj cluster) throws IOException, MessagingException, NamingException {
    String clusterDescription = cluster.getRequiredDescription();

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n"
            + "</BODY>\n" + "</HTML>\n";

    CFAsteriskSMWarUtil warUtil = new CFAsteriskSMWarUtil();
    warUtil.sendEMailToUser(resetUser,/*  www .  ja v  a2s . c o  m*/
            "You requested a password reset for your account with " + clusterDescription + "?", msgBody);
}

From source file:net.nan21.dnet.core.web.controller.ui.extjs.AbstractUiExtjsController.java

protected void _prepare(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    if (logger.isInfoEnabled()) {
        logger.info("Handling request for ui.extjs: ", request.getPathInfo());
    }//from  ww  w. jav  a 2  s  . c  om

    String server = request.getServerName();
    int port = request.getServerPort();
    // String contextPath = request.getContextPath();
    // String path = request.getServletPath();

    String userRolesStr = null;

    try {
        ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        IUser user = su.getUser();

        IUserSettings prefs = user.getSettings();

        Session.user.set(user);

        model.put("constantsJsFragment", this.getConstantsJsFragment());
        model.put("user", user);

        DateFormatAttribute[] masks = DateFormatAttribute.values();
        Map<String, String> dateFormatMasks = new HashMap<String, String>();
        for (int i = 0, len = masks.length; i < len; i++) {
            DateFormatAttribute mask = masks[i];
            if (mask.isForJs()) {
                dateFormatMasks.put(mask.name().replace("EXTJS_", ""), prefs.getDateFormat(mask.name()));
            }
        }

        model.put("dateFormatMasks", dateFormatMasks);

        model.put("modelDateFormat", this.getSettings().get(Constants.PROP_EXTJS_MODEL_DATE_FORMAT));

        model.put("decimalSeparator", prefs.getDecimalSeparator());
        model.put("thousandSeparator", prefs.getThousandSeparator());

        StringBuffer sb = new StringBuffer();
        int i = 0;
        for (String role : user.getProfile().getRoles()) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append("\"" + role + "\"");
            i++;
        }
        userRolesStr = sb.toString();

    } catch (ClassCastException e) {
        // not authenticated
    }
    String hostUrl = ((request.isSecure()) ? "https" : "http") + "://" + server
            + ((port != 80) ? (":" + port) : "");// + contextPath;

    model.put("productName", this.getSettings().getProductName());
    model.put("productVersion", this.getSettings().getProductVersion());
    model.put("hostUrl", hostUrl);

    // themes
    model.put("urlUiExtjsThemes", getUiExtjsSettings().getUrlThemes());

    // DNet extjs components in core and modules
    model.put("urlUiExtjsCore", getUiExtjsSettings().getUrlCore());
    model.put("urlUiExtjsModules", getUiExtjsSettings().getUrlModules());
    model.put("urlUiExtjsModuleSubpath", getUiExtjsSettings().getModuleSupath());

    // translations for core and modules
    model.put("urlUiExtjsCoreI18n", getUiExtjsSettings().getUrlCoreI18n());
    model.put("urlUiExtjsModulesI18n", getUiExtjsSettings().getUrlModulesI18n());

    model.put("shortLanguage", this.resolveLang(request, response));
    model.put("theme", this.resolveTheme(request, response));
    model.put("sysCfg_workingMode", this.getSettings().get(Constants.PROP_WORKING_MODE));

    model.put("userRolesStr", userRolesStr);

}

From source file:org.bonitasoft.console.common.application.ApplicationURLUtils.java

/**
 * Retrieve the dedicated application URL and set it in the
 * /* w ww  . java 2s. co  m*/
 * @param request the current request
 * @param aProcessDefinitionUUID the process definition UUID
 * @return the URL of the dedicated application (null if no dedicated application is deployed for the process)
 * @throws ProcessNotFoundException
 */
public String getOrSetURLMetaData(final HttpServletRequest request,
        final ProcessDefinitionUUID aProcessDefinitionUUID) throws ProcessNotFoundException {
    String theResult = null;

    final String theMeta = AccessorUtil.getQueryDefinitionAPI().getProcessMetaData(aProcessDefinitionUUID,
            DEDICATED_APP_URL_META_NAME);

    if (theMeta == null || theMeta.length() == 0) {
        // The Metadata is not set yet.
        // Try to autodetect it.
        final String theScheme = request.getScheme();
        final String theServerName = request.getServerName();
        final int theServerPort = request.getServerPort();

        URL theApplicationURL;
        try {
            theApplicationURL = new URL(theScheme + "://" + theServerName + ":" + theServerPort + "/"
                    + aProcessDefinitionUUID + HOSTPAGE_PATH);
            final boolean urlIsReachable = checkURLConnection(theApplicationURL);
            if (urlIsReachable) {
                setProcessApplicationURLMetadata(aProcessDefinitionUUID, theApplicationURL.toString());
                if (LOGGER.isLoggable(Level.INFO)) {
                    LOGGER.log(Level.INFO,
                            "Adding the " + DEDICATED_APP_URL_META_NAME + " metadata for the process "
                                    + aProcessDefinitionUUID + ": " + theApplicationURL.toString());
                }
                theResult = theApplicationURL.toString();
            } else {
                theResult = HOMEPAGE_SERVLET_ID_IN_PATH + "?" + THEME_PARAM + "=" + aProcessDefinitionUUID;
            }
        } catch (final MalformedURLException e) {
            e.printStackTrace();
        }

    } else {
        theResult = theMeta;
    }
    /*
     * If the meta is set do not modify it else { URL theApplicationURL; try { theApplicationURL = new URL(theMeta); boolean
     * urlIsReachable = checkURLConnection(theApplicationURL); if (!urlIsReachable) { // Remove the meta as it seems to be
     * obsolete. AccessorUtil.getManagementAPI().deleteMetaData (DEDICATED_APP_URL_META_NAME + "-" +
     * aProcessDefinitionUUID); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, "Deleting metadata :" +
     * DEDICATED_APP_URL_META_NAME + "-" + aProcessDefinitionUUID + " : " + theMeta); } } else { theResult = theMeta; } }
     * catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
     */
    return theResult;
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarLoginHtml.java

protected void sendConfirmationEMail(ICFSecuritySecDeviceObj defDev, HttpServletRequest request,
        ICFSecuritySecUserObj confirmUser, ICFSecurityClusterObj cluster)
        throws IOException, MessagingException, NamingException {
    String clusterDescription = cluster.getRequiredDescription();

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID confirmationUUID = confirmUser.getOptionalEMailConfirmationUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a new account for " + confirmUser.getRequiredEMailAddress() + " with "
            + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to confirm your email address:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarConfirmEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "\">"
            + baseURI + "/CFAsteriskSMWarConfirmEMailAddressHtml?ConfirmationUUID="
            + confirmationUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the request for a new account:<br>\n" + "<A HRef=\""
            + baseURI + "/CFAsteriskSMWarCancelEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString()
            + "\">" + baseURI + "/CFAsteriskSMWarCancelEMailAddressHtml?ConfirmationUUID="
            + confirmationUUID.toString() + "</A>\n" + "</BODY>\n" + "</HTML>\n";

    CFAsteriskSMWarUtil warUtil = new CFAsteriskSMWarUtil();
    warUtil.sendEMailToUser(confirmUser, "You requested an account with " + clusterDescription + "?", msgBody);
}

From source file:org.frontcache.FrontCacheEngine.java

/**
 * do it outside init() because it's for cacheable requests only
 * //w  w w  . j  a v  a2 s. c om
 * @param context
 * @return
 */
private void getCurrentRequestURL2Context(RequestContext context) {
    HttpServletRequest httpRequest = context.getRequest();
    String portStr = "";
    int port = httpRequest.getServerPort();
    if (80 == port && "http".equals(context.getFrontCacheProtocol()))
        portStr = "";
    else if (443 == port && "https".equals(context.getFrontCacheProtocol()))
        portStr = "";
    else
        portStr = ":" + port;

    String currentRequestURL = context.getFrontCacheProtocol() + "://" + context.getFrontCacheHost() + portStr
            + context.getRequestURI() + context.getRequestQueryString();
    context.setCurrentRequestURL(currentRequestURL);
    logger.debug("currentRequestURL: " + currentRequestURL);

    return;
}

From source file:org.sample.client.TestServlet.java

/**
 * Processes requests for both HTTP/*from ww w  .  ja v  a  2s .  co m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>JAX-RS 2 Client API</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>JAX-RS 2 Client API at " + request.getContextPath() + "</h1>");
    out.println("Initializing client...<br>");
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://" + request.getServerName() + ":" + request.getServerPort()
            + request.getContextPath() + "/webresources/persons");

    out.print("POSTing...<br>");
    // POST
    MultivaluedHashMap<String, String> map = new MultivaluedHashMap<>();
    map.add("name", "Name");
    map.add("age", "17");
    target.request().post(Entity.form(map));
    out.print("POSTed a new item ...<br>");

    // GET
    out.print("GETTing...<br>");
    Person[] list = target.request().get(Person[].class);
    out.format("GOT %1$s items<br>", list.length);
    for (Person p : list) {
        out.print(p + "<br>");
    }
    out.println("... done.<br>");

    // GET with path param
    out.print("GETTing with parameter...<br>");
    Person person = target.path("{id}").resolveTemplate("id", "1").request(MediaType.APPLICATION_XML)
            .get(Person.class);
    out.print("GOT person: " + person + "<br>");
    out.println("... done.");

    out.println("</body>");
    out.println("</html>");
}

From source file:eu.europeana.uim.gui.cp.server.RetrievalServiceImpl.java

/**
 * Private method that determines the application context so that this does not have to be defined in configuration properties.
 * Ideally this should be put in the context of an overriden init() method but unfortunately it does not work there.
 *///from w  w  w.  j a va  2  s.com
private void determinelocaladress() {

    if (REPOSITORY_PREVIEW_URL == null) {
        HttpServletRequest request = this.getThreadLocalRequest();
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String contextPath = request.getContextPath();
        REPOSITORY_PREVIEW_URL = scheme + "://" + serverName + ":" + serverPort + contextPath
                + "/EuropeanaIngestionControlPanel/mongoImageView";
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarLoginHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFAstSecUserObj resetUser,
        ICFAstClusterObj cluster) throws IOException, MessagingException, NamingException {
    String clusterDescription = cluster.getRequiredDescription();

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n"
            + "</HTML>\n";

    CFAstSMWarUtil warUtil = new CFAstSMWarUtil();
    warUtil.sendEMailToUser(resetUser,/*  w  ww  .  j av a  2  s.c  om*/
            "You requested a password reset for your account with " + clusterDescription + "?", msgBody);
}