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.displaytag.tags.TableTag.java

/**
 * Will write the export. The default behavior is to write directly to the response. If the ResponseOverrideFilter
 * is configured for this request, will instead write the exported content to a map in the Request object.
 * // ww w .j ava 2 s. c om
 * @param exportView export view
 * @throws JspException for problem in clearing the response or for invalid export views
 * @throws IOException exception thrown when writing content to the response
 */
protected void writeExport(ExportView exportView) throws IOException, JspException {
    String filename = this.properties.getExportFileName(this.currentMediaType);

    HttpServletResponse response = (HttpServletResponse) this.pageContext.getResponse();
    HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();

    Map bean = (Map) request.getAttribute(FILTER_CONTENT_OVERRIDE_BODY);
    boolean usingFilter = bean != null;

    String mimeType = exportView.getMimeType();
    // original encoding, be sure to add it back after reset()
    String characterEncoding = response.getCharacterEncoding();

    if (usingFilter) {
        if (!bean.containsKey(TableTagParameters.BEAN_BUFFER)) {
            // We are running under the export filter, call it
            log.debug("Exportfilter enabled in unbuffered mode, setting headers");
            response.addHeader(TableTagParameters.PARAMETER_EXPORTING, TagConstants.EMPTY_STRING);
        } else {
            // We are running under the export filter in buffered mode
            bean.put(TableTagParameters.BEAN_CONTENTTYPE, mimeType);
            bean.put(TableTagParameters.BEAN_FILENAME, filename);

            if (exportView instanceof TextExportView) {
                StringWriter writer = new StringWriter();
                ((TextExportView) exportView).doExport(writer);
                bean.put(TableTagParameters.BEAN_BODY, writer.toString());
            } else if (exportView instanceof BinaryExportView) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                ((BinaryExportView) exportView).doExport(stream);
                bean.put(TableTagParameters.BEAN_BODY, stream.toByteArray());

            } else {
                throw new JspTagException("Export view " + exportView.getClass().getName()
                        + " must implement TextExportView or BinaryExportView");
            }

            return;
        }
    } else {
        log.debug("Exportfilter NOT enabled");
        // response can't be already committed at this time
        if (response.isCommitted()) {
            throw new ExportException(this.getClass());
        }

        try {
            response.reset();
            this.pageContext.getOut().clearBuffer();
        } catch (Exception e) {
            throw new ExportException(this.getClass());
        }
    }

    if (!usingFilter && characterEncoding != null && mimeType.indexOf("charset") == -1) //$NON-NLS-1$
    {
        mimeType += "; charset=" + characterEncoding; //$NON-NLS-1$
    }

    response.setContentType(mimeType);

    if (StringUtils.isNotEmpty(filename)) {
        response.setHeader("Content-Disposition", //$NON-NLS-1$
                "attachment; filename=\"" + filename + "\""); //$NON-NLS-1$ //$NON-NLS-2$
    }

    if (exportView instanceof TextExportView) {
        Writer writer;
        if (usingFilter) {
            writer = response.getWriter();
        } else {
            writer = this.pageContext.getOut();
        }

        ((TextExportView) exportView).doExport(writer);
    } else if (exportView instanceof BinaryExportView) {
        // dealing with binary content
        // note that this is not assured to work on any application server
        // if the filter is not enabled. According
        // to the jsp specs response.getOutputStream() should no be called
        // in jsps.
        ((BinaryExportView) exportView).doExport(response.getOutputStream());
    } else {
        throw new JspTagException("Export view " + exportView.getClass().getName()
                + " must implement TextExportView or BinaryExportView");
    }

    log.debug("Export completed");

}

From source file:com.alfaariss.oa.sso.web.profile.logout.LogoutProfile.java

