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:org.xwiki.portlet.controller.DispatchFilter.java

/**
 * {@inheritDoc}//from ww w  .j  a va  2  s  .co  m
 * 
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest
            && !Boolean.valueOf((String) request.getAttribute(ATTRIBUTE_APPLIED))) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        RequestType requestType = (RequestType) request.getAttribute(DispatchPortlet.ATTRIBUTE_REQUEST_TYPE);
        if (requestType != null) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            // Prevent nested calls to this filter.
            request.setAttribute(ATTRIBUTE_APPLIED, "true");
            switch (requestType) {
            case ACTION:
                doAction(httpRequest, httpResponse, chain);
                break;
            case RENDER:
                doRender(httpRequest, httpResponse, chain);
                break;
            case RESOURCE:
                doResource(httpRequest, httpResponse, chain);
                break;
            default:
                // We should never get here.
                break;
            }
            // Allow multiple calls to this filter, as long as they are not nested. We need this because we
            // transform redirects into dispatches and thus a request can be dispatched multiple times, but these
            // dispatches shouldn't be nested.
            request.removeAttribute(ATTRIBUTE_APPLIED);
            return;
        }
    }
    chain.doFilter(request, response);
}

From source file:org.jahia.bundles.extender.jahiamodules.JspServletWrapper.java

@Override
public void service(final ServletRequest req, final ServletResponse res) throws ServletException, IOException {
    String jspPath = getJspFilePath(req);
    if (jspPath != null) {
        req.setAttribute(Constants.JSP_FILE, jspPath);
    }/*w  w  w. j a  v a 2  s . c o  m*/

    Object currentLocaleResolver = req.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
    req.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new LocaleResolver() {

        @Override
        public Locale resolveLocale(HttpServletRequest request) {
            HttpSession session = request.getSession();
            if (session != null) {
                Locale currentLocale = (Locale) session.getAttribute(org.jahia.api.Constants.SESSION_LOCALE);
                if (currentLocale != null) {
                    return currentLocale;
                }
            }
            return request.getLocale();
        }

        @Override
        public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        }
    });

    // Prepare attributes for subsequent includes
    String p = (String) req.getAttribute("javax.servlet.include.servlet_path")
            + (String) req.getAttribute("javax.servlet.include.path_info");
    req.setAttribute("javax.servlet.include.path_info", null);
    req.setAttribute("javax.servlet.include.servlet_path", p);

    try {
        ContextClassLoaderUtils.doWithClassLoader(urlClassLoader, new Callable<Void>() {
            public Void call() throws Exception {
                jspServlet.service(req, res);
                return null;
            }
        });
    } catch (Exception e) {
        throw new ServletException("Error during servlet servicing", e);
    }
    req.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, currentLocaleResolver);
}

From source file:no.kantega.publishing.admin.content.InputScreenRenderer.java

/**
 * Lager inputskjermbilde ved  g gjennom alle attributter
 *//*w w  w  .  j a va  2s .c o  m*/
