List of usage examples for javax.servlet.http HttpServletRequest getScheme
public String getScheme();
From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebServices.java
@GET @Path("/apps/{appid}/appattempts") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public AppAttemptsInfo getAppAttempts(@Context HttpServletRequest hsr, @PathParam("appid") String appId) { init();//from w w w . j a v a 2 s .c o m ApplicationId id = WebAppUtils.parseApplicationId(recordFactory, appId); RMApp app = rm.getRMContext().getRMApps().get(id); if (app == null) { throw new NotFoundException("app with id: " + appId + " not found"); } AppAttemptsInfo appAttemptsInfo = new AppAttemptsInfo(); for (RMAppAttempt attempt : app.getAppAttempts().values()) { AppAttemptInfo attemptInfo = new AppAttemptInfo(rm, attempt, app.getUser(), hsr.getScheme() + "://"); appAttemptsInfo.add(attemptInfo); } return appAttemptsInfo; }
From source file:org.apache.sling.resourceresolver.impl.ResourceResolverImpl.java
/** * full implementation - apply sling:alias from the resource path - apply * /etc/map mappings (inkl. config backwards compat) - return absolute uri * if possible/* ww w. j a v a2s .c o m*/ * * @see org.apache.sling.api.resource.ResourceResolver#map(javax.servlet.http.HttpServletRequest, * java.lang.String) */ @Override public String map(final HttpServletRequest request, final String resourcePath) { checkClosed(); // find a fragment or query int fragmentQueryMark = resourcePath.indexOf('#'); if (fragmentQueryMark < 0) { fragmentQueryMark = resourcePath.indexOf('?'); } // cut fragment or query off the resource path String mappedPath; final String fragmentQuery; if (fragmentQueryMark >= 0) { fragmentQuery = resourcePath.substring(fragmentQueryMark); mappedPath = resourcePath.substring(0, fragmentQueryMark); logger.debug("map: Splitting resource path '{}' into '{}' and '{}'", new Object[] { resourcePath, mappedPath, fragmentQuery }); } else { fragmentQuery = null; mappedPath = resourcePath; } // cut off scheme and host, if the same as requested final String schemehostport; final String schemePrefix; if (request != null) { schemehostport = MapEntry.getURI(request.getScheme(), request.getServerName(), request.getServerPort(), "/"); schemePrefix = request.getScheme().concat("://"); logger.debug("map: Mapping path {} for {} (at least with scheme prefix {})", new Object[] { resourcePath, schemehostport, schemePrefix }); } else { schemehostport = null; schemePrefix = null; logger.debug("map: Mapping path {} for default", resourcePath); } ParsedParameters parsed = new ParsedParameters(mappedPath); final Resource res = resolveInternal(parsed.getRawPath(), parsed.getParameters()); if (res != null) { // keep, what we might have cut off in internal resolution final String resolutionPathInfo = res.getResourceMetadata().getResolutionPathInfo(); logger.debug("map: Path maps to resource {} with path info {}", res, resolutionPathInfo); // find aliases for segments. we can't walk the parent chain // since the request session might not have permissions to // read all parents SLING-2093 final LinkedList<String> names = new LinkedList<String>(); Resource current = res; String path = res.getPath(); while (path != null) { String alias = null; if (current != null && !path.endsWith(JCR_CONTENT_LEAF)) { if (factory.getMapEntries().isOptimizeAliasResolutionEnabled()) { logger.debug("map: Optimize Alias Resolution is Enabled"); String parentPath = ResourceUtil.getParent(path); if (parentPath != null) { final Map<String, String> aliases = factory.getMapEntries().getAliasMap(parentPath); if (aliases != null && aliases.containsValue(current.getName())) { for (String key : aliases.keySet()) { if (current.getName().equals(aliases.get(key))) { alias = key; break; } } } } } else { logger.debug("map: Optimize Alias Resolution is Disabled"); alias = ResourceResolverControl.getProperty(current, PROP_ALIAS); } } if (alias == null || alias.length() == 0) { alias = ResourceUtil.getName(path); } names.add(alias); path = ResourceUtil.getParent(path); if ("/".equals(path)) { path = null; } else if (path != null) { current = res.getResourceResolver().resolve(path); } } // build path from segment names final StringBuilder buf = new StringBuilder(); // construct the path from the segments (or root if none) if (names.isEmpty()) { buf.append('/'); } else { while (!names.isEmpty()) { buf.append('/'); buf.append(names.removeLast()); } } // reappend the resolutionPathInfo if (resolutionPathInfo != null) { buf.append(resolutionPathInfo); } // and then we have the mapped path to work on mappedPath = buf.toString(); logger.debug("map: Alias mapping resolves to path {}", mappedPath); } boolean mappedPathIsUrl = false; for (final MapEntry mapEntry : this.factory.getMapEntries().getMapMaps()) { final String[] mappedPaths = mapEntry.replace(mappedPath); if (mappedPaths != null) { logger.debug("map: Match for Entry {}", mapEntry); mappedPathIsUrl = !mapEntry.isInternal(); if (mappedPathIsUrl && schemehostport != null) { mappedPath = null; for (final String candidate : mappedPaths) { if (candidate.startsWith(schemehostport)) { mappedPath = candidate.substring(schemehostport.length() - 1); mappedPathIsUrl = false; logger.debug("map: Found host specific mapping {} resolving to {}", candidate, mappedPath); break; } else if (candidate.startsWith(schemePrefix) && mappedPath == null) { mappedPath = candidate; } } if (mappedPath == null) { mappedPath = mappedPaths[0]; } } else { // we can only go with assumptions selecting the first entry mappedPath = mappedPaths[0]; } logger.debug("resolve: MapEntry {} matches, mapped path is {}", mapEntry, mappedPath); break; } } // this should not be the case, since mappedPath is primed if (mappedPath == null) { mappedPath = resourcePath; } // [scheme:][//authority][path][?query][#fragment] try { // use commons-httpclient's URI instead of java.net.URI, as it can // actually accept *unescaped* URIs, such as the "mappedPath" and // return them in proper escaped form, including the path, via // toString() final URI uri = new URI(mappedPath, false); // 1. mangle the namespaces in the path String path = mangleNamespaces(uri.getPath()); // 2. prepend servlet context path if we have a request if (request != null && request.getContextPath() != null && request.getContextPath().length() > 0) { path = request.getContextPath().concat(path); } // update the path part of the URI uri.setPath(path); mappedPath = uri.toString(); } catch (final URIException e) { logger.warn("map: Unable to mangle namespaces for " + mappedPath + " returning unmangled", e); } logger.debug("map: Returning URL {} as mapping for path {}", mappedPath, resourcePath); // reappend fragment and/or query if (fragmentQuery != null) { mappedPath = mappedPath.concat(fragmentQuery); } return mappedPath; }
From source file:org.bimserver.servlets.RootServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from w ww. ja v a 2s. c o m*/ String requestOrigin = request.getHeader("Origin"); if (requestOrigin != null && !bimServer.getServerSettingsCache().isHostAllowed(requestOrigin)) { response.setStatus(403); return; } if (requestOrigin != null) { response.setHeader("Access-Control-Allow-Origin", requestOrigin); } else { response.setHeader("Access-Control-Allow-Origin", "*"); } response.setHeader("Access-Control-Allow-Headers", "Content-Type"); if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { return; } String requestUri = request.getRequestURI(); String servletContextPath = getServletContext().getContextPath(); if (requestUri.startsWith(servletContextPath)) { requestUri = requestUri.substring(servletContextPath.length()); } if (requestUri == null) { LOGGER.error("RequestURI is null"); } else { LOGGER.debug(requestUri); // LOGGER.info(requestUri); } setContentType(response, requestUri); if (request.getRequestURI().endsWith(".getbimserveraddress")) { response.setContentType("application/json; charset=utf-8"); String siteAddress = bimServer.getServerSettingsCache().getServerSettings().getSiteAddress(); if (siteAddress == null || siteAddress.trim().isEmpty()) { // Only when in setup-mode String forwardedProtocol = request.getHeader("X-Forwarded-Proto"); if (forwardedProtocol != null) { LOGGER.info("X-Forwarded-Proto " + forwardedProtocol); String port = "" + request.getServerPort(); if (request.getHeader("X-Forwarded-Port") != null) { port = request.getHeader("X-Forwarded-Port"); } siteAddress = forwardedProtocol + "://" + request.getServerName() + ":" + port + request.getContextPath(); } else { siteAddress = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); } } response.getWriter().print("{\"address\":\"" + siteAddress + "\"}"); return; } else if (requestUri.startsWith("/stream")) { LOGGER.warn("Stream request should not be going to this servlet!"); } else if (requestUri.startsWith("/soap11/") || requestUri.equals("/soap11")) { soap11Servlet.service(request, response); } else if (requestUri.startsWith("/soap12/") || requestUri.equals("/soap12")) { try { soap12Servlet.service(request, response); } catch (ClassCastException e) { LOGGER.debug("", e); } } else if (requestUri.startsWith("/syndication/") || requestUri.equals("/syndication")) { syndicationServlet.service(request, response); } else if (requestUri.startsWith("/json/") || requestUri.equals("/json")) { jsonApiServlet.service(request, response); } else if (requestUri.startsWith("/oauth/register")) { oAuthRegistrationServlet.service(request, response); } else if (requestUri.startsWith("/oauth")) { oAuthAuthorizationServlet.service(request, response); } else if (requestUri.startsWith("/upload/") || requestUri.equals("/upload")) { uploadServlet.service(request, response); } else if (requestUri.startsWith("/bulkupload/") || requestUri.equals("/bulkupload")) { bulkUploadServlet.service(request, response); } else if (requestUri.startsWith("/download/") || requestUri.equals("/download")) { downloadServlet.service(request, response); } else { if (requestUri == null || requestUri.equals("") || requestUri.equals("/")) { requestUri = "/index.html"; } String modulePath = requestUri; if (modulePath.startsWith("/apps/")) { modulePath = modulePath.substring(6); if (modulePath.indexOf("/", 1) != -1) { modulePath = modulePath.substring(0, modulePath.indexOf("/", 1)); } if (modulePath.startsWith("/")) { modulePath = modulePath.substring(1); } if (bimServer.getWebModules().containsKey(modulePath)) { String substring = requestUri.substring(6 + modulePath.length()); WebModulePlugin webModulePlugin = bimServer.getWebModules().get(modulePath); if (webModulePlugin == null) { response.setStatus(404); response.getWriter().println("No webmodule " + modulePath + " found"); return; } else { if (webModulePlugin.service(substring, response)) { return; } } } } if (bimServer.getDefaultWebModule() != null) { if (bimServer.getDefaultWebModule().service(requestUri, response)) { return; } } InputStream resourceAsStream = getServletContext().getResourceAsStream(requestUri); if (resourceAsStream != null) { IOUtils.copy(resourceAsStream, response.getOutputStream()); } else { response.setStatus(404); try { response.getWriter().println("404 - Not Found"); } catch (IllegalStateException e) { } } } } catch (Throwable e) { if (e instanceof IOException) { // Ignore } else { LOGGER.error("", e); } } }
From source file:com.squid.kraken.v4.auth.OAuth2LoginServlet.java
/** * Perform the login action via API calls. * * @param request/*from www . j ava 2s .c om*/ * @param response * @throws ServletException * @throws IOException */ private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, URISyntaxException { String responseType = request.getParameter(RESPONSE_TYPE); if (responseType == null) { responseType = RESPONSE_TYPE_TOKEN; } String customerId = request.getParameter(CUSTOMER_ID); // create a POST method to execute the login request HttpPost post; List<NameValuePair> values = new ArrayList<NameValuePair>(); if (responseType.equals(RESPONSE_TYPE_TOKEN)) { post = new HttpPost(privateServerURL + V4_RS_AUTH_TOKEN); } else { post = new HttpPost(privateServerURL + V4_RS_AUTH_CODE); } if (StringUtils.isNotBlank(customerId)) { values.add(new BasicNameValuePair(CUSTOMER_ID, customerId)); } if (request.getParameter(CLIENT_ID) != null) { values.add(new BasicNameValuePair(CLIENT_ID, request.getParameter(CLIENT_ID))); } // get login and pwd either from the request or from the session HttpSession session = request.getSession(false); String login = request.getParameter(LOGIN); if ((session != null) && (login == null)) { login = (String) session.getAttribute(LOGIN); session.setAttribute(LOGIN, null); } String password = request.getParameter(PASSWORD); if ((session != null) && (password == null)) { password = (String) session.getAttribute(PASSWORD); session.setAttribute(PASSWORD, null); } boolean isSso = false; String redirectUri = null; if (request.getParameter(REDIRECT_URI) != null) { redirectUri = request.getParameter(REDIRECT_URI).trim(); values.add(new BasicNameValuePair(REDIRECT_URI, redirectUri)); isSso = isSso(request, redirectUri); } if (isSso == false && ((login == null) || (password == null))) { showLogin(request, response); } else { if (isSso == false) { values.add(new BasicNameValuePair(LOGIN, login)); values.add(new BasicNameValuePair(PASSWORD, password)); } else { String uri = request.getScheme() + "://" + request.getServerName() + ("http".equals(request.getScheme()) && request.getServerPort() == 80 || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? "" : ":" + request.getServerPort()); post = new HttpPost(uri + V4_RS_SSO_TOKEN); if (values != null) { URL url = new URL(redirectUri); values = getQueryPairs(getRedirectParameters(url.getQuery())); } } post.setEntity(new UrlEncodedFormEntity(values)); try { String redirectUrl = redirectUri; // T489 remove any trailing # if (redirectUrl.endsWith("#")) { redirectUrl = redirectUrl.substring(0, redirectUrl.length() - 1); } if (responseType.equals(RESPONSE_TYPE_TOKEN)) { // token type // execute the login request AccessToken token = RequestHelper.processRequest(AccessToken.class, request, post); String tokenId = token.getId().getTokenId(); // redirect URL if (redirectUrl.contains(ACCESS_TOKEN_PARAM_PATTERN)) { // replace access_token parameter pattern redirectUrl = StringUtils.replace(redirectUrl, ACCESS_TOKEN_PARAM_PATTERN, tokenId); } else { // append access_token anchor redirectUrl += (!redirectUrl.contains("?")) ? "?" : "&"; redirectUrl += ACCESS_TOKEN + "=" + tokenId; } } else { // auth code type // execute the login request AuthCode codeObj = RequestHelper.processRequest(AuthCode.class, request, post); String code = codeObj.getCode(); if (redirectUrl.contains(AUTH_CODE_PARAM_PATTERN)) { // replace code parameter pattern redirectUrl = StringUtils.replace(redirectUrl, AUTH_CODE_PARAM_PATTERN, code); } else { // append code param redirectUrl += (!redirectUrl.contains("?")) ? "?" : "&"; redirectUrl += AUTH_CODE + "=" + code; } } response.sendRedirect(redirectUrl); } catch (ServerUnavailableException e1) { // Authentication server unavailable logger.error(e1.getLocalizedMessage()); request.setAttribute(KRAKEN_UNAVAILABLE, Boolean.TRUE); showLogin(request, response); return; } catch (ServiceException e2) { WebServicesException exception = e2.getWsException(); if (exception != null) { if (exception.getCustomers() != null) { // multiple customers found request.setAttribute(DUPLICATE_USER_ERROR, Boolean.TRUE); request.setAttribute(CUSTOMERS_LIST, exception.getCustomers()); // save the credentials for later use request.getSession().setAttribute(LOGIN, login); request.getSession().setAttribute(PASSWORD, password); } else { String errorMessage = exception.getError(); if (!errorMessage.contains("Password")) { request.setAttribute(ERROR, exception.getError()); } else { request.setAttribute(ERROR, Boolean.TRUE); } } } else { request.setAttribute(ERROR, Boolean.TRUE); } // forward to login page showLogin(request, response); return; } catch (SSORedirectException error) { response.sendRedirect(error.getRedirectURL()); } } }
From source file:org.kaaproject.kaa.server.admin.controller.KaaAdminController.java
private PageLinkDto createNext(PageLinkDto pageLink, HttpServletRequest request) { if (pageLink != null && pageLink.getNext() == null) { StringBuilder nextUrl = new StringBuilder(); nextUrl.append(request.getScheme()).append("://").append(request.getServerName()); int port = request.getServerPort(); if (HTTP_PORT != port && HTTPS_PORT != port) { nextUrl.append(":").append(port); }//from w ww . j av a2 s. c o m String next = nextUrl.append(request.getRequestURI()).append("?").append(pageLink.getNextUrlPart()) .toString(); pageLink.setNext(next); LOG.debug("Generated next url {}", next); } return pageLink; }
From source file:org.alfresco.web.forms.RenderingEngineTemplateImpl.java
/** * Builds the model to pass to the rendering engine. */// ww w . j av a 2s . co m protected Map<QName, Object> buildModel(final FormInstanceData formInstanceData, final Rendition rendition) throws IOException, SAXException { final String formInstanceDataAvmPath = formInstanceData.getPath(); final String renditionAvmPath = rendition.getPath(); final String parentPath = AVMNodeConverter.SplitBase(formInstanceDataAvmPath)[0]; final String sandboxUrl = AVMUtil.getPreviewURI(AVMUtil.getStoreName(formInstanceDataAvmPath)); final String webappUrl = AVMUtil.buildWebappUrl(formInstanceDataAvmPath); final HashMap<QName, Object> model = new HashMap<QName, Object>(); // add simple scalar parameters model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "date", namespacePrefixResolver), new Date()); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "avm_sandbox_url", namespacePrefixResolver), sandboxUrl); model.put(RenderingEngineTemplateImpl.PROP_RESOURCE_RESOLVER, new RenderingEngine.TemplateResourceResolver() { public InputStream resolve(final String name) { final NodeService nodeService = RenderingEngineTemplateImpl.this.getServiceRegistry() .getNodeService(); final NodeRef parentNodeRef = nodeService .getPrimaryParent(RenderingEngineTemplateImpl.this.getNodeRef()).getParentRef(); if (logger.isDebugEnabled()) { logger.debug("request to resolve resource " + name + " webapp url is " + webappUrl + " and data dictionary workspace is " + parentNodeRef); } final NodeRef result = nodeService.getChildByName(parentNodeRef, ContentModel.ASSOC_CONTAINS, name); if (result != null) { final ContentService contentService = RenderingEngineTemplateImpl.this .getServiceRegistry().getContentService(); try { if (logger.isDebugEnabled()) { logger.debug("found " + name + " in data dictonary: " + result); } return contentService.getReader(result, ContentModel.PROP_CONTENT) .getContentInputStream(); } catch (Exception e) { logger.warn(e); } } if (name.startsWith(WEBSCRIPT_PREFIX)) { try { final FacesContext facesContext = FacesContext.getCurrentInstance(); final ExternalContext externalContext = facesContext.getExternalContext(); final HttpServletRequest request = (HttpServletRequest) externalContext .getRequest(); String decodedName = URLDecoder.decode(name.substring(WEBSCRIPT_PREFIX.length())); String rewrittenName = decodedName; if (decodedName.contains("${storeid}")) { rewrittenName = rewrittenName.replace("${storeid}", AVMUtil.getStoreName(formInstanceDataAvmPath)); } else { if (decodedName.contains("{storeid}")) { rewrittenName = rewrittenName.replace("{storeid}", AVMUtil.getStoreName(formInstanceDataAvmPath)); } } if (decodedName.contains("${ticket}")) { AuthenticationService authenticationService = Repository .getServiceRegistry(facesContext).getAuthenticationService(); final String ticket = authenticationService.getCurrentTicket(); rewrittenName = rewrittenName.replace("${ticket}", ticket); } else { if (decodedName.contains("{ticket}")) { AuthenticationService authenticationService = Repository .getServiceRegistry(facesContext).getAuthenticationService(); final String ticket = authenticationService.getCurrentTicket(); rewrittenName = rewrittenName.replace("{ticket}", ticket); } } final String webscriptURI = (request.getScheme() + "://" + request.getServerName() + ':' + request.getServerPort() + request.getContextPath() + "/wcservice/" + rewrittenName); if (logger.isDebugEnabled()) { logger.debug("loading webscript: " + webscriptURI); } final URI uri = new URI(webscriptURI); return uri.toURL().openStream(); } catch (Exception e) { logger.warn(e); } } try { final String[] path = (name.startsWith("/") ? name.substring(1) : name).split("/"); for (int i = 0; i < path.length; i++) { path[i] = URLEncoder.encode(path[i]); } final URI uri = new URI(webappUrl + '/' + StringUtils.join(path, '/')); if (logger.isDebugEnabled()) { logger.debug("loading " + uri); } return uri.toURL().openStream(); } catch (Exception e) { logger.warn(e); return null; } } }); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "form_instance_data_file_name", namespacePrefixResolver), AVMNodeConverter.SplitBase(formInstanceDataAvmPath)[1]); model.put( QName.createQName(NamespaceService.ALFRESCO_PREFIX, "rendition_file_name", namespacePrefixResolver), AVMNodeConverter.SplitBase(renditionAvmPath)[1]); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parent_path", namespacePrefixResolver), parentPath); final FacesContext fc = FacesContext.getCurrentInstance(); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "request_context_path", namespacePrefixResolver), fc.getExternalContext().getRequestContextPath()); // add methods final FormDataFunctions fdf = this.getFormDataFunctions(); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "encodeQuotes", namespacePrefixResolver), new RenderingEngine.TemplateProcessorMethod() { public Object exec(final Object[] arguments) throws IOException, SAXException { if (arguments.length != 1) { throw new IllegalArgumentException( "expected 1 argument to encodeQuotes. got " + arguments.length); } if (!(arguments[0] instanceof String)) { throw new ClassCastException("expected arguments[0] to be a " + String.class.getName() + ". got a " + arguments[0].getClass().getName() + "."); } String text = (String) arguments[0]; if (logger.isDebugEnabled()) { logger.debug("tpm_encodeQuotes('" + text + "'), parentPath = " + parentPath); } final String result = fdf.encodeQuotes(text); return result; } }); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parseXMLDocument", namespacePrefixResolver), new RenderingEngine.TemplateProcessorMethod() { public Object exec(final Object[] arguments) throws IOException, SAXException { if (arguments.length != 1) { throw new IllegalArgumentException( "expected 1 argument to parseXMLDocument. got " + arguments.length); } if (!(arguments[0] instanceof String)) { throw new ClassCastException("expected arguments[0] to be a " + String.class.getName() + ". got a " + arguments[0].getClass().getName() + "."); } String path = (String) arguments[0]; path = AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE); if (logger.isDebugEnabled()) { logger.debug("tpm_parseXMLDocument('" + path + "'), parentPath = " + parentPath); } final Document d = fdf.parseXMLDocument(path); return d != null ? d.getDocumentElement() : null; } }); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parseXMLDocuments", namespacePrefixResolver), new RenderingEngine.TemplateProcessorMethod() { public Object exec(final Object[] arguments) throws IOException, SAXException { if (arguments.length > 2) { throw new IllegalArgumentException("expected exactly one or two arguments to " + "parseXMLDocuments. got " + arguments.length); } if (!(arguments[0] instanceof String)) { throw new ClassCastException("expected arguments[0] to be a " + String.class.getName() + ". got a " + arguments[0].getClass().getName() + "."); } if (arguments.length == 2 && !(arguments[1] instanceof String)) { throw new ClassCastException("expected arguments[1] to be a " + String.class.getName() + ". got a " + arguments[1].getClass().getName() + "."); } String path = arguments.length == 2 ? (String) arguments[1] : ""; path = AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE); final String formName = (String) arguments[0]; if (logger.isDebugEnabled()) { logger.debug("tpm_parseXMLDocuments('" + formName + "','" + path + "'), parentPath = " + parentPath); } final Map<String, Document> resultMap = fdf.parseXMLDocuments(formName, path); if (logger.isDebugEnabled()) { logger.debug("received " + resultMap.size() + " documents in " + path + " with form name " + formName); } // create a root document for rooting all the results. we do this // so that each document root element has a common parent node // and so that xpath axes work properly final Document rootNodeDocument = XMLUtil.newDocument(); final Element rootNodeDocumentEl = rootNodeDocument.createElementNS( NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":file_list"); rootNodeDocumentEl.setAttribute("xmlns:" + NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI); rootNodeDocument.appendChild(rootNodeDocumentEl); final List<Node> result = new ArrayList<Node>(resultMap.size()); for (Map.Entry<String, Document> e : resultMap.entrySet()) { final Element documentEl = e.getValue().getDocumentElement(); documentEl.setAttribute("xmlns:" + NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI); documentEl.setAttributeNS(NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":file_name", e.getKey()); final Node n = rootNodeDocument.importNode(documentEl, true); rootNodeDocumentEl.appendChild(n); result.add(n); } return result.toArray(new Node[result.size()]); } }); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "_getAVMPath", namespacePrefixResolver), new RenderingEngine.TemplateProcessorMethod() { public Object exec(final Object[] arguments) { if (arguments.length != 1) { throw new IllegalArgumentException( "expected one argument to _getAVMPath. got " + arguments.length); } if (!(arguments[0] instanceof String)) { throw new ClassCastException("expected arguments[0] to be a " + String.class.getName() + ". got a " + arguments[0].getClass().getName() + "."); } final String path = (String) arguments[0]; if (logger.isDebugEnabled()) { logger.debug("tpm_getAVMPAth('" + path + "'), parentPath = " + parentPath); } return AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE); } }); // add the xml document model.put(RenderingEngine.ROOT_NAMESPACE, formInstanceData.getDocument()); return model; }
From source file:org.ecocean.Encounter.java
public String getUrl(HttpServletRequest request) { return request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/encounters/encounter.jsp?number=" + this.getCatalogNumber(); }
From source file:org.openmeetings.servlet.outputhandler.ScreenRequestHandler.java
@Override public Template handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Context ctx) {//w ww. j a va 2 s . c om try { if (getSessionManagement() == null) { return getVelocityView().getVelocityEngine().getTemplate("booting.vm"); } String sid = httpServletRequest.getParameter("sid"); if (sid == null) { sid = "default"; } log.debug("sid: " + sid); Long users_id = getSessionManagement().checkSession(sid); if (users_id == 0) { //checkSession will return 0 in case of invalid session throw new Exception("Request from invalid user " + users_id); } String publicSID = httpServletRequest.getParameter("publicSID"); if (publicSID == null) { throw new Exception("publicSID is empty: " + publicSID); } String room = httpServletRequest.getParameter("room"); if (room == null) room = "default"; String domain = httpServletRequest.getParameter("domain"); if (domain == null) { throw new Exception("domain is empty: " + domain); } String languageAsString = httpServletRequest.getParameter("languageAsString"); if (languageAsString == null) { throw new Exception("languageAsString is empty: " + domain); } Long language_id = Long.parseLong(languageAsString); String rtmphostlocal = httpServletRequest.getParameter("rtmphostlocal"); if (rtmphostlocal == null) { throw new Exception("rtmphostlocal is empty: " + rtmphostlocal); } String red5httpport = httpServletRequest.getParameter("red5httpport"); if (red5httpport == null) { throw new Exception("red5httpport is empty: " + red5httpport); } String record = httpServletRequest.getParameter("record"); if (record == null) { throw new Exception("recorder is empty: "); } String httpRootKey = httpServletRequest.getParameter("httpRootKey"); if (httpRootKey == null) { throw new Exception("httpRootKey is empty could not start sharer"); } String baseURL = httpServletRequest.getScheme() + "://" + rtmphostlocal + ":" + red5httpport + httpRootKey; // make a complete name out of domain(organisation) + roomname String roomName = domain + "_" + room; // trim whitespaces cause it is a directory name roomName = StringUtils.deleteWhitespace(roomName); ctx.put("rtmphostlocal", rtmphostlocal); // rtmphostlocal ctx.put("red5httpport", red5httpport); // red5httpport log.debug("httpRootKey " + httpRootKey); String codebase = baseURL + "screen"; ctx.put("codebase", codebase); String httpSharerURL = baseURL + "ScreenServlet"; ctx.put("webAppRootKey", httpRootKey); ctx.put("httpSharerURL", httpSharerURL); ctx.put("APP_NAME", getCfgManagement().getAppName()); ctx.put("SID", sid); ctx.put("ROOM", room); ctx.put("DOMAIN", domain); ctx.put("PUBLIC_SID", publicSID); ctx.put("RECORDER", record); String requestedFile = roomName + ".jnlp"; httpServletResponse.setContentType("application/x-java-jnlp-file"); httpServletResponse.setHeader("Content-Disposition", "Inline; filename=\"" + requestedFile + "\""); log.debug("language_id :: " + language_id); String label_viewer = "Viewer"; String label_sharer = "Sharer"; try { label_viewer = getLabels(language_id, 728, 729, 736, 742); label_sharer = getLabels(language_id, 730, 731, 732, 733, 734, 735, 737, 738, 739, 740, 741, 742, 844, 869, 870, 871, 872, 878, 1089, 1090, 1091, 1092, 1093, 1465, 1466, 1467, 1468, 1469, 1470, 1471, 1472, 1473, 1474, 1475, 1476, 1477); } catch (Exception e) { log.error("Error resolving Language labels : ", e); } ctx.put("LABELVIEWER", label_viewer); ctx.put("LABELSHARER", label_sharer); log.debug("Creating JNLP Template for TCP solution"); try { final String screenShareDirName = "screensharing"; //libs StringBuilder libs = new StringBuilder(); File screenShareDir = new File(ScopeApplicationAdapter.webAppPath, screenShareDirName); for (File jar : screenShareDir.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".jar"); } })) { libs.append("\t\t<jar href=\"").append(jar.getName()).append("\"/>\n"); } addKeystore(ctx); ctx.put("LIBRARIES", libs); log.debug("RTMP Sharer labels :: " + label_sharer); codebase = baseURL + screenShareDirName; ConnectionType conType = ConnectionType.valueOf(httpServletRequest.getParameter("connectionType")); String startUpClass; switch (conType) { case rtmp: startUpClass = "org.openmeetings.screen.webstart.RTMPScreenShare"; break; case rtmps: startUpClass = "org.openmeetings.screen.webstart.RTMPSScreenShare"; break; case rtmpt: startUpClass = "org.openmeetings.screen.webstart.RTMPTScreenShare"; break; default: throw new Exception("Unknown connection type"); } String orgIdAsString = httpServletRequest.getParameter("organization_id"); if (orgIdAsString == null) { throw new Exception("orgIdAsString is empty could not start sharer"); } ctx.put("organization_id", orgIdAsString); ctx.put("startUpClass", startUpClass); ctx.put("codebase", codebase); ctx.put("red5-host", rtmphostlocal); ctx.put("red5-app", OpenmeetingsVariables.webAppRootKey + "/" + room); Configuration configuration = getCfgManagement().getConfKey(3L, "default.quality.screensharing"); String default_quality_screensharing = "1"; if (configuration != null) { default_quality_screensharing = configuration.getConf_value(); } ctx.put("default_quality_screensharing", default_quality_screensharing); //invited guest does not have valid user_id (have user_id == -1) ctx.put("user_id", users_id); String port = httpServletRequest.getParameter("port"); if (port == null) { throw new Exception("port is empty: "); } ctx.put("port", port); String allowRecording = httpServletRequest.getParameter("allowRecording"); if (allowRecording == null) { throw new Exception("allowRecording is empty: "); } ctx.put("allowRecording", allowRecording); } catch (Exception e) { log.error("invalid configuration value for key screen_viewer!"); } String template = "screenshare.vm"; return getVelocityView().getVelocityEngine().getTemplate(template); } catch (Exception er) { log.error("[ScreenRequestHandler]", er); System.out.println("Error downloading: " + er); } return null; }
From source file:org.kuali.continuity.security.KualiAuthenticationProcessingFilterEntryPoint.java
protected String buildRedirectUrlToLoginPage(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) { String loginForm;/*from www. ja v a 2 s .com*/ HttpSession session = request.getSession(false); if (session.getAttribute(SecurityEnum.DIRECT_LOGIN_CUSTOM_URL.toString()) != null) { loginForm = this.getLoginFormUrl() + session.getAttribute(SecurityEnum.DIRECT_LOGIN_CUSTOM_URL.toString()); } else if ((session.getAttribute(SecurityEnum.SHIBBOLETH_LOGIN_IDP_ID.toString()) != null && session.getAttribute(SecurityEnum.SHIBBOLETH_LOGIN_CUSTOM_URL.toString()) != null) && (!"".equals(session.getAttribute(SecurityEnum.SHIBBOLETH_LOGIN_IDP_ID.toString())) && !"".equals(session.getAttribute(SecurityEnum.SHIBBOLETH_LOGIN_CUSTOM_URL.toString())))) { return this.inCommonMetadataService.getLoginUrl( (String) session.getAttribute(SecurityEnum.SHIBBOLETH_LOGIN_IDP_ID.toString()), (String) session.getAttribute(SecurityEnum.SHIBBOLETH_LOGIN_CUSTOM_URL.toString())); } else { //Direct login String customUrl = SecurityUtil.getCookieValue(request.getCookies(), SecurityEnum.KUALI_DIRECTLOGIN_COOKIE_KEY.toString()); String shibbolethIdp = SecurityUtil.getCookieValue(request.getCookies(), SecurityEnum.SHIBBOLETH_LOGIN_IDP_ID.toString()); String shibbolethCustomUrl = SecurityUtil.getCookieValue(request.getCookies(), SecurityEnum.SHIBBOLETH_LOGIN_CUSTOM_URL.toString()); //System.out.println(" Session timed out. customUrl is: " + customUrl + " shibbolethIdp is: " + shibbolethIdp); if (customUrl == null && (shibbolethIdp == null || shibbolethCustomUrl == null)) { //Client cleared all cookies loginForm = this.getLogoutUrl() + "?error=" + "3"; } else if (customUrl != null && (shibbolethIdp == null || shibbolethCustomUrl == null)) { //Direct Login loginForm = this.getLoginFormUrl() + customUrl; } else if (customUrl == null && (shibbolethIdp != null && shibbolethCustomUrl != null)) { //Shibboleth Login //Invalidate the session //TODO: Session problem. Have to test this..!!!!! if (session != null) { session.invalidate(); } return this.inCommonMetadataService.getLoginUrl(shibbolethIdp, shibbolethCustomUrl); } else { loginForm = this.getLoginFormUrl(); } } int serverPort = portResolver.getServerPort(request); String scheme = request.getScheme(); RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder(); urlBuilder.setScheme(scheme); urlBuilder.setServerName(request.getServerName()); urlBuilder.setPort(serverPort); urlBuilder.setContextPath(request.getContextPath()); urlBuilder.setPathInfo(loginForm); if (forceHttps && "http".equals(scheme)) { Integer httpsPort = portMapper.lookupHttpsPort(new Integer(serverPort)); if (httpsPort != null) { // Overwrite scheme and port in the redirect URL urlBuilder.setScheme("https"); urlBuilder.setPort(httpsPort.intValue()); } else { logger.warn("Unable to redirect to HTTPS as no port mapping found for HTTP port " + serverPort); } } return urlBuilder.getUrl(); }
From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java
public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) { HttpServletRequest initialRequest = (HttpServletRequest) request; this.session = session; this.authorization = authorization; //Copy common data authType = initialRequest.getAuthType(); contextPath = initialRequest.getContextPath(); remoteUser = initialRequest.getRemoteUser(); userPrincipal = initialRequest.getUserPrincipal(); requestedSessionId = initialRequest.getRequestedSessionId(); requestedSessionIdValid = initialRequest.isRequestedSessionIdValid(); attributes = new HashMap(); Enumeration attributeNames = initialRequest.getAttributeNames(); while (attributeNames.hasMoreElements()) { String name = (String) attributeNames.nextElement(); Object attribute = initialRequest.getAttribute(name); if ((null != name) && (null != attribute)) { attributes.put(name, attribute); }//from ww w .j a v a2s. c om } // Warning: For some reason, the various javax.include.* attributes are // not available via the getAttributeNames() call. This may be limited // to a Liferay issue but when the MainPortlet dispatches the call to // the MainServlet, all of the javax.include.* attributes can be // retrieved using this.request.getAttribute() but they do NOT appear in // the Enumeration of names returned by getAttributeNames(). So here // we manually add them to our map to ensure we can find them later. String[] incAttrKeys = Constants.INC_CONSTANTS; for (int index = 0; index < incAttrKeys.length; index++) { String incAttrKey = incAttrKeys[index]; Object incAttrVal = initialRequest.getAttribute(incAttrKey); if (incAttrVal != null) { attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey)); } } headers = new HashMap(); Enumeration headerNames = initialRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); Enumeration values = initialRequest.getHeaders(name); headers.put(name, Collections.list(values)); } parameters = new HashMap(); Enumeration parameterNames = initialRequest.getParameterNames(); while (parameterNames.hasMoreElements()) { String name = (String) parameterNames.nextElement(); parameters.put(name, initialRequest.getParameterValues(name)); } scheme = initialRequest.getScheme(); serverName = initialRequest.getServerName(); serverPort = initialRequest.getServerPort(); secure = initialRequest.isSecure(); //Copy servlet specific data cookies = initialRequest.getCookies(); method = initialRequest.getMethod(); pathInfo = initialRequest.getPathInfo(); pathTranslated = initialRequest.getPathTranslated(); queryString = initialRequest.getQueryString(); requestURI = initialRequest.getRequestURI(); try { requestURL = initialRequest.getRequestURL(); } catch (NullPointerException e) { //TODO remove this catch block when GlassFish bug is addressed if (log.isErrorEnabled()) { log.error("Null Protocol Scheme in request", e); } HttpServletRequest req = initialRequest; requestURL = new StringBuffer( "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI()); } servletPath = initialRequest.getServletPath(); servletSession = initialRequest.getSession(); isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie(); isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL(); characterEncoding = initialRequest.getCharacterEncoding(); contentLength = initialRequest.getContentLength(); contentType = initialRequest.getContentType(); protocol = initialRequest.getProtocol(); remoteAddr = initialRequest.getRemoteAddr(); remoteHost = initialRequest.getRemoteHost(); initializeServlet2point4Properties(initialRequest); }