Example usage for javax.servlet ServletContext getAttribute

List of usage examples for javax.servlet ServletContext getAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletContext getAttribute.

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the servlet container attribute with the given name, or null if there is no attribute by that name.

Usage

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteResponseTest.java

@Test
public void testStreamResponse() throws IOException, MimeTypeParseException {
    UrlRewriteProcessor rewriter = EasyMock.createNiceMock(UrlRewriteProcessor.class);
    EasyMock.expect(rewriter.getConfig()).andReturn(null).anyTimes();

    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
    EasyMock.expect(context.getAttribute(UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME))
            .andReturn(rewriter).anyTimes();

    FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
    EasyMock.expect(config.getInitParameter(UrlRewriteServletFilter.RESPONSE_BODY_FILTER_PARAM))
            .andReturn("test-filter").anyTimes();
    EasyMock.expect(config.getServletContext()).andReturn(context).anyTimes();

    HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
    HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);

    EasyMock.replay(rewriter, context, config, request, response);

    UrlRewriteResponse rewriteResponse = new UrlRewriteResponse(config, request, response);

    String content = "content to test gzip streaming";
    testStreamResponseGzip(content, rewriteResponse, false);
    testStreamResponseGzip(content, rewriteResponse, true);
}

From source file:org.apache.hadoop.hdfs.server.namenode.DfsServlet.java

/**
 * Create a {@link NameNode} proxy from the current {@link ServletContext}. 
 */// w  ww  . j a va2  s. c om
protected ClientProtocol createNameNodeProxy() throws IOException {
    ServletContext context = getServletContext();
    // if we are running in the Name Node, use it directly rather than via 
    // rpc
    NameNode nn = (NameNode) context.getAttribute("name.node");
    if (nn != null) {
        return nn;
    }
    InetSocketAddress nnAddr = (InetSocketAddress) context.getAttribute("name.node.address");
    Configuration conf = new Configuration((Configuration) context.getAttribute(JspHelper.CURRENT_CONF));
    return DFSClient.createNamenode(nnAddr, conf);
}

From source file:org.exoplatform.frameworks.jcr.web.CommandControllerServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ServletContext servletCtx = getServletContext();
    ExoContainer container = (ExoContainer) servletCtx.getAttribute(WebConstants.EXO_CONTAINER);
    final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    boolean hasChanged = false;
    ClassLoader pcClassLoader = null;
    if (container == null) {
        container = PortalContainer.getCurrentInstance(servletCtx);
        if (container instanceof PortalContainer) {
            PortalContainer pc = (PortalContainer) container;
            pcClassLoader = pc.getPortalClassLoader();
            servletCtx = pc.getPortalContext();
        }/*from  ww  w .j a v  a  2  s.c o  m*/
    }

    SessionProviderService sessionProviderService = (SessionProviderService) container
            .getComponentInstanceOfType(SessionProviderService.class);

    RepositoryService repositoryService = (RepositoryService) container
            .getComponentInstanceOfType(RepositoryService.class);

    GenericWebAppContext ctx;
    try {
        ctx = new GenericWebAppContext(servletCtx, request, response,
                sessionProviderService.getSessionProvider(null), // null for
                // ThreadLocalSessionProvider
                repositoryService.getDefaultRepository());
    } catch (final RepositoryException e) {
        throw new IOException() {
            @Override
            public Throwable getCause() {
                return e;
            }
        };
    } catch (final RepositoryConfigurationException e) {
        throw new IOException() {
            @Override
            public Throwable getCause() {
                return e;
            }
        };
    }

    CommandService commandService = (CommandService) container.getComponentInstanceOfType(CommandService.class);
    String catalogName = (String) ctx.get(WebConstants.CATALOG_NAME);

    // command from context
    String commandName = (String) ctx.get("Command");
    if (commandName == null)
        throw new ServletException("No Command found at the Context");
    Command cmd;
    if (catalogName == null)
        cmd = commandService.getCatalog().getCommand(commandName);
    else
        cmd = commandService.getCatalog(catalogName).getCommand(commandName);

    if (cmd == null)
        throw new ServletException("No Command found " + commandName);
    try {
        if (pcClassLoader != null) {
            // Set the portal classloader to get all the resources defined within the portal context
            Thread.currentThread().setContextClassLoader(pcClassLoader);
            hasChanged = true;
        }
        cmd.execute(ctx);
    } catch (Exception e) {
        log.error("An error occurs while executing the command " + commandName, e);
        throw new ServletException(e);
    } finally {
        if (hasChanged) {
            // Re-set the old classloader
            Thread.currentThread().setContextClassLoader(currentClassLoader);
        }
    }
}

