Example usage for javax.servlet ServletRequest setAttribute

List of usage examples for javax.servlet ServletRequest setAttribute

Introduction

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

Prototype

public void setAttribute(String name, Object o);

Source Link

Document

Stores an attribute in this request.

Usage

From source file:de.innovationgate.wgpublisher.WGPDeployer.java

public synchronized DeployedLayout deployInlineTML(WGTMLModule tmlLib, String inlineName, String code,
        int codeOffset, ServletRequest req) throws DeployerException {

    if (tmlLib == null) {
        throw new DeployerException(
                "Tried to deploy tml module \"null\". Maybe a tml module is not accessible");
    }/*from ww  w.ja v  a2s. c om*/

    DesignReference ref;
    try {
        ref = WGADesignManager.createDesignReference(tmlLib);
    } catch (WGAPIException e1) {
        throw new DeployerException("Error retrieving design reference for " + tmlLib.getDocumentKey(), e1);
    }

    String databaseKey = (String) tmlLib.getDatabase().getDbReference();
    String resourceName = null;
    String mediaKey = null;

    try {
        String codeHash = String.valueOf(code.hashCode());
        String layoutKey = ref.toString() + "///" + codeHash;

        if (tmlLib.isVariant()) {
            layoutKey = layoutKey + "//" + databaseKey;
        }

        DeployedLayout existingLayout = _layoutMappings.get(layoutKey);
        if (existingLayout != null) {
            return existingLayout;
        }

        req.setAttribute(REQATTRIB_TML_DEPLOYED, true);

        mediaKey = tmlLib.getMediaKey().toLowerCase();
        if (_core.isMediaKeyDefined(mediaKey) == false) {
            _core.addMediaMapping(new MediaKey(mediaKey, "text/html", false, false), false);
        }

        String completeCode = buildTMLCode(tmlLib,
                "Inline " + inlineName + " of " + tmlLib.getName() + " (" + tmlLib.getMediaKey() + ")",
                layoutKey, code);

        resourceName = tmlLib.getName().toLowerCase();
        LOG.debug("Deploying inline " + inlineName + " of tml " + mediaKey + "/" + resourceName + " ("
                + ref.getDesignProviderReference().toString() + ")");
        return mapAndDeployLayout(tmlLib, layoutKey, completeCode);
    } catch (Exception e) {
        throw new DeployerException(
                "Error deploying tml " + databaseKey + "/" + resourceName + " (" + mediaKey + ")", e);
    }

}

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

