Example usage for javax.servlet.http HttpServletResponse isCommitted

List of usage examples for javax.servlet.http HttpServletResponse isCommitted

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse isCommitted.

Prototype

public boolean isCommitted();

Source Link

Document

Returns a boolean indicating if the response has been committed.

Usage

From source file:org.exist.http.urlrewrite.XQueryURLRewrite.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws IOException, ServletException {
    if (rewriteConfig == null) {
        configure();/*from   w  ww .j a  v  a 2 s .c o  m*/
        rewriteConfig = new RewriteConfig(this);
    }

    final long start = System.currentTimeMillis();
    final HttpServletRequest request = servletRequest;
    final HttpServletResponse response = servletResponse;

    if (LOG.isTraceEnabled()) {
        LOG.trace(request.getRequestURI());
    }
    final Descriptor descriptor = Descriptor.getDescriptorSingleton();
    if (descriptor != null && descriptor.requestsFiltered()) {
        final String attr = (String) request.getAttribute("XQueryURLRewrite.forwarded");
        if (attr == null) {
            //                request = new HttpServletRequestWrapper(request, /*formEncoding*/ "utf-8" );
            //logs the request if specified in the descriptor
            descriptor.doLogRequestInReplayLog(request);

            request.setAttribute("XQueryURLRewrite.forwarded", "true");
        }
    }

    Subject user = defaultUser;

    Subject requestUser = HttpAccount.getUserFromServletRequest(request);
    if (requestUser != null) {
        user = requestUser;
    } else {
        // Secondly try basic authentication
        final String auth = request.getHeader("Authorization");
        if (auth != null) {
            requestUser = authenticator.authenticate(request, response);
            if (requestUser != null) {
                user = requestUser;
            }
        }
    }

    try {
        configure();
        //checkCache(user);

        final RequestWrapper modifiedRequest = new RequestWrapper(request);
        final URLRewrite staticRewrite = rewriteConfig.lookup(modifiedRequest);
        if (staticRewrite != null && !staticRewrite.isControllerForward()) {
            modifiedRequest.setPaths(staticRewrite.resolve(modifiedRequest), staticRewrite.getPrefix());

            if (LOG.isTraceEnabled()) {
                LOG.trace("Forwarding to target: " + staticRewrite.getTarget());
            }
            staticRewrite.doRewrite(modifiedRequest, response);
        } else {

            if (LOG.isTraceEnabled()) {
                LOG.trace("Processing request URI: " + request.getRequestURI());
            }
            if (staticRewrite != null) {
                // fix the request URI
                staticRewrite.updateRequest(modifiedRequest);
            }

            // check if the request URI is already in the url cache
            ModelAndView modelView = getFromCache(request.getHeader("Host") + request.getRequestURI(), user);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Checked cache for URI: " + modifiedRequest.getRequestURI() + " original: "
                        + request.getRequestURI());
            }
            // no: create a new model and view configuration
            if (modelView == null) {
                modelView = new ModelAndView();
                // Execute the query
                Sequence result = Sequence.EMPTY_SEQUENCE;
                DBBroker broker = null;
                try {
                    broker = pool.get(user);
                    modifiedRequest.setAttribute(RQ_ATTR_REQUEST_URI, request.getRequestURI());

                    final Properties outputProperties = new Properties();

                    outputProperties.setProperty(OutputKeys.INDENT, "yes");
                    outputProperties.setProperty(OutputKeys.ENCODING, "UTF-8");
                    outputProperties.setProperty(OutputKeys.MEDIA_TYPE, MimeType.XML_TYPE.getName());

                    result = runQuery(broker, modifiedRequest, response, modelView, staticRewrite,
                            outputProperties);

                    logResult(broker, result);

                    if (response.isCommitted()) {
                        return;
                    }

                    // process the query result
                    if (result.getItemCount() == 1) {
                        final Item resource = result.itemAt(0);
                        if (!Type.subTypeOf(resource.getType(), Type.NODE)) {
                            throw new ServletException(
                                    "XQueryURLRewrite: urlrewrite query should return an element!");
                        }
                        Node node = ((NodeValue) resource).getNode();
                        if (node.getNodeType() == Node.DOCUMENT_NODE) {
                            node = ((Document) node).getDocumentElement();
                        }
                        if (node.getNodeType() != Node.ELEMENT_NODE) {
                            //throw new ServletException("Redirect XQuery should return an XML element!");
                            response(broker, response, outputProperties, result);
                            return;
                        }
                        Element elem = (Element) node;
                        if (!(Namespaces.EXIST_NS.equals(elem.getNamespaceURI()))) {
                            response(broker, response, outputProperties, result);
                            return;
                            //                            throw new ServletException("Redirect XQuery should return an element in namespace " + Namespaces.EXIST_NS);
                        }

                        if (Namespaces.EXIST_NS.equals(elem.getNamespaceURI())
                                && "dispatch".equals(elem.getLocalName())) {
                            node = elem.getFirstChild();
                            while (node != null) {
                                if (node.getNodeType() == Node.ELEMENT_NODE
                                        && Namespaces.EXIST_NS.equals(node.getNamespaceURI())) {
                                    final Element action = (Element) node;
                                    if ("view".equals(action.getLocalName())) {
                                        parseViews(modifiedRequest, action, modelView);
                                    } else if ("error-handler".equals(action.getLocalName())) {
                                        parseErrorHandlers(modifiedRequest, action, modelView);
                                    } else if ("cache-control".equals(action.getLocalName())) {
                                        final String option = action.getAttribute("cache");
                                        modelView.setUseCache("yes".equals(option));
                                    } else {
                                        final URLRewrite urw = parseAction(modifiedRequest, action);
                                        if (urw != null) {
                                            modelView.setModel(urw);
                                        }
                                    }
                                }
                                node = node.getNextSibling();
                            }
                            if (modelView.getModel() == null) {
                                modelView.setModel(new PassThrough(config, elem, modifiedRequest));
                            }
                        } else if (Namespaces.EXIST_NS.equals(elem.getNamespaceURI())
                                && "ignore".equals(elem.getLocalName())) {
                            modelView.setModel(new PassThrough(config, elem, modifiedRequest));
                            final NodeList nl = elem.getElementsByTagNameNS(Namespaces.EXIST_NS,
                                    "cache-control");
                            if (nl.getLength() > 0) {
                                elem = (Element) nl.item(0);
                                final String option = elem.getAttribute("cache");
                                modelView.setUseCache("yes".equals(option));
                            }
                        } else {
                            response(broker, response, outputProperties, result);
                            return;
                        }
                    } else if (result.getItemCount() > 1) {
                        response(broker, response, outputProperties, result);
                        return;
                    }

                    if (modelView.useCache()) {
                        LOG.debug("Caching request to " + request.getRequestURI());
                        urlCache.put(modifiedRequest.getHeader("Host") + request.getRequestURI(), modelView);
                    }

                } finally {
                    pool.release(broker);
                }

                // store the original request URI to org.exist.forward.request-uri
                modifiedRequest.setAttribute(RQ_ATTR_REQUEST_URI, request.getRequestURI());
                modifiedRequest.setAttribute(RQ_ATTR_SERVLET_PATH, request.getServletPath());

            }
            if (LOG.isTraceEnabled()) {
                LOG.trace("URLRewrite took " + (System.currentTimeMillis() - start) + "ms.");
            }
            final HttpServletResponse wrappedResponse = new CachingResponseWrapper(response,
                    modelView.hasViews() || modelView.hasErrorHandlers());
            if (modelView.getModel() == null) {
                modelView.setModel(new PassThrough(config, modifiedRequest));
            }

            if (staticRewrite != null) {
                if (modelView.getModel().doResolve()) {
                    staticRewrite.rewriteRequest(modifiedRequest);
                } else {
                    modelView.getModel().setAbsolutePath(modifiedRequest);
                }
            }
            modifiedRequest.allowCaching(!modelView.hasViews());
            doRewrite(modelView.getModel(), modifiedRequest, wrappedResponse);

            int status = ((CachingResponseWrapper) wrappedResponse).getStatus();
            if (status == HttpServletResponse.SC_NOT_MODIFIED) {
                response.flushBuffer();
            } else if (status < 400) {
                if (modelView.hasViews()) {
                    applyViews(modelView, modelView.views, response, modifiedRequest, wrappedResponse);
                } else {
                    ((CachingResponseWrapper) wrappedResponse).flush();
                }
            } else {
                // HTTP response code indicates an error
                if (modelView.hasErrorHandlers()) {
                    final byte[] data = ((CachingResponseWrapper) wrappedResponse).getData();
                    if (data != null) {
                        modifiedRequest.setAttribute(RQ_ATTR_ERROR, new String(data, UTF_8));
                    }
                    applyViews(modelView, modelView.errorHandlers, response, modifiedRequest, wrappedResponse);
                } else {
                    flushError(response, wrappedResponse);
                }
            }
        }
        //            Sequence result;
        //            if ((result = (Sequence) request.getAttribute(RQ_ATTR_RESULT)) != null) {
        //                writeResults(response, broker, result);
        //            }
    } catch (final Throwable e) {
        LOG.error("Error while processing " + servletRequest.getRequestURI() + ": " + e.getMessage(), e);
        throw new ServletException("An error occurred while processing request to "
                + servletRequest.getRequestURI() + ": " + e.getMessage(), e);

    }
}

