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.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;
    }//www.j  a v a  2  s .c om
    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.pagecrumb.proxy.ProxyFilter.java

/**
 * TODO Add hander for null baseURL //from  w w w . j  a  v a  2s.  c  o  m
 * @param ServletRequest servletrequest - request from client
 * @param ervletResponse servletresponse - response from server
 */
@Override
public void doFilter(ServletRequest servletrequest, final ServletResponse servletresponse, FilterChain chain)
        throws IOException, ServletException {
    log.info("Before invoking chain");
    try {
        String baseURL = ((HttpServletRequest) servletrequest).getQueryString();
        if (baseURL != null) {
            log.info(this.getClass().toString() + " " + "Requested URL: " + baseURL);

            // TODO Must not pass request to .css or .ico etc. to the GenericResponseWrapper
            // Must use regex here, every thing that ends with ".*" must not be passed except

            //if (baseURL.matches(".*?\\.css.*")) {
            //   GenericResponseWrapper responseWrapper 
            //      = new GenericResponseWrapper((HttpServletResponse) servletresponse, baseURL, "css");   
            //   chain.doFilter(servletrequest, responseWrapper);
            //}
            if (baseURL.matches(".*?\\.png.*") || baseURL.matches(".*?\\.ico.*")
                    || baseURL.matches(".*?\\.gif.*") || baseURL.matches(".*?\\.jpeg.*")
                    || baseURL.matches(".*?\\.jpg.*") || baseURL.matches(".*?\\.js.*")) { // Do not process Javascript for now 
                // Pass the wrapper on to the next filter or servlet
                log.info("Bypassing Parser - Just do Filter");
                chain.doFilter(servletrequest, servletresponse);
            } else {
                String gwtModuleBase = (String) servletrequest.getAttribute("X-GWT-Module-Base");
                log.info("Module-Base: " + gwtModuleBase);
                GenericResponseWrapper responseWrapper = new GenericResponseWrapper(
                        (HttpServletResponse) servletresponse, baseURL);
                chain.doFilter(servletrequest, responseWrapper);
                log.info("Content type was " + responseWrapper.getContentType());
            }
        } else {
            PrintWriter pw = servletresponse.getWriter();
            pw.println("<html><body><p>Oops, query URL is missing.</p></body></html>");
        }
    } catch (ServletException e) {
        log.error("Caught Servlet Exception");
        Throwable rootCause = e.getRootCause();
        log.error("Root cause is " + rootCause.toString());
        if (rootCause instanceof RuntimeException) { // This is true for any FacesException.
            log.error("Rethrowing exception as RuntimeException" + rootCause.toString());
            throw (RuntimeException) rootCause; // Throw wrapped RuntimeException instead of ServletException.
        } else {
            throw e;
        }
    }
    log.info("After invoking chain");
}

From source file:org.b3log.solo.filter.PageCacheFilter.java

