Example usage for javax.servlet.http HttpServletResponse SC_SEE_OTHER

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

Introduction

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

Prototype

int SC_SEE_OTHER

To view the source code for javax.servlet.http HttpServletResponse SC_SEE_OTHER.

Click Source Link

Document

Status code (303) indicating that the response to the request can be found under a different URI.

Usage

From source file:org.jahia.bin.Render.java

/**
 * This method allows you to define where you want to redirect the user after request.
 *
 * @param url//from w w  w  .  j av  a2  s .c  om
 * @param path
 * @param req
 * @param resp
 * @param parameters
 * @param bypassCache If true we will append a parameter to the URL that should match the id of the resource to refresh
 * @throws IOException
 */
public static void performRedirect(String url, String path, HttpServletRequest req, HttpServletResponse resp,
        Map<String, List<String>> parameters, boolean bypassCache) throws IOException {
    String renderedURL = null;

    List<String> stringList = parameters.get(NEW_NODE_OUTPUT_FORMAT);
    String outputFormat = !CollectionUtils.isEmpty(stringList) && stringList.get(0) != null ? stringList.get(0)
            : "html";

    stringList = parameters.get(REDIRECT_HTTP_RESPONSE_CODE);
    int responseCode = !CollectionUtils.isEmpty(stringList) && !StringUtils.isBlank(stringList.get(0))
            ? Integer.parseInt(stringList.get(0))
            : HttpServletResponse.SC_SEE_OTHER;

    stringList = parameters.get(REDIRECT_TO);
    String stayOnPage = !CollectionUtils.isEmpty(stringList) && !StringUtils.isBlank(stringList.get(0))
            ? StringUtils.substringBeforeLast(stringList.get(0), ";")
            : null;

    if (!Login.isAuthorizedRedirect(req, stayOnPage, true)) {
        logger.warn("Unauthorized attempt redirect to {}", stayOnPage);
        stayOnPage = null;
    }

    if (!StringUtils.isEmpty(stayOnPage)) {
        renderedURL = stayOnPage + (!StringUtils.isEmpty(outputFormat) ? "." + outputFormat : "");
    } else if (!StringUtils.isEmpty(url)) {
        String requestedURL = req.getRequestURI();
        //            String encodedPath = URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
        String decodedURL = URLDecoder.decode(requestedURL, "UTF-8");

        int index = decodedURL.indexOf(path);

        renderedURL = decodedURL.substring(0, index) + url
                + (!StringUtils.isEmpty(outputFormat) ? "." + outputFormat : "");
    }
    if (bypassCache) {
        stringList = parameters.get(RESOURCE_ID);
        String formuuid = !CollectionUtils.isEmpty(stringList) && !StringUtils.isBlank(stringList.get(0))
                ? stringList.get(0)
                : null;
        if (formuuid != null) {
            renderedURL = renderedURL + "?ec=" + formuuid;
        }
    }
    if (!StringUtils.isEmpty(renderedURL)) {
        String redirect = resp.encodeRedirectURL(renderedURL);
        if (SettingsBean.getInstance().isDisableJsessionIdParameter()) {
            String s = ";" + SettingsBean.getInstance().getJsessionIdParameterName();
            if (redirect.contains(s)) {
                redirect = SessionidRemovalResponseWrapper.removeJsessionId(redirect);
            }
        }
        if (StringUtils.isEmpty(stayOnPage)) {
            resp.setHeader("Location", redirect);
        } else if (responseCode == HttpServletResponse.SC_SEE_OTHER) {
            resp.setHeader("Location", redirect);
        }
        if (responseCode == HttpServletResponse.SC_FOUND) {
            resp.sendRedirect(redirect);
        } else {
            resp.setStatus(responseCode);
        }
    }
}

From source file:org.kuali.test.utils.Utils.java

public static boolean isRedirectResponse(int status) {
    return ((status == HttpServletResponse.SC_MOVED_TEMPORARILY)
            || (status == HttpServletResponse.SC_MOVED_PERMANENTLY)
            || (status == HttpServletResponse.SC_SEE_OTHER));

}

From source file:org.nema.medical.mint.server.controller.JobsController.java

