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.hbase.http.HttpServer.java

/**
 * Does the user sending the HttpServletRequest has the administrator ACLs? If
 * it isn't the case, response will be modified to send an error to the user.
 *
 * @param servletContext//from   w  w w .  ja  v a2  s.  c o m
 * @param request
 * @param response used to send the error response if user does not have admin access.
 * @return true if admin-authorized, false otherwise
 * @throws IOException
 */
public static boolean hasAdministratorAccess(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    Configuration conf = (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);
    // If there is no authorization, anybody has administrator access.
    if (!conf.getBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false)) {
        return true;
    }

    String remoteUser = request.getRemoteUser();
    if (remoteUser == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Unauthenticated users are not " + "authorized to access this page.");
        return false;
    }

    if (servletContext.getAttribute(ADMINS_ACL) != null
            && !userHasAdministratorAccess(servletContext, remoteUser)) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "User " + remoteUser + " is unauthorized to access this page.");
        return false;
    }

    return true;
}

From source file:org.apache.struts2.views.freemarker.FreemarkerManager.java

public final synchronized freemarker.template.Configuration getConfiguration(ServletContext servletContext)
        throws TemplateException {
    freemarker.template.Configuration config = (freemarker.template.Configuration) servletContext
            .getAttribute(CONFIG_SERVLET_CONTEXT_KEY);

    if (config == null) {
        config = createConfiguration(servletContext);

        // store this configuration in the servlet context
        servletContext.setAttribute(CONFIG_SERVLET_CONTEXT_KEY, config);
    }/*w  w w.j  ava 2s.  c o m*/

    config.setWhitespaceStripping(true);

    return config;
}

From source file:org.red5.logging.ContextLoggingListener.java

public void contextInitialized(ServletContextEvent event) {
    ServletContext servletContext = event.getServletContext();
    String contextName = servletContext.getContextPath().replaceAll("/", "");
    if ("".equals(contextName)) {
        contextName = "root";
    }/*  w w w .j  av  a  2  s .  com*/
    System.out.printf("Context init: %s%n", contextName);
    ConfigurableWebApplicationContext appctx = (ConfigurableWebApplicationContext) servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (appctx != null) {
        System.out.printf(
                "ConfigurableWebApplicationContext is not null in ContextLoggingListener for: %s, this indicates a misconfiguration or load order problem%n",
                contextName);
    }
    try {
        // get the selector
        ContextSelector selector = Red5LoggerFactory.getContextSelector();
        // get the logger context for this servlet / app context by name
        URL url = servletContext.getResource(String.format("/WEB-INF/classes/logback-%s.xml", contextName));
        if (url != null && Files.exists(Paths.get(url.toURI()))) {
            System.out.printf("Context logger config found: %s%n", url.toURI());
        } else {
            url = servletContext.getResource("/WEB-INF/classes/logback.xml");
            if (url != null && Files.exists(Paths.get(url.toURI()))) {
                System.out.printf("Context logger config found: %s%n", url.toURI());
            }
        }
        // get the logger context for the servlet context
        LoggerContext loggerContext = url != null
                ? ((LoggingContextSelector) selector).getLoggerContext(contextName, url)
                : selector.getLoggerContext(contextName);
        // set the logger context for use elsewhere in the servlet context
        servletContext.setAttribute(Red5LoggerFactory.LOGGER_CONTEXT_ATTRIBUTE, loggerContext);
        // get the root logger for this context
        Logger logger = Red5LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME, contextName);
        logger.info("Starting up context: {}", contextName);
    } catch (Exception e) {
        System.err.printf("LoggingContextSelector is not the correct type: %s%n", e.getMessage());
        e.printStackTrace();
    }
}

From source file:be.fedict.eid.idp.sp.protocol.openid.AuthenticationRequestServlet.java

/**
 * {@inheritDoc}//from   w w w.  j av  a2  s .c  o  m
 */