/**
 * Try to write response from cache./*w  w w .  j a v a2s .co  m*/
 *
 * @param request the specified request
 * @param response the specified response
 * @param chain filter chain
 * @throws IOException io exception
 * @throws ServletException servlet exception
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    final long startTimeMillis = System.currentTimeMillis();
    request.setAttribute(Keys.HttpRequest.START_TIME_MILLIS, startTimeMillis);

    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    final String requestURI = httpServletRequest.getRequestURI();
    LOGGER.log(Level.FINER, "Request URI[{0}]", requestURI);

    if (StaticResources.isStatic(httpServletRequest)) {
        final String path = httpServletRequest.getServletPath() + httpServletRequest.getPathInfo();
        LOGGER.log(Level.FINEST, "Requests a static resource, forwards to servlet[path={0}]", path);
        request.getRequestDispatcher(path).forward(request, response);

        return;
    }

    if (!Latkes.isPageCacheEnabled()) {
        LOGGER.log(Level.FINEST, "Page cache is disabled");
        chain.doFilter(request, response);

        return;
    }

    final String skinDirName = (String) httpServletRequest.getAttribute(Keys.TEMAPLTE_DIR_NAME);
    if ("mobile".equals(skinDirName)) {
        // Mobile request, bypasses page caching
        chain.doFilter(request, response);

        return;
    }

    String pageCacheKey;
    final String queryString = httpServletRequest.getQueryString();
    pageCacheKey = (String) request.getAttribute(Keys.PAGE_CACHE_KEY);
    if (Strings.isEmptyOrNull(pageCacheKey)) {
        pageCacheKey = PageCaches.getPageCacheKey(requestURI, queryString);
        request.setAttribute(Keys.PAGE_CACHE_KEY, pageCacheKey);
    }

    final JSONObject cachedPageContentObject = PageCaches.get(pageCacheKey, httpServletRequest,
            (HttpServletResponse) response);

    if (null == cachedPageContentObject) {
        LOGGER.log(Level.FINER, "Page cache miss for request URI[{0}]", requestURI);
        chain.doFilter(request, response);

        return;
    }

    final String cachedType = cachedPageContentObject.optString(PageCaches.CACHED_TYPE);

    try {
        // If cached an article that has view password, dispatches the password form
        if (langPropsService.get(PageTypes.ARTICLE.getLangeLabel()).equals(cachedType)
                && cachedPageContentObject.has(PageCaches.CACHED_PWD)) {
            JSONObject article = new JSONObject();

            final String articleId = cachedPageContentObject.optString(PageCaches.CACHED_OID);

            article.put(Keys.OBJECT_ID, articleId);
            article.put(Article.ARTICLE_VIEW_PWD, cachedPageContentObject.optString(PageCaches.CACHED_PWD));

            if (articles.needViewPwd(httpServletRequest, article)) {
                article = articleRepository.get(articleId); // Loads the article entity

                final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                try {
                    httpServletResponse.sendRedirect(Latkes.getServePath() + "/console/article-pwd"
                            + articles.buildArticleViewPwdFormParameters(article));
                    return;
                } catch (final Exception e) {
                    httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    }

    try {
        LOGGER.log(Level.FINEST, "Writes resposne for page[pageCacheKey={0}] from cache", pageCacheKey);
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        final PrintWriter writer = response.getWriter();
        String cachedPageContent = cachedPageContentObject.getString(PageCaches.CACHED_CONTENT);
        final String topBarHTML = TopBars.getTopBarHTML((HttpServletRequest) request,
                (HttpServletResponse) response);
        cachedPageContent = cachedPageContent.replace(Common.TOP_BAR_REPLACEMENT_FLAG, topBarHTML);

        final String cachedTitle = cachedPageContentObject.getString(PageCaches.CACHED_TITLE);
        LOGGER.log(Level.FINEST, "Cached value[key={0}, type={1}, title={2}]",
                new Object[] { pageCacheKey, cachedType, cachedTitle });

        statistics.incBlogViewCount((HttpServletRequest) request, (HttpServletResponse) response);

        final long endimeMillis = System.currentTimeMillis();
        final String dateString = DateFormatUtils.format(endimeMillis, "yyyy/MM/dd HH:mm:ss");
        final String msg = String.format("<!-- Cached by B3log Solo(%1$d ms), %2$s -->",
                endimeMillis - startTimeMillis, dateString);
        LOGGER.finer(msg);
        cachedPageContent += Strings.LINE_SEPARATOR + msg;
        writer.write(cachedPageContent);
        writer.flush();
        writer.close();
    } catch (final JSONException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    } catch (final ServiceException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    }
}

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

/**
 * Get app specific data./*w ww . j ava2 s  .  c  om*/
 * @param fieldInfo The field to decode
 * @param request Where we will pull the data from.
 * @return The appropriate value
 */
private String getAppSpecific(FieldInfo fieldInfo, Request request) {

    ServletRequest sr = request.getRequest();
    HttpServletRequest hsr = null;
    if (sr instanceof HttpServletRequest)
        hsr = (HttpServletRequest) sr;

    switch (fieldInfo.xType) {
    case FieldInfo.X_PARAMETER:
        return wrap(urlEncode(sr.getParameter(fieldInfo.value)));
    case FieldInfo.X_REQUEST:
        return wrap(sr.getAttribute(fieldInfo.value));
    case FieldInfo.X_SESSION:
        HttpSession session = null;
        if (hsr != null) {
            session = hsr.getSession(false);
            if (session != null)
                return wrap(session.getAttribute(fieldInfo.value));
        }
        break;
    case FieldInfo.X_COOKIE:
        Cookie[] c = hsr.getCookies();
        for (int i = 0; c != null && i < c.length; i++) {
            if (fieldInfo.value.equals(c[i].getName())) {
                return wrap(c[i].getValue());
            }
        }
    case FieldInfo.X_APP:
        return wrap(request.getContext().getServletContext().getAttribute(fieldInfo.value));
    case FieldInfo.X_SERVLET_REQUEST:
        if (fieldInfo.location == FieldInfo.X_LOC_AUTHTYPE) {
            return wrap(hsr.getAuthType());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REMOTEUSER) {
            return wrap(hsr.getRemoteUser());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONID) {
            return wrap(hsr.getRequestedSessionId());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDFROMCOOKIE) {
            return wrap("" + hsr.isRequestedSessionIdFromCookie());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDVALID) {
            return wrap("" + hsr.isRequestedSessionIdValid());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CONTENTLENGTH) {
            return wrap("" + hsr.getContentLength());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CHARACTERENCODING) {
            return wrap(hsr.getCharacterEncoding());
        } else if (fieldInfo.location == FieldInfo.X_LOC_LOCALE) {
            return wrap(hsr.getLocale());
        } else if (fieldInfo.location == FieldInfo.X_LOC_PROTOCOL) {
            return wrap(hsr.getProtocol());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SCHEME) {
            return wrap(hsr.getScheme());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SECURE) {
            return wrap("" + hsr.isSecure());
        }
        break;
    default:
        ;
    }

    return "-";

}

From source file:com.netspective.sparx.form.DialogContext.java

/**
 * Calculate what the next state or stage of the dialog should be.
 *///from   w w w  .  j a  v  a2 s .  c  o  m
public void calcState() {
    dialog.makeStateChanges(this, STATECALCSTAGE_BEFORE_VALIDATION);

    ServletRequest request = getRequest();
    DialogFlags dialogFlags = dialog.getDialogFlags();

    boolean ignoreValidation = false;
    if (dialog.getDialogFlags().flagIsSet(DialogFlags.ALLOW_PENDING_DATA)) {
        String ignoreValidationOption = request.getParameter(dialog.getPendDataParamName());
        if (ignoreValidationOption != null && !ignoreValidationOption.equals("no")) {
            ignoreValidation = true;
            validationContext.setValidationStage(DialogValidationContext.VALSTAGE_IGNORE);
        }
    }

    autoExecuteRequested = dialog.isAutoExecByDefault();
    if (!autoExecuteRequested && !dialog.getDialogFlags().flagIsSet(DialogFlags.DISABLE_AUTO_EXECUTE)) {
        String autoExecOption = request.getParameter(Dialog.PARAMNAME_AUTOEXECUTE);
        if (autoExecOption == null || autoExecOption.length() == 0)
            // if no autoexec is defined in the request parameter, look for it also in the request attribute
            autoExecOption = (String) request.getAttribute(Dialog.PARAMNAME_AUTOEXECUTE);

        if (dialog.isAutoExec(this, autoExecOption))
            autoExecuteRequested = true;
    }
    boolean executeButtonPressed = (request.getParameter(dialog.getSubmitDataParamName()) != null)
            || (request.getParameter(dialog.getCancelDataParamName()) != null
                    && dialog.getDialogFlags().flagIsSet(DialogFlags.ALLOW_EXECUTE_WITH_CANCEL_BUTTON));
    if (autoExecuteRequested || executeButtonPressed || ignoreValidation) {
        if (!dialogFlags.flagIsSet(DialogFlags.ALLOW_MULTIPLE_EXECUTES) && state.isAlreadyExecuted()) {
            getValidationContext().addError(dialog.getMultipleExecErrorMessage().getTextValue(this));
            state.reset(this);
            return;
        }

        if (dialog.isValid(this)) {
            state.setExecuteMode(true);
            autoExecuted = autoExecuteRequested;
        } else
            state.setExecuteMode(false);
    }

    dialog.makeStateChanges(this, STATECALCSTAGE_AFTER_VALIDATION);
}

From source file:org.dspace.app.webui.jsptag.LayoutTag.java

public int doStartTag() throws JspException {
    ServletRequest request = pageContext.getRequest();

    // Sort out location bar
    if (locbar == null) {
        locbar = "auto";
    }//from w ww .ja  v  a2 s . com

    // These lists will contain titles and links to put in the location
    // bar
    List<String> parents = new ArrayList<String>();
    List<String> parentLinks = new ArrayList<String>();

    if (locbar.equalsIgnoreCase("off")) {
        // No location bar
        request.setAttribute("dspace.layout.locbar", Boolean.FALSE);
    } else {
        // We'll always add "DSpace Home" to the a location bar
        parents.add(ConfigurationManager.getProperty("dspace.name"));

        if (locbar.equalsIgnoreCase("nolink")) {
            parentLinks.add("");
        } else {
            parentLinks.add("/");
        }

        // Add other relevant components to the location bar
        if (locbar.equalsIgnoreCase("link")) {
            // "link" mode - next thing in location bar is taken from
            // parameters of tag, with a link
            if (parentTitle != null) {
                parents.add(parentTitle);
                parentLinks.add(parentLink);
            } else if (parentTitleKey != null) {
                parents.add(LocaleSupport.getLocalizedMessage(pageContext, parentTitleKey));
                parentLinks.add(parentLink);
            }

        } else if (locbar.equalsIgnoreCase("commLink")) {
            // "commLink" mode - show all parent communities
            Community[] comms = (Community[]) request.getAttribute("dspace.communities");

            if (comms != null) {
                for (int i = 0; i < comms.length; i++) {
                    parents.add(comms[i].getMetadata("name"));
                    parentLinks.add("/handle/" + comms[i].getHandle());
                }
            }
        } else if (locbar.equalsIgnoreCase("nolink")) {
            // "nolink" mode - next thing in location bar is taken from
            // parameters of tag, with no link
            if (parentTitle != null) {
                parents.add(parentTitle);
                parentLinks.add("");
            }
        } else {
            // Grab parents from the URL - these should have been picked up
            // by the HandleServlet
            Collection col = (Collection) request.getAttribute("dspace.collection");
            Community[] comms = (Community[]) request.getAttribute("dspace.communities");

            if (comms != null) {
                for (int i = 0; i < comms.length; i++) {
                    parents.add(comms[i].getMetadata("name"));
                    parentLinks.add("/handle/" + comms[i].getHandle());
                }

                if (col != null) {
                    parents.add(col.getMetadata("name"));
                    parentLinks.add("/handle/" + col.getHandle());
                }
            }
        }

        request.setAttribute("dspace.layout.locbar", Boolean.TRUE);
    }

    request.setAttribute("dspace.layout.parenttitles", parents);
    request.setAttribute("dspace.layout.parentlinks", parentLinks);

    // Navigation bar: "default" is default :)
    if (navbar == null) {
        navbar = "default";
    }

    if (navbar.equals("off")) {
        request.setAttribute("dspace.layout.navbar", "off");
    } else {
        request.setAttribute("dspace.layout.navbar", templatePath + "navbar-" + navbar + ".jsp");
    }

    // Set title
    if (title != null) {
        request.setAttribute("dspace.layout.title", title);
    } else if (titleKey != null) {
        request.setAttribute("dspace.layout.title", LocaleSupport.getLocalizedMessage(pageContext, titleKey));
    } else {
        request.setAttribute("dspace.layout.title", "NO TITLE");
    }

    // Set feedData if present
    if (feedData != null && !"NONE".equals(feedData)) {
        // set the links' reference - community or collection
        boolean commLinks = feedData.startsWith("comm:");
        boolean collLinks = feedData.startsWith("coll:");
        if (commLinks) {
            Community com = (Community) request.getAttribute("dspace.community");
            request.setAttribute("dspace.layout.feedref", com.getHandle());
        } else if (collLinks) {
            Collection col = (Collection) request.getAttribute("dspace.collection");
            request.setAttribute("dspace.layout.feedref", col.getHandle());
        } else //feed is across all of DSpace and not Community/Collection specific
        {
            request.setAttribute("dspace.layout.feedref", FeedServlet.SITE_FEED_KEY);
        }

        // build a list of link attributes for each link format
        String[] formats = feedData.substring(feedData.indexOf(':') + 1).split(",");
        List<String> linkParts = new ArrayList<String>();
        // each link has a mime-type, title, and format (used in href URL)
        for (int i = 0; i < formats.length; i++) {
            if ("rss_1.0".equals(formats[i])) {
                linkParts.add("rdf+xml");
            } else {
                linkParts.add("rss+xml");
            }

            if (commLinks) {
                linkParts.add("Items in Community");
            } else if (collLinks) {
                linkParts.add("Items in Collection");
            } else {
                linkParts.add("Items in " + ConfigurationManager.getProperty("dspace.name"));
            }

            linkParts.add(formats[i]);
        }
        request.setAttribute("dspace.layout.linkparts", linkParts);
    } else {
        request.setAttribute("dspace.layout.feedref", "NONE");
    }

    return EVAL_BODY_BUFFERED;
}

From source file:org.apache.struts2.jasper.runtime.PageContextImpl.java

private void _initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL,
        boolean needsSession, int bufferSize, boolean autoFlush) throws IOException {

    // initialize state
    this.servlet = servlet;
    this.config = servlet.getServletConfig();
    this.context = config.getServletContext();
    this.errorPageURL = errorPageURL;
    this.request = request;
    this.response = response;

    // Setup session (if required)
    if (request instanceof HttpServletRequest && needsSession)
        this.session = ((HttpServletRequest) request).getSession();
    if (needsSession && session == null)
        throw new IllegalStateException("Page needs a session and none is available");

    // initialize the initial out ...
    depth = -1;/*from   w  w w .j  av a  2s. co m*/
    if (this.baseOut == null) {
        this.baseOut = new JspWriterImpl(response, bufferSize, autoFlush);
    } else {
        this.baseOut.init(response, bufferSize, autoFlush);
    }
    this.out = baseOut;

    // register names/values as per spec
    setAttribute(OUT, this.out);
    setAttribute(REQUEST, request);
    setAttribute(RESPONSE, response);

    if (session != null)
        setAttribute(SESSION, session);

    setAttribute(PAGE, servlet);
    setAttribute(CONFIG, config);
    setAttribute(PAGECONTEXT, this);
    setAttribute(APPLICATION, context);

    isIncluded = request.getAttribute("javax.servlet.include.servlet_path") != null;
}

From source file:org.apache.jasper.runtime.PageContextImpl.java

private void _initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL,
        boolean needsSession, int bufferSize, boolean autoFlush) throws IOException {

    // initialize state
    this.servlet = servlet;
    this.config = servlet.getServletConfig();
    this.context = config.getServletContext();
    this.needsSession = needsSession;
    this.errorPageURL = errorPageURL;
    this.bufferSize = bufferSize;
    this.autoFlush = autoFlush;
    this.request = request;
    this.response = response;

    // Setup session (if required)
    if (request instanceof HttpServletRequest && needsSession)
        this.session = ((HttpServletRequest) request).getSession();
    if (needsSession && session == null)
        throw new IllegalStateException("Page needs a session and none is available");

    // initialize the initial out ...
    depth = -1;/*from  w  w w  .j a v a2  s .c o  m*/
    if (this.baseOut == null) {
        this.baseOut = new JspWriterImpl(response, bufferSize, autoFlush);
    } else {
        this.baseOut.init(response, bufferSize, autoFlush);
    }
    this.out = baseOut;

    // register names/values as per spec
    setAttribute(OUT, this.out);
    setAttribute(REQUEST, request);
    setAttribute(RESPONSE, response);

    if (session != null)
        setAttribute(SESSION, session);

    setAttribute(PAGE, servlet);
    setAttribute(CONFIG, config);
    setAttribute(PAGECONTEXT, this);
    setAttribute(APPLICATION, context);

    isIncluded = request.getAttribute("javax.servlet.include.servlet_path") != null;
}

