List of usage examples for javax.servlet.http HttpServletRequest getScheme
public String getScheme();
From source file:org.apache.atlas.web.filters.AtlasKnoxSSOAuthenticationFilter.java
/** * Create the URL to be used for authentication of the user in the absence * of a JWT token within the incoming request. * * @param request for getting the original request URL * @return url to use as login url for redirect *///ww w . j ava 2s . c om protected String constructLoginURL(HttpServletRequest request, boolean isXMLRequest) { String delimiter = "?"; if (authenticationProviderUrl.contains("?")) { delimiter = "&"; } StringBuilder loginURL = new StringBuilder(); if (isXMLRequest) { String atlasApplicationURL = ""; String referalURL = request.getHeader("referer"); if (referalURL == null) { atlasApplicationURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); } else { atlasApplicationURL = referalURL; } loginURL.append(authenticationProviderUrl).append(delimiter).append(originalUrlQueryParam).append("=") .append(atlasApplicationURL); } else { loginURL.append(authenticationProviderUrl).append(delimiter).append(originalUrlQueryParam).append("=") .append(request.getRequestURL().append(getOriginalQueryString(request))); } return loginURL.toString(); }
From source file:com.greenline.guahao.web.module.common.exception.PortalExceptionResolver.java
@Override public ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {//from w ww .j av a2s .c om logger.error("url=" + (request.getServerName() + CommonUtils.getBeforeRepath(request))); // ? ModelAndView mv = super.doResolveException(request, response, handler, ex); mv.setViewName(domainFilter.getAuthorization(request).getErrorViewName(request, response)); response.setStatus(HttpServletResponse.SC_OK); String servername = (String) request.getAttribute("servername"); if (StringUtils.isNotBlank(servername)) { // ???url 0 1? String domain_showurl = (String) request.getAttribute("domain_showurl"); if (StringUtils.isNotBlank(domain_showurl) && "0".equals(domain_showurl)) { String domainservername = request.getScheme() + "://" + servername + CommonUtils.getServerPort(request); mv.getModelMap().put("guahaoServer", domainservername); } } return mv; }
From source file:com.worldsmostinterestinginfographic.servlet.CallbackServlet.java
/** * Servlet to handle initial callback in response to an authorization request. * * Will check for the presence of an authorization code. If present, will attempt to make an access token request * using the authorization code. This is all done in accordance with the authorization code grant workflow in the * OAuth 2 specification [RFC 6749]. If no authorization code is detected, the authorization code is expired, or any * other errors occur, the user will be sent to an error page. * * @param request The HTTP request sent by the client * @param response The HTTP response that the server will send back to the client * * @see <a href="https://tools.ietf.org/html/rfc6749">RFC 6749 - The OAuth 2.0 Authorization Framework</a> *//*w w w .j a va2s .c om*/ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check for the presence of an authorization code String authorizationCode = request.getParameter("code"); if (!StringUtils.isEmpty(authorizationCode)) { // Get access token log.info("[" + request.getSession().getId() + "] Starting session. Requesting access token with authorization code " + LoggingUtils.anonymize(authorizationCode)); String tokenEndpoint = Model.TOKEN_ENDPOINT + "?grant_type=authorization_code&code=" + authorizationCode + "&redirect_uri=" + URLEncoder.encode( (request.getScheme() + "://" + request.getServerName() + Model.REDIRECTION_ENDPOINT), StandardCharsets.UTF_8.name()) + "&client_id=" + Model.CLIENT_ID + "&client_secret=" + Model.CLIENT_SECRET; String accessToken = OAuth2Utils.requestAccessToken(tokenEndpoint); if (StringUtils.isEmpty(accessToken)) { response.sendRedirect("/uh-oh"); return; } // Get profile data log.info("[" + request.getSession().getId() + "] Access token " + LoggingUtils.anonymize(accessToken) + " received. Requesting profile data."); User user = facebookService.getProfile(accessToken); if (user == null) { response.sendRedirect("/uh-oh"); return; } // Here we go log.info("[" + request.getSession().getId() + "] Hello, " + LoggingUtils.anonymize(Objects.toString(user.getId())) + "!"); Model.cache.put(request.getSession().getId() + ".profile", user); Model.cache.put(request.getSession().getId() + ".token", accessToken); response.sendRedirect("/you-rock"); } else if (request.getParameter("error") != null) { // An error happened during authorization code request String error = request.getParameter("error"); String errorDescription = request.getParameter("error_description"); request.getSession().setAttribute("error", error); request.getSession().setAttribute("errorDescription", errorDescription); log.severe("[" + request.getSession().getId() + "] Error encountered during authorization code request: " + error + " - " + errorDescription); response.sendRedirect("/uh-oh"); } else { log.warning("[" + request.getSession().getId() + "] No authorization code or error message detected at redirection endpoint"); response.sendRedirect("/uh-oh"); } }
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarCreateNewAccountHtml.java
protected void sendConfirmationEMail(HttpServletRequest request, ICFSecuritySecUserObj confirmUser, ICFSecurityClusterObj cluster) throws IOException, MessagingException, NamingException { final String S_ProcName = "sendConfirmationEMail"; Properties props = System.getProperties(); String clusterDescription = cluster.getRequiredDescription(); String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI().toString(); int lastSlash = thisURI.lastIndexOf('/'); String baseURI = thisURI.substring(0, lastSlash); UUID confirmationUUID = confirmUser.getOptionalEMailConfirmationUuid(); String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n" + "<p>\n" + "You requested a new account for login " + confirmUser.getRequiredLoginId() + " with " + clusterDescription + ".\n" + "<p>" + "Please click on the following link to confirm your email address:<br>\n" + "<A HRef=\"" + baseURI + "/CFAsteriskSMWarConfirmEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "\">" + baseURI + "/CFAsteriskSMWarConfirmEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "</A>\n" + "<p>" + "Or click on the following link to cancel the request for a new account:<br>\n" + "<A HRef=\"" + baseURI + "/CFAsteriskSMWarCancelEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "\">" + baseURI + "/CFAsteriskSMWarCancelEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "</A>\n" + "</BODY>\n" + "</HTML>\n"; CFAsteriskSMWarUtil warUtil = new CFAsteriskSMWarUtil(); warUtil.sendEMailToUser(confirmUser, "You requested an account with " + clusterDescription + "?", msgBody); }
From source file:gal.udc.fic.muei.tfm.dap.flipper.web.rest.AccountResource.java
/** * POST /register -> register the user. *//*from w w w.j a va 2 s.c o m*/ @RequestMapping(value = "/register", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE) @Timed public ResponseEntity<?> registerAccount(@Valid @RequestBody UserDTO userDTO, HttpServletRequest request) { return userRepository.findOneByLogin(userDTO.getLogin()) .map(user -> new ResponseEntity<>("login already in use", HttpStatus.BAD_REQUEST)) .orElseGet(() -> userRepository.findOneByEmail(userDTO.getEmail()) .map(user -> new ResponseEntity<>("e-mail address already in use", HttpStatus.BAD_REQUEST)) .orElseGet(() -> { User user = userService.createUserInformation(userDTO.getLogin(), userDTO.getPassword(), userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail().toLowerCase(), userDTO.getLangKey()); String baseUrl = request.getScheme() + // "http" "://" + // "://" request.getServerName() + // "myhost" ":" + // ":" request.getServerPort(); // "80" mailService.sendActivationEmail(user, baseUrl); return new ResponseEntity<>(HttpStatus.CREATED); })); }
From source file:eu.supersede.fe.rest.NotificationRest.java
@RequestMapping("") public List<Notification> getByUserId(Authentication authentication, HttpServletRequest request, @RequestParam(defaultValue = "true") Boolean toRead) { String scheme;/*w ww.ja va2 s .c o m*/ String host; String port; if (request.getHeader("x-forwarded-proto") != null || request.getHeader("x-forwarded-host") != null || request.getHeader("x-forwarded-port") != null) { scheme = request.getHeader("x-forwarded-proto") != null ? request.getHeader("x-forwarded-proto") : "http"; host = request.getHeader("x-forwarded-host") != null ? request.getHeader("x-forwarded-host") : request.getServerName(); port = request.getHeader("x-forwarded-port") != null ? request.getHeader("x-forwarded-port") : null; } else { scheme = request.getScheme(); host = request.getServerName(); port = new Integer(request.getServerPort()).toString(); } String baseUrl = port != null ? scheme + "://" + host + ":" + port + "/#/" : scheme + "://" + host + "/#/"; DatabaseUser currentUser = (DatabaseUser) authentication.getPrincipal(); User u = users.getOne(currentUser.getUserId()); List<Notification> ns; if (toRead) { ns = notifications.findByUserAndReadOrderByCreationTimeDesc(u, !toRead); } else { ns = notifications.findByUserOrderByCreationTimeDesc(u); } for (Notification n : ns) { if (n.getLink() != null && !n.getLink().equals("")) { try { URI uri = new URI(n.getLink()); if (!uri.isAbsolute()) { n.setLink(baseUrl + n.getLink()); } } catch (URISyntaxException e) { log.debug("Error inside link: " + e.getMessage()); } } } return ns; }
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarCreateNewAccountHtml.java
protected void sendConfirmationEMail(HttpServletRequest request, ICFAstSecUserObj confirmUser, ICFAstClusterObj cluster) throws IOException, MessagingException, NamingException { final String S_ProcName = "sendConfirmationEMail"; Properties props = System.getProperties(); String clusterDescription = cluster.getRequiredDescription(); String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI().toString(); int lastSlash = thisURI.lastIndexOf('/'); String baseURI = thisURI.substring(0, lastSlash); UUID confirmationUUID = confirmUser.getOptionalEMailConfirmationUuid(); String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n" + "<p>\n" + "You requested a new account for login " + confirmUser.getRequiredLoginId() + " with " + clusterDescription + ".\n" + "<p>" + "Please click on the following link to confirm your email address:<br>\n" + "<A HRef=\"" + baseURI + "/CFAstSMWarConfirmEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "\">" + baseURI + "/CFAstSMWarConfirmEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "</A>\n" + "<p>" + "Or click on the following link to cancel the request for a new account:<br>\n" + "<A HRef=\"" + baseURI + "/CFAstSMWarCancelEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "\">" + baseURI + "/CFAstSMWarCancelEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "</A>\n" + "</BODY>\n" + "</HTML>\n"; CFAstSMWarUtil warUtil = new CFAstSMWarUtil(); warUtil.sendEMailToUser(confirmUser, "You requested an account with " + clusterDescription + "?", msgBody); }
From source file:de.thm.arsnova.controller.LoginController.java
@RequestMapping(value = { "/auth/dialog" }, method = RequestMethod.GET) @ResponseBody//from w ww .j a va 2s . com public View dialog(@RequestParam("type") final String type, @RequestParam(value = "successurl", defaultValue = "/") String successUrl, @RequestParam(value = "failureurl", defaultValue = "/") String failureUrl, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { View result = null; /* Use URLs from a request parameters for redirection as long as the * URL is not absolute (to prevent abuse of the redirection). */ if (UrlUtils.isAbsoluteUrl(successUrl)) { successUrl = "/"; } if (UrlUtils.isAbsoluteUrl(failureUrl)) { failureUrl = "/"; } String serverUrl = request.getScheme() + "://" + request.getServerName(); /* Handle proxy * TODO: It might be better, to support the proposed standard: http://tools.ietf.org/html/rfc7239 */ int port = "".equals(request.getHeader("X-Forwarded-Port")) ? Integer.valueOf(request.getHeader("X-Forwarded-Port")) : request.getServerPort(); if ("https".equals(request.getScheme())) { if (443 != port) { serverUrl = serverUrl + ":" + String.valueOf(port); } } else { if (80 != port) { serverUrl = serverUrl + ":" + String.valueOf(port); } } request.getSession().setAttribute("ars-login-success-url", serverUrl + successUrl); request.getSession().setAttribute("ars-login-failure-url", serverUrl + failureUrl); if ("cas".equals(type)) { casEntryPoint.commence(request, response, null); } else if ("twitter".equals(type)) { final String authUrl = twitterProvider.getAuthorizationUrl(new HttpUserSession(request)); result = new RedirectView(authUrl); } else if ("facebook".equals(type)) { facebookProvider.setFields("id,link"); facebookProvider.setScope(""); final String authUrl = facebookProvider.getAuthorizationUrl(new HttpUserSession(request)); result = new RedirectView(authUrl); } else if ("google".equals(type)) { final String authUrl = googleProvider.getAuthorizationUrl(new HttpUserSession(request)); result = new RedirectView(authUrl); } return result; }
From source file:org.eclipse.orion.internal.server.hosting.HostedStatusDecorator.java
/** * Adds status field to a representation of a site configuration. * @param siteConfigJson The JSONObject representing a single site configuration. * @param user The user making the request. * @param resource The original request passed to the decorator. *//*from w w w . j a v a 2 s . c om*/ private void addStatus(HttpServletRequest req, JSONObject siteConfigJson, UserInfo user, URI resource) throws JSONException { String id = siteConfigJson.getString(ProtocolConstants.KEY_ID); SiteInfo siteConfiguration = SiteInfo.getSite(user, id); if (siteConfiguration == null) return; IHostedSite site = HostingActivator.getDefault().getHostingService().get(siteConfiguration, user); JSONObject hostingStatus = new JSONObject(); if (site != null) { hostingStatus.put(SiteConfigurationConstants.KEY_HOSTING_STATUS_STATUS, "started"); //$NON-NLS-1$ String portSuffix = ":" + req.getLocalPort(); //$NON-NLS-1$ // Whatever scheme was used to access the resource, assume it's used for the sites too // Hosted site also shares same contextPath String hostedUrl = req.getScheme() + "://" + site.getHost() + portSuffix + req.getContextPath(); //$NON-NLS-1$ hostingStatus.put(SiteConfigurationConstants.KEY_HOSTING_STATUS_URL, hostedUrl); } else { hostingStatus.put(SiteConfigurationConstants.KEY_HOSTING_STATUS_STATUS, "stopped"); //$NON-NLS-1$ } siteConfigJson.put(SiteConfigurationConstants.KEY_HOSTING_STATUS, hostingStatus); }
From source file:com.netflix.genie.web.controllers.JobRestControllerUnitTests.java
/** * Make sure directory forwarding happens when all conditions are met. * * @throws IOException on error//from w w w.j a v a 2 s . c o m * @throws ServletException on error * @throws GenieException on error */ @Test public void canHandleForwardJobOutputRequestWithError() throws IOException, ServletException, GenieException { this.jobsProperties.getForwarding().setEnabled(true); final String jobId = UUID.randomUUID().toString(); final String forwardedFrom = null; final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.doNothing().when(this.genieResourceHttpRequestHandler).handleRequest(request, response); final String jobHostName = UUID.randomUUID().toString(); Mockito.when(this.jobSearchService.getJobHost(jobId)).thenReturn(jobHostName); //Mock parts of the http request final String http = "http"; Mockito.when(request.getScheme()).thenReturn(http); final int port = 8080; Mockito.when(request.getServerPort()).thenReturn(port); final String requestURI = "/" + jobId + "/" + UUID.randomUUID().toString(); Mockito.when(request.getRequestURI()).thenReturn(requestURI); Mockito.when(request.getHeaderNames()).thenReturn(null); final String requestUrl = UUID.randomUUID().toString(); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(requestUrl)); final int errorCode = 404; Mockito.when(this.restTemplate.execute(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString())) .thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)); this.controller.getJobOutput(jobId, forwardedFrom, request, response); Mockito.verify(this.jobSearchService, Mockito.times(1)).getJobHost(Mockito.eq(jobId)); Mockito.verify(this.restTemplate, Mockito.times(1)).execute(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString()); Mockito.verify(response, Mockito.times(1)).sendError(Mockito.eq(errorCode), Mockito.anyString()); Mockito.verify(this.genieResourceHttpRequestHandler, Mockito.never()).handleRequest(request, response); }