@Override
public void init(ServletConfig config) throws ServletException {

    this.userIdentifier = config.getInitParameter(USER_IDENTIFIER_PARAM);
    this.spDestination = config.getInitParameter(SP_DESTINATION_PARAM);
    this.spDestinationPage = config.getInitParameter(SP_DESTINATION_PAGE_PARAM);
    this.languages = config.getInitParameter(LANGUAGES_PARAM);
    this.authenticationRequestServiceLocator = new ServiceLocator<AuthenticationRequestService>(
            AUTHN_REQUEST_SERVICE_PARAM, config);

    // validate necessary configuration params
    if (null == this.userIdentifier && !this.authenticationRequestServiceLocator.isConfigured()) {
        throw new ServletException("need to provide either " + USER_IDENTIFIER_PARAM + " or "
                + AUTHN_REQUEST_SERVICE_PARAM + "(Class) init-params");
    }

    if (null == this.spDestination && null == this.spDestinationPage
            && !this.authenticationRequestServiceLocator.isConfigured()) {
        throw new ServletException("need to provide either " + SP_DESTINATION_PARAM + " or "
                + SP_DESTINATION_PAGE_PARAM + " or " + AUTHN_REQUEST_SERVICE_PARAM + "(Class) init-param");
    }

    // SSL configuration
    String trustServer = config.getInitParameter(TRUST_SERVER_PARAM);
    if (null != trustServer) {
        this.trustServer = Boolean.parseBoolean(trustServer);
    }
    X509Certificate serverCertificate = null;
    if (this.authenticationRequestServiceLocator.isConfigured()) {
        AuthenticationRequestService service = this.authenticationRequestServiceLocator.locateService();
        serverCertificate = service.getServerCertificate();
    }

    if (this.trustServer) {

        LOG.warn("Trusting all SSL server certificates!");
        try {
            OpenIDSSLSocketFactory.installAllTrusted();
        } catch (Exception e) {
            throw new ServletException("could not install OpenID SSL Socket Factory: " + e.getMessage(), e);
        }
    } else if (null != serverCertificate) {

        LOG.info("Trusting specified SSL certificate: " + serverCertificate);
        try {
            OpenIDSSLSocketFactory.install(serverCertificate);
        } catch (Exception e) {
            throw new ServletException("could not install OpenID SSL Socket Factory: " + e.getMessage(), e);
        }
    }

    ServletContext servletContext = config.getServletContext();
    this.consumerManager = (ConsumerManager) servletContext.getAttribute(CONSUMER_MANAGER_ATTRIBUTE);

    if (null == this.consumerManager) {
        try {
            if (this.trustServer || null != serverCertificate) {

                TrustManager trustManager;
                if (this.trustServer) {
                    trustManager = new OpenIDTrustManager();
                } else {
                    trustManager = new OpenIDTrustManager(serverCertificate);
                }

                SSLContext sslContext = SSLContext.getInstance("SSL");
                TrustManager[] trustManagers = { trustManager };
                sslContext.init(null, trustManagers, null);
                HttpFetcherFactory httpFetcherFactory = new HttpFetcherFactory(sslContext,
                        SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                YadisResolver yadisResolver = new YadisResolver(httpFetcherFactory);
                RealmVerifierFactory realmFactory = new RealmVerifierFactory(yadisResolver);
                HtmlResolver htmlResolver = new HtmlResolver(httpFetcherFactory);
                XriResolver xriResolver = Discovery.getXriResolver();
                Discovery discovery = new Discovery(htmlResolver, yadisResolver, xriResolver);
                this.consumerManager = new ConsumerManager(realmFactory, discovery, httpFetcherFactory);

            } else {
                this.consumerManager = new ConsumerManager();
            }
        } catch (Exception e) {
            throw new ServletException("could not init OpenID ConsumerManager");
        }
        servletContext.setAttribute(CONSUMER_MANAGER_ATTRIBUTE, this.consumerManager);
    }
}

From source file:org.apache.hadoop.raid.CorruptFileCounterServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletContext context = getServletContext();
    RaidNode raidNode = (RaidNode) context.getAttribute("raidnode");
    PrintWriter out = response.getWriter();
    Map<String, Map<CorruptFileStatus, Long>> corruptFilesCounterMap = raidNode.getCorruptFilesCounterMap();
    String path = request.getParameter(CORRUPT_DIR_KEY);
    String sorterField = request.getParameter("sorter/field");
    String sorterOrder = request.getParameter("sorter/order");
    if (path == null || path.length() == 0) {
        String monitorDir = request.getParameter("root");
        if (monitorDir == null || monitorDir.length() == 0) {
            generateWarningText(out, corruptFilesCounterMap, raidNode);
        } else {/*from   w w  w  .  j a  v a 2  s  .  co m*/
            String status = request.getParameter("status");
            if (status == null || status.length() == 0) {
                String recoveryTime = request.getParameter("recoverytime");
                if (recoveryTime == null || recoveryTime.length() == 0) {
                    generateWarningText(out, corruptFilesCounterMap, raidNode);
                } else {
                    generateFilesContent(out, monitorDir, Long.parseLong(recoveryTime), raidNode);
                }
            } else {
                generateFileStatus(out, monitorDir, status, raidNode, sorterField, sorterOrder);
            }
        }
    } else {
        if (corruptFilesCounterMap.containsKey(path)) {
            out.println(corruptFilesCounterMap.get(path).get(CorruptFileStatus.RAID_UNRECOVERABLE)
                    + corruptFilesCounterMap.get(path).get(CorruptFileStatus.NOT_RAIDED_UNRECOVERABLE));
        }
    }
    InjectionHandler.processEventIO(InjectionEvent.RAID_HTTPSERVER_TIMEOUT);
}

