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.hyperic.hq.ui.taglib.HelpTag.java

public int doStartTag() throws JspException {
    JspWriter output = pageContext.getOut();
    String helpURL = HELP_BASE_URL;
    String helpUrlFromProFile = null;

    if (context) {
        ServletContext servletContext = pageContext.getServletContext();
        if (servletContext != null) {
            helpUrlFromProFile = (String) servletContext.getAttribute("helpBaseURL");
            log.debug("helpUrlFromPropertyFile=" + helpUrlFromProFile);
        }/*from w  ww.jav a2  s  . com*/
        if (!StringUtils.isEmpty(helpUrlFromProFile)) {
            helpURL = helpUrlFromProFile;
        }

        /* ignore context for now   
         *   String helpContext = (String) pageContext.getRequest().getAttribute(Constants.PAGE_TITLE_KEY);
                      
              if ( helpContext != null)
        helpURL = helpURL + "/?key=ui-" + helpContext;
        */
    }
    //helpURL+=key;      

    try {
        output.print(helpURL);
    } catch (IOException e) {
        throw new JspException(e);
    }

    return SKIP_BODY;
}

From source file:org.intermine.web.logic.session.SessionMethods.java

/**
 * Return the ReportObjects Map from the session or create and return it if it doesn't exist.
 *
 * @param session the HttpSession to get the ReportObjects Map from
 * @return the (possibly new) ReportObjects Map
 *///from   www.j a v a2 s . c om
public static ReportObjectFactory getReportObjects(HttpSession session) {
    ServletContext servletContext = session.getServletContext();
    ReportObjectFactory reportObjects = (ReportObjectFactory) servletContext
            .getAttribute(Constants.REPORT_OBJECT_CACHE);

    // Build map from object id to ReportObject
    if (reportObjects == null) {
        InterMineAPI im = getInterMineAPI(session);
        WebConfig webConfig = getWebConfig(servletContext);
        Properties webProperties = getWebProperties(servletContext);
        reportObjects = new ReportObjectFactory(im, webConfig, webProperties);
        servletContext.setAttribute(Constants.REPORT_OBJECT_CACHE, reportObjects);
    }

    return reportObjects;
}

From source file:com.cloudera.oryx.ml.serving.als.Ingest.java

@Override
@PostConstruct/*from w ww.j  av  a2 s. com*/
public void init() {
    super.init();
    ServletContext context = getServletContext();
    fileItemFactory = new DiskFileItemFactory(1 << 16,
            (File) context.getAttribute("javax.servlet.context.tempdir"));
    fileItemFactory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(context));
}

From source file:com.manydesigns.portofino.interceptors.SecurityInterceptor.java

public Resolution intercept(ExecutionContext context) throws Exception {
    logger.debug("Retrieving Stripes objects");
    ActionBeanContext actionContext = context.getActionBeanContext();
    ActionBean actionBean = context.getActionBean();
    Method handler = context.getHandler();

    logger.debug("Retrieving Servlet API objects");
    HttpServletRequest request = actionContext.getRequest();

    Subject subject = SecurityUtils.getSubject();

    if (!SecurityLogic.satisfiesRequiresAdministrator(request, actionBean, handler)) {
        return new ForbiddenAccessResolution();
    }/* w  ww.  j  a  v  a 2  s  .  c  om*/

    logger.debug("Checking page permissions");
    boolean isNotAdmin = !SecurityLogic.isAdministrator(request);
    if (isNotAdmin) {
        ServletContext servletContext = context.getActionBeanContext().getServletContext();
        Configuration configuration = (Configuration) servletContext
                .getAttribute(BaseModule.PORTOFINO_CONFIGURATION);
        Permissions permissions;
        Dispatch dispatch = DispatcherUtil.getDispatch(request);
        String resource;
        boolean allowed;
        if (dispatch != null) {
            logger.debug("The protected resource is a page action");
            resource = dispatch.getLastPageInstance().getPath();
            allowed = SecurityLogic.hasPermissions(configuration, dispatch, subject, handler);
        } else {
            logger.debug("The protected resource is a plain Stripes ActionBean");
            resource = request.getRequestURI();
            permissions = new Permissions();
            allowed = SecurityLogic.hasPermissions(configuration, permissions, subject, handler,
                    actionBean.getClass());
        }
        if (!allowed) {
            logger.info("Access to {} is forbidden", resource);
            return new ForbiddenAccessResolution();
        }
    }

    logger.debug("Security check passed.");
    return context.proceed();
}

From source file:edu.jhu.pha.vospace.DbPoolServlet.java

@Override
public void init() throws ServletException {
    ServletContext context = this.getServletContext();

    Configuration conf = (Configuration) context.getAttribute("configuration");

    try {//from  w  ww.  j a  va 2s  .c o  m
        Class.forName(conf.getString("db.driver"));
    } catch (ClassNotFoundException e) {
        logger.error(e);
        throw new ServletException(e);
    }

    GenericObjectPool pool = new GenericObjectPool(null);
    pool.setMinEvictableIdleTimeMillis(6 * 60 * 60 * 1000);
    pool.setTimeBetweenEvictionRunsMillis(30 * 60 * 1000);
    pool.setNumTestsPerEvictionRun(-1);

    DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory(conf.getString("db.url"),
            conf.getString("db.login"), conf.getString("db.password"));

    PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, pool, null, "SELECT * FROM mysql.db",
            false, true);
    new PoolingDriver().registerPool("dbPool", pool);
}