From source file:helma.servlet.AbstractServletClient.java

/**
 * Handle a request.//from www.  j a  v  a  2s  .  com
 *
 * @param request ...
 * @param response ...
 *
 * @throws ServletException ...
 * @throws IOException ...
 */
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    RequestTrans reqtrans = new RequestTrans(request, response, getPathInfo(request));

    try {
        // get the character encoding
        String encoding = request.getCharacterEncoding();

        if (encoding == null) {
            // no encoding from request, use the application's charset
            encoding = getApplication().getCharset();
        }

        // read cookies
        Cookie[] reqCookies = request.getCookies();

        if (reqCookies != null) {
            for (int i = 0; i < reqCookies.length; i++) {
                try {
                    // get Cookies
                    String key = reqCookies[i].getName();

                    if (sessionCookieName.equals(key)) {
                        reqtrans.setSession(reqCookies[i].getValue());
                    }
                    reqtrans.setCookie(key, reqCookies[i]);
                } catch (Exception badCookie) {
                    log("Error setting cookie", badCookie);
                }
            }
        }

        // get the cookie domain to use for this response, if any.
        String resCookieDomain = cookieDomain;

        if (resCookieDomain != null) {
            // check if cookieDomain is valid for this response.
            // (note: cookieDomain is guaranteed to be lower case)
            // check for x-forwarded-for header, fix for bug 443
            String proxiedHost = request.getHeader("x-forwarded-host");
            if (proxiedHost != null) {
                if (proxiedHost.toLowerCase().indexOf(resCookieDomain) == -1) {
                    resCookieDomain = null;
                }
            } else {
                String host = (String) reqtrans.get("http_host");
                // http_host is guaranteed to be lower case 
                if (host != null && host.indexOf(resCookieDomain) == -1) {
                    resCookieDomain = null;
                }
            }
        }

        // check if session cookie is present and valid, creating it if not.
        checkSessionCookie(request, response, reqtrans, resCookieDomain);

        // read and set http parameters
        parseParameters(request, reqtrans, encoding);

        // read file uploads
        List uploads = null;
        ServletRequestContext reqcx = new ServletRequestContext(request);

        if (ServletFileUpload.isMultipartContent(reqcx)) {
            // get session for upload progress monitoring
            UploadStatus uploadStatus = getApplication().getUploadStatus(reqtrans);
            try {
                uploads = parseUploads(reqcx, reqtrans, uploadStatus, encoding);
            } catch (Exception upx) {
                log("Error in file upload", upx);
                String message;
                boolean tooLarge = (upx instanceof FileUploadBase.SizeLimitExceededException);
                if (tooLarge) {
                    message = "File upload size exceeds limit of " + uploadLimit + " kB";
                } else {
                    message = upx.getMessage();
                    if (message == null || message.length() == 0) {
                        message = upx.toString();
                    }
                }
                if (uploadStatus != null) {
                    uploadStatus.setError(message);
                }

                if (uploadSoftfail || uploadStatus != null) {
                    reqtrans.set("helma_upload_error", message);
                } else {
                    int errorCode = tooLarge ? HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE
                            : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                    sendError(response, errorCode, "Error in file upload: " + message);
                    return;
                }
            }
        }

        ResponseTrans restrans = getApplication().execute(reqtrans);

        // delete uploads if any
        if (uploads != null) {
            for (int i = 0; i < uploads.size(); i++) {
                ((FileItem) uploads.get(i)).delete();
            }
        }

        // if the response was already written and committed by the application
        // we can skip this part and return
        if (response.isCommitted()) {
            return;
        }

        // set cookies
        if (restrans.countCookies() > 0) {
            CookieTrans[] resCookies = restrans.getCookies();

            for (int i = 0; i < resCookies.length; i++)
                try {
                    Cookie c = resCookies[i].getCookie("/", resCookieDomain);

                    response.addCookie(c);
                } catch (Exception x) {
                    getApplication().logEvent("Error adding cookie: " + x);
                }
        }

        // write response
        writeResponse(request, response, reqtrans, restrans);
    } catch (Exception x) {
        log("Exception in execute", x);
        try {
            if (debug) {
                sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server error: " + x);
            } else {
                sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "The server encountered an error while processing your request. "
                                + "Please check back later.");
            }
        } catch (IOException iox) {
            log("Exception in sendError", iox);
        }
    }
}