From source file:org.apache.pluto.driver.PortalStartupListener.java

/**
 * Receives the startup notification and subsequently starts up the portal
 * driver. The following are done in this order:
 * <ol>//from ww  w .  j  av  a2s .  com
 * <li>Retrieve the ResourceConfig File</li>
 * <li>Parse the ResourceConfig File into ResourceConfig Objects</li>
 * <li>Create a Portal Context</li>
 * <li>Create the ContainerServices implementation</li>
 * <li>Create the Portlet Container</li>
 * <li>Initialize the Container</li>
 * <li>Bind the configuration to the ServletContext</li>
 * <li>Bind the container to the ServletContext</li>
 * <ol>
 *
 * @param event the servlet context event.
 */
public void contextInitialized(ServletContextEvent event) {
    LOG.info("Starting up Pluto Portal Driver. . .");

    ServletContext servletContext = event.getServletContext();

    WebApplicationContext springContext = null;

    try {
        springContext = (WebApplicationContext) servletContext
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

    } catch (RuntimeException ex) {
        String msg = "Problem getting Spring context: " + ex.getMessage();
        LOG.error(msg, ex);
        throw ex;
    }

    LOG.debug(" [1a] Loading DriverConfiguration. . . ");
    DriverConfiguration driverConfiguration = (DriverConfiguration) springContext
            .getBean("DriverConfiguration");

    driverConfiguration.init(servletContext);

    LOG.debug(" [1b] Registering DriverConfiguration. . .");
    servletContext.setAttribute(DRIVER_CONFIG_KEY, driverConfiguration);

    LOG.debug(" [2a] Loading Optional AdminConfiguration. . .");
    AdminConfiguration adminConfiguration = (AdminConfiguration) springContext.getBean("AdminConfiguration");

    if (adminConfiguration != null) {
        LOG.debug(" [2b] Registering Optional AdminConfiguration");
        servletContext.setAttribute(ADMIN_CONFIG_KEY, adminConfiguration);
    } else {
        LOG.info("Optional AdminConfiguration not found. Ignoring.");
    }

    //        LOG.debug(" [3a] Loading VWBConfiguration. . .");
    //        VWBConfiguration vwbconfig = (VWBConfiguration)springContext.getBean("VWBConfiguration");
    //        vwbconfig.init(servletContext);

    //        LOG.debug(" [3b] Registering VWBConfiguration. . .");
    //        servletContext.setAttribute(VWB_CONFIG_KEY, vwbconfig);
    //        PortalSessionServiceImpl.init(vwbconfig);

    initContainer(servletContext);

    LOG.info("********** Pluto Portal Driver Started **********\n\n");
}

From source file:com.esd.ps.LoginController.java

/**
 * ??//  w ww .j  a  v  a 2 s . c om
 * @param loginName
 * @param request
 * @return
 */
