Example usage for javax.servlet ServletRequest getAttribute

List of usage examples for javax.servlet ServletRequest getAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletRequest getAttribute.

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.

Usage

From source file:edu.cornell.mannlib.vitro.webapp.filters.WebappDaoFactorySDBPrep.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    if (request.getAttribute("WebappDaoFactorySDBPrep.setup") != null) {
        // don't run multiple times
        filterChain.doFilter(request, response);
        return;/*from w w w. j a va 2 s.  c  o  m*/
    }

    for (Pattern skipPattern : skipPatterns) {
        Matcher match = skipPattern.matcher(((HttpServletRequest) request).getRequestURI());
        if (match.matches()) {
            log.debug("request matched a skipPattern, skipping VitroRequestPrep");
            filterChain.doFilter(request, response);
            return;
        }
    }

    OntModelSelector oms = ModelContext.getUnionOntModelSelector(_ctx);
    OntModelSelector baseOms = ModelContext.getBaseOntModelSelector(_ctx);
    String defaultNamespace = (String) _ctx.getAttribute("defaultNamespace");
    WebappDaoFactory wadf = null;
    VitroRequest vreq = new VitroRequest((HttpServletRequest) request);

    List<String> langs = new ArrayList<String>();

    log.debug("Accept-Language: " + vreq.getHeader("Accept-Language"));
    Enumeration<Locale> locs = vreq.getLocales();
    while (locs.hasMoreElements()) {
        Locale locale = locs.nextElement();
        langs.add(locale.toString().replace("_", "-"));
    }
    if (langs.isEmpty()) {
        langs.add("en");
    }
    WebappDaoFactoryConfig config = new WebappDaoFactoryConfig();
    config.setDefaultNamespace(defaultNamespace);
    config.setPreferredLanguages(langs);

    RDFServiceFactory factory = RDFServiceUtils.getRDFServiceFactory(_ctx);

    //RDFService rdfService = factory.getRDFService();
    RDFService unfilteredRDFService = factory.getShortTermRDFService();
    RDFService rdfService = null;

    if (!"false"
            .equals(ConfigurationProperties.getBean(vreq).getProperty("RDFService.languageFilter", "true"))) {
        rdfService = new LanguageFilteringRDFService(unfilteredRDFService, langs);
    } else {
        rdfService = unfilteredRDFService;
    }

    Dataset dataset = new RDFServiceDataset(rdfService);
    wadf = new WebappDaoFactorySDB(rdfService, oms, config);
    WebappDaoFactory assertions = new WebappDaoFactorySDB(rdfService, baseOms, config,
            SDBDatasetMode.ASSERTIONS_ONLY);
    vreq.setRDFService(rdfService);
    vreq.setUnfilteredRDFService(unfilteredRDFService);
    vreq.setWebappDaoFactory(wadf);
    vreq.setAssertionsWebappDaoFactory(assertions);
    vreq.setFullWebappDaoFactory(wadf);
    vreq.setUnfilteredWebappDaoFactory(
            new WebappDaoFactorySDB(rdfService, ModelContext.getUnionOntModelSelector(_ctx)));
    vreq.setDataset(dataset);
    vreq.setOntModelSelector(baseOms);

    vreq.setJenaOntModel(ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, dataset.getDefaultModel()));

    request.setAttribute("WebappDaoFactorySDBPrep.setup", 1);

    try {
        filterChain.doFilter(request, response);
        return;
    } finally {
        if (wadf != null) {
            wadf.close();
        }
    }

}

