Example usage for javax.servlet.http HttpServletRequest getServerName

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

Introduction

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

Prototype

public String getServerName();

Source Link

Document

Returns the host name of the server to which the request was sent.

Usage

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  w ww . ja  va 2  s. com

    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: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.
 *//*  w  w w. java 2 s  .  co m*/
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_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,//ww  w .  ja  v  a 2  s . c  om
            "You requested a password reset for your account with " + clusterDescription + "?", msgBody);
}

From source file:com.qualogy.qafe.web.upload.DatagridUploadServlet.java

@SuppressWarnings("unchecked")
private void writeUploadInfo(HttpServletRequest request) {
    writeLog("Document Upload!");

    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        Object name = headerNames.nextElement();
        if (name != null) {
            writeLog("Header - " + name + " : " + request.getHeader((String) name));
        }//  www .j  a v  a 2  s.  co m
    }

    writeLog("ServletRemoteAddr: " + request.getRemoteAddr());
    writeLog("Remote Host: " + request.getRemoteHost());
    writeLog("Remote User: " + request.getRemoteUser());
    writeLog("Protocol: " + request.getProtocol());
    writeLog("Server Name: " + request.getServerName());
    writeLog("Server Port: " + request.getServerPort());
    writeLog("Request URL: " + request.getRequestURL());

}

From source file:com.janrain.backplane.server.Backplane1Controller.java

private void aniLogPollMessages(HttpServletRequest request, String referer, String version, String bus,
        String channel, List<BackplaneMessage> messages) {
    if (!anilogger.isEnabled()) {
        return;/*from ww w  .  j  a v  a  2 s  .  c om*/
    }

    String channelId = "https://" + request.getServerName() + "/" + version + "/bus/" + bus + "/channel/"
            + channel;
    String siteHost = (referer != null) ? ServletUtil.getHostFromUrl(referer) : null;

    Map<String, Object> aniEvent = new HashMap<String, Object>();
    aniEvent.put("channel_id", channelId);
    aniEvent.put("bus", bus);
    aniEvent.put("version", version);
    aniEvent.put("site_host", siteHost);
    List<String> messageIds = new ArrayList<String>();
    for (BackplaneMessage message : messages) {
        messageIds.add(message.getIdValue());
    }
    aniEvent.put("message_ids", messageIds);

    aniLog("poll_messages", aniEvent);
}

From source file:com.vmware.appfactory.common.base.AbstractController.java

/**
 * Get a full server path url including current web app context.
 * e.g. http(s)://(hostname)(:optional_port)/(web_context)/
 *
 * @param request - a HttpServletRequest.
 * @return a server path url/*from   w  w w. j ava 2 s.  c  o  m*/
 */
protected String getFullContextPath(HttpServletRequest request) {
    if (request == null) {
        throw new IllegalArgumentException("request must NOT be null!");
    }
    int port = request.getLocalPort();
    final StringBuilder url = new StringBuilder();
    /* http(s)://hostname */
    url.append(request.getScheme()).append("://").append(request.getServerName());
    if (port != 80) {
        /* http(s)://hostname:xxxx */
        url.append(":" + port);
    }
    /* http(s)://hostname(:xxxx)/web_context/ */
    url.append(request.getContextPath()).append("/");

    return url.toString();
}

From source file:br.com.flucianofeijao.security.JsfLoginUrlAuthenticationEntryPoint.java

protected String buildRedirectUrlToLoginPage(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) {

    String loginForm = determineUrlToUseForThisRequest(request, response, authException);

    if (UrlUtils.isAbsoluteUrl(loginForm)) {
        return loginForm;
    }/*ww w . ja va  2  s .co  m*/

    int serverPort = portResolver.getServerPort(request);
    String scheme = request.getScheme();

    RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();

    urlBuilder.setScheme(scheme);
    urlBuilder.setServerName(request.getServerName());
    urlBuilder.setPort(serverPort);
    urlBuilder.setContextPath(request.getContextPath());
    urlBuilder.setPathInfo(loginForm);

    if (forceHttps && "http".equals(scheme)) {
        Integer httpsPort = portMapper.lookupHttpsPort(Integer.valueOf(serverPort));

        if (httpsPort != null) {
            // Overwrite scheme and port in the redirect URL
            urlBuilder.setScheme("https");
            urlBuilder.setPort(httpsPort.intValue());
        } else {
            logger.warn("Unable to redirect to HTTPS as no port mapping found for HTTP port " + serverPort);
        }
    }

    return urlBuilder.getUrl();
}

From source file:jp.or.openid.eiwg.scim.servlet.ResourceTypes.java