From source file:org.artifactory.webapp.servlet.RepoFilter.java

@SuppressWarnings("OverlyComplexMethod")
private void execute(FilterChain chain, final HttpServletRequest request, HttpServletResponse response,
        String servletPath) throws IOException, ServletException {
    if (log.isDebugEnabled()) {
        log.debug("Entering request {}.", requestDebugString(request));
    }//ww w  .  j a v  a 2s .co  m
    if (request.getRequestURI().endsWith("treebrowser")) {
        ArtifactoryRequest artifactoryRequest = new HttpArtifactoryRequest(request);
        request.setAttribute(ATTR_ARTIFACTORY_REPOSITORY_PATH, artifactoryRequest.getRepoPath());
        request.setAttribute(ATTR_ARTIFACTORY_REQUEST_PROPERTIES, artifactoryRequest.getProperties());
    }
    boolean repoRequest = servletPath != null && RequestUtils.isRepoRequest(request, true);
    if (repoRequest && servletPath.startsWith("/" + ArtifactoryRequest.LIST_BROWSING_PATH)
            && servletPath.endsWith("/")) {
        ArtifactoryRequest artifactoryRequest = new HttpArtifactoryRequest(request);
        String repoKey = artifactoryRequest.getRepoKey();
        if (VirtualRepoDescriptor.GLOBAL_VIRTUAL_REPO_KEY.equals(repoKey)
                && ConstantValues.disableGlobalRepoAccess.getBoolean()) {
            // The global /repo is disabled. Cannot be used here, returning 403!
            String msg = "Accessing the global virtual repository /repo is disabled!";
            log.warn(msg);
            response.sendError(HttpStatus.SC_FORBIDDEN, msg);
            return;
        }
        doRepoListing(request, response, servletPath, artifactoryRequest);
        return;
    }

    String method = request.getMethod().toLowerCase().intern();

    if (repoRequest) {
        ArtifactoryRequest artifactoryRequest = new HttpArtifactoryRequest(request);
        //Handle upload and download requests
        ArtifactoryResponse artifactoryResponse = new HttpArtifactoryResponse(response);

        if (artifactoryRequest.isDirectoryRequest() && isGetOrHeadRequest(method)) {
            //Check that this is not a recursive call
            if (artifactoryRequest.isRecursive()) {
                String msg = "Recursive call detected for '" + request + "'. Returning nothing.";
                artifactoryResponse.sendError(HttpStatus.SC_NOT_FOUND, msg, log);
                return;
            }
            log.debug("Serving a directory get request.");
            String repoKey = artifactoryRequest.getRepoKey();
            if (VirtualRepoDescriptor.GLOBAL_VIRTUAL_REPO_KEY.equals(repoKey)
                    && ConstantValues.disableGlobalRepoAccess.getBoolean()) {
                // The global /repo is disabled. Cannot be used here, returning 403!
                String msg = "Accessing the global virtual repository /repo is disabled!";
                log.warn(msg);
                response.sendError(HttpStatus.SC_FORBIDDEN, msg);
                return;
            }
            doRepoListing(request, response, servletPath, artifactoryRequest);
            return;
        }

        try {
            initRequestContext(method, artifactoryRequest, artifactoryResponse);
            if (isGetOrHeadRequest(method)) {

                /**
                 * Do not check for this parameter when not performing a get/head request so that the container
                 * doesn't try to read the parameters and verify the size of the form in case of an upload
                 */
                if (artifactoryRequest.getParameter(ArtifactRestConstants.TRACE_PARAM) != null) {
                    //Re-init the context with the trace logging response
                    artifactoryResponse = new TraceLoggingResponse(artifactoryResponse);
                    initRequestContext(method, artifactoryRequest, artifactoryResponse);
                }

                // TODO: Should we return 405 Method not allowed for head request on properties:
                // TODO: For now the HEAD request will ignore this properties query param
                if (artifactoryRequest.getParameter(ArtifactRestConstants.PROPERTIES_PARAM) != null) {
                    //Set the response to return only the properties of the item in json format
                    artifactoryResponse.setPropertiesMediaType(MediaType.APPLICATION_JSON.toString());
                }
                if (artifactoryRequest.getParameter(ArtifactRestConstants.PROPERTIES_XML_PARAM) != null) {
                    //Set the response to return only the properties of the item in json format
                    artifactoryResponse.setPropertiesMediaType(MediaType.APPLICATION_XML.toString());
                }

                doDownload(request, response, method, artifactoryRequest, artifactoryResponse);
                return;
            }

            if ("put".equals(method)) {
                doUpload(artifactoryRequest, artifactoryResponse);
                return;
            }

            doWebDavMethod(request, response, method, artifactoryRequest, artifactoryResponse);
        } finally {
            RepoRequests.destroy();
        }

    } else if (!response.isCommitted()) {
        // Webdav request not on repository, return 403
        if (RequestUtils.isWebdavRequest(request)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            if (log.isDebugEnabled()) {
                log.debug("Received webdav request on " + servletPath + " which is not a repository!\n"
                        + "Returning " + HttpServletResponse.SC_FORBIDDEN);
            }
        } else {
            // TODO: [by dan] this is a workaround for the Git LFS bug in 0.5.1 - see RTFACT-7587 remove this ugly
            // TODO: hack when we decide we can drop support for versions < 0.5.2 or when Jersey is updated above 2.0
            chain.doFilter(wrapRequestIfNeeded(request), response);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Exiting request " + requestDebugString(request));
    }
}

From source file:spark.webserver.MatcherFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, // NOSONAR
        FilterChain chain) throws IOException, ServletException { // NOSONAR
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; // NOSONAR
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

    String httpMethodStr = httpRequest.getMethod().toLowerCase(); // NOSONAR
    String uri = httpRequest.getRequestURI(); // NOSONAR
    String acceptType = httpRequest.getHeader(ACCEPT_TYPE_REQUEST_MIME_HEADER);

    String bodyContent = null;/*  w w  w  .  j  ava  2 s .c  o  m*/
    if (!isStaticFileRequest(servletRequest, servletResponse, chain)) {
        RequestWrapper req = new RequestWrapper();
        ResponseWrapper res = new ResponseWrapper();

        try {
            // BEFORE filters
            List<RouteMatch> matchSet = routeMatcher.findTargetsForRequestedRoute(HttpMethod.before, uri,
                    acceptType);

            for (RouteMatch filterMatch : matchSet) {
                Object filterTarget = filterMatch.getTarget();
                if (filterTarget instanceof spark.Filter) {
                    Request request = RequestResponseFactory.create(filterMatch, httpRequest);
                    Response response = RequestResponseFactory.create(httpResponse);

                    spark.Filter filter = (spark.Filter) filterTarget;

                    req.setDelegate(request);
                    res.setDelegate(response);

                    filter.handle(req, res);

                    String bodyAfterFilter = Access.getBody(response);
                    if (bodyAfterFilter != null) {
                        bodyContent = bodyAfterFilter;
                    }
                }
            }
            // BEFORE filters, END

            HttpMethod httpMethod = HttpMethod.valueOf(httpMethodStr);

            RouteMatch match = null;
            match = routeMatcher.findTargetForRequestedRoute(httpMethod, uri, acceptType);

            Object target = null;
            if (match != null) {
                target = match.getTarget();
            } else if (httpMethod == HttpMethod.head && bodyContent == null) {
                // See if get is mapped to provide default head mapping
                bodyContent = routeMatcher.findTargetForRequestedRoute(HttpMethod.get, uri, acceptType) != null
                        ? ""
                        : null;
            } else if (httpMethod == HttpMethod.options && bodyContent == null) {
                // CON-476: For an OPTIONS request, attempt to get all the
                // targets for the route and specify those in the response
                Set<HttpMethod> methods = routeMatcher.findMethodsForRequestedPath(uri, acceptType);
                if (!methods.isEmpty()) {
                    httpResponse.setHeader("Allow", StringUtils.join(methods, ','));
                    bodyContent = "";
                }

            }

            if (target != null) {
                try {
                    String result = null;
                    if (target instanceof Route) {
                        Route route = ((Route) target);
                        Request request = RequestResponseFactory.create(match, httpRequest);
                        Response response = RequestResponseFactory.create(httpResponse);

                        req.setDelegate(request);
                        res.setDelegate(response);

                        Object element = route.handle(req, res);
                        result = route.render(element);
                    }
                    if (result != null) {
                        bodyContent = result;
                    }
                } catch (HaltException hEx) { // NOSONAR
                    throw hEx; // NOSONAR
                } catch (Exception e) {
                    Logger.error("", e);
                    httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    bodyContent = INTERNAL_ERROR;
                }
            }

            // AFTER filters
            matchSet = routeMatcher.findTargetsForRequestedRoute(HttpMethod.after, uri, acceptType);

            for (RouteMatch filterMatch : matchSet) {
                Object filterTarget = filterMatch.getTarget();
                if (filterTarget instanceof spark.Filter) {
                    Request request = RequestResponseFactory.create(filterMatch, httpRequest);
                    Response response = RequestResponseFactory.create(httpResponse);

                    req.setDelegate(request);
                    res.setDelegate(response);

                    spark.Filter filter = (spark.Filter) filterTarget;
                    filter.handle(req, res);

                    String bodyAfterFilter = Access.getBody(response);
                    if (bodyAfterFilter != null) {
                        bodyContent = bodyAfterFilter;
                    }
                }
            }
            // AFTER filters, END
        } catch (HaltException hEx) {
            httpResponse.setStatus(hEx.getStatusCode());
            if (hEx.getBody() != null) {
                bodyContent = hEx.getBody();
            } else {
                bodyContent = "";
            }
        }
    }

    boolean consumed = bodyContent != null;

    if (!consumed && hasOtherHandlers) {
        throw new NotConsumedException();
    }

    if (!consumed && !isServletContext) {
        httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        bodyContent = String.format(NOT_FOUND, uri);
        consumed = true;
    }

    if (consumed) {
        // Write body content
        if (!httpResponse.isCommitted()) {
            if (httpResponse.getContentType() == null) {
                httpResponse.setContentType("text/html; charset=utf-8");
            }
            httpResponse.getOutputStream().write(bodyContent.getBytes("utf-8"));
        }
    } else if (chain != null) {
        chain.doFilter(httpRequest, httpResponse);
    }

}