public void generateInputScreen() throws IOException, SystemException, ServletException {
    JspWriter out = pageContext.getOut();
    ServletRequest request = pageContext.getRequest();

    Map<String, List<ValidationError>> fieldErrors = new HashMap<>();
    ValidationErrors errors = (ValidationErrors) request.getAttribute("errors");
    if (errors != null) {
        for (ValidationError error : errors.getErrors()) {
            if (error.getField() != null && error.getField().length() > 0) {
                List<ValidationError> errorsForField = fieldErrors.get(error.getField());
                if (errorsForField == null) {
                    errorsForField = new ArrayList<>();
                    fieldErrors.put(error.getField(), errorsForField);
                }
                errorsForField.add(error);
            }
        }
    }

    ContentTemplate template = null;
    if (attributeType == AttributeDataType.CONTENT_DATA) {
        template = contentTemplateAO.getTemplateById(content.getContentTemplateId(), true);
    } else if (attributeType == AttributeDataType.META_DATA && content.getMetaDataTemplateId() > 0) {
        template = MetadataTemplateCache.getTemplateById(content.getContentTemplateId(), true);
    }

    String globalHelpText = null;
    if (template != null) {
        globalHelpText = template.getHelptext();
    }

    if (globalHelpText != null && globalHelpText.length() > 0) {
        out.print(
                "<div id=\"TemplateGlobalHelpText\" class=\"ui-state-highlight\">" + globalHelpText + "</div>");
    }

    request.setAttribute("content", content);

    int tabIndex = 100; // Tab index for attribute
    List<Attribute> attributes = content.getAttributes(attributeType);
    for (Attribute attribute : attributes) {
        tabIndex = renderAttribute(out, request, fieldErrors, attribute, tabIndex);
    }
    request.setAttribute("maxTabindex", Math.max(tabIndex, 500));
}

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

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

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    // retrieve userId and project instance from previous filters in chain
    String userId = (String) request.getAttribute(Consts.ATTRIBUTE_USERID);
    Project project = (Project) request.getAttribute(Consts.ATTRIBUTE_PROJECT);
    boolean isAnonymousUser = BooleanUtils
            .toBoolean((Boolean) request.getAttribute(Consts.ATTRIBUTE_ANONYMOUS_USER));
    boolean isProjectAdmin = BooleanUtils
            .toBoolean((Boolean) request.getAttribute(Consts.ATTRIBUTE_PROJECTADMIN));

    String servletPath = httpRequest.getServletPath();
    String pathInfo = httpRequest.getPathInfo();

    if (servletPath.startsWith(Consts.URL_PROJECTS)) {
        // handle access to project detail page
        if (project != null && !Permits.hasProjectPermit(Permit.ALLOW, Permit.ACTION_GET, project)) {
            AccessControlException e = new AccessControlException(MessageFormat.format(
                    "User ''{0}'' is not authorized to view project ''{1}''", userId, project.getProjectId()));
            FilterUtil.handleACException(httpRequest, response, e);
            return;
        }/*from   w  w w.  j a  v a  2  s. c  o m*/
        // handle URL starting with /projects
        String actionValue = request.getParameter(Consts.PARAM_ACTION);
        if (project != null && Consts.PARAM_VALUE_EDIT.equals(actionValue)) {
            // handle /projects/{projectId}?action=edit
            if (!isProjectAdmin) {
                AccessControlException e = new AccessControlException(
                        MessageFormat.format("User ''{0}'' is not authorized to edit project ''{1}''", userId,
                                project.getProjectId()));
                FilterUtil.handleACException(httpRequest, response, e);
                return;
            }
        } else if (project == null && StringUtils.isNotBlank(pathInfo)) {
            // handle /projects/{projectId} with unknown projectId => project creation dialog
            if (isAnonymousUser) {
                AccessControlException e = new AccessControlException(
                        "Anonymous users are not authorized to create new projects");
                FilterUtil.handleACException(httpRequest, response, e);
                return;
            }
        }
    } else {
        // handle all other URLs not starting with /projects
        if (isAnonymousUser) {
            AccessControlException e = new AccessControlException(
                    "Anonymous users are not authorized to view this page");
            FilterUtil.handleACException(request, response, e);
            return;
        }
        if (StringUtils.isNotBlank(pathInfo)) {
            if (project == null) {
                FilterException e = new FilterException(MessageFormat
                        .format("No project instance available although servlet path is {0}.", servletPath));
                FilterUtil.handleException(request, response, e);
                return;
            } else if (!isProjectAdmin) {
                AccessControlException e = new AccessControlException(
                        "User is not authorized to view this page");
                FilterUtil.handleACException(request, response, e);
                return;
            }
        }
    }

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

From source file:org.springframework.security.web.FilterChainProxy.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean clearContext = request.getAttribute(FILTER_APPLIED) == null;
    if (clearContext) {
        try {/*from w  w w  .j ava2 s  .c  o  m*/
            request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
            doFilterInternal(request, response, chain);
        } finally {
            SecurityContextHolder.clearContext();
            request.removeAttribute(FILTER_APPLIED);
        }
    } else {
        doFilterInternal(request, response, chain);
    }
}

From source file:org.commoncrawl.service.listcrawler.MultiPartFilter.java

private void deleteFiles(ServletRequest request) {
    ArrayList files = (ArrayList) request.getAttribute(FILES);
    if (files != null) {
        Iterator iter = files.iterator();
        while (iter.hasNext()) {
            UploadFileData file = (UploadFileData) iter.next();
            try {
                // file.incomingFile.delete();
            } catch (Exception e) {
                _context.log("failed to delete " + file.incomingFile, e);
            }//from  w  ww .  j  ava 2s.c o m
        }
    }
}

