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:com.janrain.backplane2.server.Backplane2Controller.java

private void aniLogNewMessage(HttpServletRequest request, BackplaneMessage message, Token token) {
    if (!anilogger.isEnabled()) {
        return;//from ww w.j av a2  s .c o m
    }

    String bus = message.getBus();
    String channel = message.getChannel();
    String channelId = "https://" + request.getServerName() + "/v2/bus/" + bus + "/channel/" + channel;
    String clientId = token.get(Token.TokenField.ISSUED_TO_CLIENT_ID);
    Map<String, Object> aniEvent = new HashMap<String, Object>();
    aniEvent.put("channel_id", channelId);
    aniEvent.put("bus", bus);
    aniEvent.put("client_id", clientId);

    aniLog("new_message", aniEvent);
}

From source file:com.janrain.backplane2.server.Backplane2Controller.java

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

    String siteHost = (referer != null) ? ServletUtil.getHostFromUrl(referer) : null;
    String serverName = request.getServerName();
    Map<String, Object> aniEvent = new HashMap<String, Object>();

    List<Map<String, String>> messagesMeta = new ArrayList<Map<String, String>>();
    for (BackplaneMessage message : messages) {
        String bus = message.getBus();
        String channelId = "https://" + serverName + "/v2/bus/" + bus + "/channel/" + message.getChannel();
        Map<String, String> anotherMeta = new HashMap<String, String>();
        anotherMeta.put("id", message.getIdValue());
        anotherMeta.put("bus", bus);
        anotherMeta.put("channel_id", channelId);
        messagesMeta.add(anotherMeta);
    }
    aniEvent.put("messages", messagesMeta);
    aniEvent.put("site_host", siteHost);

    aniLog("poll_messages", aniEvent);
}

From source file:de.appsolve.padelcampus.utils.LoginUtil.java

public void deleteLoginCookie(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(COOKIE_LOGIN_TOKEN)) {
                if (cookie.getValue() != null && cookie.getValue().split(":").length == 2) {
                    LoginCookie loginCookie = loginCookieDAO.findByUUID(cookie.getValue().split(":")[0]);
                    if (loginCookie != null) {
                        loginCookieDAO.deleteById(loginCookie.getId());
                        break;
                    }//from w ww  . j  a  v  a2s.c  o m
                }
            }
        }
    }
    deleteCookie(request, response, null);
    deleteCookie(request, response, "/");
    deleteCookie(request, response, "/page");
    deleteCookie(request, response, "/admin");
    deleteCookie(request, response, "/login");
    deleteCookie(request, response, "/admin/events");
    deleteCookie(request, response, "/admin/events/edit");
    deleteCookie(request, response, "/events/event");
    Cookie cookie = new Cookie(COOKIE_LOGIN_TOKEN, null);
    cookie.setDomain(request.getServerName());
    cookie.setMaxAge(0);
    response.addCookie(cookie);
}

From source file:com.janrain.backplane2.server.Backplane2Controller.java

private void aniLogNewChannel(HttpServletRequest request, String referer, String bus, String scope) {
    if (!anilogger.isEnabled()) {
        return;//from www.  j a  v  a2s  .c  o  m
    }

    int delim = scope.indexOf("channel:");
    String channel = scope.substring(delim + 8);
    String channelId = "https://" + request.getServerName() + "/v2/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("site_host", siteHost);

    aniLog("new_channel", aniEvent);
}