From source file:org.apache.zeppelin.realm.kerberos.KerberosRealm.java

/**
 * If the request has a valid authentication token it allows the request to continue to
 * the target resource,/*from www .  j  a  v a  2 s.  c o  m*/
 * otherwise it triggers a GSS-API sequence for authentication
 *
 * @param request     the request object.
 * @param response    the response object.
 * @param filterChain the filter chain object.
 * @throws IOException      thrown if an IO error occurred.
 * @throws ServletException thrown if a processing error occurred.
 */
public void doKerberosAuth(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    boolean unauthorizedResponse = true;
    int errCode = HttpServletResponse.SC_UNAUTHORIZED;
    AuthenticationException authenticationEx = null;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    boolean isHttps = "https".equals(httpRequest.getScheme());
    try {
        boolean newToken = false;
        AuthenticationToken token;
        try {
            token = getToken(httpRequest);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Got token {} from httpRequest {}", token, getRequestURL(httpRequest));
                if (null != token) {
                    LOG.debug("token.isExpired() = " + token.isExpired());
                }
            }
        } catch (AuthenticationException ex) {
            LOG.warn("AuthenticationToken ignored: " + ex.getMessage());
            if (!ex.getMessage().equals("Empty token")) {
                // will be sent back in a 401 unless filter authenticates
                authenticationEx = ex;
            }
            token = null;
        }
        if (managementOperation(token, httpRequest, httpResponse)) {
            if (token == null || token.isExpired()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] triggering authentication. handler: {}", getRequestURL(httpRequest),
                            this.getClass());
                }
                token = authenticate(httpRequest, httpResponse);
                if (token != null && token != AuthenticationToken.ANONYMOUS) {
                    //            TODO(vr): uncomment when we move to Hadoop 2.8+
                    //            if (token.getMaxInactives() > 0) {
                    //              token.setMaxInactives(System.currentTimeMillis()
                    //                  + getTokenMaxInactiveInterval() * 1000);
                    //            }
                    if (token.getExpires() != 0) {
                        token.setExpires(System.currentTimeMillis() + getTokenValidity() * 1000);
                    }
                }
                newToken = true;
            }
            if (token != null) {
                unauthorizedResponse = false;
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest),
                            token.getUserName());
                }
                final AuthenticationToken authToken = token;
                httpRequest = new HttpServletRequestWrapper(httpRequest) {

                    @Override
                    public String getAuthType() {
                        return authToken.getType();
                    }

                    @Override
                    public String getRemoteUser() {
                        return authToken.getUserName();
                    }

                    @Override
                    public Principal getUserPrincipal() {
                        return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                    }
                };

                // If cookie persistence is configured to false,
                // it means the cookie will be a session cookie.
                // If the token is an old one, renew the its tokenMaxInactiveInterval.
                if (!newToken && !isCookiePersistent() && getTokenMaxInactiveInterval() > 0) {
                    //            TODO(vr): uncomment when we move to Hadoop 2.8+
                    //            token.setMaxInactives(System.currentTimeMillis()
                    //                + getTokenMaxInactiveInterval() * 1000);
                    token.setExpires(token.getExpires());
                    newToken = true;
                }
                if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                    String signedToken = signer.sign(token.toString());
                    createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                            token.getExpires(), isCookiePersistent(), isHttps);
                }
                KerberosToken kerberosToken = new KerberosToken(token.getUserName(), token.toString());
                SecurityUtils.getSubject().login(kerberosToken);
                doFilter(filterChain, httpRequest, httpResponse);
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("managementOperation returned false for request {}." + " token: {}",
                        getRequestURL(httpRequest), token);
            }
            unauthorizedResponse = false;
        }
    } catch (AuthenticationException ex) {
        // exception from the filter itself is fatal
        errCode = HttpServletResponse.SC_FORBIDDEN;
        authenticationEx = ex;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Authentication exception: " + ex.getMessage(), ex);
        } else {
            LOG.warn("Authentication exception: " + ex.getMessage());
        }
    }
    if (unauthorizedResponse) {
        if (!httpResponse.isCommitted()) {
            createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isCookiePersistent(),
                    isHttps);
            // If response code is 401. Then WWW-Authenticate Header should be
            // present.. reset to 403 if not found..
            if ((errCode == HttpServletResponse.SC_UNAUTHORIZED)
                    && (!httpResponse.containsHeader(KerberosAuthenticator.WWW_AUTHENTICATE))) {
                errCode = HttpServletResponse.SC_FORBIDDEN;
            }
            if (authenticationEx == null) {
                httpResponse.sendError(errCode, "Authentication required");
            } else {
                httpResponse.sendError(errCode, authenticationEx.getMessage());
            }
        }
    }
}