@RequestMapping(method = RequestMethod.POST, value = "/jobs/createstudy")
public void createStudy(HttpServletRequest req, HttpServletResponse res) throws IOException {

    String studyUUID = UUID.randomUUID().toString();
    String jobID = UUID.randomUUID().toString();

    File jobFolder = new File(jobTemp, jobID);
    jobFolder.mkdirs();/*from   w  w  w .  j  a  v  a2  s.  c o m*/

    // the list of files uploaded
    List<File> files = new ArrayList<File>();

    // the set of form parameters
    Map<String, String> params = new HashMap<String, String>();

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "expected multipart form data");
        return;
    }

    try {
        handleUpload(req, jobFolder, files, params);
    } catch (FileUploadException e) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "unable to parse multipart form data");
        return;
    }

    Iterator<File> iterator = files.iterator();
    if (!iterator.hasNext()) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "at least one file (containing metadata) is required.");
        return;
    }

    JobInfo jobInfo = new JobInfo();
    jobInfo.setId(jobID);
    jobInfo.setStudyID(studyUUID);
    jobInfo.setStatus(JobStatus.IN_PROGRESS);
    jobInfo.setStatusDescription("0% complete");
    String jobURI = req.getContextPath() + "/jobs/status/" + jobInfo.getId();
    jobInfoDAO.saveOrUpdateJobInfo(jobInfo);

    final MetadataType dataDictionary = availableTypes.get("DICOM");

    StudyCreateProcessor processor = new StudyCreateProcessor(jobFolder, new File(studiesRoot, studyUUID),
            dataDictionary, req.getRemoteUser(), req.getRemoteHost(), jobInfoDAO, studyDAO, updateDAO);
    executor.execute(processor); // process immediately in the background

    res.setStatus(HttpServletResponse.SC_SEE_OTHER);
    res.setHeader("Location", jobURI);
}

From source file:org.nema.medical.mint.server.controller.JobsController.java

@RequestMapping(method = RequestMethod.POST, value = "/jobs/updatestudy")
public void updateStudy(HttpServletRequest req, HttpServletResponse res) throws IOException {

    String jobID = UUID.randomUUID().toString();
    File jobFolder = new File(jobTemp, jobID);
    jobFolder.mkdirs();//from ww w. j  a  v  a2  s . c  o  m

    // the list of files uploaded
    List<File> files = new ArrayList<File>();

    // the set of form parameters
    Map<String, String> params = new HashMap<String, String>();

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "expected multipart form data");
        return;
    }

    try {
        handleUpload(req, jobFolder, files, params);
    } catch (FileUploadException e) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "unable to parse multipart form data");
        return;
    }

    if (files.size() < 1) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "at least one file (containing metadata) is required.");
        return;
    }

    if (!params.containsKey(HttpMessagePart.STUDY_UUID.toString())) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing parameter " + HttpMessagePart.STUDY_UUID);
        return;
    }

    final String studyUUID = params.get(HttpMessagePart.STUDY_UUID.toString());

    final Utils.StudyStatus studyStatus = Utils.validateStudyStatus(studiesRoot, studyUUID, res, studyDAO);
    if (studyStatus != Utils.StudyStatus.OK) {
        return;
    }

    if (!params.containsKey(HttpMessagePart.OLD_VERSION.toString())) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing parameter " + HttpMessagePart.OLD_VERSION);
        return;
    }

    final String oldVersionString = params.get(HttpMessagePart.OLD_VERSION.toString());
    final int oldVersion = StringUtils.isBlank(oldVersionString) ? -1 : Integer.parseInt(oldVersionString);

    JobInfo jobInfo = new JobInfo();
    jobInfo.setId(jobID);
    jobInfo.setStudyID(studyUUID);
    jobInfo.setStatus(JobStatus.IN_PROGRESS);
    jobInfo.setStatusDescription("0% complete");
    String jobURI = req.getContextPath() + "/jobs/status/" + jobInfo.getId();
    jobInfoDAO.saveOrUpdateJobInfo(jobInfo);

    File studyFolder = new File(studiesRoot, studyUUID);

    final StudyUpdateProcessor processor = new StudyUpdateProcessor(jobFolder, studyFolder, availableTypes,
            oldVersion, req.getRemoteUser(), req.getRemoteHost(), jobInfoDAO, studyDAO, updateDAO);
    executor.execute(processor); // process immediately in the background

    res.setStatus(HttpServletResponse.SC_SEE_OTHER);
    res.setHeader("Location", jobURI);

}