From source file:controller.FacebookServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w ww  . j  a v a 2s.  c  om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    System.out.println("POST POST!!!!!!!!!!!!!!");
    String requestUri = request.getRequestURI();
    String servletAddress = "http://" + request.getServerName() + ":" + request.getServerPort()
            + "/WebServiceFacebook/";
    System.out.println("ADD:" + servletAddress);

    if (RegexUtil.regexRemoveUserId.matcher(requestUri).find()) {
        //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/removeUser/likes?user=1
        FacebookDAO dao = new FacebookDAO(servletAddress);
        try {

            int idUser = Integer.valueOf(request.getParameter("idUser"));
            User u = dao.getUserById(idUser);

            dao.removeUser(u);
            response.getWriter().write("REMOVE USER");

        } catch (FacebookDAOException ex) {
            System.out.println("Erro ao excluir!" + ex.getMessage());
            ;
        }
    }

    else if (RegexUtil.regexUpdateUser.matcher(requestUri).find()) {
        //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/updateUser/likes?name=Elias&email=elias@hotmail.com&id=1
        FacebookDAO dao = new FacebookDAO(servletAddress);
        try {
            String name = request.getParameter("name");
            String email = request.getParameter("email");
            int id = Integer.valueOf(request.getParameter("idUser"));

            User u = new User(id, name, email);
            dao.updateUser(u);
            response.getWriter().write("UPDATE USER");

        } catch (FacebookDAOException ex) {
            System.out.println("Erro ao atualizar!" + ex.getMessage());
            ;
        }
    } else if (RegexUtil.regexPOSTLogin.matcher(requestUri).find()) {

        FacebookDAO dao = new FacebookDAO(servletAddress);
        try {
            User u = dao.login(request.getParameter("email"), request.getParameter("password"));
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(u);
            ServletUtil.writeJSON(response, json);
        } catch (FacebookDAOException ex) {
            System.out.println("Erro login!" + ex.getMessage());
            ;
        }
        System.out.println("POST LOGIN!");

    } else if (RegexUtil.regexPOSTPhoto.matcher(requestUri).find()) {
        System.out.println("POST PHOTO!!!!!!!!!!!!!!!!!!");
        try {
            //File post para celular
            doFilePost64(request);
            //File post de formulrio
            doFilePost(request);
        } catch (FacebookDAOException ex) {
            Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    } else if (RegexUtil.regexPOSTRegister.matcher(requestUri).find()) {
        //File post de formulrio
        doFilePost(request);

    } else if (RegexUtil.regexUserLikesPost.matcher(requestUri).find()) {
        //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/likes?user=1&post=2
        User u = new User(Integer.valueOf(request.getParameter("user")));
        Post p = new Post(Integer.valueOf(request.getParameter("post")));
        System.out.println("Like:" + u + "--" + p);
        FacebookDAO dao = new FacebookDAO(servletAddress);
        try {
            dao.addLikeInPost(u, p);
            response.getWriter().write("LIKE");
        } catch (FacebookDAOException ex) {
            System.out.println("Erro login!" + ex.getMessage());
            ;
        }
        System.out.println("POST LOGIN!");

    } else if (RegexUtil.regexStartFriendship.matcher(requestUri).find()) {
        //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/likes?user=1&post=2
        User u1 = new User(Integer.valueOf(request.getParameter("user1")));
        User u2 = new User(Integer.valueOf(request.getParameter("user2")));
        FacebookDAO dao = new FacebookDAO(servletAddress);
        try {
            dao.saveFriendship(u1, u2);
            dao.saveFriendship(u2, u1);
            response.getWriter().write("FRIENDS");
        } catch (FacebookDAOException ex) {
            System.out.println("Erro login!" + ex.getMessage());
            ;
        }
        System.out.println("POST LOGIN!");

    } else if (RegexUtil.regexPOSTComment.matcher(requestUri).find()) {
        //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/likes?user=1&post=2
        String content = request.getParameter("content");
        User u = new User(Integer.valueOf(request.getParameter("user")));
        Post p = new Post(Integer.valueOf(request.getParameter("post")));
        Comment c = new Comment(u, content);
        System.out.println("PostComment:" + c);
        FacebookDAO dao = new FacebookDAO(servletAddress);
        try {
            int idPost = dao.saveComment(c, p);
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(idPost);
            ServletUtil.writeJSON(response, json);
        } catch (FacebookDAOException ex) {
            System.out.println("Impossvel salvar post!" + ex.getMessage());
            ;
        }
        System.out.println("POST LOGIN!");
    }

    else if (RegexUtil.regexUserRemoveLikesAlbumComment.matcher(requestUri).find()) {
        //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/removeLikes?user=1&albumcomment=1

        int getidUser = Integer.valueOf(request.getParameter("user"));
        int getidAlbum = Integer.valueOf(request.getParameter("albumcomment"));

        User u = new User(getidUser);
        AlbumComment a = new AlbumComment(getidAlbum);
        FacebookDAO dao = new FacebookDAO(servletAddress);

        try {
            dao.removeLikeInComment(u, a);
            response.getWriter().write("REMOVE LIKE IN ALBUM COMMENT");

        } catch (FacebookDAOException ex) {
            System.out.println("Impossvel deletar like do comentrio do lbum!" + ex.getMessage());
            ;
        }
    }

    else if (RegexUtil.regexUserRemoveLikesPhotoComment.matcher(requestUri).find()) {
        //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/removeLikes?user=1&albumcomment=1

        int getidUser = Integer.valueOf(request.getParameter("user"));
        int getidPhoto = Integer.valueOf(request.getParameter("photocomment"));

        User u = new User(getidUser);
        PhotoComment p = new PhotoComment(getidPhoto);
        FacebookDAO dao = new FacebookDAO(servletAddress);

        try {
            dao.removeLikeInComment(u, p);
            response.getWriter().write("REMOVE LIKE IN PHOTO COMMENT");

        } catch (FacebookDAOException ex) {
            System.out.println("Impossvel deletar like do comentrio do lbum!" + ex.getMessage());
            ;
        }
    }

    else if (RegexUtil.regexUserRemoveLikesPostComment.matcher(requestUri).find()) {
        //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/removeLikes?user=1&albumcomment=1

        int getidUser = Integer.valueOf(request.getParameter("user"));
        int getidPost = Integer.valueOf(request.getParameter("postcomment"));

        User u = new User(getidUser);
        PostComment p = new PostComment(getidPost);
        FacebookDAO dao = new FacebookDAO(servletAddress);

        try {
            dao.removeLikeInComment(u, p);
            response.getWriter().write("REMOVE LIKE IN POST COMMENT");

        } catch (FacebookDAOException ex) {
            System.out.println("Impossvel deletar like do comentrio do lbum!" + ex.getMessage());
            ;
        }
    }
}

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

