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.pluto.driver.tags.PortletWindowStateAnchorTag.java

/**
 * Method invoked when the start tag is encountered.
 * @throws JspException  if an error occurs.
 *//*from w w  w .  ja v  a2s  .co  m*/
public int doStartTag() throws JspException {

    // Ensure that the modeAnchor tag resides within a portlet tag.
    PortletTag parentTag = (PortletTag) TagSupport.findAncestorWithClass(this, PortletTag.class);
    if (parentTag == null) {
        throw new JspException("Portlet window controls may only reside " + "within a pluto:portlet tag.");
    }

    portletId = parentTag.getPortletId();
    // Evaluate portlet ID attribute.
    evaluatePortletId();

    // Retrieve the portlet window config for the evaluated portlet ID.
    ServletContext servletContext = pageContext.getServletContext();
    DriverConfiguration driverConfig = (DriverConfiguration) servletContext
            .getAttribute(AttributeKeys.DRIVER_CONFIG);

    if (isWindowStateAllowed(driverConfig, state)) {
        // Retrieve the portal environment.
        PortalRequestContext portalEnv = PortalRequestContext
                .getContext((HttpServletRequest) pageContext.getRequest());

        PortalURL portalUrl = portalEnv.createPortalURL();
        portalUrl.setWindowState(evaluatedPortletId, new WindowState(state));

        // Build a string buffer containing the anchor tag
        StringBuffer tag = new StringBuffer();
        //            tag.append("<a class=\"" + ToolTips.CSS_CLASS_NAME + "\" href=\"" + portalUrl.toString() + "\">");
        //            tag.append("<span class=\"" + state + "\"></span>");
        //            tag.append("<span class=\"" + ToolTips.CSS_CLASS_NAME + "\">");
        //            tag.append(ToolTips.forWindowState(new WindowState(state)));
        //            tag.append("</span></a>");
        tag.append("<a title=\"");
        tag.append(ToolTips.forWindowState(new WindowState(state)));
        tag.append("\" ");
        tag.append("href=\"" + portalUrl.toString() + "\">");
        tag.append("<img border=\"0\" src=\"" + icon + "\" />");
        tag.append("</a>");

        // Print the mode anchor tag.
        try {
            JspWriter out = pageContext.getOut();
            out.print(tag.toString());
        } catch (IOException ex) {
            throw new JspException(ex);
        }
    }

    // Continue to evaluate the tag body.
    return EVAL_BODY_INCLUDE;
}

From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.InitiateUploadInventory.java

/**
 * This method is used to read properties from Application context.
 * /*from   ww  w  .java2  s  .c  om*/
 * @return SUCCESS
 */
@Override
public String execute() throws Exception {

    /*
     * Properties properties = new Properties(); InputStream inputStream =
     * this.getClass().getClassLoader()
     * .getResourceAsStream("config/LMS.properties"); logger.debug(">>>>" +
     * inputStream); properties.load(inputStream); agent_sale_comm_rate =
     * properties .getProperty("agent_sale_comm_rate"); logger.debug("agent
     * rate>>>" + agent_sale_comm_rate); retailer_sale_comm_rate =
     * properties .getProperty("retailer_sale_comm_rate");
     * agent_pwt_comm_rate = properties.getProperty("agent_pwt_comm_rate");
     * retailer_pwt_comm_rate = properties
     * .getProperty("retailer_pwt_comm_rate"); govt_pwt_comm_rate =
     * properties .getProperty("retailer_pwt_comm_rate"); govtCommRate =
     * properties.getProperty("govt_comm_rate");
     */

    ServletContext sc = ServletActionContext.getServletContext();
    agent_sale_comm_rate = (String) sc.getAttribute("AGT_SALE_COMM_RATE");
    retailer_sale_comm_rate = (String) sc.getAttribute("RET_SALE_COMM_RATE");
    agent_pwt_comm_rate = (String) sc.getAttribute("AGT_PWT_COMM_RATE");
    retailer_pwt_comm_rate = (String) sc.getAttribute("RET_PWT_COMM_RATE");
    govtCommRate = (String) sc.getAttribute("GOVT_COMM_RATE");
    logger.debug(govtCommRate + "govtCommRate");
    session = getRequest().getSession();
    session.setAttribute("START_DATE", null);
    Date currDate = new Date();
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    String strCurrDate = dateFormat.format(currDate);

    logger.debug(strCurrDate + "dateeeeeeeee");
    session.setAttribute("START_DATE", strCurrDate);

    QueryHelper searchQuery = new QueryHelper();
    List searchResults = searchQuery.SearchSupplier();

    if (searchResults != null && searchResults.size() > 0) {
        logger.debug(searchResults);
        session.setAttribute("SUPPLIER_SEARCH_RESULTS", searchResults);

    } else {
        session.setAttribute("SUPPLIER_SEARCH_RESULTS", null);
    }
    this.setAgent_sale_comm_rate(agent_sale_comm_rate);
    session.setAttribute("x", this);
    return SUCCESS;

}

From source file:com.skilrock.lms.web.roleMgmt.common.PrivsInterceptor.java