From source file:axiom.servlet.AbstractServletClient.java

/**
 * Handle a request./*from  w  ww  . j a va  2  s . c  o m*/
 *
 * @param request ...
 * @param response ...
 *
 * @throws ServletException ...
 * @throws IOException ...
 */
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final String httpMethod = request.getMethod();
    if (!"POST".equalsIgnoreCase(httpMethod) && !"GET".equalsIgnoreCase(httpMethod)) {
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "HTTP Method " + httpMethod + " not supported.");
        return;
    }

    RequestTrans reqtrans = new RequestTrans(request, response, getPathInfo(request));

    try {
        // get the character encoding
        String encoding = request.getCharacterEncoding();

        if (encoding == null) {
            // no encoding from request, use the application's charset
            encoding = getApplication().getCharset();
        }

        // read and set http parameters
        parseParameters(request, reqtrans, encoding);

        List uploads = null;
        ServletRequestContext reqcx = new ServletRequestContext(request);

        if (ServletFileUpload.isMultipartContent(reqcx)) {
            // get session for upload progress monitoring
            UploadStatus uploadStatus = getApplication().getUploadStatus(reqtrans);
            try {
                uploads = parseUploads(reqcx, reqtrans, uploadStatus, encoding);
            } catch (Exception upx) {
                System.err.println("Error in file upload: " + upx);
                if (uploadSoftfail) {
                    String msg = upx.getMessage();
                    if (msg == null || msg.length() == 0) {
                        msg = upx.toString();
                    }
                    reqtrans.set("axiom_upload_error", msg);
                } else if (upx instanceof FileUploadBase.SizeLimitExceededException) {
                    sendError(response, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                            "File upload size exceeds limit of " + uploadLimit + "kB");
                    return;
                } else {
                    sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Error in file upload: " + upx);
                    return;
                }
            }
        }

        parseCookies(request, reqtrans, encoding);

        // do standard HTTP variables
        String host = request.getHeader("Host");

        if (host != null) {
            host = host.toLowerCase();
            reqtrans.set("http_host", host);
        }

        String referer = request.getHeader("Referer");

        if (referer != null) {
            reqtrans.set("http_referer", referer);
        }

        try {
            long ifModifiedSince = request.getDateHeader("If-Modified-Since");

            if (ifModifiedSince > -1) {
                reqtrans.setIfModifiedSince(ifModifiedSince);
            }
        } catch (IllegalArgumentException ignore) {
        }

        String ifNoneMatch = request.getHeader("If-None-Match");

        if (ifNoneMatch != null) {
            reqtrans.setETags(ifNoneMatch);
        }

        String remotehost = request.getRemoteAddr();

        if (remotehost != null) {
            reqtrans.set("http_remotehost", remotehost);
        }

        // get the cookie domain to use for this response, if any.
        String resCookieDomain = cookieDomain;

        if (resCookieDomain != null) {
            // check if cookieDomain is valid for this response.
            // (note: cookieDomain is guaranteed to be lower case)
            // check for x-forwarded-for header, fix for bug 443
            String proxiedHost = request.getHeader("x-forwarded-host");
            if (proxiedHost != null) {
                if (proxiedHost.toLowerCase().indexOf(cookieDomain) == -1) {
                    resCookieDomain = null;
                }
            } else if ((host != null) && host.toLowerCase().indexOf(cookieDomain) == -1) {
                resCookieDomain = null;
            }
        }

        // check if session cookie is present and valid, creating it if not.
        checkSessionCookie(request, response, reqtrans, resCookieDomain);

        String browser = request.getHeader("User-Agent");

        if (browser != null) {
            reqtrans.set("http_browser", browser);
        }

        String language = request.getHeader("Accept-Language");

        if (language != null) {
            reqtrans.set("http_language", language);
        }

        String authorization = request.getHeader("authorization");

        if (authorization != null) {
            reqtrans.set("authorization", authorization);
        }

        ResponseTrans restrans = getApplication().execute(reqtrans);

        // if the response was already written and committed by the application
        // we can skip this part and return
        if (response.isCommitted()) {
            return;
        }

        // set cookies
        if (restrans.countCookies() > 0) {
            CookieTrans[] resCookies = restrans.getCookies();

            for (int i = 0; i < resCookies.length; i++)
                try {
                    Cookie c = resCookies[i].getCookie("/", resCookieDomain);

                    response.addCookie(c);
                } catch (Exception ignore) {
                    ignore.printStackTrace();
                }
        }

        // write response
        writeResponse(request, response, reqtrans, restrans);

    } catch (Exception x) {
        try {
            if (debug) {
                sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server error: " + x);
                x.printStackTrace();
            } else {
                sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "The server encountered an error while processing your request. "
                                + "Please check back later.");
            }

            log("Exception in execute: " + x);
        } catch (IOException io_e) {
            log("Exception in sendError: " + io_e);
        }
    }
}

