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:org.apache.cocoon.servlet.DebugFilter.java

/**
 * Log debug information about the current environment.
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *///  w  ww. ja  v  a2  s . c o  m
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
        throws IOException, ServletException {
    // we don't do debug msgs if this is not a http servlet request
    if (!(req instanceof HttpServletRequest)) {
        filterChain.doFilter(req, res);
        return;
    }
    try {
        ++activeRequestCount;
        final HttpServletRequest request = (HttpServletRequest) req;

        if (getLogger().isDebugEnabled()) {
            final StringBuffer msg = new StringBuffer();

            msg.append("DEBUGGING INFORMATION:").append(lineSeparator);
            msg.append("REQUEST: ").append(request.getRequestURI()).append(lineSeparator).append(lineSeparator);
            msg.append("CONTEXT PATH: ").append(request.getContextPath()).append(lineSeparator);
            msg.append("SERVLET PATH: ").append(request.getServletPath()).append(lineSeparator);
            msg.append("PATH INFO: ").append(request.getPathInfo()).append(lineSeparator).append(lineSeparator);

            msg.append("REMOTE HOST: ").append(request.getRemoteHost()).append(lineSeparator);
            msg.append("REMOTE ADDRESS: ").append(request.getRemoteAddr()).append(lineSeparator);
            msg.append("REMOTE USER: ").append(request.getRemoteUser()).append(lineSeparator);
            msg.append("REQUEST SESSION ID: ").append(request.getRequestedSessionId()).append(lineSeparator);
            msg.append("REQUEST PREFERRED LOCALE: ").append(request.getLocale().toString())
                    .append(lineSeparator);
            msg.append("SERVER HOST: ").append(request.getServerName()).append(lineSeparator);
            msg.append("SERVER PORT: ").append(request.getServerPort()).append(lineSeparator)
                    .append(lineSeparator);

            msg.append("METHOD: ").append(request.getMethod()).append(lineSeparator);
            msg.append("CONTENT LENGTH: ").append(request.getContentLength()).append(lineSeparator);
            msg.append("PROTOCOL: ").append(request.getProtocol()).append(lineSeparator);
            msg.append("SCHEME: ").append(request.getScheme()).append(lineSeparator);
            msg.append("AUTH TYPE: ").append(request.getAuthType()).append(lineSeparator).append(lineSeparator);
            msg.append("CURRENT ACTIVE REQUESTS: ").append(activeRequestCount).append(lineSeparator);

            // log all of the request parameters
            final Enumeration e = request.getParameterNames();

            msg.append("REQUEST PARAMETERS:").append(lineSeparator).append(lineSeparator);

            while (e.hasMoreElements()) {
                String p = (String) e.nextElement();

                msg.append("PARAM: '").append(p).append("' ").append("VALUES: '");
                String[] params = request.getParameterValues(p);
                for (int i = 0; i < params.length; i++) {
                    msg.append("[" + params[i] + "]");
                    if (i != (params.length - 1)) {
                        msg.append(", ");
                    }
                }

                msg.append("'").append(lineSeparator);
            }

            // log all of the header parameters
            final Enumeration e2 = request.getHeaderNames();

            msg.append("HEADER PARAMETERS:").append(lineSeparator).append(lineSeparator);

            while (e2.hasMoreElements()) {
                String p = (String) e2.nextElement();

                msg.append("PARAM: '").append(p).append("' ").append("VALUES: '");
                Enumeration e3 = request.getHeaders(p);
                while (e3.hasMoreElements()) {
                    msg.append("[" + e3.nextElement() + "]");
                    if (e3.hasMoreElements()) {
                        msg.append(", ");
                    }
                }

                msg.append("'").append(lineSeparator);
            }

            msg.append(lineSeparator).append("SESSION ATTRIBUTES:").append(lineSeparator).append(lineSeparator);

            // log all of the session attributes
            final HttpSession session = ((HttpServletRequest) req).getSession(false);
            if (session != null) {
                // Fix bug #12139: Session can be modified while still
                // being enumerated here
                synchronized (session) {
                    final Enumeration se = session.getAttributeNames();
                    while (se.hasMoreElements()) {
                        String p = (String) se.nextElement();
                        msg.append("PARAM: '").append(p).append("' ").append("VALUE: '")
                                .append(session.getAttribute(p)).append("'").append(lineSeparator);
                    }
                }
            }
            getLogger().debug(msg.toString());
        }

        // Delegate
        filterChain.doFilter(request, res);
    } finally {
        --activeRequestCount;
    }
}