public void refreshSession(HttpSession session) {
    ServletContext sc = ServletActionContext.getServletContext();
    String sesVariables = (String) sc.getAttribute("SESSION_VARIABLES");
    List sesVar = Arrays.asList(sesVariables.split(","));

    Enumeration sesEnum = session.getAttributeNames();
    while (sesEnum.hasMoreElements()) {
        Object variable = sesEnum.nextElement();
        if (!sesVar.contains(variable.toString())) {
            session.removeAttribute(variable.toString());
        }//w  ww.j a v a2  s  .  c om
    }
}

From source file:org.b3log.latke.Latkes.java

/**
 * Gets a file in web application with the specified path.
 *
 * @param path the specified path//from  ww  w.j  a  v a2 s.  c o m
 * @return file,
 * @see ServletContext#getResource(String)
 * @see ServletContext#getResourceAsStream(String)
 */
public static File getWebFile(final String path) {
    final ServletContext servletContext = AbstractServletListener.getServletContext();

    File ret;

    try {
        final URL resource = servletContext.getResource(path);

        if (null == resource) {
            return null;
        }

        ret = FileUtils.toFile(resource);

        if (null == ret) {
            final File tempdir = (File) servletContext.getAttribute("javax.servlet.context.tempdir");

            ret = new File(tempdir.getPath() + path);

            FileUtils.copyURLToFile(resource, ret);

            ret.deleteOnExit();
        }

        return ret;
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Reads file [path=" + path + "] failed", e);

        return null;
    }
}

From source file:com.meltmedia.cadmium.servlets.guice.CadmiumListener.java

public static File sharedContextRoot(Properties configProperties, ServletContext context, Logger log) {
    File sharedContentRoot = null;

    if (configProperties.containsKey(BASE_PATH_ENV)) {
        sharedContentRoot = new File(configProperties.getProperty(BASE_PATH_ENV));
        if (!sharedContentRoot.exists() || !sharedContentRoot.canRead() || !sharedContentRoot.canWrite()) {
            if (!sharedContentRoot.mkdirs()) {
                sharedContentRoot = null;
            }/*from   w  w w.j ava  2  s . c o  m*/
        }
    }

    if (sharedContentRoot == null) {
        log.warn("Could not access cadmium content root.  Using the tempdir.");
        sharedContentRoot = (File) context.getAttribute("javax.servlet.context.tempdir");
        configProperties.setProperty(BASE_PATH_ENV, sharedContentRoot.getAbsoluteFile().getAbsolutePath());
    }
    return sharedContentRoot;
}

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

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "WEBHDFS";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(// ww w.j av  a 2 s. co  m
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    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.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<SynchronousServletOutputStreamAdapter>() {
                @Override
                public SynchronousServletOutputStreamAdapter answer() throws Throwable {
                    return new SynchronousServletOutputStreamAdapter() {
                        @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));
    WebHdfsHaDispatch dispatch = new WebHdfsHaDispatch();
    dispatch.setHttpClient(new DefaultHttpClient());
    dispatch.setHaProvider(provider);
    dispatch.init();
    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:org.debux.webmotion.server.WebMotionServer.java

/**
 * @param request request to found servlet context
 * @return server context in servlet context
 */// w  w  w  .ja  v  a  2 s . c o m
protected ServerContext getServerContext(HttpServletRequest request) {
    ServletContext servletContext = request.getServletContext();
    ServerContext serverContext = (ServerContext) servletContext
            .getAttribute(ServerContext.ATTRIBUTE_SERVER_CONTEXT);
    return serverContext;
}

From source file:org.apache.hadoop.gateway.ha.dispatch.DefaultHaDispatchTest.java

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "OOZIE";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(//from  w  w w  .j  a  va  2 s.  c o m
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    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.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<SynchronousServletOutputStreamAdapter>() {
                @Override
                public SynchronousServletOutputStreamAdapter answer() throws Throwable {
                    return new SynchronousServletOutputStreamAdapter() {
                        @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));
    DefaultHaDispatch dispatch = new DefaultHaDispatch();
    dispatch.setHttpClient(new DefaultHttpClient());
    dispatch.setHaProvider(provider);
    dispatch.setServiceRole(serviceName);
    dispatch.init();
    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:org.apache.struts.util.ModuleUtils.java

/**
 * Return the desired ModuleConfig object stored in context, if it exists,
 * null otherwise.//from w  w w .  j a  v a  2s.c  o  m
 *
 * @param prefix  The module prefix of the desired module
 * @param context The ServletContext for this web application
 * @return the ModuleConfig object specified, or null if not found in the
 *         context.
 */
public ModuleConfig getModuleConfig(String prefix, ServletContext context) {
    if ((prefix == null) || "/".equals(prefix)) {
        return (ModuleConfig) context.getAttribute(Globals.MODULE_KEY);
    } else {
        return (ModuleConfig) context.getAttribute(Globals.MODULE_KEY + prefix);
    }
}

From source file:com.tremolosecurity.proxy.auth.persistentCookie.PersistentCookie.java

@Override
public void init(ServletContext ctx, HashMap<String, Attribute> init) {
    this.cfgMgr = (ConfigManager) ctx.getAttribute(ProxyConstants.TREMOLO_CONFIG);

}