From source file:com.truthbean.core.web.kindeditor.FileUpload.java

@Override
public void service(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {

    final PageContext pageContext;
    HttpSession session = null;/*  w w w.j  a  v a2 s .c  o  m*/
    final ServletContext application;
    final ServletConfig config;
    JspWriter out = null;
    final Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
        response.setContentType("text/html; charset=UTF-8");
        pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
        _jspx_page_context = pageContext;
        application = pageContext.getServletContext();
        config = pageContext.getServletConfig();
        session = pageContext.getSession();
        out = pageContext.getOut();
        _jspx_out = out;

        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");

        /**
         * KindEditor JSP
         *
         * JSP???? ??
         *
         */
        // ?
        String savePath = pageContext.getServletContext().getRealPath("/") + "resource/";

        String savePath$ = savePath;

        // ?URL
        String saveUrl = request.getContextPath() + "/resource/";

        // ???
        HashMap<String, String> extMap = new HashMap<>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

        // ?
        long maxSize = 10 * 1024 * 1024 * 1024L;

        response.setContentType("text/html; charset=UTF-8");

        if (!ServletFileUpload.isMultipartContent(request)) {
            out.println(getError(""));
            return;
        }
        // 
        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
            out.println(getError("?"));
            return;
        }
        // ??
        if (!uploadDir.canWrite()) {
            out.println(getError("??"));
            return;
        }

        String dirName = request.getParameter("dir");
        if (dirName == null) {
            dirName = "image";
        }
        if (!extMap.containsKey(dirName)) {
            out.println(getError("???"));
            return;
        }
        // 
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        List items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            if (!item.isFormField()) {
                // ?
                if (item.getSize() > maxSize) {
                    out.println(getError("??"));
                    return;
                }
                // ??
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if (!Arrays.asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                    out.println(getError("??????\n??"
                            + extMap.get(dirName) + "?"));
                    return;
                }

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                try {
                    File uploadedFile = new File(savePath, newFileName);
                    item.write(uploadedFile);
                } catch (Exception e) {
                    out.println(getError(""));
                    return;
                }

                JSONObject obj = new JSONObject();
                obj.put("error", 0);
                obj.put("url", saveUrl + newFileName);

                request.getSession().setAttribute("fileName", savePath$ + fileName);
                request.getSession().setAttribute("filePath", savePath + newFileName);
                request.getSession().setAttribute("fileUrl", saveUrl + newFileName);

                out.println(obj.toJSONString());
            }
        }

        out.write('\r');
        out.write('\n');
    } catch (IOException | FileUploadException t) {
        if (!(t instanceof javax.servlet.jsp.SkipPageException)) {
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0) {
                if (response.isCommitted()) {
                    out.flush();
                } else {
                    out.clearBuffer();
                }
            }
            if (_jspx_page_context != null) {
                _jspx_page_context.handlePageException(t);
            } else {
                throw new ServletException(t);
            }
        }
    } finally {
        _jspxFactory.releasePageContext(_jspx_page_context);
    }
}

From source file:org.springframework.security.oauth.consumer.filter.OAuthConsumerContextFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    OAuthSecurityContextImpl context = new OAuthSecurityContextImpl();
    context.setDetails(request);/*  w w w .j a v a  2  s  . c  om*/

    Map<String, OAuthConsumerToken> rememberedTokens = getRememberMeServices().loadRememberedTokens(request,
            response);
    Map<String, OAuthConsumerToken> accessTokens = new TreeMap<String, OAuthConsumerToken>();
    Map<String, OAuthConsumerToken> requestTokens = new TreeMap<String, OAuthConsumerToken>();
    if (rememberedTokens != null) {
        for (Map.Entry<String, OAuthConsumerToken> tokenEntry : rememberedTokens.entrySet()) {
            OAuthConsumerToken token = tokenEntry.getValue();
            if (token != null) {
                if (token.isAccessToken()) {
                    accessTokens.put(tokenEntry.getKey(), token);
                } else {
                    requestTokens.put(tokenEntry.getKey(), token);
                }
            }
        }
    }

    context.setAccessTokens(accessTokens);
    OAuthSecurityContextHolder.setContext(context);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Storing access tokens in request attribute '" + getAccessTokensRequestAttribute() + "'.");
    }

    try {
        try {
            request.setAttribute(getAccessTokensRequestAttribute(),
                    new ArrayList<OAuthConsumerToken>(accessTokens.values()));
            chain.doFilter(request, response);
        } catch (Exception e) {
            try {
                ProtectedResourceDetails resourceThatNeedsAuthorization = checkForResourceThatNeedsAuthorization(
                        e);
                String neededResourceId = resourceThatNeedsAuthorization.getId();
                while (!accessTokens.containsKey(neededResourceId)) {
                    OAuthConsumerToken token = requestTokens.remove(neededResourceId);
                    if (token == null) {
                        token = getTokenServices().getToken(neededResourceId);
                    }

                    String verifier = request.getParameter(OAuthProviderParameter.oauth_verifier.toString());
                    // if the token is null OR
                    // if there is NO access token and (we're not using 1.0a or the verifier is not null)
                    if (token == null || (!token.isAccessToken()
                            && (!resourceThatNeedsAuthorization.isUse10a() || verifier == null))) {
                        //no token associated with the resource, start the oauth flow.
                        //if there's a request token, but no verifier, we'll assume that a previous oauth request failed and we need to get a new request token.
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Obtaining request token for resource: " + neededResourceId);
                        }

                        //obtain authorization.
                        String callbackURL = response.encodeRedirectURL(getCallbackURL(request));
                        token = getConsumerSupport().getUnauthorizedRequestToken(neededResourceId, callbackURL);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Request token obtained for resource " + neededResourceId + ": " + token);
                        }

                        //okay, we've got a request token, now we need to authorize it.
                        requestTokens.put(neededResourceId, token);
                        getTokenServices().storeToken(neededResourceId, token);
                        String redirect = getUserAuthorizationRedirectURL(resourceThatNeedsAuthorization, token,
                                callbackURL);

                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Redirecting request to " + redirect
                                    + " for user authorization of the request token for resource "
                                    + neededResourceId + ".");
                        }

                        request.setAttribute(
                                "org.springframework.security.oauth.consumer.AccessTokenRequiredException", e);
                        this.redirectStrategy.sendRedirect(request, response, redirect);
                        return;
                    } else if (!token.isAccessToken()) {
                        //we have a presumably authorized request token, let's try to get an access token with it.
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Obtaining access token for resource: " + neededResourceId);
                        }

                        //authorize the request token and store it.
                        try {
                            token = getConsumerSupport().getAccessToken(token, verifier);
                        } finally {
                            getTokenServices().removeToken(neededResourceId);
                        }

                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Access token " + token + " obtained for resource " + neededResourceId
                                    + ". Now storing and using.");
                        }

                        getTokenServices().storeToken(neededResourceId, token);
                    }

                    accessTokens.put(neededResourceId, token);

                    try {
                        //try again
                        if (!response.isCommitted()) {
                            request.setAttribute(getAccessTokensRequestAttribute(),
                                    new ArrayList<OAuthConsumerToken>(accessTokens.values()));
                            chain.doFilter(request, response);
                        } else {
                            //dang. what do we do now?
                            throw new IllegalStateException(
                                    "Unable to reprocess filter chain with needed OAuth2 resources because the response is already committed.");
                        }
                    } catch (Exception e1) {
                        resourceThatNeedsAuthorization = checkForResourceThatNeedsAuthorization(e1);
                        neededResourceId = resourceThatNeedsAuthorization.getId();
                    }
                }
            } catch (OAuthRequestFailedException eo) {
                fail(request, response, eo);
            } catch (Exception ex) {
                Throwable[] causeChain = getThrowableAnalyzer().determineCauseChain(ex);
                OAuthRequestFailedException rfe = (OAuthRequestFailedException) getThrowableAnalyzer()
                        .getFirstThrowableOfType(OAuthRequestFailedException.class, causeChain);
                if (rfe != null) {
                    fail(request, response, rfe);
                } else {
                    // Rethrow ServletExceptions and RuntimeExceptions as-is
                    if (ex instanceof ServletException) {
                        throw (ServletException) ex;
                    } else if (ex instanceof RuntimeException) {
                        throw (RuntimeException) ex;
                    }

                    // Wrap other Exceptions. These are not expected to happen
                    throw new RuntimeException(ex);
                }
            }
        }
    } finally {
        OAuthSecurityContextHolder.setContext(null);
        HashMap<String, OAuthConsumerToken> tokensToRemember = new HashMap<String, OAuthConsumerToken>();
        tokensToRemember.putAll(requestTokens);
        tokensToRemember.putAll(accessTokens);
        getRememberMeServices().rememberTokens(tokensToRemember, request, response);
    }
}