public int loginName(String loginName, HttpServletRequest request) {
    ServletContext servletContext = request.getSession().getServletContext();
    if (servletContext.getAttribute(loginName) == null) {
        servletContext.setAttribute(loginName, loginName);
        return 1;
    }
    return 0;
}

From source file:org.apache.hadoop.gateway.hdfs.dispatch.WebHdfsHaHttpClientDispatchTest.java

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "WEBHDFS";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(/* w w w  .ja v  a2 s.  c o  m*/
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000"));
    HaProvider provider = new DefaultHaProvider(descriptor);
    URI uri1 = new URI("http://unreachable-host");
    URI uri2 = new URI("http://reachable-host");
    ArrayList<String> urlList = new ArrayList<String>();
    urlList.add(uri1.toString());
    urlList.add(uri2.toString());
    provider.addHaService(serviceName, urlList);
    FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);

    EasyMock.expect(filterConfig.getInitParameter(WebHdfsHaHttpClientDispatch.RESOURCE_ROLE_ATTRIBUTE))
            .andReturn(serviceName).anyTimes();
    EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME))
            .andReturn(provider).anyTimes();

    BasicHttpParams params = new BasicHttpParams();

    HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class);
    EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes();
    EasyMock.expect(outboundRequest.getURI()).andReturn(uri1).anyTimes();
    EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes();

    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getRequestURL()).andReturn(new StringBuffer(uri2.toString())).once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0))
            .once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1))
            .once();

    HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.expect(outboundResponse.getOutputStream()).andAnswer(new IAnswer<ServletOutputStream>() {
        @Override
        public ServletOutputStream answer() throws Throwable {
            return new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                    throw new IOException("unreachable-host");
                }
            };
        }
    }).once();
    EasyMock.replay(filterConfig, servletContext, outboundRequest, inboundRequest, outboundResponse);
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    WebHdfsHaHttpClientDispatch dispatch = new WebHdfsHaHttpClientDispatch();
    dispatch.init(filterConfig);
    long startTime = System.currentTimeMillis();
    try {
        dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } catch (IOException e) {
        //this is expected after the failover limit is reached
    }
    long elapsedTime = System.currentTimeMillis() - startTime;
    Assert.assertEquals(uri2.toString(), provider.getActiveURL(serviceName));
    //test to make sure the sleep took place
    Assert.assertTrue(elapsedTime > 1000);
}

From source file:jp.terasoluna.fw.web.struts.reset.ResetterImpl.java

/**
 * ResetterResources CX^X?B//from  ww  w.  j  a va  2s. co  m
 *
 * @param request NGXg?
 * @return ResetterResources CX^X
 * @see jp.terasoluna.fw.web.struts.reset.ActionReset
 * @see jp.terasoluna.fw.web.struts.reset.FieldReset
 */
protected ResetterResources getResetterResources(HttpServletRequest request) {

    // Prefix
    String prefix = ModuleUtil.getPrefix(request);

    // ServletContext
    ServletContext application = RequestUtil.getServletContext(request);

    // ResetterResource
    ResetterResources resources = (ResetterResources) application
            .getAttribute(ResetterResources.RESETTER_RESOURCES_KEY + prefix);

    return resources;
}

From source file:org.apache.hadoop.http.HttpServer2.java

/**
 * Does the user sending the HttpServletRequest has the administrator ACLs? If
 * it isn't the case, response will be modified to send an error to the user.
 *
 * @param response used to send the error response if user does not have admin access.
 * @return true if admin-authorized, false otherwise
 * @throws IOException/*from  w ww  .  ja va  2 s .c o  m*/
 */
public static boolean hasAdministratorAccess(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    Configuration conf = (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);
    // If there is no authorization, anybody has administrator access.
    if (!conf.getBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false)) {
        return true;
    }

    String remoteUser = request.getRemoteUser();
    if (remoteUser == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Unauthenticated users are not " + "authorized to access this page.");
        return false;
    }

    if (servletContext.getAttribute(ADMINS_ACL) != null
            && !userHasAdministratorAccess(servletContext, remoteUser)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN,
                "User " + remoteUser + " is unauthorized to access this page.");
        return false;
    }

    return true;
}