List of usage examples for javax.servlet ServletContext getAttribute
public Object getAttribute(String name);
null
if there is no attribute by that name. From source file:org.artifactory.webapp.servlet.ArtifactoryContextConfigListener.java
/** * Disable sessionId in URL (Servlet 3.0 containers) by setting the session tracking mode to SessionTrackingMode.COOKIE * For Servlet container < 3.0 we use different method (for tomcat 6 we use custom context.xml and for jetty * there is a custom jetty.xml file)./*from w w w.j av a2 s. co m*/ */ @SuppressWarnings("unchecked") private void setSessionTrackingMode(ServletContext servletContext) { // Only for Servlet container version 3.0 and above if (servletContext.getMajorVersion() < 3) { return; } // We cannot use ConstantValue.enableURLSessionId.getBoolean() since ArtifactoryHome is not binded yet. ArtifactoryHome artifactoryHome = (ArtifactoryHome) servletContext .getAttribute(ArtifactoryHome.SERVLET_CTX_ATTR); if (artifactoryHome == null) { throw new IllegalStateException("Artifactory home not initialized."); } if (artifactoryHome.getArtifactoryProperties() .getBooleanProperty(ConstantValues.supportUrlSessionTracking)) { getLogger().debug("Skipping setting session tracking mode to COOKIE, enableURLSessionId flag it on."); return; } try { // load enum with reflection ClassLoader cl = ClassUtils.getDefaultClassLoader(); Class<Enum> trackingModeEnum = (Class<Enum>) cl.loadClass("javax.servlet.SessionTrackingMode"); Enum cookieTrackingMode = Enum.valueOf(trackingModeEnum, "COOKIE"); // reflective call servletContext.setSessionTrackingModes(trackingModes) Method method = servletContext.getClass().getMethod("setSessionTrackingModes", Set.class); method.setAccessible(true); ReflectionUtils.invokeMethod(method, servletContext, Sets.newHashSet(cookieTrackingMode)); getLogger().debug("Successfully set session tracking mode to COOKIE"); } catch (Exception e) { getLogger().warn("Failed to set session tracking mode: " + e.getMessage()); } }
From source file:org.apache.nifi.web.ContentViewerController.java
/** * Gets the content and defers to registered viewers to generate the markup. * * @param request servlet request/*from w ww . j a va 2s. co m*/ * @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; try { contentRequest = getContentRequest(request); } catch (final Exception e) { request.setAttribute("title", "Error"); request.setAttribute("messages", "Unable to interpret content request."); // forward to the error page final ServletContext viewerContext = servletContext.getContext("/nifi"); viewerContext.getRequestDispatcher("/message").forward(request, response); return; } 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", "Access 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 unexpected 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 resetting in case we need to detect the content type or char encoding try (final BufferedInputStream bis = new BufferedInputStream(downloadableContent.getContent());) { final String mimeType; final String normalizedMimeType; // 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 || StringUtils .startsWithIgnoreCase(downloadableContent.getType(), 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(); } // Extract only mime type and subtype from content type (anything after the first ; are parameters) // Lowercase so subsequent code does not need to implement case insensitivity normalizedMimeType = mimeType.split(";", 2)[0].toLowerCase(); // 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(normalizedMimeType); // 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 normalizedMimeType; } @Override public String getRawContentType() { 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); } }
From source file:com.athena.sqs.MessageDispatchListener.java
public void contextInitialized(ServletContextEvent sce) { ServletContext servletContext = sce.getServletContext(); sqsConfigLocation = servletContext.getInitParameter("sqsConfigLocation"); String realPath = servletContext.getRealPath(sqsConfigLocation); if (logger.isDebugEnabled()) { logger.debug("****************** SQS Config ******************"); logger.debug("LOCATION : " + sqsConfigLocation); logger.debug("REAL LOCATION : " + realPath); logger.debug("************************************************"); }//w ww. j a v a2 s. c o m ApplicationContext applicationContext = (ApplicationContext) servletContext .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); // TODO : You can load your own application config here }
From source file:easyJ.http.upload.CommonsMultipartRequestHandler.java
/** * Returns the path to the temporary directory to be used for uploaded files * which are written to disk. The directory used is determined from the * first of the following to be non-empty. * <ol>/*from www. jav a2s . c o m*/ * <li>A temp dir explicitly defined either using the <code>tempDir</code> * servlet init param, or the <code>tempDir</code> attribute of the * <controller> element in the Struts config file.</li> * <li>The container-specified temp dir, obtained from the * <code>javax.servlet.context.tempdir</code> servlet context attribute.</li> * <li>The temp dir specified by the <code>java.io.tmpdir</code> system * property.</li> * (/ol> * * @param mc * The module config instance for which the path should be * determined. * @return The path to the directory to be used to store uploaded files. */ protected String getRepositoryPath(ModuleConfig mc) { // First, look for an explicitly defined temp dir. String tempDir = mc.getControllerConfig().getTempDir(); // If none, look for a container specified temp dir. if (tempDir == null || tempDir.length() == 0) { if (servlet != null) { ServletContext context = servlet.getServletContext(); File tempDirFile = (File) context.getAttribute("javax.servlet.context.tempdir"); tempDir = tempDirFile.getAbsolutePath(); } // If none, pick up the system temp dir. if (tempDir == null || tempDir.length() == 0) { tempDir = System.getProperty("java.io.tmpdir"); } } return tempDir; }
From source file:com.skilrock.lms.web.accMgmt.common.AgentPaymentSubmit.java
/** * This method is used to submit the payment made by the Agent * /* w ww . j a v a2s .co m*/ * @return SUCCESS * @throws LMSException */ public String start() { HttpSession session = null; String isCREnable = "INACTIVE"; try { session = getRequest().getSession(); ServletContext sc = ServletActionContext.getServletContext(); UserInfoBean userBean = (UserInfoBean) session.getAttribute("USER_INFO"); logger.info( "REQUEST_CASH_PAYMENT_MENU-" + request.getAttribute("AUDIT_ID") + ":" + userBean.getUserId()); isCREnable = (String) sc.getAttribute("IS_CASH_REGISTER"); if ("ACTIVE".equalsIgnoreCase(isCREnable)) { QueryHelper qp = new QueryHelper(); isCREnable = qp.checkDrawerAvailablity(userBean.getUserId()); if ("INACTIVE".equals(isCREnable)) { throw new LMSException(LMSErrors.DRAWER_NOT_ASSIGN_ERROR_CODE, LMSErrors.DRAWER_NOT_ASSIGN_ERROR_MESSAGE); } } isCashRegister = isCREnable; //session.setAttribute("isCashRegister",isCREnable); agentInfoMap = CommonMethods.getOrgInfoMap(userBean.getUserOrgId(), "AGENT", userBean.getRoleId()); logger.info("RESPONSE_CASH_PAYMENT_MENU-: cash register" + isCREnable); } catch (LMSException le) { logger.error("Exception", le); logger.info("RESPONSE_CASH_PAYMENT_MENU-: ErrorCode:" + le.getErrorCode() + " ErrorMessage:" + le.getErrorMessage()); request.setAttribute("LMS_EXCEPTION", le.getErrorMessage()); return "applicationException"; } catch (Exception e) { e.printStackTrace(); logger.info("RESPONSE_CASH_PAYMENT_MENU-: ErrorCode:" + LMSErrors.GENERAL_EXCEPTION_ERROR_CODE + " ErrorMessage:" + LMSErrors.GENERAL_EXCEPTION_ERROR_MESSAGE); request.setAttribute("LMS_EXCEPTION", LMSErrors.GENERAL_EXCEPTION_ERROR_MESSAGE); return "applicationException"; } return SUCCESS; }
From source file:org.apache.hadoop.hbase.http.TestHttpServer.java
@Test public void testRequiresAuthorizationAccess() throws Exception { Configuration conf = new Configuration(); ServletContext context = Mockito.mock(ServletContext.class); Mockito.when(context.getAttribute(HttpServer.CONF_CONTEXT_ATTRIBUTE)).thenReturn(conf); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); //requires admin access to instrumentation, FALSE by default Assert.assertTrue(HttpServer.isInstrumentationAccessAllowed(context, request, response)); //requires admin access to instrumentation, TRUE conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_INSTRUMENTATION_REQUIRES_ADMIN, true); conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, true); AccessControlList acls = Mockito.mock(AccessControlList.class); Mockito.when(acls.isUserAllowed(Mockito.<UserGroupInformation>any())).thenReturn(false); Mockito.when(context.getAttribute(HttpServer.ADMINS_ACL)).thenReturn(acls); Assert.assertFalse(HttpServer.isInstrumentationAccessAllowed(context, request, response)); }
From source file:org.apache.myfaces.component.html.util.StreamingResourceLoader.java
public void serveResource(ServletContext context, HttpServletRequest request, HttpServletResponse response, String resourceUri) throws IOException { // Technically here we should check for "/header.css" on the end of the url. But right now, // this ResourceLoader only ever serves that one "virtual" css resource, so this request // cannot be for anything else... int pos = resourceUri.indexOf("/"); Long requestId = new Long(Long.parseLong(resourceUri.substring(0, pos), 10)); StreamingThreadManager manager = (StreamingThreadManager) context.getAttribute(StreamingThreadManager.KEY); StreamingThreadManager.HeaderInfoEntry headerInfoEntry = manager.getHeaderInfo(requestId); if (headerInfoEntry == null) { log.warn("No streamable resources found for request: " + requestId + " resourceUri: " + resourceUri); return;//from ww w. j a va 2 s.co m } /* * Ensure the browser doesn't cache this response. We never generate the same url twice * (the requestId value embedded in the url changes for each request) so storing the * response in a browser cache is just a waste; the cached data would never be used again. */ response.setHeader("pragma", "no-cache"); response.setHeader("Cache-control", "no-cache, must-revalidate"); try { PrintWriter pw = response.getWriter(); StreamingAddResource.StreamablePositionedInfo positionedInfo; try { while ((positionedInfo = headerInfoEntry.fetchInfo()) != null) { positionedInfo.writePositionedInfo(response, pw); pw.flush(); } pw.close(); } catch (InterruptedException e) { throw (IOException) new IOException().initCause(e); } } finally { manager.removeHeaderInfo(requestId); } }
From source file:serendip.struts.plugins.thymeleaf.ThymeleafSpringResult.java
@Override public void execute(ActionInvocation actionInvocation) throws Exception { TemplateEngine templateEngine = templateEngineProvider.get(); HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); ServletContext servletContext = ServletActionContext.getServletContext(); Object action = actionInvocation.getAction(); // Action instance put to Thymeleaf context. Map<String, Object> variables = bindStrutsContest(action); // Locale by Struts2-Action. Locale locale = ((LocaleProvider) action).getLocale(); // Spring-ApplicationContext. //ApplicationContext appctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); ApplicationContext appctx = (ApplicationContext) servletContext .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); // Use SpringWebContext( by Thymeleaf-spring plugin. ) SpringWebContext context = new SpringWebContext(request, response, servletContext, locale, variables, appctx);//www. ja v a 2 s .com // response to TemplateEngine. response.setContentType("text/html"); response.setCharacterEncoding(defaultEncoding); templateEngine.process(templateName, context, response.getWriter()); }
From source file:com.adito.boot.Util.java
/** * Dump all servlet context attributes to {@link System#err}. * //www .ja v a2 s . c om * @param context context to get attributes from */ public static void dumpServletContextAttributes(ServletContext context) { System.err.println("Servlet context attributes for"); for (Enumeration e = context.getAttributeNames(); e.hasMoreElements();) { String n = (String) e.nextElement(); System.err.println(" " + n + " = " + context.getAttribute(n)); } }
From source file:org.apache.hadoop.hbase.http.TestHttpServer.java
@Test public void testHasAdministratorAccess() throws Exception { Configuration conf = new Configuration(); conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false); ServletContext context = Mockito.mock(ServletContext.class); Mockito.when(context.getAttribute(HttpServer.CONF_CONTEXT_ATTRIBUTE)).thenReturn(conf); Mockito.when(context.getAttribute(HttpServer.ADMINS_ACL)).thenReturn(null); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getRemoteUser()).thenReturn(null); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); //authorization OFF Assert.assertTrue(HttpServer.hasAdministratorAccess(context, request, response)); //authorization ON & user NULL response = Mockito.mock(HttpServletResponse.class); conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, true); Assert.assertFalse(HttpServer.hasAdministratorAccess(context, request, response)); Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED), Mockito.anyString()); //authorization ON & user NOT NULL & ACLs NULL response = Mockito.mock(HttpServletResponse.class); Mockito.when(request.getRemoteUser()).thenReturn("foo"); Assert.assertTrue(HttpServer.hasAdministratorAccess(context, request, response)); //authorization ON & user NOT NULL & ACLs NOT NULL & user not in ACLs response = Mockito.mock(HttpServletResponse.class); AccessControlList acls = Mockito.mock(AccessControlList.class); Mockito.when(acls.isUserAllowed(Mockito.<UserGroupInformation>any())).thenReturn(false); Mockito.when(context.getAttribute(HttpServer.ADMINS_ACL)).thenReturn(acls); Assert.assertFalse(HttpServer.hasAdministratorAccess(context, request, response)); Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED), Mockito.anyString()); //authorization ON & user NOT NULL & ACLs NOT NULL & user in in ACLs response = Mockito.mock(HttpServletResponse.class); Mockito.when(acls.isUserAllowed(Mockito.<UserGroupInformation>any())).thenReturn(true); Mockito.when(context.getAttribute(HttpServer.ADMINS_ACL)).thenReturn(acls); Assert.assertTrue(HttpServer.hasAdministratorAccess(context, request, response)); }