From source file:com.mirantis.cachemod.filter.CacheFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    if (request.getAttribute(conf.getAlreadyFilteredKey()) != null || !isCacheable(request)) {

        /*/* www . ja  v  a 2s . c  o  m*/
         *  This request is not Cacheable
         */

        chain.doFilter(request, response);
    } else {
        request.setAttribute(conf.getAlreadyFilteredKey(), Boolean.TRUE);

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        boolean fragmentRequest = isFragment(httpRequest);

        String key = conf.getCacheKeyProvider().createKey(httpRequest);

        CacheEntry cacheEntry = conf.getCacheProvider().getEntry(key);
        if (cacheEntry != null) {

            if (!fragmentRequest) {

                /*
                 * -1 of no in header
                 */
                long clientLastModified = httpRequest.getDateHeader("If-Modified-Since");

                /*
                 * Reply with SC_NOT_MODIFIED for client that has newest page 
                 */
                if ((clientLastModified != -1) && (clientLastModified >= cacheEntry.getLastModified())) {
                    ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return;
                }
            }

            writeCacheToResponse(cacheEntry, response, fragmentRequest);

        } else {
            cacheEntry = conf.getCacheProvider().instantiateEntry();

            CacheHttpServletResponse cacheResponse = new CacheHttpServletResponse(
                    (HttpServletResponse) response, cacheEntry, conf, fragmentRequest);
            chain.doFilter(request, cacheResponse);

            if (cacheResponse.getStatus() == HttpServletResponse.SC_OK) {
                cacheResponse.commit();
                if (conf.getUserDataProvider() != null) {
                    cacheEntry.setUserData(conf.getUserDataProvider().createUserData(httpRequest));
                }
                conf.getCacheProvider().putEntry(key, cacheEntry);
            }
        }
    }

}

From source file:com.xt.views.taglib.html.BaseFieldTag.java

/**
 * ?value// w ww . ja  v a  2s .c  o m
 * 
 * @return
 * @throws JspException
 */
protected void caculateValue() throws JspException {
    try {
        ServletRequest req = pageContext.getRequest();
        if (req.getAttribute("GET_VALUE_FROM_PARAMS") != null) {
            beforeFormatedValue = req.getParameter(property);
        } else {
            beforeFormatedValue = TagUtils.getInstance().lookup(pageContext, name, property, null);
        }
    } catch (Throwable e) {
        // ??
        LogWriter.warn(e.getMessage());
    }
    this.value = myFormatValue(beforeFormatedValue);
}

From source file:com.easyshop.common.web.filter.SetCommonDataFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    ////w  w  w . j  a v a  2s  . c  o  m
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    if (request.getAttribute(Constants.CONTEXT_PATH) == null) {
        request.setAttribute(Constants.CONTEXT_PATH, httpServletRequest.getContextPath());
    }
    if (request.getAttribute(Constants.WEB_BASE) == null) {
        request.setAttribute(Constants.WEB_BASE, webBase);
    }

    //?
    String currentPageStr = request.getParameter(currentPageParamKey);
    if (StringUtils.isNotBlank(currentPageStr)) {
        try {
            Integer currentPage = Integer.valueOf(currentPageStr);
            PageContext.setCurrentPage(currentPage);
        } catch (NumberFormatException e) {
            //e.printStackTrace();
            LOGGER.warn(
                    "?'currentPage'?,???,?{}",
                    currentPageStr);
        }
    }

    String pageSizeStr = request.getParameter(pageSizeParamKey);
    if (StringUtils.isNotBlank(pageSizeStr)) {
        try {
            Integer pageSize = Integer.valueOf(pageSizeStr);
            PageContext.setPageSize(pageSize);
        } catch (NumberFormatException e) {
            //e.printStackTrace();
            LOGGER.warn(
                    "?'pageSize'?,???,?{}",
                    pageSizeStr);
        }
    }

    try {
        chain.doFilter(request, response);
    } finally {
        PageContext.clear();
    }
}

From source file:org.apache.tiles.web.util.TilesDecorationFilter.java

/**
 * Returns the request base, i.e. the the URL to calculate all the relative
 * paths./*from w w  w  . ja  v  a  2s. co m*/
 *
 * @param request The request object to use.
 * @return The request base.
 */
private String getRequestBase(ServletRequest request) {
    // Included Path
    String include = (String) request.getAttribute("javax.servlet.include.servlet_path");
    if (include != null) {
        return include;
    }

    // As opposed to includes, if a forward occurs, it will update the servletPath property
    // and include the original as the request attribute.
    return ((HttpServletRequest) request).getServletPath();
}

