List of usage examples for javax.servlet.http HttpServletRequest getRequestURL
public StringBuffer getRequestURL();
From source file:com.envision.envservice.filter.RedmineFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Content-Type", "application/json; charset=utf-8"); String requestType = request.getMethod(); String url = ""; String api_key = ""; String param = ""; String result = ""; if (requestType == "GET" || "GET".equals(requestType)) { url = getRedmineUrl(request.getRequestURL().toString()); api_key = getSessionApiKey(request); if (api_key == null || "".equals(api_key)) { return; }//from w w w. j a va 2 s. c om WebApplicationContext webAppContext = ContextLoader.getCurrentWebApplicationContext(); RedmineHttpRequestService redmineHttpRequestService = (RedmineHttpRequestService) webAppContext .getBean("redmineHttpRequestService"); result = redmineHttpRequestService.doGET(url, api_key); } else if (requestType == "POST" || "POST".equals(requestType)) { url = getRedmineUrl(request.getRequestURL().toString()); api_key = getSessionApiKey(request); if (api_key == null || "".equals(api_key)) { return; } param = getParam(request.getInputStream()); WebApplicationContext webAppContext = ContextLoader.getCurrentWebApplicationContext(); RedmineHttpRequestService redmineHttpRequestService = (RedmineHttpRequestService) webAppContext .getBean("redmineHttpRequestService"); result = redmineHttpRequestService.doPost(url, param, api_key); } else if (requestType == "PUT" || "PUT".equals(requestType)) { url = getRedmineUrl(request.getRequestURL().toString()); api_key = getSessionApiKey(request); if (api_key == null || "".equals(api_key)) { return; } param = getParam(request.getInputStream()); WebApplicationContext webAppContext = ContextLoader.getCurrentWebApplicationContext(); RedmineHttpRequestService redmineHttpRequestService = (RedmineHttpRequestService) webAppContext .getBean("redmineHttpRequestService"); result = redmineHttpRequestService.doPut(url, param, api_key); } else { return; } response.getWriter().write(result); return; }
From source file:ch.gadp.alfresco.OAuthSSOAuthenticationFilter.java
private GoogleProfileInfo getUserProfile(HttpServletRequest req, HttpServletResponse resp, String authcode) throws IOException { logger.warn("Getting user profile"); OAuthService oauthService = this.getOAuthService(req.getRequestURL().toString()); /*/*from w w w . jav a2s . com*/ String oauthVerifierToken = req.getParameter("oauth_verifier"); if (oauthVerifierToken == null) { this.processNoRequestToken(req, resp); return null; } */ // getting access token // Verifier verifier = new Verifier(oauthVerifierToken); // Token accessToken = oauthService.getAccessToken(requestToken, verifier); Verifier verifier = new Verifier(authcode); Token accessToken = oauthService.getAccessToken(null, verifier); OAuthRequest request = new OAuthRequest(Verb.GET, getConfigurationValue(API_URI)); oauthService.signRequest(accessToken, request); Response oauthResponse = request.send(); Gson gson = new Gson(); return gson.fromJson(oauthResponse.getBody(), GoogleProfileInfo.class); }
From source file:com.persistent.cloudninja.controller.CloudNinjaAuthFilter.java
private void redirectToACSPage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { rsBundle = ResourceBundle.getBundle("acs"); String acsIDPUrl = rsBundle.getString("acs.idp.url"); String wtRealm = httpServletRequest.getRequestURL().toString(); int index = 0; int count = 0; //get the URL up to application context while (count < 5) { index = wtRealm.indexOf("/", index + 1); count++;//from w w w . j a v a 2 s . c om } if (index != -1) { wtRealm = wtRealm.substring(0, index); } String waValue = rsBundle.getString("wa.acs"); String acsURL = new StringBuilder().append(acsIDPUrl).append("?wa=").append(waValue).append("&wtrealm=") .append(wtRealm).toString(); httpServletResponse.sendRedirect(acsURL); }
From source file:org.wso2.carbon.core.transports.CarbonServlet.java
private void processWithGetProcessor(HttpServletRequest request, HttpServletResponse response, String item) throws Exception { OverflowBlob temporaryData = new OverflowBlob(256, 4048, "_servlet", ".dat"); try {// w ww. ja v a 2s .c o m CarbonHttpRequest carbonHttpRequest = new CarbonHttpRequest("GET", request.getRequestURI(), request.getRequestURL().toString()); Enumeration names = request.getParameterNames(); while (names.hasMoreElements()) { Object name = names.nextElement(); if (name != null && name instanceof String) { carbonHttpRequest.setParameter((String) name, request.getParameter((String) name)); } } carbonHttpRequest.setContextPath(request.getContextPath()); carbonHttpRequest.setQueryString(request.getQueryString()); CarbonHttpResponse carbonHttpResponse = new CarbonHttpResponse(temporaryData.getOutputStream()); (getRequestProcessors.get(item)).process(carbonHttpRequest, carbonHttpResponse, configContext); // adding headers Map responseHeaderMap = carbonHttpResponse.getHeaders(); for (Object obj : responseHeaderMap.entrySet()) { Map.Entry entry = (Map.Entry) obj; response.setHeader(entry.getKey().toString(), entry.getValue().toString()); } // setting status code response.setStatus(carbonHttpResponse.getStatusCode()); // setting error codes if (carbonHttpResponse.isError()) { if (carbonHttpResponse.getStatusMessage() != null) { response.sendError(carbonHttpResponse.getStatusCode(), carbonHttpResponse.getStatusMessage()); } else { response.sendError(carbonHttpResponse.getStatusCode()); } } if (carbonHttpResponse.isRedirect()) { response.sendRedirect(carbonHttpResponse.getRedirect()); } if (carbonHttpResponse.getHeaders().get(HTTP.CONTENT_TYPE) != null) { response.setContentType(carbonHttpResponse.getHeaders().get(HTTP.CONTENT_TYPE)); } temporaryData.writeTo(response.getOutputStream()); } finally { temporaryData.release(); } }
From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxy.java
/** * For a redirect response from the target server, this translates {@code theUrl} to redirect to * and translates it to one the original client can use. *///w w w . j a v a 2 s . co m private String rewriteUrlFromResponse(HttpProxyContext proxyContext, String theUrl) { HttpServletRequest servletRequest = proxyContext.getRequest(); //TODO document example paths final String targetUri = proxyContext.getTargetPath(); if (theUrl.startsWith(targetUri)) { String curUrl = servletRequest.getRequestURL().toString();//no query String pathInfo = servletRequest.getPathInfo(); if (pathInfo != null) { assert curUrl.endsWith(pathInfo); curUrl = curUrl.substring(0, curUrl.length() - pathInfo.length());//take pathInfo off } theUrl = curUrl + theUrl.substring(targetUri.length()); } return theUrl; }
From source file:com.epam.training.storefront.controllers.pages.payment.PaymentDetailsPageController.java
@ModelAttribute("checkoutSteps") public List<CheckoutSteps> addCheckoutStepsToModel(final HttpServletRequest request) { final String baseUrl = UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString()) .replacePath(request.getContextPath()).build().toUriString(); return MultiStepCheckoutController.createCheckoutSteps(baseUrl); }
From source file:com.streamsets.lib.security.http.SSOUserAuthenticator.java
StringBuffer getRequestUrl(HttpServletRequest request, Set<String> queryStringParamsToRemove) { StringBuffer requestUrl;//from w ww .j a v a2 s.c om if (this.dpmBaseUrl != null && !isDataCollector) { requestUrl = new StringBuffer(this.dpmBaseUrl); requestUrl.append(request.getRequestURI()); } else { requestUrl = new StringBuffer(request.getRequestURL()); } String qs = request.getQueryString(); if (qs != null) { String qsSeparator = "?"; for (String paramArg : Splitter.on("&").split(qs)) { String[] paramArgArr = paramArg.split("=", 2); if (!queryStringParamsToRemove.contains(paramArgArr[0])) { requestUrl.append(qsSeparator).append(paramArg); qsSeparator = "&"; } } } return requestUrl; }
From source file:io.hops.hopsworks.api.tensorflow.TensorboardProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { String email = servletRequest.getUserPrincipal().getName(); LOGGER.log(Level.FINE, "Request URL: {0}", servletRequest.getRequestURL()); String uri = servletRequest.getRequestURI(); // valid hostname regex: // https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address Pattern urlPattern = Pattern.compile("([a-zA-Z0-9\\-\\.]{2,255}:[0-9]{4,6})(/.*$)"); Matcher urlMatcher = urlPattern.matcher(uri); String hostPortPair = ""; String uriToFinish = "/"; if (urlMatcher.find()) { hostPortPair = urlMatcher.group(1); uriToFinish = urlMatcher.group(2); }//from w w w.ja va2 s .c o m if (hostPortPair.isEmpty()) { throw new ServletException("Couldn't extract host:port from: " + servletRequest.getRequestURI()); } Pattern appPattern = Pattern.compile("(application_.*?_\\d*)"); Matcher appMatcher = appPattern.matcher(servletRequest.getRequestURI()); Pattern elasticPattern = Pattern.compile("(experiments)"); Matcher elasticMatcher = elasticPattern.matcher(servletRequest.getRequestURI()); if (elasticMatcher.find()) { List<TensorBoard> TBList = tensorBoardFacade.findByUserEmail(email); if (TBList == null) { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "This TensorBoard is not running right now"); } boolean foundTB = false; for (TensorBoard tb : TBList) { if (tb.getEndpoint().equals(hostPortPair)) { foundTB = true; break; } } if (!foundTB) { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "This TensorBoard is not running right now"); return; } targetUri = uriToFinish; String theHost = "http://" + hostPortPair; URI targetUriHost; try { targetUriObj = new URI(targetUri); targetUriHost = new URI(theHost); } catch (Exception e) { throw new ServletException("Trying to process targetUri init parameter: ", e); } targetHost = URIUtils.extractHost(targetUriHost); servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); servletRequest.setAttribute(ATTR_URI_FINISH, uriToFinish); servletRequest.setAttribute(ATTR_HOST_PORT, hostPortPair); try { super.service(servletRequest, servletResponse); } catch (IOException ex) { sendErrorResponse(servletResponse, "This TensorBoard is not ready to serve requests right now, " + "try refreshing the page"); return; } } else if (appMatcher.find()) { String appId = appMatcher.group(1); YarnApplicationstate appState = yarnApplicationstateFacade.findByAppId(appId); if (appState == null) { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "You don't have the access right for this application"); return; } String projectName = hdfsUsersBean.getProjectName(appState.getAppuser()); ProjectDTO project; try { project = projectController.getProjectByName(projectName); } catch (ProjectException ex) { throw new ServletException(ex); } Users user = userFacade.findByEmail(email); boolean inTeam = false; for (ProjectTeam pt : project.getProjectTeam()) { if (pt.getUser().equals(user)) { inTeam = true; break; } } if (!inTeam) { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "You don't have the access right for this application"); return; } if (appState.getAppsmstate() != null && (appState.getAppsmstate().equalsIgnoreCase(YarnApplicationState.FINISHED.toString()) || appState.getAppsmstate().equalsIgnoreCase(YarnApplicationState.KILLED.toString()))) { sendErrorResponse(servletResponse, "This TensorBoard has finished running"); return; } targetUri = uriToFinish; String theHost = "http://" + hostPortPair; URI targetUriHost; try { targetUriObj = new URI(targetUri); targetUriHost = new URI(theHost); } catch (Exception e) { throw new ServletException("Trying to process targetUri init parameter: ", e); } targetHost = URIUtils.extractHost(targetUriHost); servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); servletRequest.setAttribute(ATTR_URI_FINISH, uriToFinish); servletRequest.setAttribute(ATTR_HOST_PORT, hostPortPair); try { super.service(servletRequest, servletResponse); } catch (IOException ex) { sendErrorResponse(servletResponse, "This TensorBoard is not running right now"); return; } } else { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "You don't have the access right for this application"); return; } }
From source file:com.erudika.para.security.TwitterAuthFilter.java
/** * Handles an authentication request.// w w w .j a v a 2 s .co m * @param request HTTP request * @param response HTTP response * @return an authentication object that contains the principal object if successful. * @throws IOException ex */ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException { final String requestURI = request.getRequestURI(); UserAuthentication userAuth = null; if (requestURI.endsWith(TWITTER_ACTION)) { String verifier = request.getParameter("oauth_verifier"); if (verifier == null) { String callback = Utils.urlEncode(request.getRequestURL().toString()); Map<String, String[]> params = new HashMap<String, String[]>(); params.put("oauth_callback", new String[] { callback }); HttpPost tokenPost = new HttpPost(FLOW_URL1); tokenPost.setHeader(HttpHeaders.AUTHORIZATION, OAuth1HmacSigner.sign("POST", FLOW_URL1, params, Config.TWITTER_APP_ID, Config.TWITTER_SECRET, null, null)); tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); CloseableHttpResponse resp1 = httpclient.execute(tokenPost); if (resp1.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) { String decoded = EntityUtils.toString(resp1.getEntity()); for (String pair : decoded.split("&")) { if (pair.startsWith("oauth_token")) { response.sendRedirect(FLOW_URL2 + pair); return null; } } } } else { String token = request.getParameter("oauth_token"); Map<String, String[]> params = new HashMap<String, String[]>(); params.put("oauth_verifier", new String[] { verifier }); HttpPost tokenPost = new HttpPost(FLOW_URL3); tokenPost.setEntity(new StringEntity("oauth_verifier=" + verifier)); tokenPost.setHeader(HttpHeaders.AUTHORIZATION, OAuth1HmacSigner.sign("POST", FLOW_URL3, params, Config.TWITTER_APP_ID, Config.TWITTER_SECRET, token, null)); tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); CloseableHttpResponse resp2 = httpclient.execute(tokenPost); if (resp2.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) { String decoded = EntityUtils.toString(resp2.getEntity()); String oauthToken = null; String oauthSecret = null; for (String pair : decoded.split("&")) { if (pair.startsWith("oauth_token_secret")) { oauthSecret = pair.substring(19); } else if (pair.startsWith("oauth_token")) { oauthToken = pair.substring(12); } } userAuth = getOrCreateUser(null, oauthToken, oauthSecret); } } } User user = SecurityUtils.getAuthenticatedUser(userAuth); if (userAuth == null || user == null || user.getIdentifier() == null) { throw new BadCredentialsException("Bad credentials."); } else if (!user.getActive()) { throw new LockedException("Account is locked."); } return userAuth; }