From source file:org.castafiore.utils.ComponentUtil.java

public static void loadApplication(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    String applicationId = request.getParameter("casta_applicationid");
    String userIdentity = request.getParameter("casta_userid");
    String portalPath = request.getParameter("casta_portalpath");
    //Enumeration params = request.getParameterNames();
    //request.getp
    if (applicationId != null) {

        Application application = (Application) request.getSession().getAttribute(applicationId);
        boolean isNew = false;
        if (application == null && applicationId != null) {
            isNew = true;// ww  w.j  av  a2s. c o m

            //logger.debug("application :" + applicationId + " not found in session. Loading fresh application from registry");
            application = ApplicationRegistryUtil.getApplicationRegistry().getApplication(request, response);
            if (application == null) {
                //logger.error("there is no bean with name " + applicationId  + " configured in application registry");
                throw new ServletException(
                        "there is no bean with name " + applicationId + " configured in application registry");
            }
            if (!application.getName().equals(applicationId)) {
                //logger.error("The application Id configured in application-registry should be the same as the application name");
                throw new ServletException(
                        "The application Id configured in application-registry should be the same as the application name.");
            }

            //isnew = true;

        }
        Map para = request.getParameterMap();
        Iterator keys = para.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next().toString();
            String val = request.getParameter(key);
            application.getConfigContext().put(key, val);
        }
        application.getConfigContext().put("contextPath", ((HttpServletRequest) request).getContextPath());
        application.getConfigContext().put("serverName", request.getServerName());
        application.getConfigContext().put("serverPort", request.getServerPort());
        application.getConfigContext().put("session", request.getSession());
        application.getConfigContext().put("remoteAddress", request.getRemoteAddr());
        application.getConfigContext().put("sessionid", request.getSession().getId());
        application.getConfigContext().put("context", request.getSession());

        if (userIdentity != null) {
            application.getConfigContext().put("remoteUser", userIdentity);
        }
        if (portalPath != null) {
            application.getConfigContext().put("portalPath", portalPath);
        }
        CastafioreApplicationContextHolder.setApplicationContext(application);
        if (isNew) {
            application.refresh();
        }
        if (application instanceof WebServletAwareApplication) {
            ((WebServletAwareApplication) application).setRequest(request);
            ((WebServletAwareApplication) application).setResponse(response);

        }
    }
}

From source file:com.flexive.shared.FxContext.java

/**
 * Constructor//w ww  .  ja va 2s .  co  m
 *
 * @param request    the request
 * @param divisionId the division
 * @param isWebdav   true if this is an webdav request
 * @param forceSession
 */
private FxContext(HttpServletRequest request, int divisionId, boolean isWebdav, boolean forceSession) {
    final HttpSession session = request.getSession(forceSession);
    this.sessionID = session != null ? session.getId() : null;
    this.requestURI = request.getRequestURI();
    this.contextPath = request.getContextPath();
    this.serverName = request.getServerName();
    this.serverPort = request.getServerPort();
    this.requestUriNoContext = request.getRequestURI().substring(request.getContextPath().length());
    this.webDAV = isWebdav;
    if (this.webDAV) {
        // Cut away servlet path, eg. "/webdav/"
        this.requestUriNoContext = this.requestUriNoContext.substring(request.getServletPath().length());
    }
    this.globalAuthenticated = session != null && session.getAttribute(ADMIN_AUTHENTICATED) != null;
    //get the real remote host incase a proxy server is used
    String forwardedFor = request.getHeader("x-forwarded-for");
    if (forwardedFor != null && !StringUtils.isBlank(String.valueOf(forwardedFor))) {
        final int clientSplit = forwardedFor.indexOf(',');
        final String clientIp = clientSplit == -1 ? forwardedFor : forwardedFor.substring(0, clientSplit);
        this.remoteHost = clientIp.replace("[", "").replace("]", "");
    } else {
        this.remoteHost = request.getRemoteAddr();
    }
    this.division = divisionId;
    initFormatters();
}

