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.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:be.fedict.eid.dss.sp.bean.SPBean.java

private byte[] setRequest(HttpServletRequest httpServletRequest, String language, String target) {

    byte[] document = (byte[]) httpServletRequest.getSession()
            .getAttribute(UploadServlet.DOCUMENT_SESSION_ATTRIBUTE);

    this.language = language;
    this.contentType = (String) httpServletRequest.getSession().getAttribute("ContentType");
    this.relayState = UUID.randomUUID().toString();
    LOG.debug("RelayState: " + this.relayState);

    this.destination = "../eid-dss/protocol/simple";
    this.target = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + ":"
            + httpServletRequest.getServerPort() + httpServletRequest.getContextPath() + "/" + target
            + "?requestId=" + new Random().nextInt(1000);

    // store data on session for response handling
    httpServletRequest.getSession().setAttribute("target", this.target);
    httpServletRequest.getSession().setAttribute("RelayState", this.relayState);

    return document;
}

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

/**
 * Processes requests for both HTTP/*from www  .  j  a v  a  2s. c  o 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:it.cnr.icar.eric.server.interfaces.soap.RegistryBSTServlet.java

@SuppressWarnings("unused")
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/plain");

    String requestUri = req.getRequestURI();
    String servletPath = req.getServletPath();
    String scheme = req.getScheme();
    String serverName = req.getServerName();
    String queryString = req.getQueryString();
    String ericName = RegistryProperties.getInstance().getProperty("eric.name", "eric");
    int serverPort = req.getServerPort();
    StringBuffer sb = new StringBuffer();
    sb.append(scheme).append("://").append(serverName).append(':');
    sb.append(serverPort);//w w w  .j  a  va 2s  . com
    sb.append('/');
    sb.append(ericName);
    sb.append("/registry/thin/browser.jsp");
    String url = sb.toString();

    PrintWriter wt = resp.getWriter();
    wt.println(ServerResourceBundle.getInstance().getString("message.urlForSOAP"));
    wt.println(ServerResourceBundle.getInstance().getString("message.urlForWebAccess", new Object[] { url }));
    wt.flush();
    wt.close();
}

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 ww.  j  ava  2  s  . com*/

    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: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 w w .j av  a2 s. c o m
            "You requested a password reset for your account with " + clusterDescription + "?", msgBody);
}

From source file:seava.j4e.web.controller.ui.extjs.AbstractUiExtjsController.java

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

    response.setContentType("text/html;charset=UTF-8");

    if (logger.isInfoEnabled()) {
        logger.info("Handling request for ui.extjs: ", request.getPathInfo());
    }//from   w w  w  . j a v a  2 s .  co  m

    String server = request.getServerName();
    int port = request.getServerPort();

    String userRolesStr = null;

    this.prepareRequest(request, response);

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

        IUserSettings prefs = user.getSettings();

        Session.user.set(user);

        model.put("statics", BeansWrapper.getDefaultInstance().getStaticModels());
        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.getDateFormatMask(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", StringEscapeUtils.escapeJavaScript(this.getSettings().getProductName()));
    model.put("productDescription", this.getSettings().getProductDescription());
    model.put("productVersion", this.getSettings().getProductVersion());
    model.put("productVendor", this.getSettings().getProductVendor());
    model.put("productUrl", this.getSettings().getProductUrl());
    model.put("hostUrl", hostUrl);
    model.put("ctxpath", this.getSettings().get(Constants.PROP_CTXPATH));

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

    // DNet extjs components in core and modules
    model.put("urlUiExtjsLib", getUiExtjsSettings().getUrlLib());
    model.put("urlUiExtjsCore", getUiExtjsSettings().getUrlCore());
    model.put("urlUiExtjsCoreI18n", getUiExtjsSettings().getUrlCoreI18n());

    model.put("urlUiExtjsModules", getUiExtjsSettings().getUrlModules());
    model.put("urlUiExtjsModuleSubpath", getUiExtjsSettings().getModuleSubpath());
    model.put("urlUiExtjsModuleUseBundle", getUiExtjsSettings().isModuleUseBundle());

    String lang = this.resolveLang(request, response);
    model.put("shortLanguage", StringEscapeUtils.escapeJavaScript(lang));

    String theme = this.resolveTheme(request, response);
    model.put("theme", StringEscapeUtils.escapeJavaScript(theme));

    model.put("sysCfg_workingMode", this.getSettings().get(Constants.PROP_WORKING_MODE));

    model.put("userRolesStr", userRolesStr);

}

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

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

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

    if (UrlUtils.isAbsoluteUrl(loginForm)) {
        return loginForm;
    }/*  w  w w  . j a va  2  s  . c om*/

    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(serverPort);

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

    return urlBuilder.getUrl();
}

From source file:it.cnr.icar.eric.server.interfaces.soap.RegistrySAMLServlet.java

/**
 * This method is a copy of the respective method from RegistrySOAPServlet.
 * It informs the user about GET requests and the corresponding URL for Web
 * Access./*  ww  w  .  ja v a2s . c o m*/
 */

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/plain");

    String scheme = request.getScheme();
    String serverName = request.getServerName();

    String ericName = RegistryProperties.getInstance().getProperty("eric.name", "eric");

    int serverPort = request.getServerPort();

    StringBuffer sb = new StringBuffer();

    sb.append(scheme).append("://").append(serverName).append(':');
    sb.append(serverPort);
    sb.append('/');
    sb.append(ericName);
    sb.append("/registry/thin/browser.jsp");

    String url = sb.toString();

    PrintWriter wt = response.getWriter();

    wt.println(ServerResourceBundle.getInstance().getString("message.urlForSOAP"));
    wt.println(ServerResourceBundle.getInstance().getString("message.urlForWebAccess", new Object[] { url }));

    wt.flush();
    wt.close();
}

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

/**
 * Processes requests for both HTTP//from w  w w  .  ja v  a2s .  c o 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>Servlet TestServlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
    Client client = ClientBuilder.newClient();
    client.register(MyClientReaderInterceptor.class).register(MyClientWriterInterceptor.class);
    WebTarget target = client.target("http://" + request.getServerName() + ":" + request.getServerPort()
            + request.getContextPath() + "/webresources/fruits");
    System.out.println("GET request");
    String result = target.request().get(String.class);
    out.println("Received response: " + result + "<br><br>");

    System.out.println("POST request");
    result = target.request().post(Entity.text("1"), String.class);
    out.println("Received response: " + result + "<br><br>");

    out.println("Check server.log for client/server interceptor output.");
    out.println("</body>");
    out.println("</html>");
}