From source file:com.origami.sgm.services.ejbs.censocat.FotosServlet.java

protected void genFactory() {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    if (this.getServletConfig() != null && this.getServletConfig().getServletContext() != null) {
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute(ServletContext.TEMPDIR);
        factory.setRepository(repository);
        uploadFotoBean.setFactory(factory);
    }/*  w ww .j  a  va 2  s.  c  om*/
}

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

@SuppressWarnings("unchecked")
public void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    Map<String, String[]> pmap = request.getParameterMap();
    try {//  w ww.  java 2 s .c om
        ServletContext context = getServletContext();
        final FSImage nnImage = (FSImage) context.getAttribute("name.system.image");
        final TransferFsImage ff = new TransferFsImage(pmap, request, response);
        final Configuration conf = (Configuration) getServletContext().getAttribute(JspHelper.CURRENT_CONF);
        if (UserGroupInformation.isSecurityEnabled() && !isValidRequestor(request.getRemoteUser(), conf)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "Only Namenode and Secondary Namenode may access this servlet");
            LOG.warn("Received non-NN/SNN request for image or edits from " + request.getRemoteHost());
            return;
        }

        UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                if (ff.getImage()) {
                    // send fsImage
                    TransferFsImage.getFileServer(response.getOutputStream(), nnImage.getFsImageName());
                } else if (ff.getEdit()) {
                    // send edits
                    TransferFsImage.getFileServer(response.getOutputStream(), nnImage.getFsEditName());
                } else if (ff.putImage()) {
                    // issue a HTTP get request to download the new fsimage 
                    nnImage.validateCheckpointUpload(ff.getToken());
                    reloginIfNecessary().doAs(new PrivilegedExceptionAction<Void>() {
                        @Override
                        public Void run() throws Exception {
                            TransferFsImage.getFileClient(ff.getInfoServer(), "getimage=1",
                                    nnImage.getFsImageNameCheckpoint());
                            return null;
                        }
                    });

                    nnImage.checkpointUploadDone();
                }
                return null;
            }

            // We may have lost our ticket since the last time we tried to open
            // an http connection, so log in just in case.
            private UserGroupInformation reloginIfNecessary() throws IOException {
                // This method is only called on the NN, therefore it is safe to
                // use these key values.
                return UserGroupInformation.loginUserFromKeytabAndReturnUGI(
                        SecurityUtil.getServerPrincipal(conf.get(DFS_NAMENODE_KRB_HTTPS_USER_NAME_KEY),
                                NameNode.getAddress(conf).getHostName()),
                        conf.get(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY));
            }
        });

    } catch (Exception ie) {
        String errMsg = "GetImage failed. " + StringUtils.stringifyException(ie);
        response.sendError(HttpServletResponse.SC_GONE, errMsg);
        throw new IOException(errMsg);
    } finally {
        response.getOutputStream().close();
    }
}

From source file:org.apache.struts.tiles.TilesUtilImpl.java

/**
 * Get definition factory from appropriate servlet context.
 * @return Definitions factory or <code>null</code> if not found.
 *///from   w w  w . ja  v  a  2  s. co  m
public DefinitionsFactory getDefinitionsFactory(ServletRequest request, ServletContext servletContext) {

    return (DefinitionsFactory) servletContext.getAttribute(DEFINITIONS_FACTORY);
}

From source file:org.apache.asterix.api.http.servlet.ShutdownAPIServlet.java

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

    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");

    PrintWriter out = response.getWriter();
    OutputFormat format = OutputFormat.JSON;
    String accept = request.getHeader("Accept");
    if ((accept == null) || (accept.contains("application/x-adm"))) {
        format = OutputFormat.ADM;/*from   www  .  j a  v  a 2 s  .  com*/
    } else if (accept.contains("application/json")) {
        format = OutputFormat.JSON;
    }
    StringWriter sw = new StringWriter();
    IOUtils.copy(request.getInputStream(), sw, StandardCharsets.UTF_8.name());

    ServletContext context = getServletContext();
    IHyracksClientConnection hcc;
    try {
        synchronized (context) {
            hcc = (IHyracksClientConnection) context.getAttribute(HYRACKS_CONNECTION_ATTR);
            response.setStatus(HttpServletResponse.SC_ACCEPTED);
            hcc.stopCluster();
        }
    } catch (Exception e) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
        ResultUtils.apiErrorHandler(out, e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

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

public void testDoFilter() throws ServletException, IOException, NamingException {
    LdapIpDirFilter filter = new LdapIpDirFilter();
    String baseName = "ou=proxyroles,dc=mycompany,dc=com";
    DummyLdapContext dlc = new DummyLdapContext();
    filter.initialize(baseName, dlc);//from  w w w  .  ja va2 s  . c om
    request.setRemoteIPAddress("127.0.0.1");

    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);
    assertNotNull(context.getAttribute("name.node.address"));
    assertNotNull(context.getAttribute("name.conf"));

    request.removeAttribute("org.apache.hadoop.hdfsproxy.authorized.userID");
    FilterChain mockFilterChain = new DummyFilterChain();
    filter.doFilter(request, response, mockFilterChain);
    assertEquals(request.getAttribute("org.apache.hadoop.hdfsproxy.authorized.userID"), "testuser");

}