From source file:org.jaggeryjs.jaggery.core.listeners.WebAppSessionListener.java

@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    ServletContext ctx = httpSessionEvent.getSession().getServletContext();

    List<Object> jsListeners = (List<Object>) ctx.getAttribute(JaggeryCoreConstants.JS_CREATED_LISTENERS);
    if (jsListeners == null) {
        return;//from w w  w  .ja v a2  s.c o m
    }

    JaggeryContext shared = WebAppManager.sharedJaggeryContext(ctx);
    Context cx = shared.getEngine().enterContext();
    JaggeryContext context = CommonManager.getJaggeryContext();
    if (CommonManager.getJaggeryContext() == null) {
        context = WebAppManager.clonedJaggeryContext(ctx);
        CommonManager.setJaggeryContext(context);
    }
    RhinoEngine engine = context.getEngine();
    ScriptableObject clonedScope = context.getScope();

    JavaScriptProperty session = new JavaScriptProperty("session");
    session.setValue(cx.newObject(clonedScope, "Session", new Object[] { httpSessionEvent.getSession() }));
    session.setAttribute(ScriptableObject.READONLY);
    RhinoEngine.defineProperty(clonedScope, session);

    for (Object jsListener : jsListeners) {
        CommonManager.getCallstack(context).push((String) jsListener);
        try {
            ScriptReader sr = new ScriptReader(ctx.getResourceAsStream((String) jsListener)) {
                @Override
                protected void build() throws IOException {
                    try {
                        sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                    } catch (ScriptException e) {
                        throw new IOException(e);
                    }
                }
            };
            engine.exec(sr, clonedScope, null);
        } catch (ScriptException e) {
            log.error(e.getMessage(), e);
        } finally {
            CommonManager.getCallstack(context).pop();
        }
    }
    Context.exit();
}

From source file:org.apache.struts.util.ModuleUtils.java

/**
 * Return the list of module prefixes that are defined for this web
 * application.  <strong>NOTE</strong> - the "" prefix for the default
 * module is not included in this list.//from w  w  w  .  ja  v a 2 s  . co m
 *
 * @param context The ServletContext for this web application.
 * @return An array of module prefixes.
 */
public String[] getModulePrefixes(ServletContext context) {
    return (String[]) context.getAttribute(Globals.MODULE_PREFIXES_KEY);
}

From source file:org.apache.hadoop.hdfsproxy.TestProxyFilter.java

public void testDoFilterHttp() throws ServletException, IOException {
    ProxyFilter filter = new ProxyFilter();

    ServletContext context = config.getServletContext();
    context.removeAttribute("name.node.address");
    context.removeAttribute("name.conf");
    assertNull(context.getAttribute("name.node.address"));
    assertNull(context.getAttribute("name.conf"));

    filter.init(config);//w  w  w  .  j  a  v  a 2  s.co m

    assertNotNull(context.getAttribute("name.node.address"));
    assertNotNull(context.getAttribute("name.conf"));

    request.removeAttribute("authorized.ugi");
    assertNull(request.getAttribute("authorized.ugi"));

    FilterChain mockFilterChain = new DummyFilterChain();
    filter.doFilter(request, response, mockFilterChain);
    assertEquals(request.getAttribute("authorized.ugi").toString(), "nobody,test");

}

