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:com.sonicle.webtop.core.app.WebTopApp.java

/**
 * Gets WebTopApp object stored as context's attribute.
 * @param context The servlet context//  w  w w . jav a 2 s.  co  m
 * @return WebTopApp object
 * @throws java.lang.IllegalStateException
 */
public static WebTopApp get(ServletContext context) throws IllegalStateException {
    WebTopApp wta = (WebTopApp) context.getAttribute(ContextLoader.WEBTOPAPP_ATTRIBUTE_KEY);
    if (wta == null)
        throw new IllegalStateException(
                "WebTop environment is not correctly loaded. Please see log files for more details.");
    return wta;
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatchTest.java

@Test
public void testCallToSecureClusterWithDelegationToken() throws URISyntaxException, IOException {
    DefaultDispatch defaultDispatch = new DefaultDispatch();
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);
    GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
    EasyMock.expect(gatewayConfig.isHadoopKerberosSecured()).andReturn(true).anyTimes();
    EasyMock.expect(servletContext.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE))
            .andReturn(gatewayConfig).anyTimes();
    ServletInputStream inputStream = EasyMock.createNiceMock(ServletInputStream.class);
    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getQueryString()).andReturn("delegation=123").anyTimes();
    EasyMock.expect(inboundRequest.getInputStream()).andReturn(inputStream).anyTimes();
    EasyMock.expect(inboundRequest.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.replay(gatewayConfig, servletContext, inboundRequest);
    HttpEntity httpEntity = defaultDispatch.createRequestEntity(inboundRequest);
    assertFalse("buffering in the presence of delegation token",
            (httpEntity instanceof PartiallyRepeatableHttpEntity));
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatchTest.java

@Test
public void testCallToNonSecureClusterWithoutDelegationToken() throws URISyntaxException, IOException {
    DefaultDispatch defaultDispatch = new DefaultDispatch();
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);
    GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
    EasyMock.expect(gatewayConfig.isHadoopKerberosSecured()).andReturn(false).anyTimes();
    EasyMock.expect(servletContext.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE))
            .andReturn(gatewayConfig).anyTimes();
    ServletInputStream inputStream = EasyMock.createNiceMock(ServletInputStream.class);
    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getInputStream()).andReturn(inputStream).anyTimes();
    EasyMock.expect(inboundRequest.getQueryString()).andReturn("a=123").anyTimes();
    EasyMock.expect(inboundRequest.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.replay(gatewayConfig, servletContext, inboundRequest);
    HttpEntity httpEntity = defaultDispatch.createRequestEntity(inboundRequest);
    assertFalse("buffering in non secure cluster", (httpEntity instanceof PartiallyRepeatableHttpEntity));
}

From source file:com.rapid.forms.RapidFormAdapter.java

@Override
public UserFormDetails getNewFormDetails(RapidRequest rapidRequest) {
    // get the servlet context
    ServletContext servletContext = rapidRequest.getRapidServlet().getServletContext();
    // the master form id as a string
    String nextFormIdString = (String) servletContext.getAttribute(NEXT_FORM_ID);
    // if null set to "0"
    if (nextFormIdString == null)
        nextFormIdString = "0";
    // add 1 to the master form id
    String formId = Integer.toString(Integer.parseInt(nextFormIdString) + 1);
    // retain it in the context
    servletContext.setAttribute(NEXT_FORM_ID, formId);
    // return it/* w  w  w  .j av a  2 s.  co m*/
    return new UserFormDetails(formId, null);
}

From source file:org.artifactory.webapp.servlet.ArtifactoryContextConfigListener.java

