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.rm.dispatch.RMHaDispatchTest.java

@Test
public void testConnectivityFailure() throws Exception {
    String serviceName = "RESOURCEMANAGER";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(/*from   w ww.jav  a  2 s . c om*/
            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<>();
    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<ServletOutputStream>() {
        @Override
        public ServletOutputStream answer() throws Throwable {
            return new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                    throw new IOException("unreachable-host");
                }

                @Override
                public void setWriteListener(WriteListener arg0) {
                }

                @Override
                public boolean isReady() {
                    return false;
                }
            };
        }
    }).once();
    EasyMock.replay(filterConfig, servletContext, outboundRequest, inboundRequest, outboundResponse);
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    RMHaDispatch dispatch = new RMHaDispatch();
    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:br.gov.jfrj.siga.libs.webwork.SigaAnonimoActionSupport.java

public Object getSharedContextAttribute(String name) {
    ServletContext sigaContext = getContext().getContext("/siga");
    if (sigaContext == null)
        return null;
    String sessionId = getRequest().getSession().getId();
    return sigaContext.getAttribute(sessionId + "-" + name);
}

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

public void handleRequest(HttpServletRequest request, HttpServletResponse response, String query)
        throws IOException {
    // enable cross-origin resource sharing
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

    SessionConfig sessionConfig = initResponse(request, response);
    QueryTranslator.ResultDelivery resultDelivery = whichResultDelivery(request);

    ServletContext context = getServletContext();
    IHyracksClientConnection hcc;// w ww  .ja  v a 2 s  .  co m
    IHyracksDataset hds;

    try {
        synchronized (context) {
            hcc = (IHyracksClientConnection) context.getAttribute(HYRACKS_CONNECTION_ATTR);
            hds = (IHyracksDataset) context.getAttribute(HYRACKS_DATASET_ATTR);
            if (hds == null) {
                hds = new HyracksDataset(hcc, ResultReader.FRAME_SIZE, ResultReader.NUM_READERS);
                context.setAttribute(HYRACKS_DATASET_ATTR, hds);
            }
        }

        IParser parser = parserFactory.createParser(query);
        List<Statement> aqlStatements = parser.parse();
        if (!containsForbiddenStatements(aqlStatements)) {
            MetadataManager.INSTANCE.init();
            IStatementExecutor translator = statementExecutorFactory.create(aqlStatements, sessionConfig,
                    compilationProvider);
            translator.compileAndExecute(hcc, hds, resultDelivery);
        }
    } catch (AsterixException | TokenMgrError | org.apache.asterix.aqlplus.parser.TokenMgrError pe) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, pe.getMessage(), pe);
        String errorMessage = ResultUtil.buildParseExceptionMessage(pe, query);
        JSONObject errorResp = ResultUtil.getErrorResponse(2, errorMessage, "",
                ResultUtil.extractFullStackTrace(pe));
        sessionConfig.out().write(errorResp.toString());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
        ResultUtil.apiErrorHandler(sessionConfig.out(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:de.zib.gndms.kit.monitor.GroovyMoniServlet.java

/**
 * Retrieves role name and monitor server reference from servlet context.
 *
 * @param servletConfig/*from   w ww .  j  a v  a  2 s .c om*/
 * @throws ServletException
 */
@Override
public synchronized void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig); // Overridden method
    final ServletContext servletContext = servletConfig.getServletContext();
    moniServer = (GroovyMoniServer) servletContext.getAttribute(GroovyMoniServer.ATTR_MONITOR_SERVER);
    roleName = (String) servletContext.getAttribute(GroovyMoniServer.ATTR_ROLE_NAME);
}

From source file:org.apache.hadoop.hbase.http.HttpServer.java

/**
 * Checks the user has privileges to access to instrumentation servlets.
 * <p>//ww w. java 2 s  .co m
 * If <code>hadoop.security.instrumentation.requires.admin</code> is set to FALSE
 * (default value) it always returns TRUE.
 * </p><p>
 * If <code>hadoop.security.instrumentation.requires.admin</code> is set to TRUE
 * it will check that if the current user is in the admin ACLS. If the user is
 * in the admin ACLs it returns TRUE, otherwise it returns FALSE.
 * </p>
 *
 * @param servletContext the servlet context.
 * @param request the servlet request.
 * @param response the servlet response.
 * @return TRUE/FALSE based on the logic decribed above.
 */
public static boolean isInstrumentationAccessAllowed(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    Configuration conf = (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);

    boolean access = true;
    boolean adminAccess = conf
            .getBoolean(CommonConfigurationKeys.HADOOP_SECURITY_INSTRUMENTATION_REQUIRES_ADMIN, false);
    if (adminAccess) {
        access = hasAdministratorAccess(servletContext, request, response);
    }
    return access;
}

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