From source file:commands.SendAnalysisRequest.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response, Controller controller) {
    //http://commons.apache.org/proper/commons-fileupload/using.html
    //process only if its multipart content
    String page = "Problem.jsp";
    if (ServletFileUpload.isMultipartContent(request)) {
        try {/*from   ww w.j a va2  s. c o  m*/
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // Configure a repository (to ensure a secure temp location is used)
            ServletContext servletContext = controller.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            System.out.println("File repository absolute path: " + repository.getAbsolutePath());

            factory.setRepository(repository);

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            //parametros chave-valor (path valor)
            HashMap<String, String[]> params = new HashMap<String, String[]>();
            //parametros chave-valor para multimedia (path e array de bytes)
            HashMap<String, byte[]> mediaParams = new HashMap<String, byte[]>();

            // Tratando todos os parametros/itens da pagina (arquivos e no-arquivos)
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                //key (path)
                FileItem item = iter.next();
                String key = item.getFieldName();

                if (item.isFormField()) {
                    //printFormField(item);
                    //value
                    String[] value = new String[1];
                    value[0] = item.getString();
                    params.put(key, value);
                } else {
                    //printUploadedFile(item);
                    byte[] value = item.get();
                    mediaParams.put(key, value);
                }
            }

            //File uploaded successfully
            //              request.setAttribute("message", "File Uploaded Successfully");
            long result = new ParamedicController().sendAnalysisRequest(params, 1, mediaParams);

            if (result == -1) {
                request.setAttribute("message", "Occurred a problem to sending analysis request");
            } else {
                request.setAttribute("idAnalysis", result);
                request.setAttribute("message", "Analysis request sent successfully");
                page = "AnalysisResponseSearch.jsp";
                //RequestDispatcher reqDispatcher = request.getRequestDispatcher("AnalysisResponseSearch.jsp");
                //reqDispatcher.forward(request, response);
            }

            //                request.getRequestDispatcher("AnalysisResponseSearch.jsp").forward(request, response);
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
            ex.printStackTrace();
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }
    try {
        request.getRequestDispatcher(page).forward(request, response);
    } catch (ServletException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:no.kantega.publishing.spring.OpenAksessContextLoaderListener.java

private File getDataDirectory(ServletContext context) {
    File dataDirectory = (File) context.getAttribute(DataDirectoryContextListener.DATA_DIRECTORY_ATTR);

    if (dataDirectory == null) {
        throw new NullPointerException(
                "dataDirectory attribute " + DataDirectoryContextListener.DATA_DIRECTORY_ATTR + " was not set");
    }/*from   w w w  .j  a v a 2s .  c  om*/
    return dataDirectory;
}

From source file:org.eclipse.equinox.http.servlet.internal.multipart.MultipartSupportImpl.java

public MultipartSupportImpl(ExtendedServletDTO servletDTO, ServletContext servletContext) {
    this.servletDTO = servletDTO;

    // Must return non-null File. See Servlet 3.1 4.8.1
    File baseStorage = (File) servletContext.getAttribute(ServletContext.TEMPDIR);

    if (servletDTO.multipartLocation.length() > 0) {
        File storage = new File(servletDTO.multipartLocation);

        if (!storage.isAbsolute()) {
            storage = new File(baseStorage, storage.getPath());
        }/* ww w.j  a v  a  2 s. c o m*/

        baseStorage = storage;
    }

    checkPermission(baseStorage, servletContext);

    baseStorage.mkdirs();

    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setRepository(baseStorage);

    if (servletDTO.multipartFileSizeThreshold > 0) {
        factory.setSizeThreshold(servletDTO.multipartFileSizeThreshold);
    }

    upload = new ServletFileUpload(factory);

    if (servletDTO.multipartMaxFileSize > -1L) {
        upload.setFileSizeMax(servletDTO.multipartMaxFileSize);
    }

    if (servletDTO.multipartMaxRequestSize > -1L) {
        upload.setSizeMax(servletDTO.multipartMaxRequestSize);
    }
}

From source file:gov.nih.nci.ncicb.cadsr.common.security.LogoutServlet.java

protected ApplicationServiceLocator getApplicationServiceLocator(ServletContext sc)
        throws ServiceLocatorException {
    ApplicationServiceLocator appServiceLocator = (ApplicationServiceLocator) sc
            .getAttribute(ApplicationServiceLocator.APPLICATION_SERVICE_LOCATOR_CLASS_KEY);
    if (appServiceLocator == null)
        throw new ServiceLocatorException("Could no find ApplicationServiceLocator with key ="
                + ApplicationServiceLocator.APPLICATION_SERVICE_LOCATOR_CLASS_KEY);
    return appServiceLocator;
}