/* * Registers a subcontext with red5 */ public void registerSubContext(String webAppKey) { // get the sub contexts - servlet context ServletContext ctx = servletContext.getContext(webAppKey); if (ctx == null) { ctx = servletContext; } ContextLoader loader = new ContextLoader(); ConfigurableWebApplicationContext appCtx = (ConfigurableWebApplicationContext) loader.initWebApplicationContext(ctx); appCtx.setParent(applicationContext); appCtx.refresh(); ctx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appCtx); ConfigurableBeanFactory appFactory = appCtx.getBeanFactory(); logger.debug("About to grab Webcontext bean for " + webAppKey); Context webContext = (Context) appCtx.getBean("web.context"); webContext.setCoreBeanFactory(parentFactory); webContext.setClientRegistry(clientRegistry); webContext.setServiceInvoker(globalInvoker); webContext.setScopeResolver(globalResolver); webContext.setMappingStrategy(globalStrategy); WebScope scope = (WebScope) appFactory.getBean("web.scope"); scope.setServer(server); scope.setParent(global); scope.register(); scope.start(); // register the context so we dont try to reinitialize it registeredContexts.add(ctx); }
private void handleStudentAssetManager(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext servletContext2 = this.getServletContext(); ServletContext vlewrappercontext = servletContext2.getContext("/vlewrapper"); User user = ControllerUtil.getSignedInUser(); String studentuploads_base_dir = portalProperties.getProperty("studentuploads_base_dir"); try { // get the run String runId = request.getParameter("runId"); Run run = runService.retrieveById(new Long(runId)); // get the project id Project project = run.getProject(); Serializable projectId = project.getId(); // set the project id into the request so the vlewrapper controller has access to it request.setAttribute("projectId", projectId + ""); // get the workgroup id List<Workgroup> workgroupListByOfferingAndUser = workgroupService.getWorkgroupListByOfferingAndUser(run, user); Workgroup workgroup = workgroupListByOfferingAndUser.get(0); Long workgroupId = workgroup.getId(); // set the workgroup id into the request so the vlewrapper controller has access to it request.setAttribute( "dirName", run.getId() + "/" + workgroupId + "/unreferenced"); // looks like /studentuploads/[runId]/[workgroupId]/unreferenced String commandParamter = request.getParameter("command"); if (commandParamter != null && "studentAssetCopyForReference".equals(commandParamter)) { request.setAttribute( "referencedDirName", run.getId() + "/" + workgroupId + "/referenced"); // if we're copying student asset for reference, also pass along // the referenced dir. looks like // /studentuploads/[runId]/[workgroupId]/referenced } if (studentuploads_base_dir != null) { request.setAttribute("studentuploads_base_dir", studentuploads_base_dir); } // forward the request to the vlewrapper controller RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/vle/studentassetmanager.html"); requestDispatcher.forward(request, response); } catch (NumberFormatException e) { e.printStackTrace(); } catch (ObjectNotFoundException e) { e.printStackTrace(); } }
private String captureResponse(ServletRequest req, ServletResponse res, String uri) throws ServletException, IOException { CapturingResponseWrapper responseWrapper = new CapturingResponseWrapper((HttpServletResponse) res); RequestDispatcher dispatcher = servletContext.getContext(uri).getRequestDispatcher(uri); if (dispatcher == null) { return null; } dispatcher.forward(req, responseWrapper); return responseWrapper.getCapturedResponseString(); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Shared Info"; out.println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">" + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" + "<UL>\n" + " <LI>Session:"); HttpSession session = request.getSession(true); Enumeration attributes = session.getAttributeNames(); out.println(getAttributeList(attributes)); out.println(" <LI>Current Servlet Context:"); ServletContext application = getServletContext(); attributes = application.getAttributeNames(); out.println(getAttributeList(attributes)); out.println(" <LI>Servlet Context of /shareTest1:"); application = application.getContext("/shareTest1"); if (application == null) { out.println("Context sharing disabled"); } else { attributes = application.getAttributeNames(); out.println(getAttributeList(attributes)); } out.println(" <LI>Cookies:<UL>"); Cookie[] cookies = request.getCookies(); if ((cookies == null) || (cookies.length == 0)) { out.println(" <LI>No cookies found."); } else { Cookie cookie; for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; out.println(" <LI>" + cookie.getName()); } } out.println(" </UL>\n" + "</UL>\n" + "</BODY></HTML>"); }
/** * Constructs an instance of a PortletWebApplicationImpl from a supplied ui application name and * corresponding <code>ServletContext</code> * * @param webApplicationName the the web application name * @param context the <code>ServletContext</code> */ public PortletWebApplicationImpl(String webApplicationName, ServletContext context) throws PortletException { super(context); this.webApplicationName = webApplicationName; // get the servlet context for the coreportlets webapp String contextURIPath; if (webApplicationName.startsWith("/")) { contextURIPath = webApplicationName; this.webApplicationName = webApplicationName.substring(1); } else { contextURIPath = "/" + webApplicationName; } // Get the cross context servlet context ServletContext ctx = context.getContext(contextURIPath); // System.err.println("contextURIPath: " + contextURIPath); // System.err.println("contextName: " + ctx.getServletContextName()); // System.err.println("context path: " + ctx.getRealPath("")); // System.err.println("testing example portlets"); // ServletContext testsc = context.getContext("/exampleportlets"); // System.err.println("description: " + ctx.getServletContextName()); // System.err.println("testing core portlets"); // testsc = context.getContext("/coreportlets"); // System.err.println("description: " + testsc.getServletContextName()); // System.err.println("context path: " + te.getRealPath("")); if (ctx == null) { log.error(webApplicationName + ": Unable to get ServletContext for: " + contextURIPath); throw new PortletException( webApplicationName + ": Unable to get ServletContext for: " + contextURIPath); } log.debug("context path: " + ctx.getRealPath("")); this.webAppDescription = ctx.getServletContextName(); // load portlet.xml loadPortlets(ctx, Thread.currentThread().getContextClassLoader()); // load services xml if (!isJSR) loadServices(ctx, Thread.currentThread().getContextClassLoader()); // load roles.xml if (!isJSR) loadRoles(ctx); // load group.xml (and if found load layout.xml) if (!isJSR) loadGroup(ctx); }
/** Gets current or cross context <code>ServletContext</code>. */ protected ServletContext getServletContext() { ServletContext sc = null; if (StringUtils.hasText(context)) { sc = servletContext.getContext(context); if (sc == null) { throw new UnsupportedOperationException( "Unable to get context for '" + context + "'. " + "Server may not have cross context support or may be configured incorrectly."); } } else { sc = servletContext; } return sc; }
/** * Handle student status requests * * @param request * @param response */ private void handleRunStatus(HttpServletRequest request, HttpServletResponse response) { ServletContext servletContext = this.getServletContext(); ServletContext vlewrappercontext = servletContext.getContext("/vlewrapper"); try { RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/runStatus.html"); // make sure the user is allowed to make this POST if (authenticateRunStatusPOST(request, response)) { // forward the request to the vlewrapper requestDispatcher.forward(request, response); } } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
private ModelAndView handlePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String type = request.getParameter("type"); ServletContext servletContext2 = this.getServletContext(); ServletContext vlewrappercontext = servletContext2.getContext("/vlewrapper"); User user = ControllerUtil.getSignedInUser(); CredentialManager.setRequestCredentials(request, user); if (type == null) { // post student data RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/postdata.html"); requestDispatcher.forward(request, response); } else if (type.equals("flag") || type.equals("inappropriateFlag") || type.equals("annotation")) { RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/annotations.html"); requestDispatcher.forward(request, response); } else if (type.equals("journal")) { RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/journaldata.html"); requestDispatcher.forward(request, response); } else if (type.equals("peerreview")) { RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/peerreview.html"); requestDispatcher.forward(request, response); } else if (type.equals("ideaBasket")) { handleIdeaBasket(request, response); } else if (type.equals("studentAssetManager")) { handleStudentAssetManager(request, response); } else if (type.equals("viewStudentAssets")) { handleViewStudentAssets(request, response); } else if (type.equals("chatLog")) { RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/chatLog.html"); requestDispatcher.forward(request, response); } else if (type.equals("studentStatus")) { handleStudentStatus(request, response); } else if (type.equals("runStatus")) { handleRunStatus(request, response); } return null; }
@Test public void aliasHit() throws IOException, ServletException { AliasHandler handler = new AliasHandler(commandProcessor, true, pathAliases); pathAliases.put("/hitPath", "/context/alternatePath"); ServletContext origContext = mock(ServletContext.class); ServletContext newContext = mock(ServletContext.class); when(request.getServletContext()).thenReturn(origContext); ArgumentCaptor<String> requestContextPath = ArgumentCaptor.forClass(String.class); when(origContext.getContext(requestContextPath.capture())).thenReturn(newContext); when(newContext.getContextPath()).thenReturn("/context"); RequestDispatcher requestDispatcher = mock(RequestDispatcher.class); ArgumentCaptor<String> requestDispatcherPath = ArgumentCaptor.forClass(String.class); when(newContext.getRequestDispatcher(requestDispatcherPath.capture())) .thenReturn(requestDispatcher); handler.handle("/hitPath", baseRequest, request, response); verify(requestDispatcher, times(1)).forward(request, response); assertEquals("/context/alternatePath", requestContextPath.getValue()); assertEquals("/alternatePath", requestDispatcherPath.getValue()); }
private void handleViewStudentAssets(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext servletContext2 = this.getServletContext(); ServletContext vlewrappercontext = servletContext2.getContext("/vlewrapper"); User user = ControllerUtil.getSignedInUser(); String studentuploads_base_dir = portalProperties.getProperty("studentuploads_base_dir"); try { // get the run String runId = request.getParameter("runId"); Run run = runService.retrieveById(new Long(runId)); // get the project id Project project = run.getProject(); Serializable projectId = project.getId(); // set the project id into the request so the vlewrapper controller has access to it request.setAttribute("projectId", projectId + ""); // set the workgroup id into the request so the vlewrapper controller has access to it if (studentuploads_base_dir != null) { request.setAttribute("studentuploads_base_dir", studentuploads_base_dir); } // workgroups is a ":" separated string of workgroups String workgroups = request.getParameter("workgroups"); request.setAttribute("dirName", workgroups); // forward the request to the vlewrapper controller RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/vle/studentassetmanager.html"); requestDispatcher.forward(request, response); } catch (NumberFormatException e) { e.printStackTrace(); } catch (ObjectNotFoundException e) { e.printStackTrace(); } }
@Override public void route( MutableHttpServletRequest servletRequest, MutableHttpServletResponse servletResponse) throws IOException, ServletException, URISyntaxException { DestinationLocation location = null; if (!StringUtilities.isBlank(defaultDst)) { servletRequest.addDestination(defaultDst, servletRequest.getRequestURI(), -1); } RouteDestination routingDestination = servletRequest.getDestination(); String rootPath = ""; if (routingDestination != null) { Destination configDestinationElement = destinations.get(routingDestination.getDestinationId()); if (configDestinationElement == null) { LOG.warn( "Invalid routing destination specified: " + routingDestination.getDestinationId() + " for domain: " + domain.getId()); ((HttpServletResponse) servletResponse).setStatus(HttpStatusCode.NOT_FOUND.intValue()); } else { location = locationBuilder.build( configDestinationElement, routingDestination.getUri(), servletRequest); rootPath = configDestinationElement.getRootPath(); } } if (location != null) { // According to the Java 6 javadocs the routeDestination passed into getContext: // "The given path [routeDestination] must begin with /, is interpreted relative to the // server's document root // and is matched against the context roots of other web applications hosted on this // container." final ServletContext targetContext = context.getContext(location.getUri().toString()); if (targetContext != null) { // Capture this for Location header processing final HttpServletRequest originalRequest = (HttpServletRequest) servletRequest.getRequest(); String uri = new DispatchPathBuilder(location.getUri().getPath(), targetContext.getContextPath()) .build(); final RequestDispatcher dispatcher = targetContext.getRequestDispatcher(uri); servletRequest.setRequestUrl(new StringBuffer(location.getUrl().toExternalForm())); servletRequest.setRequestUri(location.getUri().getPath()); requestHeaderService.setVia(servletRequest); requestHeaderService.setXForwardedFor(servletRequest); if (dispatcher != null) { LOG.debug("Attempting to route to " + location.getUri()); LOG.debug("Request URL: " + ((HttpServletRequest) servletRequest).getRequestURL()); LOG.debug("Request URI: " + ((HttpServletRequest) servletRequest).getRequestURI()); LOG.debug("Context path = " + targetContext.getContextPath()); final long startTime = System.currentTimeMillis(); try { reportingService.incrementRequestCount(routingDestination.getDestinationId()); dispatcher.forward(servletRequest, servletResponse); final long stopTime = System.currentTimeMillis(); reportingService.recordServiceResponse( routingDestination.getDestinationId(), servletResponse.getStatus(), (stopTime - startTime)); responseHeaderService.fixLocationHeader( originalRequest, servletResponse, routingDestination, location.getUri().toString(), rootPath); } catch (ClientHandlerException e) { if (e.getCause() instanceof ReadLimitReachedException) { LOG.error("Error reading request content", e); servletResponse.sendError( HttpStatusCode.REQUEST_ENTITY_TOO_LARGE.intValue(), "Error reading request content"); servletResponse.setLastException(e); } else { LOG.error("Connection Refused to " + location.getUri() + " " + e.getMessage(), e); ((HttpServletResponse) servletResponse) .setStatus(HttpStatusCode.SERVICE_UNAVAIL.intValue()); } } } } } }
/** * Loads, parses and returns the resource of the specified URI, or null if not found. The parser * is defined by the loader defined in {@link ResourceCache}. * * @param cache the resource cache. Note: its loader must extend from {@link ResourceLoader}. * @param path the URI path * @param extra the extra parameter that will be passed to {@link * ResourceLoader#parse(String,File,Object)} and {@link * ResourceLoader#parse(String,URL,Object)} */ public static final <V> V get( ResourceCache<V> cache, ServletContext ctx, String path, Object extra) { // 20050905: Tom Yeh // We don't need to handle the default name if user specifies only a dir // because it is handled by the container directly // And, web developer has to specify <welcome-file> in web.xml URL url = null; if (path == null || path.length() == 0) path = "/"; else if (path.charAt(0) != '/') { if (path.indexOf("://") > 0) { try { url = new URL(path); } catch (java.net.MalformedURLException ex) { throw new SystemException(ex); } } else path = '/' + path; } if (url == null) { if (path.startsWith("/~")) { final ServletContext ctx0 = ctx; final String path0 = path; final int j = path.indexOf('/', 2); final String ctxpath; if (j >= 0) { ctxpath = "/" + path.substring(2, j); path = path.substring(j); } else { ctxpath = "/" + path.substring(2); path = "/"; } final ExtendletContext extctx = Servlets.getExtendletContext(ctx, ctxpath.substring(1)); if (extctx != null) { url = extctx.getResource(path); // if (log.debugable()) log.debug("Resolving "+path0+" to "+url); if (url == null) return null; try { return cache.get(new ResourceInfo(path, url, extra)); } catch (Throwable ex) { final IOException ioex = getIOException(ex); if (ioex == null) throw SystemException.Aide.wrap(ex); log.warningBriefly("Unable to load " + url, ioex); } return null; } ctx = ctx.getContext(ctxpath); if (ctx == null) { // failed // if (log.debugable()) log.debug("Context not found: "+ctxpath); ctx = ctx0; path = path0; // restore } } final String flnm = ctx.getRealPath(path); if (flnm != null) { try { return cache.get(new ResourceInfo(path, new File(flnm), extra)); // it is loader's job to check the existence } catch (Throwable ex) { final IOException ioex = getIOException(ex); if (ioex == null) throw SystemException.Aide.wrap(ex); log.warningBriefly("Unable to load " + flnm, ioex); } return null; } } // try url because some server uses JAR format try { if (url == null) url = ctx.getResource(path); if (url != null) return cache.get(new ResourceInfo(path, url, extra)); } catch (Throwable ex) { final IOException ioex = getIOException(ex); if (ioex == null) throw SystemException.Aide.wrap(ex); log.warningBriefly("Unable to load " + path, ioex); } return null; }
@Override public FiberServletContext getContext(String uripath) { return new FiberServletContext(sc.getContext(uripath), ac); }
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException { if (!Aura.getConfigAdapter().isTestAllowed()) { chain.doFilter(req, res); return; } TestContextAdapter testContextAdapter = Aura.get(TestContextAdapter.class); if (testContextAdapter == null) { chain.doFilter(req, res); return; } // Check for requests to execute a JSTest, i.e. initial component GETs with particular // parameters. HttpServletRequest request = (HttpServletRequest) req; if ("GET".equals(request.getMethod())) { String contextPath = request.getContextPath(); String uri = request.getRequestURI(); String browserType = request.getParameter("aura.browserType"); if (browserType == null) { // read it from request header String ua = request.getHeader(HttpHeaders.USER_AGENT); if (ua != null) { ua = ua.toLowerCase(); if (ua.contains("chrome")) { browserType = "GOOGLECHROME"; } else if (ua.contains("safari")) { browserType = "SAFARI"; } else if (ua.contains("firefox")) { browserType = "FIREFOX"; } else if (ua.contains("ipad")) { browserType = "IPAD"; } else if (ua.contains("iphone")) { browserType = "IPHONE"; } else if (ua.contains("msie 10")) { browserType = "IE10"; } else if (ua.contains("msie 9")) { browserType = "IE9"; } else if (ua.contains("msie 8")) { browserType = "IE8"; } else if (ua.contains("msie 7")) { browserType = "IE7"; } else if (ua.contains("msie 6")) { browserType = "IE6"; } else if (ua.contains("trident/7.0")) { browserType = "IE11"; } else if (ua.contains("edge/12")) { browserType = "IE12"; } else { browserType = "OTHER"; } } } String path; if (uri.startsWith(contextPath)) { path = uri.substring(contextPath.length()); } else { path = uri; } Matcher matcher = AuraRewriteFilter.DESCRIPTOR_PATTERN.matcher(path); if (matcher.matches()) { // Extract the target component since AuraContext usually does not have the app descriptor // set yet. DefType type = "app".equals(matcher.group(3)) ? DefType.APPLICATION : DefType.COMPONENT; String namespace = matcher.group(1); String name = matcher.group(2); DefDescriptor<?> targetDescriptor = Aura.getDefinitionService() .getDefDescriptor( String.format("%s:%s", namespace, name), type.getPrimaryInterface()); // Check if a single jstest is being requested. String testToRun = jstestToRun.get(request); if (testToRun != null && !testToRun.isEmpty()) { AuraContext context = Aura.getContextService().getCurrentContext(); Format format = context.getFormat(); switch (format) { case HTML: TestCaseDef testDef; TestContext testContext; String targetUri; try { TestSuiteDef suiteDef = getTestSuite(targetDescriptor); testDef = getTestCase(suiteDef, testToRun); testDef.validateDefinition(); testDef.setCurrentBrowser(browserType); testContextAdapter.getTestContext(testDef.getQualifiedName()); testContextAdapter.release(); testContext = testContextAdapter.getTestContext(testDef.getQualifiedName()); targetUri = buildJsTestTargetUri(targetDescriptor, testDef); } catch (QuickFixException e) { ((HttpServletResponse) res).setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); res.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING); res.getWriter().append(e.getMessage()); Aura.getExceptionAdapter().handleException(e); return; } // Load any test mocks. Collection<Definition> mocks = testDef.getLocalDefs(); testContext.getLocalDefs().addAll(mocks); loadTestMocks(context, true, testContext.getLocalDefs()); // Capture the response and inject tags to load jstest. String capturedResponse = captureResponse(req, res, targetUri); if (capturedResponse != null) { res.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING); if (!Aura.getContextService().isEstablished()) { // There was an error in the original response, so just write the response out. res.getWriter().write(capturedResponse); } else { String testTag = buildJsTestScriptTag(targetDescriptor, testToRun, capturedResponse); injectScriptTags(res.getWriter(), capturedResponse, testTag); } return; } case JS: res.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING); writeJsTestScript(res.getWriter(), targetDescriptor, testToRun); return; default: // Pass it on. } } // aurajstest:jstest app is invokable in the following ways: // ?aura.mode=JSTEST - run all tests // ?aura.mode JSTEST&test=XXX - run single test // ?aura.jstest - run all tests // ?aura.jstest=XXX - run single test // ?aura.jstestrun - run all tests // TODO: delete JSTEST mode String jstestAppRequest = jstestAppFlag.get(request); Mode mode = AuraContextFilter.mode.get(request, Mode.PROD); if (mode == Mode.JSTEST || mode == Mode.JSTESTDEBUG || jstestAppRequest != null || testToRun != null) { mode = mode.toString().endsWith("DEBUG") ? Mode.AUTOJSTESTDEBUG : Mode.AUTOJSTEST; String qs = String.format("descriptor=%s:%s&defType=%s", namespace, name, type.name()); String testName = null; if (jstestAppRequest != null && !jstestAppRequest.isEmpty()) { testName = jstestAppRequest; } else if (testToRun != null && !testToRun.isEmpty()) { testName = testToRun; } if (testName != null) { qs = qs + "&test=" + testName; } String newUri = createURI( "aurajstest", "jstest", DefType.APPLICATION, mode, Authentication.AUTHENTICATED.name(), qs); RequestDispatcher dispatcher = servletContext.getContext(newUri).getRequestDispatcher(newUri); if (dispatcher != null) { dispatcher.forward(req, res); return; } } } } // Handle mock definitions specified in the tests. TestContext testContext = getTestContext(request); if (testContext == null) { // During manual testing, the test context adapter may not always get cleared. testContextAdapter.clear(); } else { ContextService contextService = Aura.getContextService(); if (!contextService.isEstablished()) { LOG.error("Aura context is not established! New context will NOT be created."); chain.doFilter(req, res); return; } AuraContext context = contextService.getCurrentContext(); // Reset mocks if requested, or for the initial GET. boolean doResetMocks = testReset.get(request, Format.HTML.equals(context.getFormat())); loadTestMocks(context, doResetMocks, testContext.getLocalDefs()); } chain.doFilter(req, res); }
@Override public ServletContext getContext(String s) { return proxy.getContext(s); }
private void handleIdeaBasket(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext servletContext2 = this.getServletContext(); ServletContext vlewrappercontext = servletContext2.getContext("/vlewrapper"); User signedInUser = ControllerUtil.getSignedInUser(); String action = request.getParameter("action"); try { // get the run String runId = request.getParameter("runId"); Run run = runService.retrieveById(new Long(runId)); // get the project id Project project = run.getProject(); Serializable projectId = project.getId(); // set the project id into the request so the vlewrapper controller has access to it request.setAttribute("projectId", projectId + ""); // get the authorities for the signed in user MutableUserDetails signedInUserDetails = signedInUser.getUserDetails(); Collection<? extends GrantedAuthority> authorities = signedInUserDetails.getAuthorities(); boolean isAdmin = false; boolean isTeacher = false; boolean isStudent = false; // this value will determine whether the user can modify anything they want in the public idea // basket boolean isPrivileged = false; for (GrantedAuthority authority : authorities) { if (authority.getAuthority().equals(UserDetailsService.ADMIN_ROLE)) { // user is an admin or teacher isAdmin = true; isPrivileged = true; } else if (authority.getAuthority().equals(UserDetailsService.TEACHER_ROLE)) { // user is an admin or teacher isTeacher = true; isPrivileged = true; } } if (!isTeacher) { isStudent = true; } request.setAttribute("isPrivileged", isPrivileged); if (isAdmin) { // user is an admin so we do not need to retrieve the workgroup id } else if (isTeacher) { // user is a teacher so we will retrieve their workgroup id for the run // get the workgroup id List<Workgroup> workgroupListByOfferingAndUser = workgroupService.getWorkgroupListByOfferingAndUser(run, signedInUser); // add nullpointer check Workgroup workgroup = workgroupListByOfferingAndUser.get(0); Long signedInWorkgroupId = workgroup.getId(); // set the workgroup id into the request so the vlewrapper controller has access to it request.setAttribute("signedInWorkgroupId", signedInWorkgroupId + ""); } else if (isStudent) { /* * the user is a student so we will make sure the run id * matches the run they are currently working on and then * retrieve their workgroup id for the run */ HashMap<String, Run> studentsToRuns = (HashMap<String, Run>) request.getSession().getServletContext().getAttribute("studentsToRuns"); String sessionId = request.getSession().getId(); if (studentsToRuns != null && studentsToRuns.containsKey(sessionId)) { Run sessionRun = studentsToRuns.get(sessionId); Long sessionRunId = sessionRun.getId(); if (sessionRunId.equals(new Long(runId))) { // get the workgroup id List<Workgroup> workgroupListByOfferingAndUser = workgroupService.getWorkgroupListByOfferingAndUser(run, signedInUser); // add nullpointer check Workgroup workgroup = workgroupListByOfferingAndUser.get(0); Long signedInWorkgroupId = workgroup.getId(); // set the workgroup id into the request so the vlewrapper controller has access to it request.setAttribute("signedInWorkgroupId", signedInWorkgroupId + ""); } else { // run id does not match the run that the student is logged in to response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Run id does not match run that student is logged in to"); return; } } else { // session id was not found which means the session probably timed out response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Session no longer valid"); return; } } // forward the request to the vlewrapper controller RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/ideaBasket.html"); requestDispatcher.forward(request, response); } catch (NumberFormatException e) { e.printStackTrace(); } catch (ObjectNotFoundException e) { e.printStackTrace(); } }
private ModelAndView handleGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String type = request.getParameter("type"); ServletContext servletContext2 = this.getServletContext(); ServletContext vlewrappercontext = servletContext2.getContext("/vlewrapper"); User user = ControllerUtil.getSignedInUser(); CredentialManager.setRequestCredentials(request, user); // get the run id String runIdString = request.getParameter("runId"); Long runId = null; if (runIdString != null) { runId = Long.parseLong(runIdString); } Run run = null; try { if (runId != null) { // get the run object run = runService.retrieveById(runId); } } catch (ObjectNotFoundException e1) { e1.printStackTrace(); } if (type == null) { // get student data RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/getdata.html"); requestDispatcher.forward(request, response); } else if (type.equals("brainstorm")) { RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/getdata.html"); requestDispatcher.forward(request, response); } else if (type.equals("aggregate")) { setProjectPath(run, request); // set the project path into the request object if (Boolean.parseBoolean(request.getParameter("allStudents"))) { // request for all students work in run. lookup workgroups in run and construct // workgroupIdString String workgroupIdStr = ""; try { Set<Workgroup> workgroups = runService.getWorkgroups(runId); for (Workgroup workgroup : workgroups) { workgroupIdStr += workgroup.getId() + ":"; } request.setAttribute("userId", workgroupIdStr); } catch (ObjectNotFoundException e) { } } RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/getdata.html"); requestDispatcher.forward(request, response); } else if (type.equals("flag") || type.equals("inappropriateFlag") || type.equals("annotation")) { // get flags /* * set the user info JSONObjects into the request so the vlewrapper servlet * has access to the teacher and classmate info */ setUserInfos(run, request); setCRaterAttributes(request); RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/annotations.html"); requestDispatcher.forward(request, response); } else if (type.equals("journal")) { RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/journaldata.html"); requestDispatcher.forward(request, response); } else if (type.equals("peerreview")) { // get the period id String periodString = request.getParameter("periodId"); Long period = null; if (periodString != null) { period = Long.parseLong(periodString); } try { /* * set the number of students in the class period for when we need * to calculate peer review opening */ Set<Workgroup> classmateWorkgroups = runService.getWorkgroups(runId, period); request.setAttribute("numWorkgroups", classmateWorkgroups.size()); } catch (ObjectNotFoundException e) { e.printStackTrace(); } RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/peerreview.html"); requestDispatcher.forward(request, response); } else if (type.equals("xlsexport") || type.equals("specialExport")) { // set the user info into the request object setUserInfos(run, request); // set the project path into the request object setProjectPath(run, request); // set the project meta data into the request object setProjectMetaData(run, request); String requestPath = ""; if (type.equals("xlsexport")) { // get the path for regular exports requestPath = "/getxls.html"; } else if (type.equals("specialExport")) { // get the path for special exports requestPath = "/getSpecialExport.html"; } RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher(requestPath); requestDispatcher.forward(request, response); } else if (type.equals("ideaBasket")) { handleIdeaBasket(request, response); } else if (type.equals("studentAssetManager")) { handleStudentAssetManager(request, response); } else if (type.equals("viewStudentAssets")) { handleViewStudentAssets(request, response); } else if (type.equals("xmppAuthenticate")) { // check if this portal is xmpp enabled first String isXMPPEnabled = portalProperties.getProperty("isXMPPEnabled"); if (isXMPPEnabled != null && Boolean.valueOf(isXMPPEnabled)) { handleWISEXMPPAuthenticate(request, response); } } else if (type.equals("cRater")) { setCRaterAttributes(request); RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/cRater.html"); requestDispatcher.forward(request, response); } else if (type.equals("chatLog")) { RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/chatLog.html"); requestDispatcher.forward(request, response); } else if (type.equals("studentStatus")) { RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/studentStatus.html"); requestDispatcher.forward(request, response); } else if (type.equals("runStatus")) { RequestDispatcher requestDispatcher = vlewrappercontext.getRequestDispatcher("/runStatus.html"); requestDispatcher.forward(request, response); } return null; }
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (PortalUtil.isMultipartRequest(request)) { UploadServletRequest uploadServletRequest = new UploadServletRequestImpl(request); request = uploadServletRequest; } String path = GetterUtil.getString(request.getPathInfo()); if ((!path.equals(StringPool.BLANK) && !path.equals(StringPool.SLASH)) || (request.getParameter("discover") != null)) { Locale locale = PortalUtil.getLocale(request, response, true); LocaleThreadLocal.setThemeDisplayLocale(locale); super.service(request, response); return; } if (_log.isDebugEnabled()) { _log.debug("Servlet context " + request.getContextPath()); } String apiPath = PortalUtil.getPathMain() + "/portal/api/jsonws"; HttpSession session = request.getSession(); ServletContext servletContext = session.getServletContext(); boolean remoteAccess = AccessControlThreadLocal.isRemoteAccess(); try { AccessControlThreadLocal.setRemoteAccess(true); String contextPath = PortalContextLoaderListener.getPortalServletContextPath(); if (servletContext.getContext(contextPath) != null) { if (!contextPath.equals(StringPool.SLASH) && apiPath.startsWith(contextPath)) { apiPath = apiPath.substring(contextPath.length()); } RequestDispatcher requestDispatcher = request.getRequestDispatcher(apiPath); requestDispatcher.forward(request, response); } else { String servletContextPath = ContextPathUtil.getContextPath(servletContext); String redirectPath = "/api/jsonws?contextPath=" + HttpUtil.encodeURL(servletContextPath); response.sendRedirect(redirectPath); } } finally { AccessControlThreadLocal.setRemoteAccess(remoteAccess); } }
/** * Gets the content and defers to registered viewers to generate the markup. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { // specify the charset in a response header response.addHeader("Content-Type", "text/html; charset=UTF-8"); // get the content final ServletContext servletContext = request.getServletContext(); final ContentAccess contentAccess = (ContentAccess) servletContext.getAttribute("nifi-content-access"); final ContentRequestContext contentRequest = getContentRequest(request); if (contentRequest.getDataUri() == null) { request.setAttribute("title", "Error"); request.setAttribute("messages", "The data reference must be specified."); // forward to the error page final ServletContext viewerContext = servletContext.getContext("/nifi"); viewerContext.getRequestDispatcher("/message").forward(request, response); return; } // get the content final DownloadableContent downloadableContent; try { downloadableContent = contentAccess.getContent(contentRequest); } catch (final ResourceNotFoundException rnfe) { request.setAttribute("title", "Error"); request.setAttribute("messages", "Unable to find the specified content"); // forward to the error page final ServletContext viewerContext = servletContext.getContext("/nifi"); viewerContext.getRequestDispatcher("/message").forward(request, response); return; } catch (final AccessDeniedException ade) { request.setAttribute("title", "Acess Denied"); request.setAttribute( "messages", "Unable to approve access to the specified content: " + ade.getMessage()); // forward to the error page final ServletContext viewerContext = servletContext.getContext("/nifi"); viewerContext.getRequestDispatcher("/message").forward(request, response); return; } catch (final Exception e) { request.setAttribute("title", "Error"); request.setAttribute("messages", "An unexcepted error has occurred: " + e.getMessage()); // forward to the error page final ServletContext viewerContext = servletContext.getContext("/nifi"); viewerContext.getRequestDispatcher("/message").forward(request, response); return; } // determine how we want to view the data String mode = request.getParameter("mode"); // if the name isn't set, use original if (mode == null) { mode = DisplayMode.Original.name(); } // determine the display mode final DisplayMode displayMode; try { displayMode = DisplayMode.valueOf(mode); } catch (final IllegalArgumentException iae) { request.setAttribute("title", "Error"); request.setAttribute("messages", "Invalid display mode: " + mode); // forward to the error page final ServletContext viewerContext = servletContext.getContext("/nifi"); viewerContext.getRequestDispatcher("/message").forward(request, response); return; } // buffer the content to support reseting in case we need to detect the content type or char // encoding try (final BufferedInputStream bis = new BufferedInputStream(downloadableContent.getContent()); ) { final String mimeType; // when standalone and we don't know the type is null as we were able to directly access the // content bypassing the rest endpoint, // when clustered and we don't know the type set to octet stream since the content was // retrieved from the node's rest endpoint if (downloadableContent.getType() == null || downloadableContent.getType().equals(MediaType.OCTET_STREAM.toString())) { // attempt to detect the content stream if we don't know what it is () final DefaultDetector detector = new DefaultDetector(); // create the stream for tika to process, buffered to support reseting final TikaInputStream tikaStream = TikaInputStream.get(bis); // provide a hint based on the filename final Metadata metadata = new Metadata(); metadata.set(Metadata.RESOURCE_NAME_KEY, downloadableContent.getFilename()); // Get mime type final MediaType mediatype = detector.detect(tikaStream, metadata); mimeType = mediatype.toString(); } else { mimeType = downloadableContent.getType(); } // add attributes needed for the header request.setAttribute("filename", downloadableContent.getFilename()); request.setAttribute("contentType", mimeType); // generate the header request.getRequestDispatcher("/WEB-INF/jsp/header.jsp").include(request, response); // remove the attributes needed for the header request.removeAttribute("filename"); request.removeAttribute("contentType"); // generate the markup for the content based on the display mode if (DisplayMode.Hex.equals(displayMode)) { final byte[] buffer = new byte[BUFFER_LENGTH]; final int read = StreamUtils.fillBuffer(bis, buffer, false); // trim the byte array if necessary byte[] bytes = buffer; if (read != buffer.length) { bytes = new byte[read]; System.arraycopy(buffer, 0, bytes, 0, read); } // convert bytes into the base 64 bytes final String base64 = Base64.encodeBase64String(bytes); // defer to the jsp request.setAttribute("content", base64); request.getRequestDispatcher("/WEB-INF/jsp/hexview.jsp").include(request, response); } else { // lookup a viewer for the content final String contentViewerUri = servletContext.getInitParameter(mimeType); // handle no viewer for content type if (contentViewerUri == null) { request.getRequestDispatcher("/WEB-INF/jsp/no-viewer.jsp").include(request, response); } else { // create a request attribute for accessing the content request.setAttribute( ViewableContent.CONTENT_REQUEST_ATTRIBUTE, new ViewableContent() { @Override public InputStream getContentStream() { return bis; } @Override public String getContent() throws IOException { // detect the charset final CharsetDetector detector = new CharsetDetector(); detector.setText(bis); detector.enableInputFilter(true); final CharsetMatch match = detector.detect(); // ensure we were able to detect the charset if (match == null) { throw new IOException("Unable to detect character encoding."); } // convert the stream using the detected charset return IOUtils.toString(bis, match.getName()); } @Override public ViewableContent.DisplayMode getDisplayMode() { return displayMode; } @Override public String getFileName() { return downloadableContent.getFilename(); } @Override public String getContentType() { return mimeType; } }); try { // generate the content final ServletContext viewerContext = servletContext.getContext(contentViewerUri); viewerContext.getRequestDispatcher("/view-content").include(request, response); } catch (final Exception e) { String message = e.getMessage() != null ? e.getMessage() : e.toString(); message = "Unable to generate view of data: " + message; // log the error logger.error(message); if (logger.isDebugEnabled()) { logger.error(StringUtils.EMPTY, e); } // populate the request attributes request.setAttribute("title", "Error"); request.setAttribute("messages", message); // forward to the error page final ServletContext viewerContext = servletContext.getContext("/nifi"); viewerContext.getRequestDispatcher("/message").forward(request, response); return; } // remove the request attribute request.removeAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE); } } // generate footer request.getRequestDispatcher("/WEB-INF/jsp/footer.jsp").include(request, response); } }
public ServletContext getContext(String arg0) { return servletContext.getContext(arg0); }
public ServletContext getContext(String arg0) { return delegate.getContext(arg0); }