private void configure(ServletContext servletContext, Logger log) throws Exception {
    long start = System.currentTimeMillis();

    ArtifactoryHome artifactoryHome = (ArtifactoryHome) servletContext
            .getAttribute(ArtifactoryHome.SERVLET_CTX_ATTR);
    VersionProviderImpl versionProvider = (VersionProviderImpl) servletContext
            .getAttribute(ArtifactoryHome.ARTIFACTORY_VERSION_PROVIDER_OBJ);
    ConverterManager converterManager = (ConverterManager) servletContext
            .getAttribute(ArtifactoryHome.ARTIFACTORY_CONVERTER_OBJ);

    if (artifactoryHome == null) {
        throw new IllegalStateException("Artifactory home not initialized.");
    }/*w ww .j  a v a  2  s .c  o  m*/
    CompoundVersionDetails runningVersionDetails = versionProvider.getRunning();

    logAsciiArt(log, artifactoryHome, runningVersionDetails);

    ApplicationContext context;
    try {
        ArtifactoryHome.bind(artifactoryHome);

        //todo consider moving to org.artifactory.webapp.servlet.ArtifactoryHomeConfigListener.contextInitialized()
        if (artifactoryHome.isHaConfigured()) {
            log.debug("Not using Artifactory lock file on HA environment");
        } else {
            artifactoryLockFile = new ArtifactoryLockFile(
                    new File(artifactoryHome.getDataDir(), LOCK_FILENAME));
            artifactoryLockFile.tryLock();
        }

        Class<?> contextClass = ClassUtils.forName("org.artifactory.spring.ArtifactoryApplicationContext",
                ClassUtils.getDefaultClassLoader());
        Constructor<?> constructor = contextClass.getConstructor(String.class, SpringConfigPaths.class,
                ArtifactoryHome.class, ConverterManager.class, VersionProviderImpl.class);
        //Construct the context name based on the context path
        //(will not work with multiple servlet containers on the same vm!)
        String contextUniqueName = HttpUtils.getContextId(servletContext);
        SpringConfigPaths springConfigPaths = SpringConfigResourceLoader.getConfigurationPaths(artifactoryHome);
        context = (ApplicationContext) constructor.newInstance(contextUniqueName, springConfigPaths,
                artifactoryHome, converterManager, versionProvider);
    } finally {
        ArtifactoryHome.unbind();
    }
    log.info("\n" + "###########################################################\n"
            + "### Artifactory successfully started ("
            + String.format("%-17s",
                    (DurationFormatUtils.formatPeriod(start, System.currentTimeMillis(), "s.S")) + " seconds)")
            + " ###\n" + "###########################################################\n");

    //Register the context for easy retrieval for faster destroy
    servletContext.setAttribute(ArtifactoryContext.APPLICATION_CONTEXT_KEY, context);
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteResponseTest.java

@Test
public void testResolve() throws Exception {

    UrlRewriteProcessor rewriter = EasyMock.createNiceMock(UrlRewriteProcessor.class);

    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
    EasyMock.expect(context.getServletContextName()).andReturn("test-cluster-name").anyTimes();
    EasyMock.expect(context.getInitParameter("test-init-param-name")).andReturn("test-init-param-value")
            .anyTimes();/* ww w . ja v  a2s . c  o  m*/
    EasyMock.expect(context.getAttribute(UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME))
            .andReturn(rewriter).anyTimes();

    FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
    EasyMock.expect(config.getInitParameter("test-filter-init-param-name"))
            .andReturn("test-filter-init-param-value").anyTimes();
    EasyMock.expect(config.getServletContext()).andReturn(context).anyTimes();

    HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
    HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);

    EasyMock.replay(rewriter, context, config, request, response);

    UrlRewriteResponse rewriteResponse = new UrlRewriteResponse(config, request, response);

    List<String> names = rewriteResponse.resolve("test-filter-init-param-name");
    assertThat(names.size(), is(1));
    assertThat(names.get(0), is("test-filter-init-param-value"));
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatchTest.java

@Test
public void testCallToSecureClusterWithoutDelegationToken() throws URISyntaxException, IOException {
    DefaultDispatch defaultDispatch = new DefaultDispatch();
    defaultDispatch.setReplayBufferSize(10);
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);
    GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
    EasyMock.expect(gatewayConfig.isHadoopKerberosSecured()).andReturn(Boolean.TRUE).anyTimes();
    EasyMock.expect(servletContext.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE))
            .andReturn(gatewayConfig).anyTimes();
    ServletInputStream inputStream = EasyMock.createNiceMock(ServletInputStream.class);
    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getQueryString()).andReturn("a=123").anyTimes();
    EasyMock.expect(inboundRequest.getInputStream()).andReturn(inputStream).anyTimes();
    EasyMock.expect(inboundRequest.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.replay(gatewayConfig, servletContext, inboundRequest);
    HttpEntity httpEntity = defaultDispatch.createRequestEntity(inboundRequest);
    assertTrue("not buffering in the absence of delegation token",
            (httpEntity instanceof PartiallyRepeatableHttpEntity));
}

From source file:edu.mit.csail.sls.wami.portal.xmlrpc.XmlRpcPortalRecognizer.java

