List of usage examples for javax.servlet.http HttpServletRequest getScheme
public String getScheme();
From source file:jp.or.openid.eiwg.scim.servlet.ServiceProviderConfigs.java
/** * GET?/* w w w . j a va 2 s .co m*/ * * @param request * @param response ? * @throws ServletException * @throws IOException */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ? ServletContext context = getServletContext(); // ?? Operation op = new Operation(); boolean result = op.Authentication(context, request); if (!result) { // errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage()); } else { // [draft-ietf-scim-api-13 3.2.2.1. Query Endpoints] // Queries MAY be performed against a SCIM resource object, a resource // type endpoint, or a SCIM server root. // ServiceProviderConfigs ?????????? // location?URL? String location = request.getScheme() + "://" + request.getServerName(); int serverPort = request.getServerPort(); if (serverPort != 80 && serverPort != 443) { location += ":" + Integer.toString(serverPort); } location += request.getContextPath(); // ?? @SuppressWarnings("unchecked") Map<String, Object> serviceProviderConfigsObject = (Map<String, Object>) context .getAttribute("ServiceProviderConfigs"); try { ObjectMapper mapper = new ObjectMapper(); StringWriter writer = new StringWriter(); mapper.writeValue(writer, serviceProviderConfigsObject); String serviceProviderConfigs = writer.toString(); serviceProviderConfigs = String.format(serviceProviderConfigs, location); response.setContentType("application/scim+json;charset=UTF-8"); response.setHeader("Location", request.getRequestURL().toString()); PrintWriter out = response.getWriter(); out.println(serviceProviderConfigs); } catch (IOException e) { e.printStackTrace(); } } }
From source file:org.infoscoop.web.OpenIDFilter.java
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { // basically just check for openId parameters HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; HttpSession session = request.getSession(); String reqUri = request.getRequestURI(); String srvPath = request.getServletPath(); String actionName = reqUri.substring(reqUri.lastIndexOf("/"), reqUri.length()); String uid = (String) session.getAttribute("Uid"); if (uid == null) { uid = (String) session.getAttribute("openid"); if (log.isInfoEnabled()) log.info(uid + " is logged in by openid."); session.setAttribute("Uid", uid); }/*from ww w . ja v a 2 s . com*/ if (uid == null) { String host_url = request.getScheme() + "://" + request.getServerName() + (request.getServerPort() != 80 && request.getServerPort() != 443 ? (":" + request.getServerPort()) : "") + request.getContextPath(); if ("/openid_login".equalsIgnoreCase(actionName)) { try { String returnToUrl = host_url + "/openid_consumer_return"; String openid = request.getParameter("openid"); List discoveries = this.consumerMgr.discover(openid); DiscoveryInformation discovered = this.consumerMgr.associate(discoveries); session.setAttribute("openid-disco", discovered); AuthRequest authReq = this.consumerMgr.authenticate(discovered, returnToUrl); if (!discovered.isVersion2()) { response.sendRedirect(authReq.getDestinationUrl(true)); } else { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body onload=\"document.forms['openid-form-redirection'].submit();\">"); out.println("<form method=\"POST\" name=\"openid-form-redirection\" action=\"" + authReq.getOPEndpoint() + "\">"); Map pm = authReq.getParameterMap(); Iterator keyit = pm.keySet().iterator(); Object key; Object value; while (keyit.hasNext()) { key = keyit.next(); value = pm.get(key); out.println("<input type=\"hidden\" name=\"" + key + "\" value=\"" + value + "\"/>"); } out.println("<button type=\"submit\">Continue...</button>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); out.flush(); } } catch (OpenIDException e) { log.error(e.getMessage(), e); } return; } else if ("/openid_consumer_return".equalsIgnoreCase(actionName)) { try { ParameterList responselist = new ParameterList(request.getParameterMap()); DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute("openid-disco"); StringBuffer receivingURL = request.getRequestURL(); String queryString = request.getQueryString(); if (queryString != null && queryString.length() > 0) receivingURL.append("?").append(request.getQueryString()); VerificationResult verification = this.consumerMgr.verify(receivingURL.toString(), responselist, discovered); // examine the verification result and extract the verified identifier Identifier verified = verification.getVerifiedId(); if (verified != null) { AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse(); session.setAttribute("openid", authSuccess.getIdentity()); session.setAttribute("openid-claimed", authSuccess.getClaimed()); System.out.println(authSuccess.getClaimed()); response.sendRedirect("."); // success } } catch (OpenIDException e) { log.error(e.getMessage(), e); if (this.opIdentifier != null) response.sendRedirect(this.opIdentifier); else { String loginUrl = host_url + "/login.jsp"; response.sendRedirect(loginUrl); } } return; } else if (!isExcludePath(request.getServletPath())) { try { if (this.opIdentifier != null) { String loginUrl = host_url + "/openid_login?openid=" + URLEncoder.encode(this.opIdentifier, "UTF-8"); response.sendRedirect(loginUrl); } else { String loginUrl = host_url + "/login.jsp"; response.sendRedirect(loginUrl); } } catch (IOException e) { log.error(e.getMessage(), e); } return; } } chain.doFilter(servletRequest, servletResponse); }
From source file:net.yacy.http.ProxyHandler.java
@Override public void handleRemote(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { sb.proxyLastAccess = System.currentTimeMillis(); RequestHeader proxyHeaders = ProxyHandler.convertHeaderFromJetty(request); setProxyHeaderForClient(request, proxyHeaders); final HTTPClient client = new HTTPClient(ClientIdentification.yacyProxyAgent); client.setTimout(timeout);// www .j a va 2 s . c om client.setHeader(proxyHeaders.entrySet()); client.setRedirecting(false); // send request try { String queryString = request.getQueryString() != null ? "?" + request.getQueryString() : ""; DigestURL digestURI = new DigestURL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getRequestURI() + queryString); if (request.getMethod().equals(HeaderFramework.METHOD_GET)) { client.GET(digestURI, false); } else if (request.getMethod().equals(HeaderFramework.METHOD_POST)) { client.POST(digestURI, request.getInputStream(), request.getContentLength(), false); } else if (request.getMethod().equals(HeaderFramework.METHOD_HEAD)) { client.HEADResponse(digestURI, false); } else { throw new ServletException("Unsupported Request Method"); } HttpResponse clientresponse = client.getHttpResponse(); int statusCode = clientresponse.getStatusLine().getStatusCode(); final ResponseHeader responseHeaderLegacy = new ResponseHeader(statusCode, clientresponse.getAllHeaders()); if (responseHeaderLegacy.isEmpty()) { throw new SocketException(clientresponse.getStatusLine().toString()); } cleanResponseHeader(clientresponse); // reserver cache entry final net.yacy.crawler.retrieval.Request yacyRequest = new net.yacy.crawler.retrieval.Request(null, digestURI, null, //requestHeader.referer() == null ? null : new DigestURI(requestHeader.referer()).hash(), "", responseHeaderLegacy.lastModified(), sb.crawler.defaultProxyProfile.handle(), 0, sb.crawler.defaultProxyProfile.timezoneOffset()); //sizeBeforeDelete < 0 ? 0 : sizeBeforeDelete); final Response yacyResponse = new Response(yacyRequest, null, responseHeaderLegacy, sb.crawler.defaultProxyProfile, false, null); final String storeError = yacyResponse.shallStoreCacheForProxy(); final boolean storeHTCache = yacyResponse.profile().storeHTCache(); final String supportError = TextParser.supports(yacyResponse.url(), yacyResponse.getMimeType()); if ( /* * Now we store the response into the htcache directory if * a) the response is cacheable AND */ (storeError == null) && /* * b) the user has configured to use the htcache OR * c) the content should be indexed */ ((storeHTCache) || (supportError != null))) { // we don't write actually into a file, only to RAM, and schedule writing the file. int l = responseHeaderLegacy.size(); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream((l < 32) ? 32 : l); final OutputStream toClientAndMemory = new MultiOutputStream( new OutputStream[] { response.getOutputStream(), byteStream }); convertHeaderToJetty(clientresponse, response); response.setStatus(statusCode); client.writeTo(toClientAndMemory); // cached bytes storeToCache(yacyResponse, byteStream.toByteArray()); } else { // no caching /*if (log.isFine()) log.logFine(reqID +" "+ url.toString() + " not cached." + " StoreError=" + ((storeError==null)?"None":storeError) + " StoreHTCache=" + storeHTCache + " SupportError=" + supportError);*/ convertHeaderToJetty(clientresponse, response); response.setStatus(statusCode); if (statusCode == HttpServletResponse.SC_OK) { // continue to serve header to client e.g. HttpStatus = 302 (while skiping content) client.writeTo(response.getOutputStream()); // may throw exception on httpStatus=302 while gzip encoded inputstream } } } catch (final SocketException se) { throw new ServletException("Socket Exception: " + se.getMessage()); } finally { client.finish(); } // we handled this request, break out of handler chain logProxyAccess(request); baseRequest.setHandled(true); }
From source file:es.itecban.deployment.executionmanager.gui.swf.service.DeletePlanCreationManager.java
private String getXMLDependencyGraphURL(HttpServletRequest request, String unitName, String unitVersion, String selectedEnv, String containerGraphList) throws Exception { String file = request.getRequestURI(); file = file.substring(0, file.indexOf("/", file.indexOf("/") + 1)); if (request.getQueryString() != null) { // file += '?' + // request.getQueryString()+"&_eventId_getXMLGraph=true&name="+unitName+"&version="+unitVersion+"&environment="+selectedEnv; file += "/unitInverseDependencies.htm" + '?' + "name=" + unitName + "&version=" + unitVersion + "&environment=" + selectedEnv.replace(' ', '+') + "&justGraph=true" + "&containerGraphList=" + containerGraphList;// w w w. java2 s.c om } URL reconstructedURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), file); return (reconstructedURL.toString()).substring(request.getScheme().length(), (reconstructedURL.toString().length())); }
From source file:fr.hoteia.qalingo.core.service.impl.UrlServiceImpl.java
public String buildDomainePathUrl(final RequestData requestData) throws Exception { final HttpServletRequest request = requestData.getRequest(); final MarketArea marketArea = requestData.getMarketArea(); final String contextNameValue = requestData.getContextNameValue(); String domainePathUrl = ""; if (marketArea != null) { String domainName = marketArea.getDomainName(contextNameValue); if (StringUtils.isNotEmpty(domainName)) { domainePathUrl = domainName; }/*from w w w. java 2 s . c o m*/ } if (StringUtils.isEmpty(domainePathUrl)) { String requestUrl = request.getRequestURL().toString(); requestUrl = requestUrl.replace("http://", ""); String[] urlBlock = requestUrl.split("/"); domainePathUrl = urlBlock[0]; } if (!domainePathUrl.startsWith("http")) { String scheme = request.getScheme(); domainePathUrl = scheme + "://" + domainePathUrl; } return domainePathUrl; }
From source file:org.kuali.kfs.module.ld.document.web.struts.ExpenseTransferDocumentActionBase.java
/** * Takes care of storing the action form in the user session and forwarding to the balance inquiry lookup action. * * @param mapping/*from ww w . ja va 2 s . c o m*/ * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward performBalanceInquiryLookup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ExpenseTransferDocumentFormBase financialDocumentForm = (ExpenseTransferDocumentFormBase) form; // when we return from the lookup, our next request's method to call is going to be refresh financialDocumentForm.registerEditableProperty(KRADConstants.DISPATCH_REQUEST_PARAMETER); TransactionalDocument document = financialDocumentForm.getTransactionalDocument(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); // parse out the important strings from our methodToCall parameter String fullParameter = (String) request.getAttribute(KFSConstants.METHOD_TO_CALL_ATTRIBUTE); // parse out business object class name for lookup String boClassName = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_BOPARM_LEFT_DEL, KFSConstants.METHOD_TO_CALL_BOPARM_RIGHT_DEL); if (StringUtils.isBlank(boClassName)) { throw new RuntimeException("Illegal call to perform lookup, no business object class name specified."); } // build the parameters for the lookup url Properties parameters = new Properties(); String conversionFields = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM1_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM1_RIGHT_DEL); if (StringUtils.isNotBlank(conversionFields)) { parameters.put(KFSConstants.CONVERSION_FIELDS_PARAMETER, conversionFields); } // pass values from form that should be pre-populated on lookup search String parameterFields = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM2_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM2_RIGHT_DEL); if (StringUtils.isNotBlank(parameterFields)) { String[] lookupParams = parameterFields.split(KFSConstants.FIELD_CONVERSIONS_SEPERATOR); for (int i = 0; i < lookupParams.length; i++) { String[] keyValue = lookupParams[i].split(KFSConstants.FIELD_CONVERSION_PAIR_SEPERATOR); // hard-coded passed value if (StringUtils.contains(keyValue[0], "'")) { parameters.put(keyValue[1], StringUtils.replace(keyValue[0], "'", "")); } // passed value should come from property else if (StringUtils.isNotBlank(request.getParameter(keyValue[0]))) { parameters.put(keyValue[1], request.getParameter(keyValue[0])); } } } // grab whether or not the "return value" link should be hidden or not String hideReturnLink = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM3_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM3_RIGHT_DEL); if (StringUtils.isNotBlank(hideReturnLink)) { parameters.put(KFSConstants.HIDE_LOOKUP_RETURN_LINK, hideReturnLink); } // anchor, if it exists if (form instanceof KualiForm && StringUtils.isNotEmpty(((KualiForm) form).getAnchor())) { parameters.put(KFSConstants.LOOKUP_ANCHOR, ((KualiForm) form).getAnchor()); } // determine what the action path is String actionPath = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM4_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM4_RIGHT_DEL); if (StringUtils.isBlank(actionPath)) { throw new IllegalStateException( "The \"actionPath\" attribute is an expected parameter for the <kul:balanceInquiryLookup> tag - it " + "should never be blank."); } // now add required parameters parameters.put(KFSConstants.DISPATCH_REQUEST_PARAMETER, "search"); parameters.put(KFSConstants.DOC_FORM_KEY, GlobalVariables.getUserSession().addObjectWithGeneratedKey(form)); parameters.put(KFSConstants.BUSINESS_OBJECT_CLASS_ATTRIBUTE, boClassName); parameters.put(KFSConstants.RETURN_LOCATION_PARAMETER, basePath + mapping.getPath() + ".do"); //parameters.put(GeneralLedgerConstants.LookupableBeanKeys.SEGMENTED_LOOKUP_FLAG_NAME, Boolean.TRUE.toString()); String lookupUrl = UrlFactory.parameterizeUrl(basePath + "/" + actionPath, parameters); return new ActionForward(lookupUrl, true); }
From source file:be.fedict.eid.idp.sp.protocol.openid.AuthenticationRequestServlet.java
/** * {@inheritDoc}/*from ww w . java2 s. c om*/ */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String spDestination; String userIdentifier; String languages; AuthenticationRequestService service = this.authenticationRequestServiceLocator.locateService(); if (null != service) { userIdentifier = service.getUserIdentifier(); spDestination = service.getSPDestination(); languages = service.getPreferredLanguages(); } else { userIdentifier = this.userIdentifier; if (null != this.spDestination) { spDestination = this.spDestination; } else { spDestination = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + this.spDestinationPage; } languages = this.languages; } try { LOG.debug("discovering the identity..."); LOG.debug("user identifier: " + userIdentifier); List discoveries = this.consumerManager.discover(userIdentifier); LOG.debug("associating with the IdP..."); DiscoveryInformation discovered = this.consumerManager.associate(discoveries); request.getSession().setAttribute("openid-disc", discovered); LOG.debug("SP destination: " + spDestination); AuthRequest authRequest = this.consumerManager.authenticate(discovered, getReturnTo(spDestination, request.getSession()), spDestination); /* * We also piggy-back an attribute fetch request. */ FetchRequest fetchRequest = FetchRequest.createFetchRequest(); // required attributes fetchRequest.addAttribute(OpenIDAXConstants.AX_FIRST_NAME_PERSON_TYPE, true); fetchRequest.addAttribute(OpenIDAXConstants.AX_LAST_NAME_PERSON_TYPE, true); fetchRequest.addAttribute(OpenIDAXConstants.AX_NAME_PERSON_TYPE, true); // optional attributes fetchRequest.addAttribute(OpenIDAXConstants.AX_GENDER_TYPE, false); fetchRequest.addAttribute(OpenIDAXConstants.AX_POSTAL_CODE_TYPE, false); fetchRequest.addAttribute(OpenIDAXConstants.AX_POSTAL_ADDRESS_TYPE, false); fetchRequest.addAttribute(OpenIDAXConstants.AX_CITY_TYPE, false); fetchRequest.addAttribute(OpenIDAXConstants.AX_NATIONALITY_TYPE, false); fetchRequest.addAttribute(OpenIDAXConstants.AX_PLACE_OF_BIRTH_TYPE, false); fetchRequest.addAttribute(OpenIDAXConstants.AX_BIRTHDATE_TYPE, false); fetchRequest.addAttribute(OpenIDAXConstants.AX_CARD_NUMBER_TYPE, false); fetchRequest.addAttribute(OpenIDAXConstants.AX_CARD_VALIDITY_BEGIN_TYPE, false); fetchRequest.addAttribute(OpenIDAXConstants.AX_CARD_VALIDITY_END_TYPE, false); fetchRequest.addAttribute(OpenIDAXConstants.AX_PHOTO_TYPE, false); fetchRequest.addAttribute(OpenIDAXConstants.AX_RRN_TYPE, false); fetchRequest.addAttribute(OpenIDAXConstants.AX_CERT_AUTHN_TYPE, false); fetchRequest.addAttribute(OpenIDAXConstants.AX_AGE_TYPE, false); authRequest.addExtension(fetchRequest, "ax"); /* * Piggy back UI Extension if any languages were specified */ if (null != languages) { UserInterfaceMessage uiMessage = new UserInterfaceMessage(); uiMessage.setLanguages(languages); authRequest.addExtension(uiMessage, "ui"); } LOG.debug("redirecting to producer with authn request..."); response.sendRedirect(authRequest.getDestinationUrl(true)); } catch (OpenIDException e) { throw new ServletException("OpenID error: " + e.getMessage(), e); } }
From source file:org.codehaus.groovy.grails.plugins.springsecurity.AjaxAwareAccessDeniedHandler.java
/** * {@inheritDoc}/* ww w . j a v a2 s.c om*/ * @see org.springframework.security.web.access.AccessDeniedHandler#handle( * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, * org.springframework.security.access.AccessDeniedException) */ 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 Acegi won't save the original request request.getSession().setAttribute(WebAttributes.SAVED_REQUEST, new DefaultSavedRequest(request, portResolver)); } if (response.isCommitted()) { return; } boolean ajaxError = ajaxErrorPage != null && SpringSecurityUtils.isAjax(request); if (errorPage == null && !ajaxError) { response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return; } 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; } String redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath; if (ajaxError) { redirectUrl += ajaxErrorPage; } else if (errorPage != null) { redirectUrl += errorPage; } response.sendRedirect(response.encodeRedirectURL(redirectUrl)); }
From source file:org.apache.servicemix.http.processors.ConsumerProcessor.java
private void processGetRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String query = request.getQueryString(); if (query != null && query.trim().equalsIgnoreCase("wsdl")) { String uri = request.getRequestURI(); if (!uri.endsWith("/")) { uri += "/"; }/*from w ww.j a v a 2s .c o m*/ uri += "main.wsdl"; response.sendRedirect(uri); return; } String path = request.getPathInfo(); if (path.charAt(0) == '/') { path = path.substring(1); } // Set protocol, host, and port in the component HttpComponent comp = (HttpComponent) endpoint.getServiceUnit().getComponent(); comp.setProtocol(request.getScheme()); comp.setHost(request.getServerName()); comp.setPort(request.getServerPort()); comp.setPath(request.getContextPath()); // Reload the wsdl endpoint.reloadWsdl(); Node node = (Node) endpoint.getWsdls().get(path); generateDocument(response, node); }
From source file:com.cyclopsgroup.waterview.servlet.ServletPageRuntime.java
/** * Default constructor of default web runtime * /*from ww w.j ava 2s.c o m*/ * @param request Http request object * @param response Http response object * @param fileUpload File upload component * @param services ServiceManager object * @throws Exception Throw it out */ ServletPageRuntime(HttpServletRequest request, HttpServletResponse response, FileUpload fileUpload, ServiceManager services) throws Exception { this.response = response; this.request = request; setSessionContext(new HttpSessionContext(request.getSession())); String requestPath = request.getPathInfo(); if (StringUtils.isEmpty(requestPath) || requestPath.equals("/")) { requestPath = "Index.jelly"; } else if (requestPath.charAt(0) == '/') { requestPath = requestPath.substring(1); } setRequestPath(requestPath); setOutput(new PrintWriter(response.getOutputStream())); if (FileUpload.isMultipartContent(request)) { setRequestParameters(new MultipartServletRequestValueParser(request, fileUpload)); } else { setRequestParameters(new ServletRequestValueParser(request)); } setServiceManager(services); StringBuffer sb = new StringBuffer(request.getScheme()); sb.append("://").append(request.getServerName()); if (request.getServerPort() != 80) { sb.append(':').append(request.getServerPort()); } sb.append(request.getContextPath()); setApplicationBaseUrl(sb.toString()); sb.append(request.getServletPath()); setPageBaseUrl(sb.toString()); Context pageContext = new DefaultContext(new HashMap()); pageContext.put("request", request); pageContext.put("response", response); setPageContext(pageContext); }