From source file:com.mirth.connect.connectors.http.HttpReceiver.java

private ConstraintSecurityHandler createSecurityHandler(Handler handler) throws Exception {
    final Authenticator authenticator = authenticatorProvider.getAuthenticator();

    final String authMethod;
    switch (authProps.getAuthType()) {
    case BASIC:/*from   ww  w . j  a  v a2s  . c  om*/
        authMethod = Constraint.__BASIC_AUTH;
        break;
    case DIGEST:
        authMethod = Constraint.__DIGEST_AUTH;
        break;
    default:
        authMethod = "customauth";
    }

    Constraint constraint = new Constraint();
    constraint.setName(authMethod);
    constraint.setRoles(new String[] { "user" });
    constraint.setAuthenticate(true);

    ConstraintMapping constraintMapping = new ConstraintMapping();
    constraintMapping.setConstraint(constraint);
    constraintMapping.setPathSpec("/*");

    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    securityHandler.setAuthenticator(new org.eclipse.jetty.security.Authenticator() {
        @Override
        public void setConfiguration(AuthConfiguration configuration) {
        }

        @Override
        public String getAuthMethod() {
            return authMethod;
        }

        @Override
        public void prepareRequest(ServletRequest request) {
        }

        @Override
        public Authentication validateRequest(final ServletRequest req, ServletResponse res, boolean mandatory)
                throws ServerAuthException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;

            String remoteAddress = StringUtils.trimToEmpty(request.getRemoteAddr());
            int remotePort = request.getRemotePort();
            String localAddress = StringUtils.trimToEmpty(request.getLocalAddr());
            int localPort = request.getLocalPort();
            String protocol = StringUtils.trimToEmpty(request.getProtocol());
            String method = StringUtils.trimToEmpty(request.getMethod());
            String requestURI = StringUtils.trimToEmpty(request.getRequestURI());
            Map<String, List<String>> headers = HttpMessageConverter.convertFieldEnumerationToMap(request);

            Map<String, List<String>> queryParameters = new LinkedHashMap<String, List<String>>();
            for (Entry<String, String[]> entry : req.getParameterMap().entrySet()) {
                queryParameters.put(entry.getKey(), Arrays.asList(entry.getValue()));
            }

            EntityProvider entityProvider = new EntityProvider() {
                @Override
                public byte[] getEntity() throws IOException {
                    byte[] entity = (byte[]) req.getAttribute(ATTRIBUTE_NAME);
                    if (entity == null) {
                        entity = IOUtils.toByteArray(req.getInputStream());
                        req.setAttribute(ATTRIBUTE_NAME, entity);
                    }
                    return entity;
                }
            };

            RequestInfo requestInfo = new RequestInfo(remoteAddress, remotePort, localAddress, localPort,
                    protocol, method, requestURI, headers, queryParameters, entityProvider,
                    configuration.getRequestInformation(request));

            try {
                AuthenticationResult result = authenticator.authenticate(requestInfo);

                for (Entry<String, List<String>> entry : result.getResponseHeaders().entrySet()) {
                    if (StringUtils.isNotBlank(entry.getKey()) && entry.getValue() != null) {
                        for (int i = 0; i < entry.getValue().size(); i++) {
                            if (i == 0) {
                                response.setHeader(entry.getKey(), entry.getValue().get(i));
                            } else {
                                response.addHeader(entry.getKey(), entry.getValue().get(i));
                            }
                        }
                    }
                }

                switch (result.getStatus()) {
                case CHALLENGED:
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    return org.eclipse.jetty.server.Authentication.SEND_CONTINUE;
                case SUCCESS:
                    Principal userPrincipal = new KnownUser(StringUtils.trimToEmpty(result.getUsername()),
                            null);
                    Subject subject = new Subject();
                    subject.getPrincipals().add(userPrincipal);
                    return new UserAuthentication(getAuthMethod(),
                            new DefaultUserIdentity(subject, userPrincipal, new String[] { "user" }));
                case FAILURE:
                default:
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    return org.eclipse.jetty.server.Authentication.SEND_FAILURE;
                }
            } catch (Throwable t) {
                logger.error("Error in HTTP authentication for " + connectorProperties.getName() + " ("
                        + connectorProperties.getName() + " \"Source\" on channel " + getChannelId() + ").", t);
                eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), null,
                        ErrorEventType.DESTINATION_CONNECTOR, "Source", connectorProperties.getName(),
                        "Error in HTTP authentication for " + connectorProperties.getName(), t));
                throw new ServerAuthException(t);
            }
        }

        @Override
        public boolean secureResponse(ServletRequest request, ServletResponse response, boolean mandatory,
                User validatedUser) throws ServerAuthException {
            return true;
        }
    });
    securityHandler.addConstraintMapping(constraintMapping);

    securityHandler.setHandler(handler);
    return securityHandler;
}