/**
 * GET?/*from  w  w  w . j  a  v  a 2s .co  m*/
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // location?URL?
        String location = request.getScheme() + "://" + request.getServerName();
        int serverPort = request.getServerPort();
        if (serverPort != 80 && serverPort != 443) {
            location += ":" + Integer.toString(serverPort);
        }
        location += request.getContextPath();

        // ?
        @SuppressWarnings("unchecked")
        ArrayList<LinkedHashMap<String, Object>> resourceTypes = (ArrayList<LinkedHashMap<String, Object>>) context
                .getAttribute("ResourceTypes");

        // location?
        Iterator<LinkedHashMap<String, Object>> resourceTypesIt = resourceTypes.iterator();
        while (resourceTypesIt.hasNext()) {
            LinkedHashMap<String, Object> resourceTypeInfo = resourceTypesIt.next();
            // meta?
            Object metaObject = SCIMUtil.getAttribute(resourceTypeInfo, "meta");
            if (metaObject != null && metaObject instanceof LinkedHashMap) {
                @SuppressWarnings("unchecked")
                LinkedHashMap<String, Object> metaInfo = (LinkedHashMap<String, Object>) metaObject;
                Object locationInfo = SCIMUtil.getAttribute(metaInfo, "location");
                if (locationInfo != null && locationInfo instanceof String) {
                    String locationValue = String.format(locationInfo.toString(), location);
                    metaInfo.put("location", locationValue);
                    resourceTypeInfo.put("meta", metaInfo);
                }
            }
        }

        try {
            // javaJSON??
            ObjectMapper mapper = new ObjectMapper();
            StringWriter writer = new StringWriter();
            mapper.writeValue(writer, resourceTypes);

            // ??
            String listResponse = "{\"schemas\":[\"urn:ietf:params:scim:api:messages:2.0:ListResponse\"],";
            listResponse += "\"totalResults\":" + resourceTypes.size();
            if (resourceTypes.size() > 0) {
                listResponse += ",\"Resources\":";
                listResponse += writer.toString();
            }
            listResponse += "}";

            response.setContentType("application/scim+json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println(listResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:jp.or.openid.eiwg.scim.servlet.Schemas.java

/**
 * GET?//from   w  w w. j av a 2  s .co m
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // location?URL?
        String location = request.getScheme() + "://" + request.getServerName();
        int serverPort = request.getServerPort();
        if (serverPort != 80 && serverPort != 443) {
            location += ":" + Integer.toString(serverPort);
        }
        location += request.getContextPath();

        // ?
        @SuppressWarnings("unchecked")
        ArrayList<LinkedHashMap<String, Object>> schemas = (ArrayList<LinkedHashMap<String, Object>>) context
                .getAttribute("Schemas");

        // location?
        Iterator<LinkedHashMap<String, Object>> schemasIt = schemas.iterator();
        while (schemasIt.hasNext()) {
            LinkedHashMap<String, Object> schemaInfo = schemasIt.next();
            // meta?
            Object metaObject = SCIMUtil.getAttribute(schemaInfo, "meta");
            if (metaObject != null && metaObject instanceof LinkedHashMap) {
                @SuppressWarnings("unchecked")
                LinkedHashMap<String, Object> metaInfo = (LinkedHashMap<String, Object>) metaObject;
                Object locationInfo = SCIMUtil.getAttribute(metaInfo, "location");
                if (locationInfo != null && locationInfo instanceof String) {
                    String locationValue = String.format(locationInfo.toString(), location);
                    metaInfo.put("location", locationValue);
                    schemaInfo.put("meta", metaInfo);
                }
            }
        }

        try {
            // javaJSON??
            ObjectMapper mapper = new ObjectMapper();
            StringWriter writer = new StringWriter();
            mapper.writeValue(writer, schemas);

            // ??
            String listResponse = "{\"schemas\":[\"urn:ietf:params:scim:api:messages:2.0:ListResponse\"],";
            listResponse += "\"totalResults\":" + schemas.size();
            if (schemas.size() > 0) {
                listResponse += ",\"Resources\":";
                listResponse += writer.toString();
            }
            listResponse += "}";

            response.setContentType("application/scim+json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println(listResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:eionet.util.Util.java

/**
 *
 * @param request//from ww  w.  j  a  va 2 s  .com
 * @return
 */
public static String getBaseHref(HttpServletRequest request) {

    String protocol = request.getProtocol().toLowerCase();
    int i = protocol.indexOf('/');
    if (i >= 0) {
        protocol = protocol.substring(0, i);
    }

    StringBuffer buf = new StringBuffer(protocol);
    buf.append("://").append(request.getServerName());
    if (request.getServerPort() > 0) {
        buf.append(":").append(request.getServerPort());
    }
    if (request.getContextPath() != null) {
        buf.append(request.getContextPath());
    }
    if (buf.toString().endsWith("/") == false) {
        buf.append("/");
    }

    return buf.toString();
}