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:fi.eis.applications.osgi.support.OsgiBundleXmlWebApplicationContext.java

/**
 * {@inheritDoc}//from www .j a  v a 2 s.  co m
 * 
 * Additionally, if the {@link BundleContext} is not set, it is looked up
 * under {@link #BUNDLE_CONTEXT_ATTRIBUTE}.
 */
public void setServletContext(ServletContext servletContext) {
    this.servletContext = servletContext;

    // look for the attribute only if there is no BundleContext available
    if (getBundleContext() == null) {

        // try to locate the bundleContext in the ServletContext
        if (servletContext != null) {
            Object context = servletContext.getAttribute(BUNDLE_CONTEXT_ATTRIBUTE);

            if (context != null) {
                Assert.isInstanceOf(BundleContext.class, context);
                //logger.debug("Using the bundle context located in the servlet context at "
                //      + BUNDLE_CONTEXT_ATTRIBUTE);
                setBundleContext((BundleContext) context);
            }
        }

        // fall back to the parent
        ApplicationContext parent = getParent();

        if (parent instanceof ConfigurableOsgiBundleApplicationContext) {
            //logger.debug("Using the application context parent's bundle context");
            setBundleContext(((ConfigurableOsgiBundleApplicationContext) parent).getBundleContext());
        }
    }
}

From source file:it.unimi.di.big.mg4j.query.QueryServlet.java

@SuppressWarnings("unchecked")
@Override/*from www. j a v  a  2  s .  co  m*/
public void init() throws ServletException {
    super.init();
    ServletContext context = getServletContext();

    if ((template = (String) getServletContext().getAttribute("template")) == null
            && (template = getInitParameter("template")) == null)
        template = DEFAULT_TEMPLATE;

    queryEngine = (QueryEngine) context.getAttribute("queryEngine");
    documentCollection = (DocumentCollection) context.getAttribute("collection");
    titleList = (BigList<? extends CharSequence>) context.getAttribute("titleList");
    indexMap = queryEngine.indexMap;
    try {
        urlEncodedMimeType = URLEncoder.encode((String) context.getAttribute("mimeType"), "UTF-8");
    } catch (UnsupportedEncodingException cantHappen) {
        throw new RuntimeException(cantHappen);
    }
    useUri = context.getAttribute("uri") == Boolean.TRUE;
    derelativise = context.getAttribute("derelativise") == Boolean.TRUE;

    if (documentCollection != null) {
        sortedIndex = new Index[indexMap.size()];
        indexMap.values().toArray(sortedIndex);
        Arrays.sort(sortedIndex, new Comparator<Index>() {
            public int compare(final Index x, final Index y) {
                return documentCollection.factory().fieldIndex(x.field)
                        - documentCollection.factory().fieldIndex(y.field);
            }
        });
    }
}

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

@Override
public UserFormDetails getResumeFormDetails(RapidRequest rapidRequest, String formId, String password)
        throws Exception {
    // get the servlet context
    ServletContext servletContext = rapidRequest.getRapidServlet().getServletContext();
    // get all app page control values from session
    Map<String, Map<String, FormPageControlValues>> userAppPageControlValues = (Map<String, Map<String, FormPageControlValues>>) servletContext
            .getAttribute(USER_FORM_PAGE_CONTROL_VALUES);
    // check we got something
    if (userAppPageControlValues == null) {
        // nothing so return null
        return null;
    } else {/*  ww  w  .  java 2  s.  c  o  m*/
        // the page controls for specified app
        Map<String, FormPageControlValues> userPageControlValues = userAppPageControlValues.get(formId);
        // null check
        if (userPageControlValues == null) {
            // form not found so fail
            return null;
        } else {
            // form found we're good
            return new UserFormDetails(formId, null, null, false, null);
        }
    }
}

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

@Test
public void testUsingDefaultBufferSize() throws URISyntaxException, IOException {
    DefaultDispatch defaultDispatch = new DefaultDispatch();
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);
    GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
    EasyMock.expect(gatewayConfig.isHadoopKerberosSecured()).andReturn(Boolean.TRUE).anyTimes();
    EasyMock.expect(gatewayConfig.getHttpServerRequestBuffer()).andReturn(16384).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));
    assertEquals(defaultDispatch.getReplayBufferSize(), 16);
    assertEquals(defaultDispatch.getReplayBufferSizeInBytes(), 16384);

    //also test normal setter and getters
    defaultDispatch.setReplayBufferSize(-1);
    assertEquals(defaultDispatch.getReplayBufferSizeInBytes(), -1);
    assertEquals(defaultDispatch.getReplayBufferSize(), -1);

    defaultDispatch.setReplayBufferSize(16);
    assertEquals(defaultDispatch.getReplayBufferSizeInBytes(), 16384);
    assertEquals(defaultDispatch.getReplayBufferSize(), 16);

}

From source file:com.ws.WS_TCS201.java

/**
 * Creates a new instance of WS_TCS201/*w w  w .ja va 2 s. c  om*/
 */
