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:com.zaizi.alfresco.crowd.sso.filter.CrowdSSOAuthenticationFilter.java

/**
 * <p>Checks if the request has been marked as no authentication needed by a previous filter</p>
 * @param servletRequest The request//from ww w.  ja v a2  s .  com
 * @param servletResponse The response
 * @param chain The filter chain
 * @return a boolean indicating if the request needs authentication or not
 * 
 * @throws IOException
 * @throws ServletException
 */
private boolean isRequestMarkedAsNoAuthenticationNeeded(ServletRequest servletRequest,
        ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    if (servletRequest.getAttribute(NO_AUTH_REQUIRED) != null) {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Authentication not required (filter), chaining ...");
        }

        chain.doFilter(servletRequest, servletResponse);
        return true;
    }
    return false;
}

From source file:gov.nih.nci.ispy.web.taglib.CorrScatterPlotTag.java

public int doStartTag() {
    chart = null;/*  w w  w . j a  v  a  2s  .c om*/
    plotPoints.clear();

    ServletRequest request = pageContext.getRequest();
    HttpSession session = pageContext.getSession();
    Object o = request.getAttribute(beanName);
    JspWriter out = pageContext.getOut();
    ServletResponse response = pageContext.getResponse();

    try {
        //retrieve the Finding from cache and build the list of PCAData points
        ISPYCorrelationFinding corrFinding = (ISPYCorrelationFinding) businessTierCache
                .getSessionFinding(session.getId(), taskId);

        Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>();
        List<String> sampleIds = new ArrayList<String>();

        List<DataPoint> points = corrFinding.getDataPoints();

        ClinicalDataService cqs = ClinicalDataServiceFactory.getInstance();
        IdMapperFileBasedService idMapper = IdMapperFileBasedService.getInstance();

        List<ISPYPlotPoint> plotPoints = new ArrayList<ISPYPlotPoint>();
        ISPYPlotPoint pp;
        SampleInfo si;
        ISPYclinicalDataQueryDTO dto;
        Set<String> sampleHolder = new HashSet<String>(); //set just holds one entry need this for the dto
        Set<PatientData> dataHolder = new HashSet<PatientData>();
        PatientData pd = null;
        for (DataPoint p : points) {
            pp = new ISPYPlotPoint(p.getId());
            pp.setX(p.getX());
            pp.setY(p.getY());
            pp.setZ(p.getZ());

            String patientId = null;

            if (corrFinding.isSampleBased()) {
                si = idMapper.getSampleInfoForLabtrackId(p.getId());
                if (si != null) {
                    pp.setSampleInfo(si);
                    patientId = si.getISPYId();
                } else {
                    logger.warn("Could not get sample info for DataPoint=" + p.getId());
                }
            } else if (corrFinding.isPatientBased()) {
                patientId = p.getId();
            }

            if (patientId != null) {
                dto = new ISPYclinicalDataQueryDTO();
                sampleHolder.clear();
                sampleHolder.add(patientId);
                dto.setRestrainingSamples(sampleHolder);
                dataHolder.clear();
                dataHolder = cqs.getClinicalData(dto);

                if (dataHolder.size() == 1) {
                    Iterator i = dataHolder.iterator();
                    pd = (PatientData) i.next();
                    pp.setPatientData(pd);
                } else {
                    logger.error("Internal Error. Did not get back correct patient data for  patientId="
                            + patientId);
                }
            }

            plotPoints.add(pp);
        }

        ISPYCorrelationScatterPlot plot = new ISPYCorrelationScatterPlot(plotPoints,
                corrFinding.getGroup1Name(), corrFinding.getGroup2Name(), corrFinding.getContinuousType1(),
                corrFinding.getContinuousType2(), corrFinding.getCorrelationValue(),
                ColorByType.valueOf(ColorByType.class, colorBy.toUpperCase()));
        chart = plot.getChart();
        ISPYImageFileHandler imageHandler = new ISPYImageFileHandler(session.getId(), "png", 650, 600);
        //The final complete path to be used by the webapplication
        String finalPath = imageHandler.getSessionTempFolder();
        String finalURLpath = imageHandler.getFinalURLPath();
        /*
         * Create the actual charts, writing it to the session temp folder
        */
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        String mapName = imageHandler.createUniqueMapName();
        //PrintWriter writer = new PrintWriter(new FileWriter(mapName));
        ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 650, 600, info);
        //ImageMapUtil.writeBoundingRectImageMap(writer,"PCAimageMap",info,true);
        //writer.close();

        /*   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(ImageMapUtil.getBoundingRectImageMapTag(mapName, true, info));
        finalURLpath = finalURLpath.replace("\\", "/");
        long randomness = System.currentTimeMillis(); //prevent image caching
        out.print("<img id=\"geneChart\" name=\"geneChart\" src=\"" + finalURLpath + "?" + randomness
                + "\" usemap=\"#" + mapName + "\" border=\"0\" />");

        //(imageHandler.getImageTag(mapFileName));

    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        logger.error(sw.toString());
    } catch (Throwable t) {
        logger.error(t);
    }

    return EVAL_BODY_INCLUDE;
}

From source file:it.cnr.icar.eric.client.ui.thin.security.SecurityUtil.java

public Set<Object> getX509CertFromRequest() {
    Set<Object> x509CertSet = null;
    ServletRequest request = (ServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();//from  w  ww .  j av a2 s. co m
    Object certObj = request.getAttribute("javax.servlet.request.X509Certificate");

    if (certObj != null) {
        try {
            java.security.cert.Certificate[] certs = (java.security.cert.Certificate[]) certObj;
            X509Certificate x509Cert = (X509Certificate) certs[0];
            x509CertSet = new HashSet<Object>();
            x509CertSet.add(x509Cert);
        } catch (ClassCastException t) {
            log.warn(WebUIResourceBundle.getInstance().getString(
                    "message.TheFollowingCertificateTypeIsNotSupported",
                    new Object[] { certObj.getClass().getName() }));
        }
    }
    return x509CertSet;
}

From source file:de.micromata.genome.gwiki.page.impl.i18n.GWikiI18NServletFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest hreq = (HttpServletRequest) request;
    HttpServletResponse hresp = (HttpServletResponse) response;
    HTTPCTX.set(Pair.make(hreq, hresp));
    initWiki(hreq, hresp);//from   w w  w .  jav  a 2  s  .co  m
    Locale loc = hreq.getLocale();
    Object ploc = request.getAttribute(LOC_KEY);
    if (ploc instanceof Locale) {
        loc = (Locale) ploc;
    }
    LocalizationContext prevLocContext = null;
    Object plc = hreq.getAttribute(LOCALIZATION_KEY);
    if (plc instanceof LocalizationContext) {
        prevLocContext = (LocalizationContext) plc;
    }

    Object prevfml = hreq.getAttribute(LOC_KEY);
    Object prevlocaiz = hreq.getAttribute(LOCALIZATION_KEY);
    try {
        hreq.setAttribute(LOC_KEY, loc);
        hreq.setAttribute(LOCALIZATION_KEY, new LocalizationContext(
                new GWikiI18NCombinedResourceBundle(loc, prevLocContext, modules), loc));

        chain.doFilter(request, response);
    } finally {
        hreq.setAttribute(LOC_KEY, prevfml);
        hreq.setAttribute(LOCALIZATION_KEY, prevlocaiz);
        HTTPCTX.set(null);
    }
}

From source file:org.sakaiproject.nakamura.http.qos.QoSFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean accepted = false;
    QoSToken qoSToken = getQoSControl(request);
    try {//ww w  .j  ava 2s  . c om
        if (request.getAttribute(suspendedAttributeName) == null) {
            accepted = qoSToken.acquire(waitMs);
            if (accepted) {
                request.setAttribute(suspendedAttributeName, Boolean.FALSE);
            } else {
                LOGGER.debug("Suspending request");
                request.setAttribute(suspendedAttributeName, Boolean.TRUE);
                Continuation continuation = ContinuationSupport.getContinuation((HttpServletRequest) request,
                        qoSToken.getMutex());
                continuation.suspend(qoSToken.getSuspendTime());
                qoSToken.queue(continuation);
                return;
            }
        } else {
            Boolean suspended = (Boolean) request.getAttribute(suspendedAttributeName);

            if (suspended.booleanValue()) {
                request.setAttribute(suspendedAttributeName, Boolean.FALSE);
                if (request.getAttribute("javax.servlet.resumed") == Boolean.TRUE) {
                    qoSToken.acquire();
                    accepted = true;
                } else {
                    // Timeout! try 1 more time.
                    accepted = qoSToken.acquire(waitMs);
                }
            } else {
                // pass through resume of previously accepted request
                qoSToken.acquire();
                accepted = true;
            }
        }

        if (accepted) {
            chain.doFilter(request, response);
        } else {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } catch (InterruptedException e) {
        LOGGER.warn("QoS", e);
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } finally {
        if (accepted) {
            qoSToken.release();
        }
    }
}

From source file:org.sonatype.nexus.security.filter.authc.NexusHttpAuthenticationFilter.java

@Override
public void postHandle(ServletRequest request, ServletResponse response) throws Exception {
    if (request.getAttribute(ANONYMOUS_LOGIN) != null) {
        try {/*from www . j ava  2s .co  m*/
            getSubject(request, response).logout();
        } catch (UnknownSessionException e) {
            // we need to prevent log spam, just log this as trace
            this.logger.trace("Failed to find session for anonymous user.", e);
        }
        if (HttpServletRequest.class.isAssignableFrom(request.getClass())) {
            HttpSession session = ((HttpServletRequest) request).getSession(false);

            if (session != null) {
                session.invalidate();
            }
        }
    }

    if (request.getAttribute(NexusJSecurityFilter.REQUEST_IS_AUTHZ_REJECTED) != null) {
        if (request.getAttribute(ANONYMOUS_LOGIN) != null) {
            sendChallenge(request, response);
        } else {

            Subject subject = getSubject(request, response);

            String username = getNexusConfiguration().getAnonymousUsername();

            if (subject != null && subject.isAuthenticated()) {
                username = subject.getPrincipal().toString();
            }

            getLogger().info(
                    "Request processing is rejected because user \"" + username + "\" lacks permissions.");

            sendForbidden(request, response);
        }
    }
}

