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:grails.plugin.springsecurity.web.access.AjaxAwareAccessDeniedHandler.java

public void handle(final HttpServletRequest request, final HttpServletResponse response,
        final AccessDeniedException e) throws IOException, ServletException {

    if (e != null && isLoggedIn() && authenticationTrustResolver.isRememberMe(getAuthentication())) {
        // user has a cookie but is getting bounced because of IS_AUTHENTICATED_FULLY,
        // so Spring Security won't save the original request
        requestCache.saveRequest(request, response);
    }//from   w  w  w  .j a  v  a 2  s.co  m

    if (response.isCommitted()) {
        return;
    }

    boolean ajaxError = ajaxErrorPage != null && SpringSecurityUtils.isAjax(request);
    if (errorPage == null && !ajaxError) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
        return;
    }

    if (useForward && (errorPage != null || ajaxError)) {
        // Put exception into request scope (perhaps of use to a view)
        request.setAttribute(WebAttributes.ACCESS_DENIED_403, e);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        request.getRequestDispatcher(ajaxError ? ajaxErrorPage : errorPage).forward(request, response);
        return;
    }

    String redirectUrl;
    String serverURL = ReflectionUtils.getGrailsServerURL();
    if (serverURL == null) {
        boolean includePort = true;
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = portResolver.getServerPort(request);
        String contextPath = request.getContextPath();
        boolean inHttp = "http".equals(scheme.toLowerCase());
        boolean inHttps = "https".equals(scheme.toLowerCase());

        if (inHttp && (serverPort == 80)) {
            includePort = false;
        } else if (inHttps && (serverPort == 443)) {
            includePort = false;
        }
        redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath;
    } else {
        redirectUrl = serverURL;
    }

    if (ajaxError) {
        redirectUrl += ajaxErrorPage;
    } else if (errorPage != null) {
        redirectUrl += errorPage;
    }
    response.sendRedirect(response.encodeRedirectURL(redirectUrl));
}

From source file:com.pagecrumb.proxy.ProxyServlet.java

@SuppressWarnings("unchecked")
protected void handleRequest(HttpServletRequest req, HttpServletResponse resp, boolean isPost)
        throws ServletException, IOException {

    log.info("contextPath=" + req.getContextPath());

    // Setup the headless browser
    WebClient webClient = new WebClient();

    webClient.setWebConnection(new UrlFetchWebConnection(webClient));

    HttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); // GAE constraint 

    // Originally, the design was to use HttpClient to execute methods
    // Now, it uses WebClient
    ClientConnectionManager connectionManager = new GAEConnectionManager();
    HttpClient httpclient = new DefaultHttpClient(connectionManager, httpParams);

    StringBuffer sb = new StringBuffer();

    log.info(getClass().toString() + " " + "URI Component=" + req.getRequestURI());
    log.info(getClass().toString() + " " + "URL Component=" + req.getRequestURL());

    if (req.getQueryString() != null) {
        //sb.append("?" + req.getQueryString());

        String s1 = Util.decodeURIComponent(req.getQueryString());
        log.info(getClass().toString() + " " + "QueryString=" + req.getQueryString());

        target = req.getQueryString();/*from w w  w . ja  va  2 s  .c om*/
        int port = req.getServerPort();
        String domain = req.getServerName();

        URL url = new URL(SCHEME, domain, port, target);
        /*
        HtmlPage page = webClient.getPage(target);
                
        //gae hack because its single threaded
         webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME);
                 
         pageString = page.asXml();
        */
    }

    sb.append(target);

    log.info(getClass().toString() + " " + "sb=" + sb.toString());

    HttpRequestBase targetRequest = null;

    if (isPost) {
        HttpPost post = new HttpPost(sb.toString());

        Enumeration<String> paramNames = req.getParameterNames();

        String paramName = null;

        List<NameValuePair> params = new ArrayList<NameValuePair>();

        while (paramNames.hasMoreElements()) {
            paramName = paramNames.nextElement();
            params.add(new BasicNameValuePair(paramName, req.getParameterValues(paramName)[0]));
        }

        post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        targetRequest = post;
    } else {
        HttpGet get = new HttpGet(sb.toString());
        targetRequest = get;
    }

    //        log.info("Request Headers");
    //        Enumeration<String> headerNames = req.getHeaderNames();
    //        String headerName = null;
    //        while(headerNames.hasMoreElements()){
    //            headerName = headerNames.nextElement();
    //            targetRequest.addHeader(headerName, req.getHeader(headerName));
    //            log.info(headerName + " : " + req.getHeader(headerName));
    //        }

    HttpResponse targetResponse = httpclient.execute(targetRequest);
    HttpEntity entity = targetResponse.getEntity();

    // Send the Response
    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
    String line = reader.readLine();

    /*
     * To use the HttpClient instead the HtmlUnit's WebClient:
     */
    while (line != null) {
        writer.write(line + "\n");
        line = reader.readLine();
    }

    //        Scanner scanner = new Scanner(pageString);
    //        while (scanner.hasNextLine()) {
    //          String s = scanner.nextLine();
    //          writer.write(s + "\n");
    //        }
    if (webClient != null) {
        webClient.closeAllWindows();
    }

    reader.close();
    writer.close();

    httpclient.getConnectionManager().shutdown();
}

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