From source file:com.viewer.controller.ViewerController.java

@RequestMapping(value = "/GetImageUrls", method = RequestMethod.POST, headers = {
        "Content-type=application/json" })
@ResponseBody/*from ww  w .j  a v a 2 s.  c  om*/

public GetImageUrlsResponse GetImageUrls(@RequestBody GetImageUrlsParameters parameters,
        HttpServletRequest request) throws Exception {

    try {

        if (com.viewer.model.helper.DotNetToJavaStringHelper.isNullOrEmpty(parameters.getPath())) {
            GetImageUrlsResponse empty = new GetImageUrlsResponse();
            empty.imageUrls = new String[0];
            return empty;
        }

        DocumentInfoOptions documentInfoOptions = new DocumentInfoOptions(parameters.getPath());
        DocumentInfoContainer documentInfoContainer = _imageHandler.getDocumentInfo(documentInfoOptions);

        int[] pageNumbers = new int[documentInfoContainer.getPages().size()];
        int count = 0;
        for (PageData page : documentInfoContainer.getPages()) {

            pageNumbers[count] = page.getNumber();
            count++;
        }

        String applicationHost = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort();
        String[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, parameters);

        GetImageUrlsResponse result = new GetImageUrlsResponse();
        result.imageUrls = imageUrls;
        return result;

    } catch (Exception e) {
        e.printStackTrace();
    }
    GetImageUrlsResponse test = null;
    return test;
}

From source file:org.cyk.ui.web.api.WebNavigationManager.java

public String url(String id, Object[] parameters, Boolean actionOutcome, Boolean partial, Boolean pretty) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    StringBuilder url = new StringBuilder();

    NavigationCase navigationCase = ((ConfigurableNavigationHandler) facesContext.getApplication()
            .getNavigationHandler()).getNavigationCase(facesContext, null, id);
    //System.out.println(id+" / "+navigationCase);
    if (navigationCase == null) {
        log.severe("No Navigation Case found for " + id);
        return url(OUTCOME_NOT_FOUND, new Object[] { "oc", id }, Boolean.FALSE, Boolean.FALSE);
    }/*from w  ww.j a  v a 2  s  .com*/
    String s = navigationCase.getToViewId(facesContext);
    if (Boolean.TRUE.equals(actionOutcome))
        url.append(s);
    else
        url.append(StringUtils.replace(s, FILE_STATIC_EXTENSION, FILE_PROCESSING_EXTENSION));

    if (Boolean.TRUE.equals(actionOutcome))
        navigationHelper.addParameter(url, QUERY_PARAMETER_FACES_REDIRECT_NAME, navigationCase.isRedirect());
    if (parameters != null && parameters.length > 0) {
        for (int i = 0; i < parameters.length - 1; i = i + 2)
            if (parameters[i + 1] == null)
                ;
            else
                navigationHelper.addParameter(url, /*(String)*/ parameters[i], parameters[i + 1]);
    }
    if (Boolean.TRUE.equals(partial))
        ;
    else {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                .getRequest();

        //FacesContext.getCurrentInstance().getExternalContext().encodeResourceURL() will trigger rewriting  

        //int countContextPath = StringUtils.countMatches(url, request.getContextPath());
        url = new StringBuilder(StringUtils.removeStartIgnoreCase(//TODO might not work always
                FacesContext.getCurrentInstance().getExternalContext().encodeResourceURL(url.toString()),
                request.getContextPath()));
        //if(StringUtils.countMatches(url, request.getContextPath())>countContextPath)

        url.insert(0, request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath());
    }

    return url.toString();
}