From source file:org.opencms.staticexport.CmsAfterPublishStaticExportHandler.java

/**
 * Exports all template resources found in a list of published resources.<p>
 * //w ww  . j a  v a 2  s. c o  m
 * @param cms the cms context, in the root site as Export user
 * @param publishedTemplateResources list of potential candidates to export
 * @param report an I_CmsReport instance to print output message, or null to write messages to the log file    
 */
protected void exportTemplateResources(CmsObject cms, List<String> publishedTemplateResources,
        I_CmsReport report) {

    CmsStaticExportManager manager = OpenCms.getStaticExportManager();
    int size = publishedTemplateResources.size();
    int count = 1;

    if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_EXPORT_TEMPLATES_1, new Integer(size)));
    }
    report.println(Messages.get().container(Messages.RPT_STATICEXPORT_TEMPLATE_RESOURCES_BEGIN_0),
            I_CmsReport.FORMAT_HEADLINE);

    StringBuffer cookies = new StringBuffer();
    // now loop through all of them and request them from the server
    Iterator<String> i = publishedTemplateResources.iterator();
    while (i.hasNext()) {
        String rfsName = i.next();
        CmsStaticExportData data = null;
        try {
            data = manager.getVfsNameInternal(cms, rfsName);
        } catch (CmsVfsResourceNotFoundException e) {
            String rfsBaseName = rfsName;
            int pos = rfsName.lastIndexOf('_');
            if (pos >= 0) {
                rfsBaseName = rfsName.substring(0, pos);
            }
            try {
                data = manager.getVfsNameInternal(cms, rfsBaseName);
            } catch (CmsVfsResourceNotFoundException e2) {
                if (LOG.isInfoEnabled()) {
                    LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_INTERNAL_VFS_RESOURCE_FOUND_1,
                            new String[] { rfsName }));
                }
            }
        }
        if (data != null) {
            data.setRfsName(rfsName);
            report.print(
                    org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_SUCCESSION_2,
                            new Integer(count++), new Integer(size)),
                    I_CmsReport.FORMAT_NOTE);
            report.print(Messages.get().container(Messages.RPT_EXPORTING_0), I_CmsReport.FORMAT_NOTE);
            report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_ARGUMENT_1,
                    rfsName));
            report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));
        } else {
            // no valid resource found for rfs name (already deleted), skip it
            continue;
        }

        try {
            CmsResource resource = data.getResource();
            try {
                Collection<String> detailPages = CmsDetailPageUtil.getAllDetailPagesWithUrlName(cms, resource);
                for (String detailPageUri : detailPages) {
                    String altRfsName = manager.getRfsName(cms, detailPageUri);
                    CmsStaticExportData detailData = new CmsStaticExportData(data.getVfsName(), altRfsName,
                            data.getResource(), data.getParameters());
                    exportTemplateResource(detailData, cookies);
                }
            } catch (CmsException e) {
                LOG.error(e.getLocalizedMessage(), e);
            }

            int status = exportTemplateResource(data, cookies);

            // write the report
            if (status == HttpServletResponse.SC_OK) {
                report.println(
                        org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
                        I_CmsReport.FORMAT_OK);
            } else if (status == HttpServletResponse.SC_NOT_MODIFIED) {
                report.println(
                        org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_SKIPPED_0),
                        I_CmsReport.FORMAT_NOTE);
            } else if (status == HttpServletResponse.SC_SEE_OTHER) {
                report.println(
                        org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_IGNORED_0),
                        I_CmsReport.FORMAT_NOTE);
            } else {
                report.println(org.opencms.report.Messages.get()
                        .container(org.opencms.report.Messages.RPT_ARGUMENT_1, new Integer(status)),
                        I_CmsReport.FORMAT_OK);
            }
        } catch (IOException e) {
            report.println(e);
        }
        //don't lock up the CPU exclusively - allow other Threads to run as well 
        Thread.yield();
    }
    report.println(Messages.get().container(Messages.RPT_STATICEXPORT_TEMPLATE_RESOURCES_END_0),
            I_CmsReport.FORMAT_HEADLINE);
}