public WS_TCS201(@Context ServletContext sc) {
    db = (DatabaseAccess) sc.getAttribute("db");
    this.connection = db.getConnection();
}

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

protected Map<String, FormPageControlValues> getUserFormPageControlValues(RapidRequest rapidRequest)
        throws Exception {
    // get the servlet context
    ServletContext servletContext = rapidRequest.getRapidServlet().getServletContext();
    // get all app page control values from the context
    Map<String, Map<String, FormPageControlValues>> userAppPageControlValues = (Map<String, Map<String, FormPageControlValues>>) servletContext
            .getAttribute(USER_FORM_PAGE_CONTROL_VALUES);
    // if null/*from   w w  w . ja  v a  2  s  .c o m*/
    if (userAppPageControlValues == null) {
        // instantiate
        userAppPageControlValues = new HashMap<String, Map<String, FormPageControlValues>>();
        // add to session
        servletContext.setAttribute(USER_FORM_PAGE_CONTROL_VALUES, userAppPageControlValues);
    }
    // get the form id
    String formId = getFormId(rapidRequest);
    // the page controls for specified app
    Map<String, FormPageControlValues> userPageControlValues = userAppPageControlValues.get(formId);
    // if null, instantiate
    if (userPageControlValues == null) {
        // instantiate
        userPageControlValues = new HashMap<String, FormPageControlValues>();
        // add to user app pages
        userAppPageControlValues.put(formId, userPageControlValues);
    }

    // example page control pre-population         
    // userPageControlValues.put("P2", new FormPageControlValues(new FormControlValue("P2_C1_", "Hello world !!!")));

    // return!
    return userPageControlValues;
}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

/**
 * Collects all PropertyEditorRegistrars in the application context and
 * calls them to register their custom editors
 *
 * @param servletContext/*w  w w .j a v  a 2 s  . c om*/
 * @param registry The PropertyEditorRegistry instance
 */
private static void registerCustomEditors(ServletContext servletContext, PropertyEditorRegistry registry) {
    if (servletContext == null) {
        return;
    }

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
    if (context == null) {
        return;
    }

    @SuppressWarnings("unchecked")
    Map<String, PropertyEditorRegistrar> editors = (Map<String, PropertyEditorRegistrar>) servletContext
            .getAttribute(PROPERTY_EDITOR_REGISTRARS);
    if (editors == null) {
        editors = context.getBeansOfType(PropertyEditorRegistrar.class);
        if (!Environment.isDevelopmentMode()) {
            servletContext.setAttribute(PROPERTY_EDITOR_REGISTRARS, editors);
        }
    }
    for (PropertyEditorRegistrar editorRegistrar : editors.values()) {
        editorRegistrar.registerCustomEditors(registry);
    }
}

From source file:com.thejustdo.servlet.CargaMasivaServlet.java

/**
 * Builds a ZIP file with all the title-value to be generated with the boxes
 * configuration./*from   ww  w .  j  av a 2s  .  co  m*/
 *
 * @param request Contains all the important data to be used.
 * @param response Allows us to write the content.
 */