From source file:demo.oauth.server.spring.SpringOAuthAuthenticationFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;

    List<String> authorities = (List<String>) request.getAttribute(OAUTH_AUTHORITIES);
    List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();

    if (authorities != null) {
        for (String authority : authorities) {
            grantedAuthorities.add(new GrantedAuthorityImpl(authority));
        }//  ww w.  j  av a 2  s .c  o m

        Authentication auth = new AnonymousAuthenticationToken(UUID.randomUUID().toString(),
                req.getUserPrincipal(), grantedAuthorities);

        SecurityContextHolder.getContext().setAuthentication(auth);
    }

    chain.doFilter(req, resp);
}

From source file:org.opensolaris.opengrok.web.PageConfig.java

/**
 * Cleanup all allocated resources (if any) from the instance attached to
 * the given request./*from   ww  w  . j av a2 s.  com*/
 *
 * @param sr request to check, cleanup. Ignored if {@code null}.
 * @see PageConfig#get(HttpServletRequest)
 */
public static void cleanup(ServletRequest sr) {
    if (sr == null) {
        return;
    }
    PageConfig cfg = (PageConfig) sr.getAttribute(ATTR_NAME);
    if (cfg == null) {
        return;
    }
    sr.removeAttribute(ATTR_NAME);
    cfg.env = null;
    cfg.req = null;
    if (cfg.eftarReader != null) {
        cfg.eftarReader.close();
    }
    ProjectHelper.cleanup();
}

From source file:jp.terasoluna.fw.web.thin.EvidenceLogFilter.java

/**
 * GrfX?O?o?B//from   www . java 2 s.  c  om
 *
 * @param req HTTPNGXg
 * @param res HTTPX|X
 * @param chain tB^`F?[
 * 
 * @throws IOException I/OG?[
 * @throws ServletException T?[ubgO
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    //NGXgtB^?B
    if (req.getAttribute(EVIDENCELOG_THRU_KEY) == null) {

        req.setAttribute(EVIDENCELOG_THRU_KEY, "true");

        evidenceLog("--------------------------------------------");

        // NGXgURI?o
        evidenceLog("RequestURI = " + ((HttpServletRequest) req).getRequestURI());

        // p??[^?o
        evidenceLog("Parameters = {");
        Map paramMap = ((HttpServletRequest) req).getParameterMap();
        Iterator iter = paramMap.keySet().iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            Object value = paramMap.get(key);
            if (value == null) {
                evidenceLog("  " + key + " = null");
            } else if (value.getClass().isArray()) {
                Object[] values = (Object[]) value;
                for (int i = 0; i < values.length; i++) {
                    String valueView = "null";
                    if (values[i] != null) {
                        valueView = values[i].toString();
                    }
                    evidenceLog("  " + key + "[" + i + "] = " + valueView);
                }
            } else {
                evidenceLog("  " + key + " = " + value.toString());
            }
        }
        evidenceLog("}");

        evidenceLog("--------------------------------------------");

    }

    // tB^T?[ubg
    chain.doFilter(req, res);
}

From source file:org.shredzone.commons.view.manager.ViewInvoker.java

/**
 * Evaluates a single parameter of the handler method's parameter list.
 *
 * @param type//from w ww  .j a  v a 2  s . c om
 *            Expected parameter type
 * @param anno
 *            {@link Annotation} of this parameter
 * @param optional
 *            if this parameter is optional and may be {@code null}
 * @param context
 *            {@link ViewContext} containing all necessary data for invoking the view
 * @return Parameter value to be passed to the method
 */