From source file:org.zkoss.zkgrails.ZKGrailsPageFilter.java

public void doFilter(ServletRequest rq, ServletResponse rs, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) rq;

    // System.out.println(">>> " + extractRequestPath(request));

    if (rq.getAttribute(FILTER_APPLIED) != null || factory.isPathExcluded(extractRequestPath(request))
            || isZK(request)) {/*from   w w  w  .  j a  v  a  2s . c  o m*/
        // ensure that filter is only applied once per request
        chain.doFilter(rq, rs);
    } else {
        request.setAttribute(FILTER_APPLIED, Boolean.TRUE);

        factory.refresh();
        DecoratorMapper decoratorMapper = factory.getDecoratorMapper();
        HttpServletResponse response = (HttpServletResponse) rs;

        // parse data into Page object (or continue as normal if Page not parseable)
        Page page = parsePage(request, response, chain);

        if (page != null) {
            page.setRequest(request);

            Decorator decorator = decoratorMapper.getDecorator(request, page);
            if (decorator != null && decorator.getPage() != null) {
                applyDecorator(page, decorator, request, response);
                return;
            }
            // if we got here, an exception occured or the decorator was null,
            // what we don't want is an exception printed to the user, so
            // we write the original page
            writeOriginal(request, response, page);
        }
    }
}

From source file:org.apache.catalina.valves.ErrorReportValve.java

/**
 * Invoke the next Valve in the sequence. When the invoke returns, check
 * the response state, and output an error report is necessary.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 * @param context The valve context used to invoke the next valve
 *  in the current processing pipeline// ww w  .j a va 2s.co  m
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response, ValveContext context)
        throws IOException, ServletException {

    // Perform the request
    context.invokeNext(request, response);

    ServletRequest sreq = (ServletRequest) request;
    Throwable throwable = (Throwable) sreq.getAttribute(Globals.EXCEPTION_ATTR);

    ServletResponse sresp = (ServletResponse) response;
    if (sresp.isCommitted()) {
        return;
    }

    if (throwable != null) {

        // The response is an error
        response.setError();

        // Reset the response (if possible)
        try {
            sresp.reset();
        } catch (IllegalStateException e) {
            ;
        }

        ServletResponse sresponse = (ServletResponse) response;
        if (sresponse instanceof HttpServletResponse)
            ((HttpServletResponse) sresponse).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    }

    response.setSuspended(false);

    try {
        report(request, response, throwable);
    } catch (Throwable tt) {
        tt.printStackTrace();
    }

}

From source file:org.springframework.http.server.reactive.ServletHttpHandlerAdapter.java

@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    if (DispatcherType.ASYNC.equals(request.getDispatcherType())) {
        Throwable ex = (Throwable) request.getAttribute(WRITE_ERROR_ATTRIBUTE_NAME);
        throw new ServletException("Write publisher error", ex);
    }//w  w  w . java 2 s .  co m

    // Start async before Read/WriteListener registration
    AsyncContext asyncContext = request.startAsync();
    asyncContext.setTimeout(-1);

    ServerHttpRequest httpRequest = createRequest(((HttpServletRequest) request), asyncContext);
    ServerHttpResponse httpResponse = createResponse(((HttpServletResponse) response), asyncContext);

    if (HttpMethod.HEAD.equals(httpRequest.getMethod())) {
        httpResponse = new HttpHeadResponseDecorator(httpResponse);
    }

    AtomicBoolean isCompleted = new AtomicBoolean();
    HandlerResultAsyncListener listener = new HandlerResultAsyncListener(isCompleted);
    asyncContext.addListener(listener);

    HandlerResultSubscriber subscriber = new HandlerResultSubscriber(asyncContext, isCompleted);
    this.httpHandler.handle(httpRequest, httpResponse).subscribe(subscriber);
}

From source file:org.jahia.bin.errors.ErrorLoggingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    Boolean alreadyForwarded = (Boolean) request.getAttribute("org.jahia.exception.forwarded");
    if (alreadyForwarded == null || !alreadyForwarded.booleanValue()) {
        handle((HttpServletRequest) request, (HttpServletResponse) response);
    }//from  w  w  w. j a  v a2  s .  co  m
    filterChain.doFilter(request, response);
}