From source file:org.opencms.staticexport.CmsStaticExportManager.java

/**
 * Exports the requested uri and at the same time writes the uri to the response output stream
 * if required.<p>// w  w w. j  a  va 2  s .c  o m
 * 
 * @param req the current request
 * @param res the current response
 * @param cms an initialised cms context (should be initialised with the "Guest" user only)
 * @param data the static export data set
 * 
 * @return status code of the export operation, status codes are the same as http status codes (200,303,304)
 * 
 * @throws CmsException in case of errors accessing the VFS
 * @throws ServletException in case of errors accessing the servlet 
 * @throws IOException in case of errors writing to the export output stream
 * @throws CmsStaticExportException if static export is disabled
 */
public int export(HttpServletRequest req, HttpServletResponse res, CmsObject cms, CmsStaticExportData data)
        throws CmsException, IOException, ServletException, CmsStaticExportException {

    CmsResource resource = data.getResource();
    String vfsName = data.getVfsName();
    String rfsName;
    if (data.getParameters() != null) {
        rfsName = data.getRfsName();
    } else {
        rfsName = addDefaultFileNameToFolder(data.getRfsName(), resource.isFolder());
    }

    // cut the site root from the vfsName and switch to the correct site
    String siteRoot = OpenCms.getSiteManager().getSiteRoot(vfsName);

    CmsI18nInfo i18nInfo = OpenCms.getLocaleManager().getI18nInfo(req, cms.getRequestContext().getCurrentUser(),
            cms.getRequestContext().getCurrentProject(), vfsName);

    String remoteAddr = m_remoteAddr;
    if (remoteAddr == null) {
        remoteAddr = CmsContextInfo.LOCALHOST;
    }

    if (siteRoot != null) {
        vfsName = vfsName.substring(siteRoot.length());
    } else {
        siteRoot = "/";
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_STATIC_EXPORT_SITE_ROOT_2, siteRoot, vfsName));
    }

    CmsContextInfo contextInfo = new CmsContextInfo(cms.getRequestContext().getCurrentUser(),
            cms.getRequestContext().getCurrentProject(), vfsName, siteRoot, i18nInfo.getLocale(),
            i18nInfo.getEncoding(), remoteAddr, CmsContextInfo.CURRENT_TIME,
            cms.getRequestContext().getOuFqn());
    CmsObject exportCms = OpenCms.initCmsObject(null, contextInfo);

    // only export those resources where the export property is set
    if (!isExportLink(exportCms, exportCms.getRequestContext().removeSiteRoot(data.getVfsName()))) {
        // the resource was not used for export, so return HttpServletResponse.SC_SEE_OTHER
        // as a signal for not exported resource
        return HttpServletResponse.SC_SEE_OTHER;
    }

    // this flag signals if the export method is used for "on demand" or "after publish". 
    // if no request and result stream are available, it was called during "export on publish"
    boolean exportOnDemand = ((req != null) && (res != null));
    CmsStaticExportResponseWrapper wrapRes = null;
    if (res != null) {
        wrapRes = new CmsStaticExportResponseWrapper(res);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_SE_RESOURCE_START_1, data));
    }

    CmsFile file = exportCms.readFile(OpenCms.initResource(exportCms, vfsName, req, wrapRes));
    vfsName = exportCms.getSitePath(file);

    // check loader id for resource
    I_CmsResourceLoader loader = OpenCms.getResourceManager().getLoader(file);
    if ((loader == null) || (!loader.isStaticExportEnabled())) {
        Object[] arguments = new Object[] { vfsName, new Integer(file.getTypeId()) };
        throw new CmsStaticExportException(
                Messages.get().container(Messages.ERR_EXPORT_NOT_SUPPORTED_2, arguments));
    }

    // ensure we have exactly the same setup as if called "the usual way"
    // we only have to do this in case of the static export on demand
    if (exportOnDemand) {
        String mimetype = OpenCms.getResourceManager().getMimeType(file.getName(),
                exportCms.getRequestContext().getEncoding());
        if (wrapRes != null) {
            wrapRes.setContentType(mimetype);
        }
        exportCms.getRequestContext().setUri(vfsName);
    }

    // do the export
    int status = -1;
    List<Locale> locales = OpenCms.getLocaleManager().getDefaultLocales(exportCms, vfsName);
    boolean exported = false;
    boolean matched = false;
    // iterate over all rules
    Iterator<CmsStaticExportRfsRule> it = getRfsRules().iterator();
    while (it.hasNext()) {
        CmsStaticExportRfsRule rule = it.next();
        // normal case
        boolean export = rule.getSource().matcher(siteRoot + vfsName).matches();
        matched |= export;
        // system folder case
        export |= (vfsName.startsWith(CmsWorkplace.VFS_PATH_SYSTEM) && rule.match(vfsName));
        if (export) {
            // the resource has to exported for this rule
            CmsObject locCms = exportCms;
            Locale locale = CmsLocaleManager.getLocale(rule.getName());
            if (locales.contains(locale)) {
                // if the locale is in the default locales for the resource
                // so adjust the locale to use for exporting
                CmsContextInfo ctxInfo = new CmsContextInfo(exportCms.getRequestContext());
                ctxInfo.setLocale(locale);
                locCms = OpenCms.initCmsObject(exportCms, ctxInfo);
            }
            // read the content in the matching locale
            byte[] content = loader.export(locCms, file, req, wrapRes);
            if (content != null) {
                // write to rfs
                exported = true;
                String locRfsName = rfsName;
                if (locales.contains(locale)) {
                    locRfsName = rule.getLocalizedRfsName(rfsName, "/");
                }
                writeResource(req, rule.getExportPath(), locRfsName, resource, content);
            }
        }
    }
    if (!matched) {
        // no rule matched
        String exportPath = getExportPath(siteRoot + vfsName);
        byte[] content = loader.export(exportCms, file, req, wrapRes);
        if (content != null) {
            exported = true;
            writeResource(req, exportPath, rfsName, resource, content);
        }
    }

    if (exported) {
        // get the wrapper status that was set
        status = (wrapRes != null) ? wrapRes.getStatus() : -1;
        if (status < 0) {
            // the status was not set, assume everything is o.k.
            status = HttpServletResponse.SC_OK;
        }
    } else {
        // the resource was not written because it was not modified. 
        // set the status to not modified
        status = HttpServletResponse.SC_NOT_MODIFIED;
    }

    return status;
}