From source file:com.netspective.sparx.navigate.query.QueryResultsNavigatorPage.java

public void handlePageBody(Writer writer, NavigationContext nc) throws ServletException, IOException {
    if (!valid) {
        writer.write(invalidMessage);/*from  ww  w . ja v a 2 s.c o m*/
        return;
    }

    final Map templateVars;
    final ServletRequest request = nc.getRequest();
    try {
        final String executionId = getQueryExectionId(nc);
        final boolean refresh = request.getParameter(refreshResultSetParamName) != null
                || request.getAttribute(refreshResultSetParamName) != null;

        QueryResultsNavigatorState queryResults = refresh ? null
                : getQueryResultsNavigatorStatesManager().getActiveUserQueryResults(this, nc, executionId);
        if (queryResults == null) {
            queryResults = constructQueryResults(nc, executionId);
            if (queryResults.getScrollState().isScrollable())
                getQueryResultsNavigatorStatesManager().setActiveUserQueryResults(nc, queryResults);
        }

        final Integer scrollToPageOverride = (Integer) request.getAttribute(activeScrollPageParamName);
        if (scrollToPageOverride != null)
            queryResults.getScrollState().scrollToPage(scrollToPageOverride.intValue());
        else {
            final String scrollToPage = request.getParameter(activeScrollPageParamName);
            if (scrollToPage != null && scrollToPage.length() > 0)
                queryResults.getScrollState().scrollToPage(Integer.parseInt(scrollToPage));
        }

        templateVars = createDefaultResultsBodyTemplateVars(nc, queryResults);
    } catch (NamingException e) {
        throw new NestableRuntimeException(e);
    } catch (SQLException e) {
        throw new NestableRuntimeException(e);
    }

    // handle the body template
    if (templateVars != null)
        getBodyTemplate().process(writer, nc, templateVars);
    else
        writer.write("No active result set found.");
}