/**
 * @see com.alfaariss.oa.api.IService#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///w w w . j a v  a 2  s.c o m
@Override
public void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws OAException {
    try {
        //Disable caching
        HttpUtils.setDisableCachingHttpHeaders(servletRequest, servletResponse);

        ISession session = (ISession) servletRequest.getAttribute(ISession.ID_NAME);
        if (session == null) {
            String sId = servletRequest.getParameter(ISession.ID_NAME);
            if (sId != null) {
                if (!SessionValidator.validateDefaultSessionId(sId)) {
                    _logger.warn("Invalid session id in request: " + sId);
                    throw new UserException(UserEvent.REQUEST_INVALID);
                }
                session = _sessionFactory.retrieve(sId);
            } else
                _logger.debug("No session attribute and no session id supplied in request");
        }

        String sTarget = resolveTarget(servletRequest);
        if (sTarget != null) {
            if (sTarget.equalsIgnoreCase(TARGET_LOGOUT_STATE)) {
                _logger.debug("Performing 'logout state' request");
                processLogoutState(servletResponse, session);
                return;
            } else if (sTarget.equalsIgnoreCase(TARGET_LOGOUT_FORCE)) {
                _logger.debug(
                        "Performing 'forced logout' request sent from IP: " + servletRequest.getRemoteAddr());
                processForceLogout(servletRequest, servletResponse, session);
                return;
            }
        }

        if (session == null) {
            _logger.debug("No valid session found");
            throw new UserException(UserEvent.REQUEST_INVALID);
        }

        _logger.debug("Performing 'logout' request sent from IP: " + servletRequest.getRemoteAddr());

        switch (session.getState()) {
        case USER_LOGOUT_IN_PROGRESS: {//logout at remote authn not finished yet
            finishFederativeLogout(servletRequest, servletResponse, session);
            break;
        }
        case USER_LOGOUT_FAILED:
        case USER_LOGOUT_PARTIAL: {//already failed, only remove what can be removed
            processForceLogout(servletRequest, servletResponse, session);
            break;
        }
        case USER_LOGOUT_SUCCESS: {//remote logout finished, do local logout
            processLocalLogout(servletRequest, servletResponse, session, null);
            break;
        }
        case USER_CANCELLED: {
            _logger.debug(new SystemLogItem(session.getId(), SystemErrors.OK, "Redirect back to Profile"));
            servletResponse.sendRedirect(session.getProfileURL());
            break;
        }
        default: {//check what needs to be done
            processDefault(servletRequest, servletResponse, session);
        }
        }
    } catch (UserException e) {
        try {
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException e1) {
            _logger.debug("Could not respond", e1);
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not perform logout request", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:org.apache.roller.weblogger.ui.rendering.servlets.PreviewServlet.java

/**
 * Handle GET requests for weblog pages.
 *///from w  w  w  . j av a2  s .  c om
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("Entering");

    Weblog weblog = null;

    WeblogPreviewRequest previewRequest = null;

    String type = null;

    try {
        previewRequest = new WeblogPreviewRequest(request);

        // type of the page we are going to preview
        type = previewRequest.getType();

        // lookup weblog specified by preview request
        weblog = previewRequest.getWeblog();
        if (weblog == null) {
            throw new WebloggerException("unable to lookup weblog: " + previewRequest.getWeblogHandle());
        }
    } catch (Exception e) {
        // some kind of error parsing the request or getting weblog
        log.debug("error creating preview request", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Get the deviceType from user agent
    MobileDeviceRepository.DeviceType deviceType = MobileDeviceRepository.getRequestType(request);

    // for previews we explicitly set the deviceType attribute
    if (request.getParameter("type") != null) {
        deviceType = request.getParameter("type").equals("standard")
                ? MobileDeviceRepository.DeviceType.standard
                : MobileDeviceRepository.DeviceType.mobile;
    }

    Weblog tmpWebsite = weblog;

    if (previewRequest.getThemeName() != null) {
        // only create temporary weblog object if theme name was specified
        // in request, which indicates we're doing a theme preview

        // try getting the preview theme
        log.debug("preview theme = " + previewRequest.getThemeName());
        Theme previewTheme = previewRequest.getTheme();

        // construct a temporary Website object for this request
        // and set the EditorTheme to our previewTheme
        tmpWebsite = new Weblog();
        tmpWebsite.setData(weblog);
        if (previewTheme != null && previewTheme.isEnabled()) {
            tmpWebsite.setEditorTheme(previewTheme.getId());
        } else if (WeblogTheme.CUSTOM.equals(previewRequest.getThemeName())) {
            tmpWebsite.setEditorTheme(WeblogTheme.CUSTOM);
        }

        // we've got to set the weblog in our previewRequest because that's
        // the object that gets referenced during rendering operations
        previewRequest.setWeblog(tmpWebsite);
    }

    // do we need to force a specific locale for the request?
    if (previewRequest.getLocale() == null && !weblog.isShowAllLangs()) {
        previewRequest.setLocale(weblog.getLocale());
    }

    Template page = null;
    if ("page".equals(previewRequest.getContext())) {
        page = previewRequest.getWeblogPage();

        // If request specified tags section index, then look for custom template
    } else if ("tags".equals(previewRequest.getContext()) && previewRequest.getTags() == null) {
        try {
            page = weblog.getTheme().getTemplateByAction(ThemeTemplate.ACTION_TAGSINDEX);
        } catch (Exception e) {
            log.error("Error getting weblog page for action 'tagsIndex'", e);
        }

        // if we don't have a custom tags page then 404, we don't let
        // this one fall through to the default template
        if (page == null) {
            if (!response.isCommitted())
                response.reset();
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // If this is a permalink then look for a permalink template
    } else if (previewRequest.getWeblogAnchor() != null) {
        try {
            page = weblog.getTheme().getTemplateByAction(ThemeTemplate.ACTION_PERMALINK);
        } catch (Exception e) {
            log.error("Error getting weblog page for action 'permalink'", e);
        }
    }

    if (page == null) {
        try {
            page = tmpWebsite.getTheme().getDefaultTemplate();
        } catch (WebloggerException re) {
            log.error("Error getting default page for preview", re);
        }
    }

    // Still no page?  Then that is a 404
    if (page == null) {
        if (!response.isCommitted())
            response.reset();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    log.debug("preview page found, dealing with it");

    // set the content type
    String pageLink = previewRequest.getWeblogPageName();
    String mimeType = pageLink != null ? RollerContext.getServletContext().getMimeType(pageLink) : null;
    String contentType = "text/html; charset=utf-8";
    if (mimeType != null) {
        // we found a match ... set the content type
        contentType = mimeType + "; charset=utf-8";
    } else if ("_css".equals(previewRequest.getWeblogPageName())) {
        // TODO: store content-type for each page so this hack is unnecessary
        contentType = "text/css; charset=utf-8";
    }

    // looks like we need to render content
    Map model = new HashMap();
    try {
        PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, request, response, "",
                false, 8192, true);

        // special hack for menu tag
        request.setAttribute("pageRequest", previewRequest);

        // populate the rendering model
        Map initData = new HashMap();
        initData.put("parsedRequest", previewRequest);
        initData.put("pageContext", pageContext);

        // define url strategy
        initData.put("urlStrategy", WebloggerFactory.getWeblogger().getUrlStrategy()
                .getPreviewURLStrategy(previewRequest.getThemeName()));

        // Load models for page previewing
        String pageModels = WebloggerConfig.getProperty("rendering.previewModels");
        ModelLoader.loadModels(pageModels, model, initData, true);

        // Load special models for site-wide blog
        if (WebloggerRuntimeConfig.isSiteWideWeblog(weblog.getHandle())) {
            String siteModels = WebloggerConfig.getProperty("rendering.siteModels");
            ModelLoader.loadModels(siteModels, model, initData, true);
        }

        // Load weblog custom models
        ModelLoader.loadCustomModels(weblog, model, initData);

        // ick, gotta load pre-3.0 model stuff as well :(
        ModelLoader.loadOldModels(model, request, response, pageContext, previewRequest, WebloggerFactory
                .getWeblogger().getUrlStrategy().getPreviewURLStrategy(previewRequest.getThemeName()));

    } catch (WebloggerException ex) {
        log.error("ERROR loading model for page", ex);

        if (!response.isCommitted())
            response.reset();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // lookup Renderer we are going to use
    Renderer renderer = null;
    try {
        log.debug("Looking up renderer");
        renderer = RendererManager.getRenderer(page, deviceType);
    } catch (Exception e) {
        // nobody wants to render my content :(
        log.error("Couldn't find renderer for page " + page.getId(), e);

        if (!response.isCommitted())
            response.reset();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // render content.  use default size of about 24K for a standard page
    CachedContent rendererOutput = new CachedContent(24567);
    try {
        log.debug("Doing rendering");
        renderer.render(model, rendererOutput.getCachedWriter());

        // flush rendered output and close
        rendererOutput.flush();
        rendererOutput.close();
    } catch (Exception e) {
        // bummer, error during rendering
        log.error("Error during rendering for page " + page.getId(), e);

        if (!response.isCommitted())
            response.reset();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // post rendering process

    // flush rendered content to response
    log.debug("Flushing response output");
    response.setContentType(contentType);
    response.setContentLength(rendererOutput.getContent().length);
    response.getOutputStream().write(rendererOutput.getContent());

    log.debug("Exiting");
}

From source file:com.alfaariss.oa.OAServlet.java

/**
 * Process HTTP requests.//from  w  w w  . j  a v a 2  s .  co m
 * 
 * Retrieve an enabled requestor profile or helper for the given request 
 * and delegate the request using the following algorithm:
 * 
 * <dl>
 *  <dt>type (helper or profile)</dt>
 *  <dd>{@link HttpServletRequest#getRequestURI()} from 
 *      {@link HttpServletRequest#getContextPath()} till '/' minus slashes</dd>
 *  <dt>id of helper or profile</dt>
 *  <dd>{@link HttpServletRequest#getRequestURI()} 
 *      first '/' till second '/' minus slashes</dd>
 * </dl>
 * 
 * @see javax.servlet.http.HttpServlet#service(
 *  javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
public void service(HttpServletRequest oRequest, HttpServletResponse oResponse)
        throws ServletException, IOException {
    try {
        String sRequestURI = oRequest.getRequestURI();

        //Check if profiles are available
        if (_profiles.isEmpty() && _helpers.isEmpty())
            oResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sRequestURI);

        //Retrieve profile
        String sContextPath = oRequest.getContextPath();
        String sServletPath = oRequest.getServletPath();

        //type = uri  - context
        String sType = sRequestURI.substring(sContextPath.length());
        if (sType.length() <= 1) {
            //No profile or helper requested
            oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } else {
            //type minus slashes 
            sType = sType.substring(1, sType.length());
            int index = sType.indexOf('/');
            if (index <= 1) {
                _logger.debug("Bad request: no id in path: " + sServletPath);
                //No id requested
                oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } else {

                String sId = sType.substring(index + 1, sType.length()); //id minus slashes 
                sType = sType.substring(0, index);
                if (_logger.isDebugEnabled())
                    _logger.debug("Processing: " + sType + " request");

                //sId = sId.substring(1, sId.length());
                index = sId.indexOf('/');
                if (index > 0) {
                    //remove suffix
                    sId = sId.substring(0, index);
                }

                try {
                    ServiceTypes type = ServiceTypes.valueOf(sType);
                    switch (type) {
                    case helpers: {
                        IHelper helper = _helpers.get(sId);
                        if (helper == null || !(helper instanceof IService))
                            oResponse.sendError(HttpServletResponse.SC_NOT_FOUND, sRequestURI);
                        else if (!helper.isEnabled())
                            oResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sRequestURI);
                        else
                            ((IService) helper).service(oRequest, oResponse);
                        break;
                    }
                    case profiles: {
                        IRequestorProfile profile = _profiles.get(sId);
                        if (profile == null || !(profile instanceof IService))
                            oResponse.sendError(HttpServletResponse.SC_NOT_FOUND, sRequestURI);
                        else
                            ((IService) profile).service(oRequest, oResponse);
                        break;
                    }
                    }
                } catch (IllegalArgumentException e) {
                    _logger.debug("Bad request", e);
                    //Invalid type requested
                    oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
                } catch (NullPointerException e) {
                    _logger.debug("Bad request", e);
                    //No type requested
                    oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
                }
            }
        }

        //send okay if no response is sent yet
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_OK);
    } catch (OAException e) {
        _logger.error("Could not process request", e);
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        _logger.fatal("Could not process request due to internal error", e);
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.alfaariss.oa.authentication.remote.saml2.profile.re.ResponseEndpoint.java

/**
 * @see com.alfaariss.oa.util.saml2.profile.ISAML2Profile#process(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*  ww  w .  jav a  2 s .  com*/
public void process(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws OAException {
    String sURL = servletRequest.getRequestURL().toString();

    if (sURL.endsWith("/"))
        sURL = sURL.substring(0, sURL.length() - 1);
    _logger.debug("Servicing response: " + sURL);

    try {
        if (sURL.endsWith(REDIRECTER)) {
            processRedirect(servletRequest, servletResponse);
        } else {
            AbstractDecodingFactory decFactory = AbstractDecodingFactory.resolveInstance(servletRequest,
                    servletResponse, _bindingProperties);

            if (decFactory == null) {
                _logger.error("No decode factory available for request");
                throw new OAException(SystemErrors.ERROR_INTERNAL);
            }

            SAMLMessageDecoder decoder = decFactory.getDecoder();

            //check all supported bindings
            String sBindingURI = decoder.getBindingURI();
            if (!_bindingProperties.isSupported(sBindingURI)) {
                _logger.error("The binding is not supported by this protocol: " + sBindingURI);
                throw new OAException(SystemErrors.ERROR_INTERNAL);
            }

            //decode request
            SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> context = decFactory
                    .getContext();

            //use metadata from requestors to set chainedMetadataProvider for current
            //issuer

            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 context
            decoder.decode(context);

            processResponse(servletRequest, servletResponse, context);
        }
    } catch (MessageDecodingException e) {
        _logger.debug("Could not decode XML in SAML request message", e);
        try {
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException e1) {
            _logger.warn("Could not send response", e1);
        }
    } catch (SecurityException e) {
        _logger.debug("the decoded message does not meet the required security constraints", e);
        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);
    }
}

From source file:org.hoteia.qalingo.core.web.mvc.controller.oauth.CallBackOAuthYahooController.java

@RequestMapping("/callback-oauth-yahoo.html*")
public ModelAndView callBackYahoo(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    final RequestData requestData = requestUtil.getRequestData(request);

    // SANITY CHECK
    if (!requestUtil.hasKnownCustomerLogged(request)) {
        try {//from   www.j a  v a  2  s .c o m

            // CLIENT ID
            EngineSetting clientIdEngineSetting = engineSettingService.getSettingOAuthAppKeyOrId();
            EngineSettingValue clientIdEngineSettingValue = clientIdEngineSetting
                    .getEngineSettingValue(OAuthType.YAHOO.name());

            // CLIENT SECRET
            EngineSetting clientSecretEngineSetting = engineSettingService.getSettingOAuthAppSecret();
            EngineSettingValue clientSecretEngineSettingValue = clientSecretEngineSetting
                    .getEngineSettingValue(OAuthType.YAHOO.name());

            if (clientIdEngineSettingValue != null && clientSecretEngineSetting != null) {
                final String clientId = clientIdEngineSettingValue.getValue();
                final String clientSecret = clientSecretEngineSettingValue.getValue();

                final String yahooCallBackURL = urlService.buildAbsoluteUrl(requestData, urlService
                        .buildOAuthCallBackUrl(requestData, OAuthType.YAHOO.getPropertyKey().toLowerCase()));

                OAuthService service = new ServiceBuilder().provider(YahooApi.class).apiKey(clientId)
                        .apiSecret(clientSecret).callback(yahooCallBackURL).build();

                final String code = request.getParameter(REQUEST_PARAM_OAUTH_VERIFIER);
                if (StringUtils.isNotEmpty(code)) {
                    Verifier verifier = new Verifier(code);
                    Token requestToken = (Token) request.getSession().getAttribute(YAHOO_OAUTH_REQUEST_TOKEN);

                    Token accessToken = service.getAccessToken(requestToken, verifier);
                    String rowResponse = accessToken.getRawResponse();
                    String[] split = rowResponse.split("&");
                    String userGuid = null;
                    if (split.length > 0) {
                        for (String value : split) {
                            if (value.contains("xoauth_yahoo_guid") && value.contains("=")) {
                                userGuid = value.split("=")[1];
                            }
                        }
                    }
                    if (StringUtils.isNotEmpty(userGuid)) {
                        OAuthRequest oauthRequest = new OAuthRequest(Verb.GET,
                                "https://social.yahooapis.com/v1/user/" + userGuid + "/profile?format=json");
                        service.signRequest(accessToken, oauthRequest);
                        Response oauthResponse = oauthRequest.send();
                        int responseCode = oauthResponse.getCode();
                        String responseBody = oauthResponse.getBody();

                        if (responseCode == 200) {
                            handleAuthenticationData(request, response, requestData, OAuthType.YAHOO,
                                    responseBody);
                        } else {
                            logger.error("Callback With " + OAuthType.YAHOO.name() + " failed!");
                        }
                    }

                } else {
                    logger.error("Callback With " + OAuthType.YAHOO.name() + " failed!");
                }
            }

        } catch (Exception e) {
            logger.error("Callback With " + OAuthType.YAHOO.name() + " failed!");
        }
    }

    // DEFAULT FALLBACK VALUE
    if (!response.isCommitted()) {
        response.sendRedirect(urlService.generateUrl(FoUrls.LOGIN, requestData));
    }

    return null;
}

From source file:org.kimios.front.MainController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String action = request.getParameter("servlet");

    /*//from www  . j av a 2 s .  c om
     * Not move this line after the upload manager process, or the document version handler
     */
    response.setContentType("application/json");
    Cookie sess = null;
    Cookie lang = null;
    try {
        sess = getCookie(request, "sessionUid");

    } catch (Exception e) {
        log.error("No session cookie", e);
    }
    try {
        lang = getCookie(request, "lang");

    } catch (Exception e) {
        log.error("No lang cookie", e);
    }
    String sessionUid = (sess != null ? sess.getValue() : null);
    String langSelected = (lang != null ? lang.getValue() : "en");
    String json = "";
    Controller c = null;
    boolean login = false;
    Map<String, String> params = ParametersExtractor.getParams(request);
    params.put("selected_lang", langSelected);
    try {
        if (action.equalsIgnoreCase("Uploader")) {
            c = new UploadManager(params, request, response);
        }
        if (action.equalsIgnoreCase("DmsEntity")) {
            c = new DmEntityControllerWeb(params);
        }
        if (action.equalsIgnoreCase("DmsMeta")) {
            c = new MetaControllerWeb(params);
        }
        if (action.equalsIgnoreCase("DmsTree")) {
            TreeControllerWeb.contextPath = request.getContextPath();
            c = new TreeControllerWeb(params);
        }
        if (action.equalsIgnoreCase("DmsSecurity")) {
            c = new SecurityControllerWeb(params);
        }
        if (action.equalsIgnoreCase("DmsExtension")) {
            c = new ExtensionControllerWeb(params);
        }
        if (action.equalsIgnoreCase("DocumentVersion")) {
            c = new DocumentVersionActionHandler(params, response);
        }
        if (action.equalsIgnoreCase("Version")) {
            c = new DocumentActionHandler(params);
        }
        if (action.equalsIgnoreCase("Folder")) {
            c = new FolderActionHandler(params);
        }
        if (action.equalsIgnoreCase("Search")) {
            c = new SearchControllerWeb(params);
        }
        if (action.equalsIgnoreCase("Workspace")) {
            c = new WorkspaceActionHandler(params);
        }
        if (action.equalsIgnoreCase("Security")) {
            c = new AuthenticationControllerWeb(params);
            try {
                login = params.get("action").equals("login");
            } catch (Exception e) {
                login = false;
            }
        }
        if (action.equalsIgnoreCase("Workflow")) {
            c = new WorkflowControllerWeb(params);
        }
        if (action.equalsIgnoreCase("Admin")) {
            c = new AdminControllerWeb(params);
        }
        if (action.equalsIgnoreCase("Studio")) {
            c = new StudioControllerWeb(params);
        }
        if (action.equalsIgnoreCase("Reporting")) {
            c = new ReportingControllerWeb(params);
        }
        if (action.equalsIgnoreCase("Log")) {
            c = new LogControllerWeb(params);
        }
        if (action.equalsIgnoreCase("Lang")) {
            c = new InternationalizationControllerWeb(params);
            ((InternationalizationControllerWeb) c).setResponse(response);
        }
        if (login) {
            sessionUid = c.execute();
            request.getSession().setAttribute("sessionUid", sessionUid);
            response.addCookie(new Cookie("sessionUid", sessionUid));
            json = "{success:true,sessionUid:\"" + sessionUid + "\"}";
            response.getWriter().write(json);
        } else {
            if (!response.isCommitted()) {
                c.setSessionUid(sessionUid);
                json = c.execute();
                log.debug("JSON " + json);
                if (!json.equals("downloadaction"))
                    response.getWriter().write(json);
            }
        }
    } catch (Exception e) {
        log.error("Error ", e);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        json = "{success:false,exception:\"" + StringEscapeUtils.escapeJava(e.getMessage()) + "\",trace:\""
                + StringEscapeUtils.escapeJava(sw.toString()) + "\"}";
        log.debug("JSON " + json);
        response.getWriter().write(json);
    }
}

From source file:org.apache.roller.weblogger.ui.rendering.servlets.PreviewResourceServlet.java

/**
 * Handles requests for user uploaded resources.
 */// w  ww.j a  v a  2  s. com
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Weblog weblog = null;
    String ctx = request.getContextPath();
    String servlet = request.getServletPath();
    String reqURI = request.getRequestURI();

    WeblogPreviewResourceRequest resourceRequest = null;
    try {
        // parse the incoming request and extract the relevant data
        resourceRequest = new WeblogPreviewResourceRequest(request);

        weblog = resourceRequest.getWeblog();
        if (weblog == null) {
            throw new WebloggerException("unable to lookup weblog: " + resourceRequest.getWeblogHandle());
        }

    } catch (Exception e) {
        // invalid resource request or weblog doesn't exist
        log.debug("error creating weblog resource request", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    log.debug("Resource requested [" + resourceRequest.getResourcePath() + "]");

    long resourceLastMod = 0;
    InputStream resourceStream = null;

    // first, see if we have a preview theme to operate from
    if (!StringUtils.isEmpty(resourceRequest.getThemeName())) {
        Theme theme = resourceRequest.getTheme();
        ThemeResource resource = theme.getResource(resourceRequest.getResourcePath());
        if (resource != null) {
            resourceLastMod = resource.getLastModified();
            resourceStream = resource.getInputStream();
        }
    }

    // second, see if resource comes from weblog's configured shared theme
    if (resourceStream == null) {
        try {
            WeblogTheme weblogTheme = weblog.getTheme();
            if (weblogTheme != null) {
                ThemeResource resource = weblogTheme.getResource(resourceRequest.getResourcePath());
                if (resource != null) {
                    resourceLastMod = resource.getLastModified();
                    resourceStream = resource.getInputStream();
                }
            }
        } catch (Exception ex) {
            // hmmm, some kind of error getting theme.  that's an error.
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    }

    // if not from theme then see if resource is in weblog's upload dir
    if (resourceStream == null) {
        try {
            MediaFileManager mmgr = WebloggerFactory.getWeblogger().getMediaFileManager();
            MediaFile mf = mmgr.getMediaFileByOriginalPath(weblog, resourceRequest.getResourcePath());
            resourceLastMod = mf.getLastModified();
            resourceStream = mf.getInputStream();

        } catch (Exception ex) {
            // still not found? then we don't have it, 404.
            log.debug("Unable to get resource", ex);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }

    // Respond with 304 Not Modified if it is not modified.
    if (ModDateHeaderUtil.respondIfNotModified(request, response, resourceLastMod)) {
        return;
    } else {
        // set last-modified date
        ModDateHeaderUtil.setLastModifiedHeader(response, resourceLastMod);
    }

    // set the content type based on whatever is in our web.xml mime defs
    response.setContentType(this.context.getMimeType(resourceRequest.getResourcePath()));

    OutputStream out = null;
    try {
        // ok, lets serve up the file
        byte[] buf = new byte[8192];
        int length = 0;
        out = response.getOutputStream();
        while ((length = resourceStream.read(buf)) > 0) {
            out.write(buf, 0, length);
        }

        // cleanup
        out.close();
        resourceStream.close();

    } catch (Exception ex) {
        log.error("Error writing resource file", ex);
        if (!response.isCommitted()) {
            response.reset();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}

From source file:org.apache.roller.weblogger.ui.rendering.servlets.PlanetFeedServlet.java

/**
 * Handle GET requests for weblog pages.
 *///from   w w  w  .  jav  a 2  s  .c  om
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("Entering");

    PlanetManager planet = PlanetFactory.getPlanet().getPlanetManager();

    PlanetRequest planetRequest = null;
    try {
        planetRequest = new PlanetRequest(request);
    } catch (Exception e) {
        // some kind of error parsing the request
        log.debug("error creating planet request", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // figure planet last modified date
    Date lastModified = planetCache.getLastModified();

    // Respond with 304 Not Modified if it is not modified.
    if (ModDateHeaderUtil.respondIfNotModified(request, response, lastModified.getTime())) {
        return;
    }

    // set content type
    String accepts = request.getHeader("Accept");
    String userAgent = request.getHeader("User-Agent");
    if (accepts != null && userAgent != null && accepts.indexOf("*/*") != -1
            && userAgent.startsWith("Mozilla")) {
        // client is a browser and now that we offer styled feeds we want
        // browsers to load the page rather than popping up the download
        // dialog, so we provide a content-type that browsers will display
        response.setContentType("text/xml");
    } else {
        response.setContentType("application/rss+xml; charset=utf-8");
    }

    // set last-modified date
    ModDateHeaderUtil.setLastModifiedHeader(response, lastModified.getTime());

    // cached content checking
    String cacheKey = PlanetCache.CACHE_ID + ":" + this.generateKey(planetRequest);
    CachedContent entry = (CachedContent) planetCache.get(cacheKey);
    if (entry != null) {
        response.setContentLength(entry.getContent().length);
        response.getOutputStream().write(entry.getContent());
        return;
    }

    // looks like we need to render content
    @SuppressWarnings("unchecked")
    HashMap<String, Object> model = new HashMap();
    try {
        // populate the rendering model
        if (request.getParameter("group") != null) {
            Planet planetObject = planet.getPlanet("default");
            model.put("group", planet.getGroup(planetObject, request.getParameter("group")));
        }
        model.put("planet", planet);
        model.put("date", new Date());
        model.put("utils", new UtilitiesModel());
        model.put("siteName", PlanetRuntimeConfig.getProperty("site.name"));
        model.put("siteDescription", PlanetRuntimeConfig.getProperty("site.description"));
        model.put("lastModified", lastModified);
        if (StringUtils.isNotEmpty(PlanetRuntimeConfig.getProperty("site.absoluteurl"))) {
            model.put("absoluteSite", PlanetRuntimeConfig.getProperty("site.absoluteurl"));
        } else {
            model.put("absoluteSite", WebloggerRuntimeConfig.getAbsoluteContextURL());
        }
        model.put("feedStyle",
                new Boolean(WebloggerRuntimeConfig.getBooleanProperty("site.newsfeeds.styledFeeds")));

        int numEntries = WebloggerRuntimeConfig.getIntProperty("site.newsfeeds.defaultEntries");
        int entryCount = numEntries;
        String sCount = request.getParameter("count");
        if (sCount != null) {
            try {
                entryCount = Integer.parseInt(sCount);
            } catch (NumberFormatException e) {
                log.warn("Improperly formatted count parameter");
            }
            if (entryCount > numEntries) {
                entryCount = numEntries;
            }
            if (entryCount < 0) {
                entryCount = 0;
            }
        }
        model.put("entryCount", new Integer(entryCount));
    } catch (Exception ex) {
        log.error("Error loading model objects for page", ex);

        if (!response.isCommitted()) {
            response.reset();
        }
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // lookup Renderer we are going to use
    Renderer renderer = null;
    try {
        log.debug("Looking up renderer");
        Template template = new StaticTemplate("templates/planet/planetrss.vm", "velocity");
        renderer = RendererManager.getRenderer(template, DeviceType.mobile);
    } catch (Exception e) {
        // nobody wants to render my content :(
        log.error("Couldn't find renderer for planet rss", e);

        if (!response.isCommitted()) {
            response.reset();
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // render content.  use default size of about 24K for a standard page
    CachedContent rendererOutput = new CachedContent(24567);
    try {
        log.debug("Doing rendering");
        renderer.render(model, rendererOutput.getCachedWriter());

        // flush rendered output and close
        rendererOutput.flush();
        rendererOutput.close();
    } catch (Exception e) {
        // bummer, error during rendering
        log.error("Error during rendering for planet rss", e);

        if (!response.isCommitted()) {
            response.reset();
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // post rendering process
    // flush rendered content to response
    log.debug("Flushing response output");
    response.setContentLength(rendererOutput.getContent().length);
    response.getOutputStream().write(rendererOutput.getContent());

    // cache rendered content.
    this.planetCache.put(cacheKey, rendererOutput);

    log.debug("Exiting");
}

From source file:org.cloudifysource.rest.controllers.ServiceController.java

/**
 * Exception handler for all of known internal server exceptions.
 *
 * @param response/*from   w ww.j a  va  2s .c o m*/
 *            The response object to edit, if not committed yet.
 * @param e
 *            The exception that occurred, from which data is read for logging and for the response error message.
 * @throws IOException
 *             Reporting failure to edit the response object
 */
@ExceptionHandler(RestErrorException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public void handleServerErrors(final HttpServletResponse response, final RestErrorException e)
        throws IOException {

    if (response.isCommitted()) {
        logger.log(Level.WARNING,
                "Caught exception, but response already commited. Not sending error message based on exception",
                e);
    } else {
        final Map<String, Object> errorDescriptionMap = e.getErrorDescription();
        final String errorMap = new ObjectMapper().writeValueAsString(errorDescriptionMap);
        logger.log(Level.INFO, "caught exception. Sending response message " + errorDescriptionMap.get("error"),
                e);
        final byte[] messageBytes = errorMap.getBytes();
        final ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(messageBytes);
    }
}