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:net.ontopia.topicmaps.webed.impl.utils.TagUtils.java

protected static VelocityEngine getVelocityEngine(ServletContext scontext) {
    VelocityEngine vengine = (VelocityEngine) scontext.getAttribute(Constants.SCTXT_VELOCITY_ENGINE);

    if (vengine == null) {

        // create a new velocity engine
        vengine = new VelocityEngine();

        // --- try to get properties from an own file
        String relPath = scontext.getInitParameter(Constants.SCTXT_VELOPROPS_PATH);
        if (relPath != null) {
            String velocityPropPath = scontext.getRealPath(relPath);
            log.info("Initialising velocity from property file: " + velocityPropPath);
            // load in properties
            Properties props = new Properties();
            try {
                props.load(new java.io.FileInputStream(velocityPropPath));
            } catch (java.io.IOException ioe) {
                throw new OntopiaRuntimeException(ioe);
            }//from w  w w  .j  a v a2 s  . co  m
            // pre-cat the real directory
            String path = props.getProperty(Velocity.FILE_RESOURCE_LOADER_PATH, null);
            if (path != null) {
                path = scontext.getRealPath(path);
                props.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
            } else {
                // no directory set, use default loader (classpath) for default templates
                props.setProperty("resource.loader", "class");
                props.setProperty("class.resource.loader.class",
                        "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
                props.setProperty("class.resource.loader.cache", "true");
            }
            try {
                vengine.init(props);
            } catch (Exception e) {
                throw new OntopiaRuntimeException(e);
            }
        } else {
            log.info("Initializing velocity with default properties.");
            // use class resource loaders
            Properties props = new Properties();
            props.setProperty("resource.loader", "class");
            props.setProperty("class.resource.loader.class",
                    "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            props.setProperty("class.resource.loader.cache", "true");
            // use log4j logging system
            props.setProperty("runtime.log.system", "org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
            props.setProperty("runtime.log.logsystem.log4j.category", "net.ontopia.velocity");
            props.setProperty("runtime.log", "velocity.log");
            try {
                vengine.init(props);
            } catch (Exception e) {
                throw new OntopiaRuntimeException(e);
            }
        }

        // add velocity engine to servlet context
        scontext.setAttribute(Constants.SCTXT_VELOCITY_ENGINE, vengine);
    }
    return vengine;
}

From source file:de.betterform.agent.web.WebUtil.java

/**
 * transforms an input document and writes it to the ServletOutputStream.
 *
 * @param context the servlet context//  w w w .  j av  a  2 s. com
 * @param response the servlet response
 * @param input an DOM input document to transform
 * @param stylesheetName the name of the stylesheet to use. This must be preloaded in CachingTransformerService. See WebFactory
 * @param params transformation parameters as a piece of DOM if any. The params object is passed as param 'params' to the stylesheets
 * @throws java.io.IOException
 */
public static void doTransform(ServletContext context, HttpServletResponse response, Document input,
        String stylesheetName, Object params) throws IOException {
    CachingTransformerService transformerService = (CachingTransformerService) context
            .getAttribute(TransformerService.TRANSFORMER_SERVICE);
    Source xmlSource = new DOMSource(input);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        Transformer transformer = transformerService.getTransformerByName(stylesheetName);
        if (params != null) {
            if (params instanceof Node) {
                transformer.setParameter("params", params);
            }
        }
        transformer.transform(xmlSource, new StreamResult(outputStream));

    } catch (TransformerException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    response.setContentType(WebUtil.HTML_CONTENT_TYPE);
    response.setContentLength(outputStream.toByteArray().length);
    response.getOutputStream().write(outputStream.toByteArray());
    response.getOutputStream().close();
}

From source file:org.apache.axis.transport.http.AxisServletBase.java

/**
 * put the engine back in to the context.
 * @param context servlet context to use
 * @param engine reference to the engine. If null, the engine is removed
 *//*from  ww  w .ja v a  2  s.c  o  m*/
private static void storeEngine(HttpServlet servlet, AxisServer engine) {
    ServletContext context = servlet.getServletContext();
    String axisServletName = servlet.getServletName();
    if (engine == null) {
        context.removeAttribute(axisServletName + ATTR_AXIS_ENGINE);
        // find if there is other AxisEngine in Context
        AxisServer server = (AxisServer) context.getAttribute(ATTR_AXIS_ENGINE);

        // no other AxisEngine in ServletContext
        if (server != null && servlet.getServletName().equals(server.getName())) {
            context.removeAttribute(ATTR_AXIS_ENGINE);
        }
    } else {
        if (context.getAttribute(ATTR_AXIS_ENGINE) == null) {
            // first Axis servlet to store its AxisEngine
            // use default name
            context.setAttribute(ATTR_AXIS_ENGINE, engine);
        }
        context.setAttribute(axisServletName + ATTR_AXIS_ENGINE, engine);
    }
}

From source file:org.frat.common.security.BaseSecurityContext.java

/**
 * .//w w w. ja va  2  s  .  c  o  m
 * 
 * @param username
 */
public static void kickOutUnLogin() {
    try {
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContext servletContext = webApplicationContext.getServletContext();

        // applicationHashSet?session
        @SuppressWarnings("unchecked")
        HashSet<HttpSession> sessions = (HashSet<HttpSession>) servletContext.getAttribute("loginSessions");
        List<HttpSession> sessionList = new ArrayList<HttpSession>();
        if (StringUtil.isObjNotNull(sessions)) {
            for (HttpSession session : sessions) {
                SysUserDto user = (SysUserDto) session.getAttribute("shiro.user");
                if (null != session && StringUtil.isObjNull(user)) {
                    // LOGGER.debug("getLastAccessedTime="+ new
                    // Date(session.getLastAccessedTime()));
                    // LOGGER.debug("now="+ new Date());
                    int diffTime = DateUtil.diffTime(new Date(), new Date(session.getLastAccessedTime()));
                    // LOGGER.debug("diffTime="+diffTime);
                    if (diffTime > 300) {
                        sessionList.add(session);
                    }
                }
            }
            for (HttpSession session : sessionList) {
                session.invalidate();
                LOGGER.debug("success kick out UnLogin session [" + session.getId() + "]");
            }
        }
    } catch (Exception e) {
        LOGGER.error("");
        LOGGER.error(StackTraceUtil.getStackTrace(e));
    }

}

From source file:net.ontopia.topicmaps.webed.impl.utils.TagUtils.java

public static ActionRegistryIF getActionRegistry(ServletRequest request) throws JspTagException {
    ServletContext servletContext = ((HttpServletRequest) request).getSession().getServletContext();
    ActionRegistryIF registry = (ActionRegistryIF) servletContext.getAttribute(Constants.AA_REGISTRY);
    if (registry != null)
        return registry;

    // Read in Action Configuration and set it to application context
    String cfgpath = servletContext.getInitParameter(Constants.SCTXT_CONFIG_PATH);
    if (cfgpath == null)
        cfgpath = "classpath:actions.xml";

    log.debug("Start reading action configuration from " + cfgpath);

    String str_delay = servletContext.getInitParameter(Constants.SCTXT_RELOAD_DELAY);
    long delay = 6000; // every 6 seconds by default
    if (str_delay != null) {
        try {//  w w w .  j  a va2 s  .  com
            delay = Long.parseLong(str_delay) * 1000; // value in milliseconds
        } catch (NumberFormatException e) {
            delay = -1;
            log.warn("Warning: Falling back to no config re-reading, " + e);
        }
    }
    String ctxtPath = ((HttpServletRequest) request).getContextPath();
    String realpath = servletContext.getRealPath("");
    ActionConfigurator aconf = new ActionConfigurator(ctxtPath, realpath, cfgpath, delay);
    ActionConfigRegistrator registrator = new ActionConfigRegistrator(servletContext);

    //!aconf.addObserver(registrator);
    //!aconf.readAndWatchRegistry();

    // HACK to make loading config files from classpath work
    aconf.readRegistryConfiguration();
    registry = aconf.getRegistry();
    registrator.configurationChanged(registry);

    log.debug("Setup action configuration for the web editor and assigned it to application context.");

    return registry;
}

From source file:org.apache.struts.webapp.tiles.portal.UserMenuAction.java

/**
 * Get catalog of available menu entries.
 * This implementation creates catalog list from the provided menu bar 
 * entries./*  ww w .  java  2s. com*/
 */
public static List getCatalog(ComponentContext context, HttpServletRequest request,
        ServletContext servletContext) throws ServletException {

    // Retrieve name used to store catalog in application context.
    // If not found, use default name
    String catalogName = (String) context.getAttribute(MENU_CATALOG_NAME_ATTRIBUTE);

    if (catalogName == null) {
        catalogName = DEFAULT_MENU_CATALOG_NAME;
    }

    // Get catalog from context
    List catalog = (List) servletContext.getAttribute(catalogName);

    // If not found, initialize it from provided default menu
    if (catalog == null) {
        Object menuBar = context.getAttribute(CATALOG_SETTING_ATTRIBUTE);
        if (menuBar == null) {
            throw new ServletException("Attribute '" + CATALOG_SETTING_ATTRIBUTE
                    + "' must be set. It define entries used in catalog");
        }

        catalog = new ArrayList();
        extractItems(catalog, menuBar, request, servletContext);
        if (catalog.size() == 0) {
            throw new ServletException("Can't initialize menu items catalog");
        }

        // save it for future use
        servletContext.setAttribute(catalogName, catalog);
    }

    return catalog;
}

From source file:org.apache.hadoop.hdfs.server.datanode.DatanodeJspHelper.java

/** Return a table containing version information. */
public static String getVersionTable(ServletContext context) {
    StringBuilder sb = new StringBuilder();
    final DataNode dataNode = (DataNode) context.getAttribute("datanode");
    sb.append("<div class='dfstable'><table>");
    sb.append("<tr><td class='col1'>Version:</td><td>");
    sb.append(VersionInfo.getVersion() + ", " + VersionInfo.getRevision());
    sb.append("</td></tr>\n" + "\n  <tr><td class='col1'>Compiled:</td><td>" + VersionInfo.getDate());
    sb.append(" by " + VersionInfo.getUser() + " from " + VersionInfo.getBranch());
    if (dataNode != null) {
        sb.append("</td></tr>\n  <tr><td class='col1'>Cluster ID:</td><td>" + dataNode.getClusterId());
    }//w  w w .j  a  v a2s  .  c o  m
    sb.append("</td></tr>\n</table></div>");
    return sb.toString();
}

From source file:jp.or.openid.eiwg.scim.util.SCIMUtil.java

/**
 * ??????/*from w  ww . java2  s  . c  o m*/
 *
 * @param context
 * @param attributeName
 * @param isCore
 * @return ?
 */
public static LinkedHashMap<String, Object> getUserAttributeInfo(ServletContext context, String attributeName,
        boolean isCore) {
    LinkedHashMap<String, Object> result = null;

    Set<String> schemaIdSet = new HashSet<>();

    // ?
    @SuppressWarnings("unchecked")
    ArrayList<LinkedHashMap<String, Object>> resourceTypes = (ArrayList<LinkedHashMap<String, Object>>) context
            .getAttribute("ResourceTypes");
    Iterator<LinkedHashMap<String, Object>> resourceTypesIt = resourceTypes.iterator();
    while (resourceTypesIt.hasNext()) {
        LinkedHashMap<String, Object> resourceTypeInfo = resourceTypesIt.next();
        Object endpoint = SCIMUtil.getAttribute(resourceTypeInfo, "endpoint");
        if (endpoint != null && endpoint.toString().equalsIgnoreCase("/Users")) {
            Object schema = SCIMUtil.getAttribute(resourceTypeInfo, "schema");
            if (schema != null) {
                schemaIdSet.add(schema.toString());
            }

            Object schemaExtensions = SCIMUtil.getAttribute(resourceTypeInfo, "schemaExtensions");
            if (schemaExtensions != null && schemaExtensions instanceof ArrayList) {
                @SuppressWarnings("unchecked")
                ArrayList<LinkedHashMap<String, Object>> schemaExtensionList = (ArrayList<LinkedHashMap<String, Object>>) schemaExtensions;
                Iterator<LinkedHashMap<String, Object>> schemaExtensionListIt = schemaExtensionList.iterator();
                while (schemaExtensionListIt.hasNext()) {
                    LinkedHashMap<String, Object> schemaExtensionInfo = schemaExtensionListIt.next();
                    schema = SCIMUtil.getAttribute(schemaExtensionInfo, "schema");
                    if (schema != null) {
                        schemaIdSet.add(schema.toString());
                    }
                }
            }

            break;
        }
    }

    // ?
    @SuppressWarnings("unchecked")
    ArrayList<LinkedHashMap<String, Object>> schemas = (ArrayList<LinkedHashMap<String, Object>>) context
            .getAttribute("Schemas");

    Iterator<LinkedHashMap<String, Object>> schemasIt = schemas.iterator();
    while (schemasIt.hasNext()) {
        LinkedHashMap<String, Object> schemaInfo = schemasIt.next();
        // id?
        Object id = SCIMUtil.getAttribute(schemaInfo, "id");
        if (id != null && id instanceof String) {
            // ??
            boolean isUserSchema = false;
            if (!schemaIdSet.isEmpty()) {
                Iterator<String> schemaIdSetIt = schemaIdSet.iterator();
                while (schemaIdSetIt.hasNext()) {
                    if (id.toString().equalsIgnoreCase(schemaIdSetIt.next())) {
                        isUserSchema = true;
                    }
                }
            }

            if (isUserSchema) {
                Object attributes = schemaInfo.get("attributes");
                if (attributes != null && attributes instanceof ArrayList) {
                    @SuppressWarnings("unchecked")
                    ArrayList<LinkedHashMap<String, Object>> attributeList = (ArrayList<LinkedHashMap<String, Object>>) attributes;
                    Iterator<LinkedHashMap<String, Object>> attributeListIt = attributeList.iterator();
                    while (attributeListIt.hasNext()) {
                        LinkedHashMap<String, Object> attributeInfo = attributeListIt.next();
                        Object name = attributeInfo.get("name");
                        // ??
                        if (attributeName.equalsIgnoreCase(name.toString())) {
                            result = attributeInfo;
                            break;
                        }
                    }
                }
            }
        }
    }

    if (result == null && isCore) {
        if (attributeName.equalsIgnoreCase("schemas")) {
            result = new LinkedHashMap<String, Object>();
            result.put("name", "schemas");
            result.put("type", "string");
            result.put("multiValued", true);
            result.put("mutability", "readWrite");
        } else if (attributeName.equalsIgnoreCase("id")) {
            result = new LinkedHashMap<String, Object>();
            result.put("name", "id");
            result.put("type", "string");
            result.put("multiValued", false);
            result.put("mutability", "readOnly");
        } else if (attributeName.equalsIgnoreCase("meta")) {
            result = new LinkedHashMap<String, Object>();
            result.put("name", "meta");
            result.put("type", "complex");
            result.put("multiValued", false);
            result.put("mutability", "readOnly");
        }
    }

    return result;
}

From source file:org.jruby.rack.mock.WebUtils.java

/**
 * Return the temporary directory for the current web application,
 * as provided by the servlet container.
 * @param servletContext the servlet context of the web application
 * @return the File representing the temporary directory
 *///from   w  ww . ja v  a  2  s  . c om
public static File getTempDir(ServletContext servletContext) {
    Assert.notNull(servletContext, "ServletContext must not be null");
    return (File) servletContext.getAttribute(TEMP_DIR_CONTEXT_ATTRIBUTE);
}

From source file:org.apache.jackrabbit.j2ee.RepositoryStartupServlet.java

/**
 * Returns an instance of this servlet. Please note, that only 1
 * repository startup servlet can exist per webapp.
 *
 * @param context the servlet context/* ww  w  .j a va2 s. c  om*/
 * @return this servlet
 */
public static RepositoryStartupServlet getInstance(ServletContext context) {
    return (RepositoryStartupServlet) context.getAttribute(CTX_PARAM_THIS);
}