From source file:org.forgerock.openidm.filter.AuthFilter.java

private X509Certificate[] getClientCerts(ServletRequest request) {

    Object checkCerts = request.getAttribute("javax.servlet.request.X509Certificate");
    if (checkCerts instanceof X509Certificate[]) {
        return (X509Certificate[]) checkCerts;
    } else {/*from w  w  w  .j av a 2 s .c om*/
        logger.warn("Unknown certificate type retrieved {}", checkCerts);
        return null;
    }
}

From source file:org.eclipse.skalli.view.internal.filter.AbstractSearchFilter.java

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

    // retrieve the logged-in user
    String userId = (String) request.getAttribute(Consts.ATTRIBUTE_USERID);
    User user = (User) request.getAttribute(Consts.ATTRIBUTE_USER);

    // calculate start param
    int start = toInt(request.getParameter(Consts.PARAM_START), 0, -1);
    // calculate count size param
    int count = toInt(request.getParameter(Consts.PARAM_COUNT), 10, 50);

    // retrieve search hits and based on that parent projects and subprojects
    SearchResult<Project> searchResult = getSearchHits(user, request, response, start, count);
    List<SearchHit<Project>> searchHits = searchResult.getResult();
    Map<String, String> natures = getProjectNatures(searchHits);
    Map<String, Project> parents = getParents(searchHits);
    Map<String, List<Project>> parentChains = getParentChains(searchHits);
    Map<String, List<SearchHit<Project>>> subprojects = getSubprojects(searchHits);
    Map<String, List<String>> sourceLinks = getSourceLinks(userId, searchHits);

    // retrieve the favorites of the user
    Favorites favorites = getFavorites(user);

    // calculate params for pager
    int resultSize = searchResult.getResultCount();
    int pages = (int) Math.ceil((double) resultSize / (double) count);
    int currentPage = (int) Math.floor((double) start / (double) count) + 1;
    long duration = searchResult.getDuration();

    // set the request attributes
    request.setAttribute(ATTRIBUTE_TITLE, getTitle(user));
    request.setAttribute(ATTRIBUTE_PROJECTS, searchHits);
    request.setAttribute(ATTRIBUTE_NATURES, natures);
    request.setAttribute(ATTRIBUTE_PARENTS, parents);
    request.setAttribute(ATTRIBUTE_PARENTCHAINS, parentChains);
    request.setAttribute(ATTRIBUTE_SUBPROJETS, subprojects);
    request.setAttribute(ATTRIBUTE_SOURCELINKS, sourceLinks);
    request.setAttribute(Consts.ATTRIBUTE_FAVORITES, favorites.asMap());
    request.setAttribute(ATTRIBUTE_DURATION, duration);
    request.setAttribute(ATTRIBUTE_START, start);
    request.setAttribute(ATTRIBUTE_VIEWSIZE, count);
    request.setAttribute(ATTRIBUTE_RESULTSIZE, resultSize);
    request.setAttribute(ATTRIBUTE_CURRENTPAGE, currentPage);
    request.setAttribute(ATTRIBUTE_PAGES, pages);
    request.setAttribute(Consts.ATTRIBUTE_USER, user);

    if (((HttpServletRequest) request).getPathInfo() == null) {
        request.getRequestDispatcher(Consts.JSP_SEARCHRESULT).forward(request, response);
        return;/*from  www.  j  a  v a 2  s  .  com*/
    }

    // proceed along the chain
    chain.doFilter(request, response);
}