From source file:controller.FacebookServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from w  ww .j  av  a 2  s . 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 doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Integer offset = 0, limit = Integer.MAX_VALUE;
    if (request.getParameterMap().containsKey("offset")) {
        offset = Integer.valueOf(request.getParameter("offset"));
    }
    if (request.getParameterMap().containsKey("limit")) {
        limit = Integer.valueOf(request.getParameter("limit"));
    }
    System.out.println(offset + "   &&&   " + limit);
    String servletAddress = "http://" + request.getServerName() + ":" + request.getServerPort()
            + "/WebServiceFacebook/";
    //Requested URI
    String requestUri = URLDecoder.decode(request.getRequestURI(), "UTF-8");
    System.out.println("URI:" + requestUri);

    //Create FacebookDAO
    FacebookDAO dao = new FacebookDAO(servletAddress);

    //Parameters
    Integer idUser = RegexUtil.MatchUserId(requestUri);
    String userName = RegexUtil.MatchName(requestUri);
    Integer idUserFriends = RegexUtil.MatchUserFriends(requestUri);
    Integer idUserPosts = RegexUtil.MatchPostsOfUser(requestUri);
    Integer idUserPostsOfFriends = RegexUtil.MatchPostsOfFriends(requestUri);
    Integer idUserAlbuns = RegexUtil.MatchAlbunsOfUserId(requestUri);
    Integer idUserPhotos = RegexUtil.MatchPhotosOfUserId(requestUri);
    Integer idPostComments = RegexUtil.MatchPostIdComments(requestUri);
    Integer idPostLikes = RegexUtil.MatchLikesOfPost(requestUri);
    Integer idPostCountLikes = RegexUtil.MatchCountLikesOfPost(requestUri);
    Integer idPostComment = RegexUtil.MatchPostCommentById(requestUri);
    Integer idAlbumComment = RegexUtil.MatchAlbumCommentById(requestUri);
    Integer idPhotoComment = RegexUtil.MatchPhotoCommentById(requestUri);
    Integer idAlbumCommentLikes = RegexUtil.MatchLikesOfAlbumComment(requestUri);
    Integer idPhotoCommentLikes = RegexUtil.MatchLikesOfPhotoComment(requestUri);
    Integer idPostCommentLikes = RegexUtil.MatchLikesOfPostComment(requestUri);

    System.out.println("idPostsOfFriends:" + idUserPostsOfFriends + " -- UserId:" + idUser + " -- userName:"
            + userName + " -- friendOfUser:" + idUserFriends + " -- userOfPost:" + userName + " -- userOfPost:"
            + idUserPosts + " -- idUserAlbuns:" + idUserAlbuns + " -- idUserPhotos:" + idUserPhotos
            + " -- idPostComments:" + idPostComments);
    System.out.println("Friends of user:" + idUserFriends);
    if (idUser != null) {
        try {
            User u = dao.getUserById(idUser);
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(u);
            System.out.println("RESULTADO BUSCA:" + u);
            ServletUtil.writeJSON(response, json);
            System.out.println("User:" + u);
        } catch (FacebookDAOException ex) {
            throw new ServletException("Impossvel encontrar usurio com id = " + idUser + "!", ex);
        }
    } else if (userName != null) {
        try {
            List<User> u = dao.searchUsersByName(userName, offset, limit);
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(u);
            System.out.println("RESULTADO BUSCA:" + u);
            ServletUtil.writeJSON(response, json);
            System.out.println(u);
        } catch (FacebookDAOException ex) {
            throw new ServletException("Impossvel encontrar resultados com para \"" + userName + "\"!", ex);
        }

    } else if (idUserFriends != null) {
        try {
            List<User> users = dao.getFriendsOfUser(new User(idUserFriends, null, null, null), 0, 100);
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(users);
            for (User u : users) {
                System.out.println(u);
            }
            ServletUtil.writeJSON(response, json);

        } catch (FacebookDAOException ex) {
            throw new ServletException(
                    "Impossvel encontrar os amigos do usurio com id = " + idUserFriends + "!", ex);
        }
    } else if (idUserPosts != null) {
        System.out.println("######## LIST POSTS OF USER " + idUserPosts);
        try {
            List<Post> posts = dao.getAllPostsOfUser(new User(idUserPosts), offset, limit);
            System.out.println(posts);
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(posts);
            ServletUtil.writeJSON(response, json);

        } catch (FacebookDAOException ex) {
            throw new ServletException(
                    "Impossvel encontrar os posts do usurio de id = " + idUserPosts + "!", ex);
        }
    } else if (idUserPostsOfFriends != null) {
        List<Post> posts;
        try {
            posts = dao.getAllFriendsPostsOfUser(new User(idUserPostsOfFriends), offset, limit);
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(posts);
            ServletUtil.writeJSON(response, json);
        } catch (FacebookDAOException ex) {
            Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (idUserAlbuns != null) {
        try {
            User u = new User(idUserAlbuns);
            List<Album> albuns = dao.getAllAlbunsOfUser(u, offset, limit);
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(albuns);
            for (Album a : albuns) {
                System.out.println(a);
            }
            ServletUtil.writeJSON(response, json);

        } catch (FacebookDAOException ex) {
            throw new ServletException(
                    "Impossvel encontrar os lbuns do usurio de id = " + idUserAlbuns + "!", ex);
        }
    } else if (idUserPhotos != null) {
        try {
            User u = new User(idUserPhotos);
            List<Photo> photos = dao.getAllPhotosOfUser(u, offset, limit);
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(photos);
            ServletUtil.writeJSON(response, json);

        } catch (FacebookDAOException ex) {
            throw new ServletException(
                    "Impossvel encontrar as photos do usurio de id = " + idUserAlbuns + "!", ex);
        }
    } else if (idPostComments != null) {
        try {
            List<Comment> comments = dao.getAllCommentsOfPost(new Post(idPostComments), offset, limit);
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(comments);
            ServletUtil.writeJSON(response, json);
        } catch (FacebookDAOException ex) {
            throw new ServletException(
                    "Impossvel encontrar comentrios para o post de id = " + idPostComments + "!", ex);
        }
    } else if (idPostLikes != null) {
        List<User> users = null;
        try {
            users = dao.getListOfLikesPost(new Post(idPostLikes), offset, limit);

            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(users);
            ServletUtil.writeJSON(response, json);

        } catch (FacebookDAOException ex) {
            Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (idPostCountLikes != null) {
        try {
            Integer number = dao.getNumberOfLikesPost(new Post(idPostCountLikes));
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(number);
            ServletUtil.writeJSON(response, json);
        } catch (FacebookDAOException ex) {
            Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (idPostComment != null) {
        try {
            Comment comentario = dao.getCommentById(idPostComment, 1);
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(comentario);
            ServletUtil.writeJSON(response, json);
        } catch (FacebookDAOException ex) {
            Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (idAlbumComment != null) {
        try {
            Comment comentario = dao.getCommentById(idAlbumComment, 2);
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(comentario);
            ServletUtil.writeJSON(response, json);
        } catch (FacebookDAOException ex) {
            Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (idPhotoComment != null) {
        try {
            Comment comentario = dao.getCommentById(idPhotoComment, 3);
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(comentario);
            ServletUtil.writeJSON(response, json);
        } catch (FacebookDAOException ex) {
            Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (idAlbumCommentLikes != null) {
        List<User> usuario = null;
        try {
            usuario = dao.getListOfLikesComment(new AlbumComment(idAlbumCommentLikes));

            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(usuario);
            ServletUtil.writeJSON(response, json);

        } catch (FacebookDAOException ex) {
            Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (idPhotoCommentLikes != null) {
        List<User> usuario = null;
        try {
            usuario = dao.getListOfLikesComment(new PhotoComment(idPhotoCommentLikes));

            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(usuario);
            ServletUtil.writeJSON(response, json);

        } catch (FacebookDAOException ex) {
            Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    else if (idPostCommentLikes != null) {
        List<User> usuario = null;
        try {
            usuario = dao.getListOfLikesComment(new PostComment(idPostCommentLikes));

            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(usuario);
            ServletUtil.writeJSON(response, json);

        } catch (FacebookDAOException ex) {
            Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:de.appsolve.padelcampus.filter.LoginFilter.java

/**
 * @param request/*from  w  w w  .  ja v  a2s. co m*/
 * @param response
 * @param chain
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String requestURI = httpRequest.getRequestURI();
        for (Pattern pattern : NO_FILTER_LIST) {
            if (pattern.matcher(requestURI).matches()) {
                sessionUtil.setCustomer(httpRequest, null);
                chain.doFilter(request, response);
                return;
            }
        }

        CustomerI customer = sessionUtil.getCustomer(httpRequest);
        if (customer == null) {
            String hostHeader = httpRequest.getHeader("host");
            if (!StringUtils.isEmpty(hostHeader)) {
                String[] hostHeaderSplit = hostHeader.split(":");
                customer = customerDAO.findByDomainName(hostHeaderSplit[0]);
            }
            if (customer == null) {
                String url = "";
                String serverName = httpRequest.getServerName();
                if (!StringUtils.isEmpty(serverName)) {
                    String[] domainParts = serverName.split("\\.");
                    if (domainParts.length > 2) {
                        url = httpRequest.getScheme() + "://" + domainParts[domainParts.length - 2] + "."
                                + domainParts[domainParts.length - 1];
                        if (httpRequest.getScheme().equals("http") && httpRequest.getServerPort() != 80) {
                            url += ":" + httpRequest.getServerPort();
                        }
                    }
                }
                url += PATH_START_PAGE;
                httpResponse.setStatus(HttpStatus.PERMANENT_REDIRECT.value());
                httpResponse.sendRedirect(url);
                return;
            }
            sessionUtil.setCustomer(httpRequest, customer);
        }

        //login user in case of valid login cookie
        Player user = sessionUtil.getUser(httpRequest);
        if (user == null) {
            Cookie[] cookies = httpRequest.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName() != null && cookie.getName().equals(COOKIE_LOGIN_TOKEN)) {
                        String cookieValue = cookie.getValue();
                        if (StringUtils.isEmpty(cookieValue)) {
                            loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                        } else {
                            String[] cookieValueSplit = cookieValue.split(":");
                            if (cookieValueSplit.length != 2) {
                                loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                            } else {
                                String uuid = cookieValueSplit[0];
                                String loginCookieRandomValue = cookieValueSplit[1];
                                LoginCookie loginCookie = loginUtil.isValidLoginCookie(uuid,
                                        loginCookieRandomValue);
                                if (loginCookie == null) {
                                    loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                                } else {
                                    Player player = playerDAO.findByUUID(loginCookie.getPlayerUUID());
                                    if (player == null) {
                                        loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                                    } else {
                                        //log user in
                                        sessionUtil.setUser(httpRequest, player);

                                        //update loginCookieHash
                                        loginUtil.updateLoginCookie(httpRequest, httpResponse);
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }

        moduleUtil.initModules(httpRequest);
    }
    chain.doFilter(request, response);
}

From source file:ch.entwine.weblounge.dispatcher.impl.WebloungeDispatcherServlet.java

/**
 * {@inheritDoc}/* w w  w.  ja v  a 2s.c  om*/
 * 
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
protected void service(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws ServletException, IOException {

    // Return the instance name if available
    if (instanceName != null) {
        httpResponse.addHeader("X-Weblounge-Instance", instanceName);
    }

    if (sites == null) {
        httpResponse.sendError(SC_SERVICE_UNAVAILABLE);
        return;
    }

    logger.debug("Serving {}", httpRequest.getRequestURI());

    // Get the site dispatcher
    Site site = securityService.getSite();
    if (site == null) {
        site = getSiteByRequest(httpRequest);
        securityService.setSite(site);
    }

    boolean isSpecialRequest = StringUtils.isNotBlank(httpRequest.getHeader("X-Weblounge-Special"));

    // See if a site dispatcher was found, and if so, if it's enabled
    if (site == null) {
        String serverName = httpRequest.getScheme() + "://" + httpRequest.getServerName();
        if (httpRequest.getServerPort() != 80)
            serverName += ":" + httpRequest.getServerPort();
        if (!wellknownFiles.contains(httpRequest.getRequestURI())
                && !missingSiteWarnings.contains(serverName)) {
            missingSiteWarnings.add(serverName);
            logger.warn("No site found to handle {}", serverName);
        }
        httpResponse.sendError(SC_NOT_FOUND);
        return;
    } else if (!site.isOnline() && !isSpecialRequest) {
        if (site.getContentRepository() == null) {
            if (!missingRepositoryWarnings.contains(site.getIdentifier())) {
                logger.warn("No content repository connected to site '{}'", site);
                missingRepositoryWarnings.add(site.getIdentifier());
            } else {
                logger.debug("No content repository connected to site '{}'", site);
            }
        } else {
            logger.debug("Ignoring request for disabled site '{}'", site);
        }
        httpResponse.sendError(SC_SERVICE_UNAVAILABLE);
        return;
    }

    // Make sure the response is buffered
    httpResponse = new BufferedHttpServletResponse(httpResponse);

    // Get the servlet that is responsible for the site's content
    Servlet siteServlet = sites.getSiteServlet(site);

    // Get the response cache, if available
    ResponseCache cache = caches.get(site.getIdentifier());

    // Wrap for caching
    if (cache != null) {
        httpResponse = cache.createCacheableResponse(httpRequest, httpResponse);
    }

    // Wrap request and response
    WebloungeRequestImpl request = new WebloungeRequestImpl(httpRequest, siteServlet, environment);
    WebloungeResponseImpl response = new WebloungeResponseImpl(httpResponse);

    // Configure request and response objects
    request.init(site);
    response.setRequest(request);
    response.setResponseCache(cache);
    response.setCharacterEncoding(DEFAULT_RESPONSE_ENCODING);
    response.setHeader("X-Powered-By", POWERED_BY);
    response.setDateHeader("Date", Calendar.getInstance().getTimeInMillis());

    // Notify listeners about starting request
    fireRequestStarted(request, response, site);

    boolean requestServed = false;

    // Ask the registered request handler if they are willing to handle
    // the request.
    try {
        securityService.setSite(site);
        request.setUser(securityService.getUser());
        for (RequestHandler handler : requestHandler) {
            try {
                logger.trace("Asking {} to serve {}", handler, request);
                if (handler.service(request, response)) {
                    requestServed = true;
                    logger.debug("{} served request {}", handler, request);
                    if (response.hasError()) {
                        logger.debug("Request processing failed on {}", request);
                        fireRequestFailed(request, response, site);
                    } else {
                        fireRequestDelivered(request, response, site);
                    }
                    return;
                }
            } catch (Throwable t) {
                response.invalidate();
                String params = RequestUtils.dumpParameters(request);
                if (t.getCause() != null) {
                    t = t.getCause();
                }
                logger.error("Request handler '{}' failed to handle {} {}",
                        new Object[] { handler, request, params });
                logger.error(t.getMessage(), t);
                DispatchUtils.sendInternalError(t.getMessage(), request, response);
                break;
            }
        }
    } finally {
        securityService.setSite(null);
        if (requestServed) {
            response.endResponse();
            response.flushBuffer();
            logger.debug("Finished processing of {}", httpRequest.getRequestURI());
        } else {
            logger.debug("No handler found for {}", request);
            DispatchUtils.sendNotFound(request, response);
            if (cache != null)
                cache.invalidate(response);
            fireRequestFailed(request, response, site);
        }
    }
}

From source file:com.provenance.cloudprovenance.policyhandler.ws.controler.PolicyRequestHandler.java

@Override
@POST//from  www .ja  v a  2  s.c  o m
@Path(value = "/{serviceId}")
public Response policyRequest(@PathParam("serviceId") String serviceId, @Context HttpServletRequest request) {

    boolean outcome = false;
    String constructFileName, environmentId, response, responseURI, responseContent, policyRequestMsg;
    String[] policyToSelect;

    try {
        constructFileName = requestFileNamePrefix + counter + "." + fileNameSuffix;
        policyRequestMsg = getBody(request);

        // Store the request to the policy traceability (in traceability
        // store)
        outcome = policyTraceability.createRequestInstance(serviceId, traceabilityType, constructFileName,
                policyRequestMsg);
        logger.info("Saved policy request to the policy traceability store");

        // Call the policy controller to validate the policy, remove
        // namespace
        environmentId = (preqProcessor.getIdforPolicyMatch(policyRequestMsg, xpathToEnvironmentId))
                .split(":")[1];

        logger.info("The environment id to match a policy is: " + environmentId);

        policyToSelect = requestPolicyMappingMap.get(environmentId);
        logger.info("policy id is: " + policyToSelect[0]);

        response = preqProcessor.executePolicyRequest(serviceId, policyRequestMsg, policyToSelect, request);
        logger.info("policy execution response: " + response);

        responseURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getRequestURI() + "/" + responseFileNamePrefix + counter;

        // TODO - process the response store in in the hashmap
        responseContent = policyResponseGen.genPolicyIdResponse(serviceId, requestFileNamePrefix + counter,
                responseFileNamePrefix + counter, responseURI);

        logger.info("Storing response in a map: Key=> " + (responseFileNamePrefix + counter));

        // Store the response to the HashTable
        policyResponseMap.put((responseFileNamePrefix + counter), response);

        if (response != null) {
            ResponseBuilder rBuilder = Response.status(201);
            rBuilder.entity(responseContent);
            return rBuilder.build();
        } else {
            ResponseBuilder rBuilder = Response.status(400);
            return rBuilder.build();
        }
    } catch (Exception e) {
        e.printStackTrace();
        ResponseBuilder rBuilder = Response.status(500);
        return rBuilder.build();

    }
}

From source file:de.uni_koeln.spinfo.maalr.webapp.controller.WebMVCController.java

@RequestMapping(value = "/persona/login", method = RequestMethod.POST)
@ResponseBody/*  w ww. j  a va2 s. c  o m*/
public String authenticateWithPersona(@RequestParam String assertion, HttpServletRequest request, Model model)
        throws IOException {

    String contextPath = Configuration.getInstance().getDictContext();

    if (SecurityContextHolder.getContext().getAuthentication() != null) {
        if (!SecurityContextHolder.getContext().getAuthentication().getName().equals("anonymousUser")) {
            Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext()
                    .getAuthentication().getAuthorities();
            for (GrantedAuthority grantedAuthority : authorities) {
                logger.info("GrantedAuthority: " + grantedAuthority.getAuthority());
                if (grantedAuthority.getAuthority().equals("ROLE_ADMIN"))
                    return contextPath + "/admin/admin";
                if (grantedAuthority.getAuthority().equals("ROLE_TRUSTED_IN"))
                    return contextPath + "/editor/editor";
                return contextPath;
            }
        }
    }

    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("assertion", assertion);
    params.add("audience", request.getScheme() + "://" + request.getServerName() + ":"
            + (request.getServerPort() == 80 ? "" : request.getServerPort()));

    // Initialize RestTamplate
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

    PersonaVerificationResponse response = restTemplate.postForObject(
            "https://verifier.login.persona.org/verify", params, PersonaVerificationResponse.class);

    logger.info("PersonaAuth: PersonaVerificationResponse={}", response.toString());

    if (response.getStatus().equals("okay")) {
        request.getSession().setMaxInactiveInterval(30 * 60); // Set session timeout to 30 minutes
        MaalrUserInfo user = users.getByEmail(response.getEmail());
        if (user == null) {
            user = register(response);
            logger.info("PersonaAuth: signed up new user for email={}", user.getEmail());
            authUser(user);
            return contextPath;
        } else {
            logger.info("PersonaAuth: user found by email={}", user.getEmail());
            authUser(user);
            return contextPath;
        }
    } else {
        logger.warn("Persona authentication failed due to reason: " + response.getReason());
        throw new IllegalStateException("Authentication failed");
    }
}