/**
 * Lager inputskjermbilde ved  g gjennom alle attributter
 *//* w  ww.ja va2  s  .  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.seasar.s2click.filter.UrlPatternFilter.java

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

    HttpServletRequest req = HttpServletRequest.class.cast(request);

    String requestUri = req.getRequestURI();
    String context = req.getContextPath();
    String queryString = req.getQueryString();

    String requestPath = requestUri.substring(context.length());
    if (StringUtils.isNotEmpty(queryString)) {
        requestPath = requestPath + "?" + queryString;
    }//from   ww w. j a  va 2 s .  c  o m
    if (logger.isDebugEnabled()) {
        logger.debug("UrlRewriteFilter???");
        logger.debug("" + requestPath);
    }

    // ?????????
    if (excludePattern != null) {
        Matcher matcher = excludePattern.matcher(requestPath);
        if (matcher.matches()) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "?????UrlRewriteFilter?????");
            }
            chain.doFilter(request, response);
            return;
        }
    }

    // HOT deploy??????ClickApp??
    S2Container container = SingletonS2ContainerFactory.getContainer();

    if (SmartDeployUtil.isHotdeployMode(container) && request.getAttribute(HOTDEPLOY_INIT_KEY) == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("UrlRewriteFilter?Click??????");
        }

        request.setAttribute(HOTDEPLOY_INIT_KEY, "initialize");
        RequestDispatcher dispatcher = request.getRequestDispatcher("/init.htm");
        dispatcher.include(request, response);
    }

    for (UrlRewriteInfo info : UrlPatternManager.getAll()) {
        Matcher matcher = info.pattern.matcher(requestPath);
        if (matcher.matches()) {
            StringBuilder realPath = new StringBuilder();
            realPath.append(info.realPath);
            for (int i = 0; i < info.parameters.length; i++) {
                if (i == 0) {
                    realPath.append("?");
                } else {
                    realPath.append("&");
                }
                realPath.append(info.parameters[i]);
                realPath.append("=");
                realPath.append(matcher.group(i + 1));
            }

            if (logger.isDebugEnabled()) {
                logger.debug(realPath.toString() + "????");
            }

            RequestDispatcher dispatcher = request.getRequestDispatcher(realPath.toString());
            dispatcher.forward(request, response);
            return;
        }
    }

    chain.doFilter(request, response);
}

From source file:com.bsb.cms.commons.page.filter.PageFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest hRequest = (HttpServletRequest) request;
    String uri = hRequest.getRequestURL().toString();
    if (uri.toLowerCase().endsWith(".jsp")) {
        chain.doFilter(request, response);
        return;//from w  w w. j  a  va  2  s . c om
    }
    /*  if (!(uri.toLowerCase().endsWith("list.htm"))) {//TODO
      //if (!(uri.toLowerCase().contains("list"))) {//TODO
        PageContext.removeContext();
        chain.doFilter(request, response);
        return;
      }*/
    if (!(uri.equals(PageContext.getLastUrl())))
        PageContext.removeContext();

    String pagec = hRequest.getParameter("page");//?
    //String pageSize = hRequest.getParameter("pageSize");//??
    String pageSize = hRequest.getParameter("rows");//??. easyui

    String sortField = hRequest.getParameter("sort");//sortField
    String order = hRequest.getParameter("order");//desc/asc

    pageSize = (StringUtils.isEmpty(pageSize)) ? "10" : pageSize;
    PageContext.setLastUrl(uri);
    PageContext page = PageContext.getContext();//-----------

    if (pagec == null)
        page.setCurrentPage(1);
    else
        page.setCurrentPage(Integer.parseInt(pagec));

    page.setPageSize(Integer.parseInt(pageSize));
    page.setPagination(true);

    if ("DESC".equalsIgnoreCase(order)) {
        page.setSortDESC(true);
    } else if ("ASC".equalsIgnoreCase(order)) {
        page.setSortDESC(false);
    }
    if ((sortField != null) && (!("".equals(sortField))))
        PageContext.initSort(sortField);

    request.setAttribute("page", page);//-----------------
    chain.doFilter(request, response);

}

From source file:org.jasig.ssp.security.uportal.KeepSessionAliveFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    boolean overrideInterval = isIntervalOverridden(request);
    if (!(overrideInterval) && interval < 0) {
        chain.doFilter(request, response);
        return;/*w  w  w  . ja  v  a 2 s .c o m*/
    }

    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    final HttpSession session = httpServletRequest.getSession(false);
    if (session == null) {
        chain.doFilter(request, response);
        return;
    }

    Long lastUpdate = (Long) session.getAttribute(SESSION_KEEP_ALIVE_ATTRIBUTE_KEY);
    if (overrideInterval || lastUpdate != null) {
        if (overrideInterval || ((System.currentTimeMillis() - lastUpdate.longValue()) >= interval)) {
            final CrossContextRestApiInvoker rest = new SimpleCrossContextRestApiInvoker();
            //ensures request is GET going into REST Invoker
            HttpServletGetRequestWrapper wrap = new HttpServletGetRequestWrapper(httpServletRequest);
            final Object origWebAsyncManager = wrap.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE);
            request.removeAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE);
            try {
                final Map<String, String[]> params = new HashMap<String, String[]>();
                final RestResponse rr = rest.invoke(wrap, httpServletResponse, "/ssp-platform/api/session.json",
                        params);
                session.setAttribute(SESSION_KEEP_ALIVE_ATTRIBUTE_KEY, System.currentTimeMillis());
            } finally {
                request.setAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, origWebAsyncManager);
            }
        }
    } else {
        session.setAttribute(SESSION_KEEP_ALIVE_ATTRIBUTE_KEY, System.currentTimeMillis());

    }

    chain.doFilter(request, response);
}