From source file:org.osjava.atom4j.servlet.AtomServlet.java

/**
 * Create a new Entry.  The jury is still out on whether AtomAPI will
 * support the creation of more than one Entry at a time.  The API
 * does specify, however, that creating an Entry will return a 
 * Location header containing the Atom URL to that Entry.  For now
 * Atom4J is returning the address of the <b>last</b> Entry created.
 * /*from w  ww.  j  a v  a  2  s  . com*/
 * PathInfo: /USER/entry
 * 
 * @param request
 */
protected void postEntry(String[] pathInfo, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Collection entries = null;
    // is this a <feed> wrapped around several <entry>'s ?
    FeedReader feedReader = new FeedReader(request.getInputStream());
    if (feedReader.getFeed() != null) {
        entries = feedReader.getFeed().getEntries();
    } else {
        // or is it really just one Entry?
        EntryReader reader = new EntryReader(request.getInputStream());
        entries = reader.getEntries();
    }
    if (entries == null || entries.size() < 1) {
        error(request, response, "No Entry Found", "No entry was found in the supplied information.");
        return;
    }

    Entry entry = null;
    Iterator iter = entries.iterator();
    while (iter.hasNext()) {
        entry = (Entry) iter.next();
        try {
            saveNewEntry(entry);
        } catch (Exception e) {
            ServletException se = new ServletException(e);
            se.fillInStackTrace();
            throw se;
        }
    }

    if (entry != null) {
        String entryLoc = new StringBuffer(baseURL).append("/atom/").append(pathInfo[0]).append("/entry/")
                .append(entry.getId()).toString();
        response.setHeader("Location", entryLoc);
        //response.setStatus( HttpServletResponse.SC_CREATED ); 
        response.setStatus(HttpServletResponse.SC_SEE_OTHER);
    }
}