From source file:org.openinfinity.sso.security.spring.InjectableSecurityContextFilterBean.java

/**
 * Filters every request and response objects and verifies that <code>org.springframework.security.core.context.SecurityContext</code> is available. 
 * If not <code>org.openinfinity.core.security.principal.Identity</code> which implements the <code>org.springframework.security.core.Authentication</code> interface will be used for storing information to local <code>org.springframework.security.core.context.SecurityContext</code>.
 */// w  w  w  .ja v  a 2  s  . com
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    LOGGER.debug("Initializing InjectableSecurityContextFilterBean for Spring security.");
    if (SecurityContextHolder.getContext() != null
            && SecurityContextHolder.getContext().getAuthentication() == null) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String sessionId = request.getAttribute(SESSION_IDENTIFIER) != null
                ? (String) request.getAttribute(SESSION_IDENTIFIER)
                : ((httpServletRequest.getHeader(SESSION_IDENTIFIER) != null)
                        ? (String) httpServletRequest.getAttribute(SESSION_IDENTIFIER)
                        : null);
        if (sessionId != null) {
            LOGGER.debug("Session identifier [" + sessionId + "] found from the request.");
            eraseSecurityContext(sessionId);
            injectIdentityBasedSecurityContext(sessionId);
        }
    }
    LOGGER.debug("Finalized injecting authentication in InjectableSecurityContextFilterBean.");
    chain.doFilter(request, response);
}