From source file:pt.iflow.flows.FlowBean.java

private int saveDataSet(UserInfoInterface userInfo, ProcessData procData, ServletRequest request, int mid) {

    String requestMid = String.valueOf(mid);
    if (null != request) {
        requestMid = (String) request.getAttribute(Const.sMID_ATTRIBUTE);
    }/*w  ww. j  a  v  a  2  s . c o m*/

    ProcessManager pm = BeanFactory.getProcessManagerBean();
    Block block = null;

    if (!procData.isInDB()) {
        if (request != null) {
            try {

                block = this.getBlock(userInfo, procData);

                if (pm.prepareProcInDB(userInfo, procData)) {

                    if (mid == Const.NO_MID) {
                        mid = procData.getMid();
                        requestMid = String.valueOf(mid);
                    }

                    if (!saveFlowState(userInfo, procData, block, true, mid, null)) {
                        Logger.error(userInfo.getUtilizador(), this, "saveDataSet",
                                "Unable to SAVE before FLOW STATE (" + block.getId() + ") for proc "
                                        + procData.getFlowId() + "-" + procData.getPid() + "-"
                                        + procData.getSubPid());
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return 0;
        }
    }

    int retObj = -1;

    int flowId = procData.getFlowId();
    int pid = procData.getPid();
    int subpid = procData.getSubPid();
    String login = userInfo.getUtilizador();

    Logger.trace(this, "saveDataSet", login + " call " + procData.getSignature());

    try {
        Activity activity = null;
        activity = pm.getUserProcessActivity(userInfo, procData.getProcessHeader());

        if (activity != null || request != null) {
            // user has process scheduled on him or
            // user made explicit request to save process data:
            // mark saved flag in process data
            procData.set(DataSetVariables.PROCESS_SAVED, "1");
        }

        if (request != null) {
            // this means that saving request was made by end-user (jsp)
            int curMid = pm.getModificationId(userInfo, procData.getProcessHeader());
            if (StringUtils.isNotEmpty(requestMid) && !StringUtils.equals(String.valueOf(curMid), requestMid)) {
                retObj = Const.ERROR_PROCESS_CHANGED;
            } else {
                retObj = pm.modifyProcessData(userInfo, procData);
            }

            if (activity == null) {
                // user does not have this process in his activity list:
                // schedule this process on him.

                // first get block to be able to get description and url
                block = this.getBlock(userInfo, procData);
                if (block != null) {
                    if (Logger.isDebugEnabled()) {
                        Logger.debug(login, this, "saveDataSet",
                                "Creating activity for user for subpid=" + subpid + ",pid " + pid + ", desc="
                                        + block.getDescription(userInfo, procData) + ", url="
                                        + Block.getDefaultUrl(userInfo, procData));
                    }

                    activity = new Activity(login, flowId, pid, subpid, 0, 0,
                            block.getDescription(userInfo, procData), Block.getDefaultUrl(userInfo, procData));
                    activity.mid = procData.getMid();

                    boolean createPriv = checkUserSelfFlowRoles(userInfo, flowId, "" + FlowRolesTO.CREATE_PRIV);
                    pm.createActivity(userInfo, activity, createPriv);
                }
            }
        } else {
            retObj = pm.modifyProcessData(userInfo, procData);
        }
    } catch (Exception e) {
        Logger.error(login, this, "saveDataSet", procData.getSignature() + "caught exception: ", e);
        retObj = -1;
    }

    if (retObj < 0) {
        Logger.warning(login, this, "saveDataSet", procData.getSignature() + "Not able to save DataSet");
    } else if (retObj == 0) {
        Logger.warning(login, this, "saveDataSet", procData.getSignature() + "No changes in DataSet");
    } else {
        Logger.debug(login, this, "saveDataSet", procData.getSignature() + "DataSet saved");
    }

    return retObj;
}