/**
 * Determines if the request should be allowed for the action
 * /*from w ww.j  a v a 2 s  .co  m*/
 * @param request
 *            The request
 * @param action
 *            The action object
 * @return True if allowed, false otherwise
 * @throws SQLException
 */
protected boolean isAllowed(HttpServletRequest request, Object action) throws SQLException {
    String json = request.getParameter("json");
    HttpSession session = null;
    String userName = null;
    if (json != null) {
        JSONObject requestData = (JSONObject) JSONSerializer.toJSON(json);
        userName = (String) requestData.get("userName");
    }

    if (userName == null) {
        session = request.getSession();
    } else {
        Map currentUserSessionMap = (Map) LMSUtility.sc.getAttribute("LOGGED_IN_USERS");
        session = (HttpSession) currentUserSessionMap.get(userName);
    }

    // logger.debug("allowedRoles::" + allowedRoles);

    // logger.debug("i am inside priv interceptor");
    String actionName = ActionContext.getContext().getName();
    logger.debug("Action Name - " + actionName);

    boolean result = false;
    ArrayList<String> userActionList = new ArrayList<String>();
    userActionList = (ArrayList<String>) session.getAttribute("ACTION_LIST");
    logger.debug("userActionList: " + userActionList);
    List<String> disableTabs;
    UserInfoBean userBean = (UserInfoBean) session.getAttribute("USER_INFO");
    ServletContext sc = ServletActionContext.getServletContext();
    if (userBean.getUserType().equals("RETAILER") && !isSaleDuration(userBean)) {
        disableTabs = Arrays.asList(((String) sc.getAttribute("RET_SALE_BOUND")).split(","));
        for (int i = 0; i < disableTabs.size(); i++) {
            if (actionName.contains(disableTabs.get(i))) {
                saleStatus = "SALE_STOP";
                return false;
            }
        }
    }
    if (!userBean.getLoginChannel().equalsIgnoreCase("WEB")) {
        return false;
    }
    if (userActionList.contains(actionName)) {
        HashMap actionServiceMap = (HashMap) session.getAttribute("PRIV_MAP");
        Iterator itrMap = actionServiceMap.entrySet().iterator();
        while (itrMap.hasNext()) {
            Map.Entry pairs = (Map.Entry) itrMap.next();
            List privList = (List) pairs.getValue();
            for (int i = 0; i < privList.size(); i++) {

                if (((PriviledgeBean) privList.get(i)).getActionMapping().equals(actionName)) {
                    refreshSession(session);
                }
            }
        }
        result = true;
    }

    return result;
}

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

/**
 * Destroyes the portlet container and removes it from servlet context.
 *
 * @param servletContext the servlet context.
 *//*from ww  w .j  a  va2s. c o m*/
private void destroyContainer(ServletContext servletContext) {
    if (LOG.isInfoEnabled()) {
        LOG.info("Shutting down Pluto Portal Driver...");
    }
    PortletContainer container = (PortletContainer) servletContext.getAttribute(CONTAINER_KEY);
    if (container != null) {
        try {
            container.destroy();
            if (LOG.isInfoEnabled()) {
                LOG.info("Pluto Portal Driver shut down.");
            }
        } catch (PortletContainerException ex) {
            LOG.error("Unable to shut down portlet container: " + ex.getMessage(), ex);
        } finally {
            servletContext.removeAttribute(CONTAINER_KEY);
        }
    }
}

From source file:org.apache.hadoop.gateway.rm.dispatch.RMHaDispatchTest.java

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "RESOURCEMANAGER";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(/*from w  w w  .ja v  a2s. c  o m*/
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    HaProvider provider = new DefaultHaProvider(descriptor);
    URI uri1 = new URI("http://passive-host");
    URI uri2 = new URI("http://other-host");
    URI uri3 = new URI("http://active-host");
    ArrayList<String> urlList = new ArrayList<>();
    urlList.add(uri1.toString());
    urlList.add(uri2.toString());
    urlList.add(uri3.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();

    BasicHttpResponse inboundResponse = EasyMock.createNiceMock(BasicHttpResponse.class);
    EasyMock.expect(inboundResponse.getStatusLine()).andReturn(getStatusLine()).anyTimes();
    EasyMock.expect(inboundResponse.getEntity()).andReturn(getResponseEntity()).anyTimes();
    EasyMock.expect(inboundResponse.getFirstHeader(LOCATION)).andReturn(getFirstHeader(uri3.toString()))
            .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");
                }

                @Override
                public void setWriteListener(WriteListener arg0) {
                }

                @Override
                public boolean isReady() {
                    return false;
                }
            };
        }
    }).once();
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    EasyMock.replay(filterConfig, servletContext, inboundResponse, outboundRequest, inboundRequest,
            outboundResponse);

    RMHaDispatch dispatch = new RMHaDispatch();
    dispatch.setHttpClient(new DefaultHttpClient());
    dispatch.setHaProvider(provider);
    dispatch.init();
    long startTime = System.currentTimeMillis();
    try {
        dispatch.setInboundResponse(inboundResponse);
        dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } catch (IOException e) {
        //this is expected after the failover limit is reached
    }
    Assert.assertEquals(uri3.toString(),
            dispatch.getUriFromInbound(inboundRequest, inboundResponse, null).toString());
    long elapsedTime = System.currentTimeMillis() - startTime;
    Assert.assertEquals(uri3.toString(), provider.getActiveURL(serviceName));
    //test to make sure the sleep took place
    Assert.assertTrue(elapsedTime > 1000);
}