From source file:org.apache.jsp.registration_jsp.java

public void _jspService(final javax.servlet.http.HttpServletRequest request,
        final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;

    try {/*from  w w w  . ja va 2  s. co m*/
        response.setContentType("text/html");
        pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
        _jspx_page_context = pageContext;
        application = pageContext.getServletContext();
        config = pageContext.getServletConfig();
        session = pageContext.getSession();
        out = pageContext.getOut();
        _jspx_out = out;

        /**
        * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
        *
        * WSO2 Inc. licenses this file to you under the Apache License,
        * Version 2.0 (the "License"); you may not use this file except
        * in compliance with the License.
        * You may obtain a copy of the License at
        *
        * http://www.apache.org/licenses/LICENSE-2.0
        *
        * Unless required by applicable law or agreed to in writing,
        * software distributed under the License is distributed on an
        * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
        * KIND, either express or implied. See the License for the
        * specific language governing permissions and limitations
        * under the License.
        */
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");

        String forwardTo;
        try {

            UserRegistrationAdminServiceClient registrationClient = new UserRegistrationAdminServiceClient();
            boolean isExistingUser = registrationClient.isUserExist(request.getParameter("reg_username"));

            if (StringUtils.equals(request.getParameter("is_validation"), "true")) {
                if (isExistingUser) {
                    out.write("User Exist");
                } else {
                    out.write("Ok");
                }
                return;
            }

            if (isExistingUser) {
                throw new Exception("User exist");
            }

            List<UserFieldDTO> fields = (List<UserFieldDTO>) session.getAttribute("fields");

            for (UserFieldDTO userFieldDTO : fields) {
                userFieldDTO.setFieldValue(request.getParameter(userFieldDTO.getFieldName()));
            }

            String username = request.getParameter("reg_username");
            char[] password = request.getParameter("reg_password").toCharArray();
            registrationClient.addUser(username, password, fields);

            forwardTo = "../dashboard/index.jag";

        } catch (Exception e) {
            String error = "An internal error occurred.";
            response.sendRedirect("create-account.jsp?sessionDataKey=" + request.getParameter("sessionDataKey")
                    + "&failedPrevious=true&errorCode=" + error);
            return;
        }

        out.write("\n");
        out.write("<html>\n");
        out.write("<head>\n");
        out.write("    <link href=\"libs/bootstrap_3.3.5/css/bootstrap.min.css\" rel=\"stylesheet\">\n");
        out.write("    <link href=\"css/Roboto.css\" rel=\"stylesheet\">\n");
        out.write("    <link href=\"css/custom-common.css\" rel=\"stylesheet\">\n");
        out.write("</head>\n");
        out.write("<body>\n");
        out.write("<div class=\"container\">\n");
        out.write("    <div id=\"infoModel\" class=\"modal fade\" role=\"dialog\">\n");
        out.write("        <div class=\"modal-dialog\">\n");
        out.write("            <div class=\"modal-content\">\n");
        out.write("                <div class=\"modal-header\">\n");
        out.write(
                "                    <button type=\"button\" class=\"close\" data-dismiss=\"modal\">&times;</button>\n");
        out.write("                    <h4 class=\"modal-title\">Information</h4>\n");
        out.write("                </div>\n");
        out.write("                <div class=\"modal-body\">\n");
        out.write("                    <p>User details successfully submitted</p>\n");
        out.write("                </div>\n");
        out.write("                <div class=\"modal-footer\">\n");
        out.write(
                "                    <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n");
        out.write("                </div>\n");
        out.write("            </div>\n");
        out.write("        </div>\n");
        out.write("    </div>\n");
        out.write("</div>\n");
        out.write("<script src=\"libs/jquery_1.11.3/jquery-1.11.3.js\"></script>\n");
        out.write("<script src=\"libs/bootstrap_3.3.5/js/bootstrap.min.js\"></script>\n");
        out.write("<script type=\"application/javascript\" >\n");
        out.write("    $(document).ready(function () {\n");
        out.write("        var infoModel = $(\"#infoModel\");\n");
        out.write("        infoModel.modal(\"show\");\n");
        out.write("        infoModel.on('hidden.bs.modal', function() {\n");
        out.write("            location.href = \"");
        out.print(Encode.forJavaScriptBlock(forwardTo));
        out.write("\";\n");
        out.write("        })\n");
        out.write("    });\n");
        out.write("</script>\n");
        out.write("</body>\n");
        out.write("</html>");
    } catch (java.lang.Throwable t) {
        if (!(t instanceof javax.servlet.jsp.SkipPageException)) {
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0)
                try {
                    if (response.isCommitted()) {
                        out.flush();
                    } else {
                        out.clearBuffer();
                    }
                } catch (java.io.IOException e) {
                }
            if (_jspx_page_context != null)
                _jspx_page_context.handlePageException(t);
            else
                throw new ServletException(t);
        }
    } finally {
        _jspxFactory.releasePageContext(_jspx_page_context);
    }
}