private Object evaluateParameter(Class<?> type, Annotation anno, boolean optional, ViewContext context)
        throws ViewException {

    if (anno instanceof Parameter) {
        String name = ((Parameter) anno).value();
        String value = context.getParameter(name);
        if (value == null && !optional) {
            throw new ViewContextException("Missing parameter " + name);
        }
        return conversionService.convert(value, type);
    }

    if (anno instanceof PathPart) {
        String part = ((PathPart) anno).value();
        String value = context.getPathParts().get(part);
        if (value != null) {
            return conversionService.convert(value, type);
        } else if (optional) {
            return conversionService.convert(null, TypeDescriptor.valueOf(String.class),
                    TypeDescriptor.valueOf(type));
        } else {
            throw new ViewException("Unsatisfied path part: " + part);
        }
    }

    if (anno instanceof Attribute) {
        String name = ((Attribute) anno).value();
        ServletRequest req = context.getValueOfType(ServletRequest.class);
        Object value = req.getAttribute(name);
        if (value == null && !optional) {
            throw new ViewContextException("Missing attribute " + name);
        }
        return conversionService.convert(value, type);
    }

    if (anno instanceof Cookie) {
        String name = ((Cookie) anno).value();
        HttpServletRequest req = context.getValueOfType(HttpServletRequest.class);
        for (javax.servlet.http.Cookie cookie : req.getCookies()) {
            if (name.equals(cookie.getName())) {
                return conversionService.convert(cookie.getValue(), type);
            }
        }
        if (optional) {
            return conversionService.convert(null, TypeDescriptor.valueOf(String.class),
                    TypeDescriptor.valueOf(type));
        } else {
            throw new ViewException("Cookie not set: " + name);
        }
    }

    if (anno instanceof SessionId) {
        HttpSession session = context.getValueOfType(HttpSession.class);
        if (session != null) {
            return conversionService.convert(session.getId(), type);
        } else {
            return conversionService.convert(null, TypeDescriptor.valueOf(String.class),
                    TypeDescriptor.valueOf(type));
        }
    }

    if (anno instanceof Qualifier) {
        // Qualifiers are always optional
        return conversionService.convert(context.getQualifier(), type);
    }

    // Finally, try to get an object of that type from the data provider
    try {
        return context.getValueOfType(type);
    } catch (ViewContextException ex) {
        // ignore and continue...
    }

    // Who the heck would need this...
    if (ViewContext.class.isAssignableFrom(type)) {
        return context;
    }

    // Alas, we cannot find anything to satisfy this parameter
    throw new ViewContextException("Unknown parameter type " + type.getName());
}

From source file:gov.nih.nci.rembrandt.web.taglib.KaplanMeierPlotTag.java

public int doStartTag() {

    ServletRequest request = pageContext.getRequest();
    HttpSession session = pageContext.getSession();
    Object o = request.getAttribute(beanName);
    JspWriter out = pageContext.getOut();
    ServletResponse response = pageContext.getResponse();
    String dataName;//from w  w w  . j  ava 2  s  .c om
    try {
        dataName = BeanUtils.getSimpleProperty(o, datasetName);
        KaplanMeierStoredData cacheData = (KaplanMeierStoredData) presentationTierCache
                .getSessionGraphingData(session.getId(), dataName);
        JFreeChart chart = CaIntegratorChartFactory
                .getKaplanMeierGraph(cacheData.getPlotPointSeriesCollection());

        RembrandtImageFileHandler imageHandler = new RembrandtImageFileHandler(session.getId(), "png", 700,
                500);
        //The final complete path to be used by the webapplication
        String finalPath = imageHandler.getSessionTempFolder();
        /**
         * Create the actual chart, writing it to the session temp folder
         */
        ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 700, 500);
        /*
         *   This is here to put the thread into a loop while it waits for the
         *   image to be available.  It has an unsophisticated timer but at 
         *   least it is something to avoid an endless loop.
         *  
         */
        boolean imageReady = false;
        int timeout = 1000;
        FileInputStream inputStream = null;
        while (!imageReady) {
            timeout--;
            try {
                inputStream = new FileInputStream(finalPath);
                inputStream.available();
                imageReady = true;
                inputStream.close();
            } catch (IOException ioe) {
                imageReady = false;
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            if (timeout <= 1) {

                break;
            }
        }
        out.print(imageHandler.getImageTag());
        out.print(createLegend(cacheData));
    } catch (IllegalAccessException e1) {
        logger.error(e1);
    } catch (InvocationTargetException e1) {
        logger.error(e1);
    } catch (NoSuchMethodException e1) {
        logger.error(e1);
    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        logger.error(e);
    } catch (Throwable t) {
        logger.error(t);
    }

    return EVAL_BODY_INCLUDE;
}