From source file:org.testdwr.custom.CustomResponseServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String pathInfo = request.getPathInfo();
    String homePage = request.getContextPath() + request.getServletPath() + "/";

    // Redirect from root dir without trailing slash to with trailing slash
    if (pathInfo == null) {
        response.sendRedirect(homePage);
        return;/*from  w w w .  j a v  a2s.  c o m*/
    }
    // Send home page
    else if (pathInfo.equals("/") || pathInfo.startsWith("/page")) {
        InputStream in = getClass().getResourceAsStream(RESOURCE_HELP);
        if (in == null) {
            log.error("Missing file " + RESOURCE_HELP);
            response.sendError(500, "Missing file " + RESOURCE_HELP);
        } else {
            response.setContentType("text/html");
            ServletOutputStream out = response.getOutputStream();
            CopyUtils.copy(in, out);
        }
    }
    // Send empty page
    else if (pathInfo.startsWith("/empty")) {
        response.setContentType("text/html");
    }
    // Handle redirects
    else if (pathInfo.matches("\\/redirect\\/[1-9][0-9][0-9]\\/.*")) {
        String responseCodeStr = pathInfo.substring(10, 10 + 3);
        int responseCode = Integer.parseInt(responseCodeStr);
        String redirectPath = URLDecoder.decode(pathInfo.substring(13), "utf-8");
        redirectPath = request.getContextPath() + request.getServletPath() + redirectPath;

        log.info("Sending " + responseCode + ":" + redirectPath + "(" + pathInfo + ")");
        switch (responseCode) {
        case HttpServletResponse.SC_MULTIPLE_CHOICES:
        case HttpServletResponse.SC_MOVED_PERMANENTLY:
        case HttpServletResponse.SC_FOUND:
        case HttpServletResponse.SC_SEE_OTHER:
            response.setHeader("Location", "/" + redirectPath);
            response.setStatus(responseCode);
            break;

        case HttpServletResponse.SC_TEMPORARY_REDIRECT:
            response.sendRedirect(redirectPath);
            break;

        default:
            response.sendError(responseCode, "/" + redirectPath);
            break;
        }
    }
    // Send 404
    else {
        response.sendError(404);
    }
}

From source file:org.znerd.yaff.YAFFCallingConvention.java