From source file:com.manydesigns.portofino.actions.admin.servletcontext.ServletContextAction.java

protected void setupForm() {
    ServletContext servletContext = context.getServletContext();
    Enumeration<String> attributeNames = servletContext.getAttributeNames();
    List<KeyValue> attributes = new ArrayList<KeyValue>();
    while (attributeNames.hasMoreElements()) {
        String key = attributeNames.nextElement();
        String value = StringUtils.abbreviate(OgnlUtils.convertValueToString(servletContext.getAttribute(key)),
                300);/*from w ww .ja  va  2 s.c o  m*/
        attributes.add(new KeyValue(key, value));
    }
    TableFormBuilder builder = new TableFormBuilder(KeyValue.class);
    builder.configNRows(attributes.size());
    builder.configMode(Mode.VIEW);
    form = builder.build();
    form.readFromObject(attributes);
}

From source file:org.apache.struts2.views.zipscript.ZipScriptResult.java

/**
 * Creates a ZipScript context from the action, loads a ZipScript template and
 * executes the template. Output is written to the servlet output stream.
 * /*w  w w .  j av a  2s. c o  m*/
 * @param finalLocation
 *            the location of the ZipScript template
 * @param invocation
 *            an encapsulation of the action execution state.
 * @throws Exception
 *             if an error occurs when creating the ZipScript context,
 *             loading or executing the template or writing output to the
 *             servlet response stream.
 */
public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    ResultData resultData = new ResultData(finalLocation);

    // get working values
    ValueStack stack = ActionContext.getContext().getValueStack();
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    JspFactory jspFactory = null;
    ServletContext servletContext = ServletActionContext.getServletContext();
    Servlet servlet = JspSupportServlet.jspSupportServlet;

    if (null == zipScriptManager) {
        zipScriptManager = (ZipScriptManager) servletContext.getAttribute(ZipScriptManager.class.getName());
        if (null == zipScriptManager) {
            zipScriptManager = new ZipScriptManager();
            servletContext.setAttribute(ZipScriptManager.class.getName(), zipScriptManager);
        }
    }

    ZipEngine zipEngine = zipScriptManager.getZipEngine(servletContext);

    boolean usedJspFactory = false;
    PageContext pageContext = (PageContext) ActionContext.getContext().get(ServletActionContext.PAGE_CONTEXT);

    if (pageContext == null && servlet != null) {
        jspFactory = JspFactory.getDefaultFactory();
        pageContext = jspFactory.getPageContext(servlet, request, response, null, true, 8192, true);
        ActionContext.getContext().put(ServletActionContext.PAGE_CONTEXT, pageContext);
        usedJspFactory = true;
    }

    try {
        String encoding = getEncoding(finalLocation);
        String contentType = getContentType(finalLocation);

        if (encoding != null) {
            contentType = contentType + ";charset=" + encoding;
        }

        Writer writer = new OutputStreamWriter(response.getOutputStream(), encoding);
        Context context = zipScriptManager.createContext(invocation, resultData, request);
        loadContext(context);

        writeOutput(context, stack, zipEngine, invocation, resultData, servletContext, request, response,
                writer);

        response.setContentType(contentType);
        writer.flush();
    } catch (Exception e) {
        log.error("Unable to render ZipScript Template, '" + finalLocation + "'", e);
        throw e;
    } catch (Throwable e) {
        log.error("Unable to render ZipScript Template, '" + finalLocation + "'", e);
        throw new Exception(e);
    } finally {
        if (usedJspFactory) {
            jspFactory.releasePageContext(pageContext);
        }
    }
    return;
}