/**
 * Load given department current page/*ww w  .  jav 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.mobileman.projecth.web.controller.PublicController.java

@RequestMapping(method = RequestMethod.POST, value = "/behandlung/pwbnvergessen")
public String resetPassword(HttpServletRequest request, HttpServletResponse response, Model model) {

    boolean captcha = CaptchaUtil.verify(request, model);

    String email = request.getParameter("email");
    if (StringUtils.isBlank(email)) {
        model.addAttribute("erroremail", true);
        return "behandlung/pwbnvergessen";
    } else {// w  w  w.  j  a v a  2  s  .  c om
        if (captcha) {
            try {
                User u = userService.findUserByEmail(email);
                if (u != null) {
                    try {

                        userService.resetCredientials(email, request.getServerName());
                        model.addAttribute("info", true);
                    } catch (Exception ex) {
                        model.addAttribute("error", true);
                    }
                } else {
                    model.addAttribute("erroremailunknown", true);
                }
            } catch (Exception ex) {
                model.addAttribute("erroremailunknown", true);
            }
        }
    }
    return "behandlung/pwbnvergessen";
}

From source file:be.fedict.eid.idp.protocol.openid.AbstractOpenIDProtocolService.java

private ServerManager getServerManager(HttpServletRequest request) {

    HttpSession httpSession = request.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    ServerManager serverManager = (ServerManager) servletContext.getAttribute(getServiceManagerAttribute());
    if (null != serverManager) {
        return serverManager;
    }/*from w w w  . j  ava  2  s  .co  m*/
    LOG.debug("creating an OpenID server manager");
    serverManager = new ServerManager();
    /*
     * Important that the shared association store and the private
     * association store are different. See also:
     * http://code.google.com/p/openid4java/source/detail?r=738
     */
    serverManager.setSharedAssociations(new InMemoryServerAssociationStore());
    serverManager.setPrivateAssociations(new InMemoryServerAssociationStore());
    String location = "https://" + request.getServerName();
    if (request.getServerPort() != 443) {
        location += ":" + request.getServerPort();
    }
    location += "/eid-idp";
    String opEndpointUrl = location + "/protocol/" + getPath();
    LOG.debug("OP endpoint URL: " + opEndpointUrl);
    serverManager.setOPEndpointUrl(opEndpointUrl);
    servletContext.setAttribute(getServiceManagerAttribute(), serverManager);
    return serverManager;
}

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

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.addDateHeader("Last-Modified", new Date().getTime());
    resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS);
    resp.addDateHeader("Expires", DateUtils.addMonths(new Date(), 1).getTime());
    boolean full = ClientUtils.toBoolean(req.getParameter(Constants.URL_PARAM_FULL));
    String topSpace = req.getParameter(Constants.URL_PARAM_TOP_SPACE);
    String urlHeight = req.getParameter(Constants.URL_PARAM_HEIGHT);

    String uuid = req.getParameter(Constants.URL_PARAM_UUID);

    if (uuid == null || "".equals(uuid)) {
        uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_SCANS_PREFIX)
                + Constants.SERVLET_SCANS_PREFIX.length() + 1);
    }//from w  w w. j  a v  a2 s.c o m

    StringBuffer baseUrl = new StringBuffer();
    baseUrl.append("http");
    if (req.getProtocol().toLowerCase().contains("https")) {
        baseUrl.append('s');
    }
    baseUrl.append("://");
    if (!URLS.LOCALHOST()) {
        baseUrl.append(req.getServerName());
    } else {
        String hostname = config.getHostname();
        if (hostname.contains("://")) {
            baseUrl.append(hostname.substring(hostname.indexOf("://") + "://".length()));
        } else {
            baseUrl.append(hostname);
        }
    }
    StringBuffer sb = new StringBuffer();
    if (topSpace != null) {
        String metadata = RESTHelper.convertStreamToString(
                RESTHelper.get(baseUrl + DJATOKA_URL_GET_METADATA + uuid, null, null, true));
        String height = null;
        height = metadata.substring(metadata.indexOf("ght\": \"") + 7, metadata.indexOf("\",\n\"dw"));
        String width = metadata.substring(metadata.indexOf("dth\": \"") + 7, metadata.indexOf("\",\n\"he"));

        int intHeight = Integer.parseInt(height);
        int intUrlHeight = Integer.parseInt(urlHeight);
        int intTopSpace = Integer.parseInt(topSpace);
        boolean isLower = intTopSpace > 0 && ((intHeight - intUrlHeight) < intTopSpace);
        String region = (isLower ? intHeight - intUrlHeight : (intTopSpace < 0 ? 0 : topSpace)) + ",1,"
                + urlHeight + "," + width;

        sb.append(baseUrl.toString()).append(DJATOKA_URL_FULL_PAGE_DETAIL).append(uuid)
                .append(DJATOKA_URL_REGION).append(region);

    } else {
        sb.append(baseUrl.toString())
                .append(full ? DJATOKA_URL_FULL_IMG : DJATOKA_URL + urlHeight + DJATOKA_URL_SUFFIX)
                .append(uuid);
    }
    resp.setContentType("image/jpeg");
    resp.sendRedirect(resp.encodeRedirectURL(sb.toString()));
}

From source file:it.cnr.icar.eric.client.ui.thin.RegistryBrowser.java

public void setStandardContextPath() {
    try {/*w w w  .j ava  2s.com*/
        HttpServletRequest request = ((HttpServletRequest) FacesContext.getCurrentInstance()
                .getExternalContext().getRequest());
        this.standardContextPath = new java.net.URL(request.getScheme(), request.getServerName(),
                request.getServerPort(), request.getContextPath());
    } catch (Exception ex) {
        log.error(WebUIResourceBundle.getInstance().getString("errorSettingStandardContext") + ex.getMessage());
    }
}