From source file:password.pwm.http.filter.RequestInitializationFilter.java

public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
        final FilterChain filterChain) throws IOException, ServletException {

    final HttpServletRequest req = (HttpServletRequest) servletRequest;
    final HttpServletResponse resp = (HttpServletResponse) servletResponse;
    final PwmApplicationMode mode = PwmApplicationMode.determineMode(req);
    final PwmURL pwmURL = new PwmURL(req);

    PwmApplication testPwmApplicationLoad = null;
    try {//from www .j  av  a  2  s.com
        testPwmApplicationLoad = ContextManager.getPwmApplication(req);
    } catch (PwmException e) {
    }

    if (testPwmApplicationLoad == null && pwmURL.isResourceURL()) {
        filterChain.doFilter(req, resp);
    } else if (pwmURL.isStandaloneWebService() || pwmURL.isJerseyWebService()) {
        filterChain.doFilter(req, resp);
    } else {
        if (mode == PwmApplicationMode.ERROR) {
            try {
                final ContextManager contextManager = ContextManager.getContextManager(req.getServletContext());
                if (contextManager != null) {
                    final ErrorInformation startupError = contextManager.getStartupErrorInformation();
                    servletRequest.setAttribute(PwmRequestAttribute.PwmErrorInfo.toString(), startupError);
                }
            } catch (Exception e) {
                if (pwmURL.isResourceURL()) {
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }

                LOGGER.error("error while trying to detect application status: " + e.getMessage());
            }

            LOGGER.error("unable to satisfy incoming request, application is not available");
            resp.setStatus(500);
            final String url = JspUrl.APP_UNAVAILABLE.getPath();
            servletRequest.getServletContext().getRequestDispatcher(url).forward(servletRequest,
                    servletResponse);
        } else {
            initializeServletRequest(req, resp, filterChain);
        }
    }
}

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;/*  w w w. j  a  v a  2  s .  c o m*/
    }

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