@Override
protected void convertResultImpl(HttpServletRequest httpRequest, FunctionRequest xinsRequest,
        HttpServletResponse httpResponse, FunctionResult xinsResult)
        throws IOException, ConvertResultException {

    // XXX: Consider changing the approach with the AppCenter class to an
    //      approach where ServletRequest.setAttribute(...) is used, see:
    //      http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletRequest.html

    // Check preconditions
    MandatoryArgumentChecker.check("xinsResult", xinsResult, "httpResponse", httpResponse, "httpRequest",
            httpRequest);//from   w w  w .j a  va2 s . c o  m

    // Possibly the HTTP request is wrapped
    Object wrapper = httpRequest.getAttribute(WRAPPED_REQUEST);
    if (wrapper != null) {
        httpRequest = (HttpServletRequest) wrapper;
    }

    // TODO: Refactor this. Perhaps split in 2 methods, one for redirects
    //       and one for site-specific requests.

    // Handle redirects
    if ("Redirect".equals(xinsRequest.getFunctionName())) {
        httpResponse.setStatus(HttpServletResponse.SC_SEE_OTHER);
        httpResponse.setHeader("Location", xinsRequest.getParameters().get("target"));
        return;

        // Handle page not found
    } else if ("NotFound".equals(xinsRequest.getFunctionName())) {
        httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;

        // Handle CSV form submissions
    } else if ("GetFormSubmissions".equals(xinsRequest.getFunctionName())) {
        httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Get a reference to the AppCenter
    AppCenter appCenter = AppCenter.get();

    // TODO: Assert httpRequest  in the context equals httpRequest
    // TODO: Assert httpResponse in the context equals httpResponse
    // TODO: Assert xinsResult   in the context equals xinsResult

    AccessContext context = appCenter.getContext();
    SiteHandler siteHandler = null;
    String functionName = xinsRequest.getFunctionName();

    // Determine the account
    PropertyReader params = xinsRequest.getParameters();
    String realmName = params.get("realmName");
    Account account = null;
    if (realmName != null) {
        Login login = appCenter.getContext().getSession().getLogin(realmName);
        if (login != null) {
            account = login.getAccount();
        }
    }
    Site site = context.getSite();
    Realm realm = (account == null) ? null : account.getRealm();
    String accountID = (account == null) ? null : account.getID();

    try {
        // Determine the function name
        siteHandler = context.getSiteHandler();

        // Serve a static file
        if ("GetFile".equals(functionName)) {
            String path = params.get("path"); // TODO: Assert path matches a certain pattern

            // Determine data context (site/realm/account) 
            DataContext dataContext = site;

            // Account-specific
            if (account != null && "true".equals(params.get("accountSpecific"))) {
                dataContext = account;
            } else if (account != null) {
                dataContext = realm;
            }

            Log.log_8136(path);
            siteHandler.serveFile(httpRequest, httpResponse, dataContext, path);

        } else {
            context.set(xinsResult, httpResponse);

            // Return form field validation result
            if ("ValidateFormField".equals(functionName)) {
                siteHandler.serveFormFieldValidationResult();

                // Serve a dynamic page (possibly transformed)
            } else {
                siteHandler.servePage(httpRequest, httpResponse);
            }
        }

        // Handle any exception, mostly ContentAccessException and IOException
    } catch (Exception cause) {
        if (siteHandler != null && siteHandler.getSite().getProperty("ErrorPage") != null) {
            Log.log_8137(cause);
            siteHandler.serveError(httpRequest, httpResponse, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } else {
            Utils.logError("Caught exception in YAFFCallingConvention.convertResultImpl method.", cause);
            throw new IOException("Failed to convert result.", cause);
        }

        // Clear the context
    } finally {
        appCenter.setContext(null);
    }
}

From source file:test.pubman.TestBase.java

/**
 * Logs in the given user with the given password.
 * /*from  w  ww.ja va2 s  .  c  o  m*/
 * @param userid The id of the user to log in.
 * @param password The password of the user to log in.
 * @return The handle for the logged in user.
 * @throws HttpException
 * @throws IOException
 * @throws ServiceException
 * @throws URISyntaxException 
 */
protected static String loginUser(String userid, String password)
        throws HttpException, IOException, ServiceException, URISyntaxException {
    String frameworkUrl = ServiceLocator.getFrameworkUrl();
    int delim1 = frameworkUrl.indexOf("//");
    int delim2 = frameworkUrl.indexOf(":", delim1);

    String host;
    int port;

    if (delim2 > 0) {
        host = frameworkUrl.substring(delim1 + 2, delim2);
        port = Integer.parseInt(frameworkUrl.substring(delim2 + 1));
    } else {
        host = frameworkUrl.substring(delim1 + 2);
        port = 80;
    }
    HttpClient client = new HttpClient();

    ProxyHelper.setProxy(client, frameworkUrl);

    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check");
    login.addParameter("j_username", userid);
    login.addParameter("j_password", password);

    client.executeMethod(login);

    login.releaseConnection();
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies());

    Cookie sessionCookie = logoncookies[0];

    PostMethod postMethod = new PostMethod(frameworkUrl + "/aa/login");
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    client.executeMethod(postMethod);

    if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) {
        throw new HttpException("Wrong status code: " + login.getStatusCode());
    }

    String userHandle = null;
    Header headers[] = postMethod.getResponseHeaders();
    for (int i = 0; i < headers.length; ++i) {
        if ("Location".equals(headers[i].getName())) {
            String location = headers[i].getValue();
            int index = location.indexOf('=');
            userHandle = new String(Base64.decode(location.substring(index + 1, location.length())));
            //System.out.println("location: "+location);
            //System.out.println("handle: "+userHandle);
        }
    }

    if (userHandle == null) {
        throw new ServiceException("User not logged in.");
    }
    return userHandle;
}