public void setParameters(ServletContext sc, Map<String, String> map) throws RecognizerException {
    this.sc = sc;
    String recDomain = (String) sc.getAttribute("recDomain");
    String developerEmail = map.get("developerEmail");
    String developerKey = map.get("developerKey");
    String recordFormat = map.get("recordFormat");
    int recordSampleRate = Integer.parseInt(map.get("recordSampleRate"));
    boolean recordIsLittleEndian = Boolean.parseBoolean(map.get("recordIsLittleEndian"));
    String incrementalResultsStr = map.get("incrementalResults");
    incrementalResults = (incrementalResultsStr == null || Boolean.parseBoolean(incrementalResultsStr));

    serverAddress = null;//  w w w . j  av a 2  s  . c om
    try {
        serverAddress = new URL(map.get("url"));
    } catch (MalformedURLException e) {
        throw new RecognizerException("Invalid recognizer url", e);
    }

    XmlRpcClientConfig config = createClientConfig(serverAddress, 10 * 1000, 10 * 1000);
    client = new XmlRpcClient();

    XmlRpcCommonsTransportFactory factory = new XmlRpcCommonsTransportFactory(client);

    // Use HTTP 1.1
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    factory.setHttpClient(httpClient);

    client.setTransportFactory(factory);
    client.setConfig(config);

    Object[] createParams = { developerEmail, developerKey, recordFormat, recordSampleRate,
            recordIsLittleEndian, recDomain };

    try {
        sessionId = (String) client.execute("Portal.createRecognizerSession", createParams);
    } catch (XmlRpcException e) {
        if (e.code == ErrorCodes.SERVER_ERROR_CODE) {
            throw new RecognizerException(e);
        } else {
            throw new RecognizerUnreachableException(e);
        }
    }

    String jsgfGrammarPath = map.get("jsgfGrammarPath");
    String jsgfGrammarLanguage = map.get("jsgfGrammarLanguage");
    if (jsgfGrammarPath != null) {
        InputStream in = sc.getResourceAsStream(jsgfGrammarPath);
        if (in == null) {
            throw new RecognizerException("Couldn't find grammar: " + jsgfGrammarPath);
        }

        String language = (jsgfGrammarLanguage != null) ? jsgfGrammarLanguage : "en-us";

        try {
            JsgfGrammar grammar = new JsgfGrammar(in, language);
            setLanguageModel(grammar);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.skilrock.lms.web.accMgmt.common.AgentPaymentSubmit.java

public String agentPayment() throws Exception {
    logger.info("REQUEST_CASH_PAYMENT_SUBMIT-" + this);
    HttpSession session = null;/* ww w  .j a v a 2  s .c om*/
    UserInfoBean userBean = null, agentInfoBean = null;
    String[] denoType = null;
    Connection con = null;
    try {
        session = getRequest().getSession();
        userBean = (UserInfoBean) session.getAttribute("USER_INFO");
        agentInfoBean = CommonMethods.fetchUserData(orgId);
        logger.info(
                "REQUEST_CASH_PAYMENT_SUBMIT-" + request.getAttribute("AUDIT_ID") + ":" + userBean.getUserId());
        String currencySymbol = (String) ServletActionContext.getServletContext()
                .getAttribute("CURRENCY_SYMBOL");
        logger.info("user_id is-" + userBean.getUserId());
        ServletContext sc = ServletActionContext.getServletContext();
        String isCREnable = (String) sc.getAttribute("IS_CASH_REGISTER");
        if (totalAmount != cashAmnt) {
            throw new LMSException(LMSErrors.CASH_PAYMENT_INVALIDATE_DATA_ERROR_CODE,
                    LMSErrors.CASH_PAYMENT_INVALIDATE_DATA_ERROR_MESSAGE);
        }
        if ("ACTIVE".equalsIgnoreCase(isCREnable)) {
            CashRegisterHelper drawerHelper = new CashRegisterHelper();
            List<String> denoList = drawerHelper.getReceivedDenoList();
            denoType = (String[]) denoList.toArray(new String[denoList.size()]);
        }
        con = DBConnect.getConnection();
        con.setAutoCommit(false);
        int retOrgId = Integer.parseInt(retOrgName);
        int agentId = agentInfoBean.getUserId();
        AgentPaymentSubmitHelper helper = new AgentPaymentSubmitHelper();
        String autoGeneRecieptNoAndId = helper.submitCashAgentAmt(orgId, "AGENT", totalAmount,
                userBean.getUserId(), userBean.getUserOrgId(), userBean.getUserType(), denoType, multiples,
                retDenoType, retMultiples, con);
        if (orgType.equalsIgnoreCase("RETAILER")) {
            RetailerPaymentSubmitHelper retailerPaymentSubmit = new RetailerPaymentSubmitHelper();
            autoGeneRecieptNoAndId = retailerPaymentSubmit.retailerCashPaySubmit(retOrgId, "RETAILER", retOrgId,
                    totalAmount, agentId, orgId, "AGENT", con);
        }
        con.commit();
        String[] autoGeneReceipt = autoGeneRecieptNoAndId.split("#");
        String autoGeneRecieptNo = autoGeneReceipt[0];
        int id = Integer.parseInt(autoGeneReceipt[1]);
        java.util.Date d = new java.util.Date();

        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        String generationTime = sdf.format(d.getTime());
        logger.info("Generation time:" + generationTime);
        boolean isThermalRcptRequired = "true".equals((String) ServletActionContext.getServletContext()
                .getAttribute("IS_CASH_RCPT_ON_THERMAL_PRINTER"));

        if (isThermalRcptRequired) {
            NumberFormat nf = NumberFormat.getInstance();
            nf.setMinimumFractionDigits(2);

            String amountCash = nf.format(totalAmount);
            String data = "data=0|txType=RECEIPT|address="
                    + CommonMethods.getOrgAddress(String.valueOf(userBean.getUserOrgId())) + "|genTime="
                    + generationTime + "|mode=Voucher|voucherNo=" + autoGeneRecieptNo + "|txDate="
                    + sdf.format(d.getTime()) + "|amount=" + amountCash + "|orgName=" + agentNameValue
                    + "|ctr=200|parentOrgName=" + userBean.getOrgName() + "|curSymbol=" + currencySymbol;
            session.setAttribute("APP_DATA", data);
        }
        session.setAttribute("totalPay", totalAmount);
        session.setAttribute("orgName", agentNameValue);
        session.setAttribute("Receipt_Id", autoGeneRecieptNo);
        GraphReportHelper graphReportHelper = new GraphReportHelper();
        if ("AGENT".equalsIgnoreCase(orgType)) {
            String parentOrgName = null;
            int userOrgID = 0;
            parentOrgName = userBean.getOrgName();
            userOrgID = userBean.getUserOrgId();
            graphReportHelper.createTextReportBO(id, parentOrgName, userOrgID,
                    (String) session.getAttribute("ROOT_PATH"));
        } else {
            graphReportHelper.createTextReportAgent(id, (String) session.getAttribute("ROOT_PATH"), orgId,
                    agentInfoBean.getOrgName());
        }
    } catch (LMSException le) {
        logger.info("RESPONSE_CASH_PAYMENT_SUBMIT-: ErrorCode:" + le.getErrorCode() + " ErrorMessage:"
                + le.getErrorMessage());
        request.setAttribute("LMS_EXCEPTION", le.getErrorMessage());
        return "applicationException";
    } catch (Exception e) {
        logger.error("Exception", e);
        logger.info("RESPONSE_CASH_PAYMENT_SUBMIT-: ErrorCode:" + LMSErrors.GENERAL_EXCEPTION_ERROR_CODE
                + " ErrorMessage:" + LMSErrors.GENERAL_EXCEPTION_ERROR_MESSAGE);
        request.setAttribute("LMS_EXCEPTION", LMSErrors.GENERAL_EXCEPTION_ERROR_MESSAGE);
        return "applicationException";
    } finally {
        try {
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    return SUCCESS;
}

From source file:nl.nn.adapterframework.pipes.CreateRestViewPipe.java

private Map retrieveParameters(HttpServletRequest httpServletRequest, ServletContext servletContext,
        String srcPrefix) throws DomBuilderException {
    String attributeKey = AppConstants.getInstance().getProperty(ConfigurationServlet.KEY_CONTEXT);
    IbisContext ibisContext = (IbisContext) servletContext.getAttribute(attributeKey);
    Map parameters = new Hashtable();
    String requestInfoXml = "<requestInfo>" + "<servletRequest>" + "<serverInfo><![CDATA["
            + servletContext.getServerInfo() + "]]></serverInfo>" + "<serverName>"
            + httpServletRequest.getServerName() + "</serverName>" + "</servletRequest>" + "</requestInfo>";
    parameters.put("requestInfo", XmlUtils.buildNode(requestInfoXml));
    parameters.put("upTime", XmlUtils.buildNode("<upTime>" + ibisContext.getUptime() + "</upTime>"));
    String machineNameXml = "<machineName>" + Misc.getHostname() + "</machineName>";
    parameters.put("machineName", XmlUtils.buildNode(machineNameXml));
    String fileSystemXml = "<fileSystem>" + "<totalSpace>" + Misc.getFileSystemTotalSpace() + "</totalSpace>"
            + "<freeSpace>" + Misc.getFileSystemFreeSpace() + "</freeSpace>" + "</fileSystem>";
    parameters.put("fileSystem", XmlUtils.buildNode(fileSystemXml));
    String applicationConstantsXml = appConstants.toXml(true);
    parameters.put("applicationConstants", XmlUtils.buildNode(applicationConstantsXml));
    String processMetricsXml = ProcessMetrics.toXml();
    parameters.put("processMetrics", XmlUtils.buildNode(processMetricsXml));
    parameters.put("menuBar", XmlUtils.buildNode(retrieveMenuBarParameter(srcPrefix)));
    parameters.put(SRCPREFIX, srcPrefix);

    return parameters;
}