From source file:pt.ist.bennu.core.presentationTier.servlets.filters.FunctionalityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    FunctionalityInfo functionality = null;
    List<SemanticComponent> linkComponents = null;
    String link = null;//from  w w  w .j  a v a 2s . c o  m

    if (!checkedConsistency) {
        checkConsistency();
        checkedConsistency = true;
    }

    if (!checkedConsistency) {
        checkConsistency();
        checkedConsistency = true;
    }

    if (isSemanticURL((HttpServletRequest) request)) {
        final String url = getSemanticURL((HttpServletRequest) request);
        linkComponents = obtainSemanticComponent(url);
        if (linkComponents != null) {
            if (!verifyAccessControl(linkComponents, (HttpServletRequest) request,
                    (HttpServletResponse) response)) {
                return;
            }
            SemanticComponent lastPart = linkComponents.get(linkComponents.size() - 1);
            link = lastPart.getPath() + lastPart.getMethodAlias();
        }
        functionality = relativeMapping.get(link);
    }
    if (functionality != null && linkComponents != null) {
        final StringBuilder stringBuilder = new StringBuilder();
        for (SemanticComponent part : linkComponents) {
            if (stringBuilder.length() > 0) {
                stringBuilder.append(Context.PATH_PART_SEPERATOR);
            }
            stringBuilder.append(part.getMatchingNode().asString());
            request.setAttribute(ContextBaseAction.CONTEXT_PATH, stringBuilder.toString());
        }
        dispatchTo(request, response, functionality.getPath() + ".do?method=" + functionality.getMethod());
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:com.microsoft.aad.adal4jsample.BasicFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        try {//www  .  j  a  v  a2  s .co  m
            String currentUri = httpRequest.getRequestURL().toString();
            String queryStr = httpRequest.getQueryString();
            String fullUrl = currentUri + (queryStr != null ? "?" + queryStr : "");

            // check if user has a AuthData in the session
            if (!AuthHelper.isAuthenticated(httpRequest)) {
                if (AuthHelper.containsAuthenticationData(httpRequest)) {
                    processAuthenticationData(httpRequest, currentUri, fullUrl);
                } else {
                    // not authenticated
                    sendAuthRedirect(httpRequest, httpResponse);
                    return;
                }
            }
            if (isAuthDataExpired(httpRequest)) {
                updateAuthDataUsingRefreshToken(httpRequest);
            }
        } catch (AuthenticationException authException) {
            // something went wrong (like expiration or revocation of token)
            // we should invalidate AuthData stored in session and redirect to Authorization server
            removePrincipalFromSession(httpRequest);
            sendAuthRedirect(httpRequest, httpResponse);
            return;
        } catch (Throwable exc) {
            httpResponse.setStatus(500);
            request.setAttribute("error", exc.getMessage());
            request.getRequestDispatcher("/error.jsp").forward(request, response);
        }
    }
    chain.doFilter(request, response);
}

From source file:org.mortbay.servlet.LLabsMultiPartFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *///w ww.  j  av a 2  s.  c om
@SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    logger.info("Received uploadRequest:" + request);
    if (Log.isDebugEnabled())
        Log.debug(getClass().getName() + ">>> Received Request");

    HttpServletRequest srequest = (HttpServletRequest) request;
    if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) {
        chain.doFilter(request, response);
        return;
    }
    if (ServletFileUpload.isMultipartContent(srequest)) {
        // Parse the request

        List<File> tempFiles = new ArrayList<File>();
        try {

            MultiMap params = new MultiMap();

            logger.info("Parsing Request");

            List<DiskFileItem> fileItems = uploadHandler.parseRequest(srequest);

            logger.info("Done Parsing Request, got FileItems:" + fileItems);

            StringBuilder filenames = new StringBuilder();

            for (final DiskFileItem diskFileItem : fileItems) {
                if (diskFileItem.getName() == null && diskFileItem.getFieldName() != null
                        && diskFileItem.getFieldName().length() > 0) {
                    params.put(diskFileItem.getFieldName(), diskFileItem.getString());
                    continue;
                }
                if (diskFileItem.getName() == null)
                    continue;
                final File tempFile = File.createTempFile("upload" + diskFileItem.getName(), ".tmp");
                tempFiles.add(tempFile);

                diskFileItem.write(tempFile);
                request.setAttribute(diskFileItem.getName(), tempFile);
                filenames.append(diskFileItem.getName()).append(",");
            }
            params.put("Filenames", filenames.toString());
            logger.info("passing on filter");
            chain.doFilter(new Wrapper(srequest, params), response);

            for (final DiskFileItem diskFileItem : fileItems) {
                diskFileItem.delete();
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            Log.warn(getClass().getName() + "MPartRequest, ERROR:" + e.getMessage());
            logger.error("FileUpload Failed", e);
            writeResponse((HttpServletResponse) response, HttpServletResponse.SC_EXPECTATION_FAILED);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            Log.warn(getClass().getName() + "MPartRequest, ERROR:" + e.getMessage());
            e.printStackTrace();
            writeResponse((HttpServletResponse) response, HttpServletResponse.SC_EXPECTATION_FAILED);
        } finally {
            for (File tempFile : tempFiles) {
                try {
                    tempFile.delete();
                } catch (Throwable t) {
                }
            }
        }
    }

}