/**
 * {@inheritDoc}/*from  w ww. j a  v  a2 s  .c  o m*/
 * 
 * @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:controller.FacebookServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/* w  w w  .j  a v  a  2 s .  co m*/
 * @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:org.openmrs.module.owa.web.controller.OwaRestController.java

@RequestMapping(value = "/rest/owa/addapp", method = RequestMethod.POST)
@ResponseBody//  ww w.  j a  va2s .c  o  m
public List<App> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    List<App> appList = new ArrayList<>();
    if (Context.hasPrivilege("Manage OWA")) {
        String message;
        HttpSession session = request.getSession();
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            File uploadedFile = new File(file.getOriginalFilename());
            file.transferTo(uploadedFile);
            try (ZipFile zip = new ZipFile(uploadedFile)) {
                if (zip.size() == 0) {
                    message = messageSourceService.getMessage("owa.blank_zip");
                    log.warn("Zip file is empty");
                    session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                    response.sendError(500, message);
                } else {
                    ZipEntry entry = zip.getEntry("manifest.webapp");
                    if (entry == null) {
                        message = messageSourceService.getMessage("owa.manifest_not_found");
                        log.warn("Manifest file could not be found in app");
                        uploadedFile.delete();
                        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                        response.sendError(500, message);
                    } else {
                        String contextPath = request.getScheme() + "://" + request.getServerName() + ":"
                                + request.getServerPort() + request.getContextPath();
                        appManager.installApp(uploadedFile, fileName, contextPath);
                        message = messageSourceService.getMessage("owa.app_installed");
                        session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, message);
                    }
                }
            } catch (Exception e) {
                message = messageSourceService.getMessage("owa.not_a_zip");
                log.warn("App is not a zip archive");
                uploadedFile.delete();
                session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                response.sendError(500, message);
            }
        }
        appManager.reloadApps();
        appList = appManager.getApps();
    }
    return appList;
}

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

@RequestMapping(value = "/persona/login", method = RequestMethod.POST)
@ResponseBody//w  w w .j ava 2  s  .  c om
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");
    }
}

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

@Override
@POST//from  ww  w  . j  a 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:com.janrain.backplane2.server.Backplane2Controller.java

/**
 * Authenticates a bus owner and stores the authenticated session (cookie) to simpleDB.
 *
 * GET: displays authentication form/*from   w w  w .  j  a  va  2 s .  c o m*/
 * POST: processes authentication and returns to /authorize
 */
@RequestMapping(value = "/authenticate", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView authenticate(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(required = false) String busOwner, @RequestParam(required = false) String password)
        throws AuthException, BackplaneServerException {

    ServletUtil.checkSecure(request);

    String httpMethod = request.getMethod();
    if ("GET".equals(httpMethod)) {
        logger.debug("returning view for GET");
        return new ModelAndView(BUS_OWNER_AUTH_FORM_JSP);
    } else if ("POST".equals(httpMethod)) {
        checkBusOwnerAuth(busOwner, password);
        persistAuthenticatedSession(response, busOwner);
        return new ModelAndView("redirect:https://" + request.getServerName() + "/v2/authorize");
    } else {
        throw new InvalidRequestException("Unsupported method for /authenticate: " + httpMethod);
    }
}

From source file:org.openmhealth.reference.servlet.Version1.java

/**
 * Builds the base URL for the request that came in. This is everything up
 * to our web applications base, e.g. "http://localhost:8080/omh".
 * /*w  ww. j  a  va 2s.  com*/
 * @param httpRequest
 *        The original HTTP request.
 * 
 * @return The base URL for the request.
 */
private String buildRootUrl(final HttpServletRequest httpRequest) {
    // It must be a HTTP request.
    StringBuilder builder = new StringBuilder("http");

    // If security was used add the "s" to make it "https".
    if (httpRequest.isSecure()) {
        builder.append('s');
    }

    // Add the protocol separator.
    builder.append("://");

    // Add the name of the server where the request was sent.
    builder.append(httpRequest.getServerName());

    // Add the port separator and the port.
    builder.append(':').append(httpRequest.getServerPort());

    // Add the context path, e.g. "/omh".
    builder.append(httpRequest.getContextPath());

    // Return the root URL.
    return builder.toString();
}