private void generateZIP(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // 1. Getting the content of the plain xhtml file.
    ServletContext sc = this.getServletConfig().getServletContext();
    File tempDir = (File) sc.getAttribute("javax.servlet.context.tempdir");
    File basePath = Utils.preparePDFDirs(tempDir, sc);
    File tmpName = new File(basePath, Constants.PDF_TMP_NAME);
    File d = new File(tempDir, Constants.TMP_TITLES);
    String _xhtml = Utils.getPlainTextFileFromContext(Constants.MASSIVE_LOCATION, sc);
    // 1.1 Cleaning the temporary directory.
    Utils.cleanDirectory(d);

    // log.info(String.format("Prev XHTML content: %s", _xhtml));

    // 2. Getting parameters to configure the PDF content.
    Map<String, String> matrix = (Map<String, String>) request.getSession().getAttribute("boxes");
    String amount = (String) request.getSession().getAttribute("boxamount");

    // 3. Generating the new xhtml per entry.
    String xhtml;
    String name;
    OutputStream os;
    File _new;
    Set<String> keys = matrix.keySet();
    int i = 1;
    try {

        for (String k : keys) {
            name = matrix.get(k);
            xhtml = String.format(_xhtml, name, k, amount);
            Utils.createTMPFile(xhtml, tmpName);
            // 2. Creating the PDF output.
            _new = new File(d, String.format("title%d.pdf", i));
            os = new FileOutputStream(_new);

            // 3. Creating the gross part.
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(tmpName);
            //renderer.setDocumentFromString(xhtml);
            renderer.layout();
            renderer.createPDF(os);
            os.flush();
            os.close();
            i++;
        }

        // log.info(String.format("New XHTML content: %s", xhtml));
        // File f = Utils.createNewFileInsideContext(
        //     Constants.PDF_LOCATION, sc, xhtml, Constants.PDF_TMP);

        // 4. Creating the ZIP file.
        File zip = new File(tempDir, Constants.ZIP_NAME);
        Utils.zipDirectory(d, zip);

        response.setHeader("Content-Type", "application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=\"titulos.zip\"");

        // 3. Writing the file to the output.
        // The csv parameter contains the path to the temp file to be writen.
        FileInputStream fis = new FileInputStream(zip);
        os = response.getOutputStream();

        byte buffer[] = new byte[256];
        int bytesRead;

        while ((bytesRead = fis.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }

        os.flush();
        os.close();
    } catch (DocumentException ex) {
        ex.printStackTrace();
        log.log(Level.SEVERE, null, ex);
    }
}

From source file:com.adito.properties.attributes.AttributeValueItem.java

/**
 * Constructor.//from www.  j ava 2s .  c  o m
 * 
 * @param definition definition
 * @param request request
 * @param value initial value
 * @param subCategory 
 */
public AttributeValueItem(AttributeDefinition definition, HttpServletRequest request, String value,
        String subCategory) {
    super(definition, request, subCategory);

    this.value = getDefinition().parseValue(value);

    // Process the type meta for any type specific parameters
    if (definition.getType() == PropertyDefinition.TYPE_TEXT_AREA) {
        this.value = value;
        StringTokenizer t = new StringTokenizer(
                definition.getTypeMeta().equals("") ? "25x5" : definition.getTypeMeta(), "x");
        try {
            columns = Integer.parseInt(t.nextToken());
            rows = Integer.parseInt(t.nextToken());
        } catch (Exception e) {
        }
    } else if (definition.getType() == PropertyDefinition.TYPE_LIST) {
        List<Pair> listItemsList = new ArrayList<Pair>();
        if (!definition.getTypeMeta().startsWith("!")) {
            for (Iterator i = ((List) definition.getTypeMetaObject()).iterator(); i.hasNext();) {
                TypeMetaListItem item = (TypeMetaListItem) i.next();
                ServletContext context = CoreServlet.getServlet().getServletContext();
                ModuleConfig moduleConfig = ModuleUtils.getInstance().getModuleConfig(request, context);
                String mrKey = (item.getMessageResourcesKey() == null ? "properties"
                        : item.getMessageResourcesKey()) + moduleConfig.getPrefix();
                MessageResources res = (MessageResources) context.getAttribute(mrKey);
                String k = definition.getName() + ".value." + item.getValue();
                String v = "";
                if (res != null) {
                    v = res.getMessage((Locale) request.getSession().getAttribute(Globals.LOCALE_KEY), k);
                    if (v == null) {
                        v = item.getValue();
                    }
                }
                Pair pair = new Pair(item.getValue(), v);
                if (item.getValue().equals(value)) {
                    this.value = pair.getValue();
                }
                listItemsList.add(pair);
            }
        } else {
            String className = definition.getTypeMeta().substring(1);
            try {
                Class clazz = Class.forName(className);
                Object obj = clazz.newInstance();
                if (obj instanceof PairListDataSource)
                    listItemsList.addAll(((PairListDataSource) obj).getValues(request));
                else
                    throw new Exception("Not a PairListDataSource.");
            } catch (Exception e) {
                log.error("Failed to create list data source.", e);
            }
            this.value = value;
        }
        listItems = new Pair[listItemsList.size()];
        listItemsList.toArray(listItems);
    } else if (definition.getType() == PropertyDefinition.TYPE_STRING) {
        columns = 25;
        if (!definition.getTypeMeta().equals("")) {
            try {
                columns = Integer.parseInt(definition.getTypeMeta());
            } catch (NumberFormatException nfe) {
            }
        }
    } else if (definition.getType() == PropertyDefinition.TYPE_INTEGER) {
        columns = 8;
        if (!definition.getTypeMeta().equals("")) {
            try {
                columns = Integer.parseInt(definition.getTypeMeta());
            } catch (NumberFormatException e) {
            }
        }
    } else if (definition.getType() == PropertyDefinition.TYPE_PASSWORD) {
        columns = 25;
        if (!definition.getTypeMeta().equals("")) {
            try {
                columns = Integer.parseInt(definition.getTypeMeta());
            } catch (NumberFormatException nfe) {
            }
        }
    } else if (definition.getType() == PropertyDefinition.TYPE_TIME_IN_MS) {
        try {
            int val = Integer.parseInt(value);
            if (definition.getTypeMeta().equalsIgnoreCase("s")) {
                this.value = String.valueOf(val / 1000);
            } else if (definition.getTypeMeta().equalsIgnoreCase("m")) {
                this.value = String.valueOf(val / 1000 / 60);
            } else if (definition.getTypeMeta().equalsIgnoreCase("h")) {
                this.value = String.valueOf(val / 1000 / 60 / 60);
            } else if (definition.getTypeMeta().equalsIgnoreCase("d")) {
                this.value = String.valueOf(val / 1000 / 60 / 60 / 24);
            } else {
                this.value = String.valueOf(val);
            }
        } catch (Exception e) {
        }
    }
}