From source file:com.alfaariss.oa.authentication.remote.saml2.profile.sp.sso.SPSingleLogout.java

private void processSAMLRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws OAException {
    SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> context = null;
    String sBindingURI = null;//ww w  .  ja  v a2s . c  o m
    try {
        //Decode message
        AbstractDecodingFactory decFactory = AbstractDecodingFactory.resolveInstance(servletRequest,
                servletResponse, _bindingProperties);
        if (decFactory == null) {
            _logger.debug("Decoding factory not created: Invalid request");
            throw new MessageDecodingException("Could not determine binding");
        }

        SAMLMessageDecoder decoder = decFactory.getDecoder();
        sBindingURI = decoder.getBindingURI();

        if (!_bindingProperties.isSupported(sBindingURI)) {
            _logger.error("The binding is not supported by this protocol: " + sBindingURI);
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        _logger.debug("Binding URI: " + sBindingURI);

        context = decFactory.getContext();
        context.setLocalEntityId(_sEntityID);
        context.setLocalEntityMetadata(_entityDescriptor);
        context.setLocalEntityRoleMetadata(_spSSODescriptor);

        String val = servletRequest.getParameter("SAMLart");
        if (val != null) {
            //SAML artifact received, requestor metadata and IssuerID must be added
            //in order to enable the decoder to decode artifact

            byte[] bb = Base64.decode(val);
            SAML2ArtifactType0004 b = null;
            SAML2ArtifactType0004Builder bf = new SAML2ArtifactType0004Builder();
            b = bf.buildArtifact(bb);

            IIDP org = _idpStorageManager.getIDP(b.getSourceID(), SAML2IDP.TYPE_SOURCEID);
            if (org != null && org instanceof SAML2IDP) {
                SAML2IDP saml2IDP = (SAML2IDP) org;
                context.setMetadataProvider(saml2IDP.getMetadataProvider());
                context.setInboundMessageIssuer(saml2IDP.getID());
                context.setOutboundMessageIssuer(_sEntityID);
            } else {
                StringBuffer sbDebug = new StringBuffer("Unknown organization specified with with SourceID '");
                sbDebug.append(Arrays.toString(b.getSourceID()));
                sbDebug.append("' in artifact: ");
                sbDebug.append(val);
                _logger.debug(sbDebug.toString());
                throw new MessageDecodingException("Could not find metadata for decoding artifact");
            }
        }

        //Decode request
        try {
            decoder.decode(context);
        } catch (SecurityException e) {
            _logger.debug("Could not decode inbound message due to security exception", e);
            throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
        }

        //verify saml message in request
        SignableSAMLObject requestMessage = context.getInboundSAMLMessage();

        if (_logger.isDebugEnabled()) {
            if (requestMessage != null)
                logXML(requestMessage);
        }

        if (requestMessage instanceof LogoutResponse) {
            processLogoutResponse(servletRequest, servletResponse, context, (LogoutResponse) requestMessage);
        } else if (requestMessage instanceof LogoutRequest) {
            //DD <LogoutRequest> signing is forced by code for HTTP POST or Redirect binding [saml-profiles-2.0-os r1223].
            boolean bMandatorySinging = sBindingURI.equals(SAMLConstants.SAML2_POST_BINDING_URI)
                    || sBindingURI.equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI);

            HTTPInTransport inTransport = (HTTPInTransport) context.getInboundMessageTransport();
            String sigParam = inTransport.getParameterValue("Signature");
            boolean bSigned = !DatatypeHelper.isEmpty(sigParam) || requestMessage.isSigned();

            if (bMandatorySinging && !bSigned) {
                _logger.debug("LogoutRequest MUST be signed if the HTTP POST or Redirect binding is used");
                throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
            }

            LogoutRequest lr = (LogoutRequest) requestMessage;
            String sReason = lr.getReason();

            processLogoutRequest(servletRequest, servletResponse, context, sBindingURI, sReason);
        } else {
            _logger.debug(
                    "Unsupported SAML message in request from issuer: " + context.getInboundMessageIssuer());
            throw new MessageDecodingException("Unsupported SAML message");
        }
    } catch (StatusException e) //SAML processing error
    {
        _eventLogger.info(new RequestorEventLogItem(null, null, null, e.getEvent(), null,
                servletRequest.getRemoteAddr(), e.getRequestorID(), this, e.getMessage()));

        sendResponse(context, servletRequest, servletResponse, sBindingURI);
    } catch (MessageDecodingException e) //Binding processing error  
    {
        _logger.debug("Decoding error", e);
        _eventLogger.info(new RequestorEventLogItem(null, null, null, RequestorEvent.REQUEST_INVALID, null,
                servletRequest.getRemoteAddr(), null, this, null));
        if (sBindingURI != null && sBindingURI.equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) {
            SOAP11Utils.sendSOAPFault(context, RequestorEvent.REQUEST_INVALID);
        } else {
            try {
                if (!servletResponse.isCommitted())
                    servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } catch (IOException e1) {
                _logger.warn("Could not send response", e1);
            }
        }
    } catch (SAML2SecurityException e) {//The message does not meet the required security constraints
        _logger.debug("Security error", e);
        _eventLogger.info(new RequestorEventLogItem(null, null, null, e.getEvent(), null,
                servletRequest.getRemoteAddr(), null, this, "Security Fault"));

        //DD Security error -> Return a "403 Forbidden" response
        try {
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (IOException e1) {
            _logger.warn("Could not send response", e1);
        }
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not process SAML request message", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}