Example usage for javax.servlet.http HttpServletResponse encodeUrl

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

Introduction

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

Prototype

@Deprecated
public String encodeUrl(String url);

Source Link

Usage

From source file:fr.mby.opa.pics.web.controller.UploadPicturesController.java

/***************************************************
 * URL: /upload/jqueryUpload upload(): receives files
 * /*  w  w w.ja  v  a 2  s. co m*/
 * @param request
 *            : MultipartHttpServletRequest auto passed
 * @param response
 *            : HttpServletResponse auto passed
 * @return LinkedList<FileMeta> as json format
 ****************************************************/
@ResponseBody
@RequestMapping(value = "/jqueryUpload", method = RequestMethod.POST)
public FileMetaList jqueryUpload(@RequestParam final Long albumId, final MultipartHttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    Assert.notNull(albumId, "No Album Id supplied !");

    final FileMetaList files = new FileMetaList();

    // 1. build an iterator
    final Iterator<String> itr = request.getFileNames();

    // 2. get each file
    while (itr.hasNext()) {

        // 2.1 get next MultipartFile
        final MultipartFile mpf = request.getFile(itr.next());

        // Here the file is uploaded

        final String originalFilename = mpf.getOriginalFilename();
        final String contentType = mpf.getContentType();

        final Matcher zipMatcher = UploadPicturesController.ZIP_CONTENT_TYPE_PATTERN.matcher(contentType);
        if (zipMatcher.find()) {

            // 2.3 create new fileMeta
            final FileMeta zipMeta = new FileMeta();
            zipMeta.setFileName(originalFilename);
            zipMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
            zipMeta.setFileType(mpf.getContentType());

            final List<Path> picturesPaths = this.processArchive(mpf);

            final Collection<Future<Void>> futures = new ArrayList<>(picturesPaths.size());
            final ExecutorService executorService = Executors
                    .newFixedThreadPool(Runtime.getRuntime().availableProcessors());

            for (final Path picturePath : picturesPaths) {
                final Future<Void> future = executorService.submit(new Callable<Void>() {

                    @Override
                    public Void call() throws Exception {
                        final String pictureFileName = picturePath.getName(picturePath.getNameCount() - 1)
                                .toString();
                        final byte[] pictureContents = Files.readAllBytes(picturePath);

                        final FileMeta pictureMeta = new FileMeta();
                        try {
                            final Picture picture = UploadPicturesController.this.createPicture(albumId,
                                    pictureFileName.toString(), pictureContents);
                            final Long imageId = picture.getImage().getId();
                            final Long thumbnailId = picture.getThumbnail().getId();

                            pictureMeta.setFileName(pictureFileName);
                            pictureMeta.setFileSize(pictureContents.length / 1024 + " Kb");
                            pictureMeta.setFileType(Files.probeContentType(picturePath));
                            pictureMeta.setUrl(
                                    response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + imageId));
                            pictureMeta.setThumbnailUrl(response
                                    .encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + thumbnailId));
                        } catch (final PictureAlreadyExistsException e) {
                            // Picture already exists !
                            pictureMeta.setError(
                                    UploadPicturesController.PICTURE_ALREADY_EXISTS_MSG + e.getFilename());
                        } catch (final UnsupportedPictureTypeException e) {
                            // Picture already exists !
                            pictureMeta.setError(
                                    UploadPicturesController.UNSUPPORTED_PICTURE_TYPE_MSG + e.getFilename());
                        }

                        files.add(pictureMeta);

                        return null;
                    }
                });
                futures.add(future);
            }

            for (final Future<Void> future : futures) {
                future.get();
            }

            files.add(zipMeta);
        }

        final Matcher imgMatcher = UploadPicturesController.IMG_CONTENT_TYPE_PATTERN.matcher(contentType);
        if (imgMatcher.find()) {
            // 2.3 create new fileMeta
            final FileMeta fileMeta = new FileMeta();
            try {
                final byte[] fileContents = mpf.getBytes();
                final Picture picture = this.createPicture(albumId, originalFilename, fileContents);

                final Long imageId = picture.getImage().getId();
                final Long thumbnailId = picture.getThumbnail().getId();

                fileMeta.setFileName(originalFilename);
                fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
                fileMeta.setFileType(mpf.getContentType());
                fileMeta.setBytes(fileContents);
                fileMeta.setUrl(response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + imageId));
                fileMeta.setThumbnailUrl(
                        response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + thumbnailId));

                // 2.4 add to files
                files.add(fileMeta);
            } catch (final PictureAlreadyExistsException e) {
                // Picture already exists !
                fileMeta.setError(UploadPicturesController.PICTURE_ALREADY_EXISTS_MSG);
            }
        }

    }

    // result will be like this
    // {files:[{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]}
    return files;
}

From source file:org.apache.click.control.Form.java

/**
 * Return the form "action" attribute URL value. If the action URL attribute
 * has not been explicitly set the form action attribute will target the
 * page containing the form. This is the default behaviour for most scenarios.
 * However if you explicitly specify the form "action" URL attribute, this
 * value will be used instead.//from   w ww .  j  av a  2  s  . com
 * <p/>
 * Setting the form action attribute is useful for situations where you want
 * a form to submit to a different page. This can also be used to have a
 * form submit to the J2EE Container for authentication, by setting the
 * action URL to "<tt>j_security_check</tt>".
 * <p/>
 * The action URL will always be encoded by the response to ensure it includes
 * the Session ID if required.
 *
 * @return the form "action" attribute URL value.
 */
public String getActionURL() {
    Context context = getContext();
    HttpServletResponse response = context.getResponse();
    if (actionURL == null) {
        HttpServletRequest request = context.getRequest();
        return response.encodeURL(ClickUtils.getRequestURI(request));

    } else {
        return response.encodeURL(actionURL);
    }
}

From source file:org.eclipse.vtp.framework.engine.http.HttpConnector.java

/**
 * Serves up a site that can be used to examine and modify active sessions.
 * /*  w ww .  j  av a 2s  .com*/
 * @param req The HTTP request.
 * @param res The HTTP response.
 * @throws ServletException If the processing fails.
 * @throws IOException If the connection fails.
 */
public synchronized void examine(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    String cmd = req.getParameter("cmd");
    String process = req.getParameter("process");
    String session = req.getParameter("session");
    String variable = req.getParameter("variable");
    String action = req.getParameter("action");
    String value = req.getParameter("value");
    Deployment deployment = null;
    if (process != null)
        deployment = deploymentsByPath.get(process);
    DeploymentSession deploymentSession = null;
    if (session != null)
        deploymentSession = deployment.getActiveSession(session);
    IDataObject parent = null, object = null;
    String fieldName = null;
    if (variable != null) {
        for (String token : variable.split("\\.")) {
            if (object == null)
                object = deploymentSession.getVariableRegistry().getVariable(token);
            else {
                parent = object;
                object = parent.getField(token);
            }
            fieldName = token;
        }
    }
    if ("unlock".equals(cmd)) {
        if (action.startsWith("Save")) {
            IVariableRegistry variables = deploymentSession.getVariableRegistry();
            if (object == null) {
                object = variables.createVariable(parent.getField(fieldName).getType());
                parent.setField(fieldName, object);
            }
            if (object instanceof IBooleanObject)
                ((IBooleanObject) object).setValue(value);
            else if (object instanceof IDateObject)
                ((IDateObject) object).setValue(value);
            else if (object instanceof IDecimalObject)
                ((IDecimalObject) object).setValue(value);
            else if (object instanceof INumberObject)
                ((INumberObject) object).setValue(value);
            else if (object instanceof IStringObject)
                ((IStringObject) object).setValue(value);
        }
        deploymentSession.unlock();
        res.sendRedirect(
                res.encodeRedirectURL("examine?cmd=variables&process=" + process + "&session=" + session));
    } else {
        String base = res.encodeURL("examine?cmd=");
        res.setContentType("text/html");
        ServletOutputStream out = res.getOutputStream();
        out.println("<html><head><title>Runtime Examination</title></head><body>");
        if ("edit".equals(cmd)) {
            out.println("<p>Application: " + process + "</p>");
            out.println("<p>Session: " + deploymentSession.getSessionID() + " : "
                    + deploymentSession.getCurrentPosition() + "</p>");
            deploymentSession.lock();
            out.println("<form action=\"examine\" method=\"post\">");
            out.println("<input type=\"hidden\" name=\"cmd\" value=\"unlock\" />");
            out.println("<input type=\"hidden\" name=\"process\" value=\"" + process + "\" />");
            out.println("<input type=\"hidden\" name=\"session\" value=\"" + session + "\" />");
            out.println("<input type=\"hidden\" name=\"variable\" value=\"" + variable + "\" />");
            out.println("<p>" + variable + " = ");
            out.println("<input type=\"text\" name=\"value\" value=\"");
            if (object != null)
                out.println(object.toString());
            out.println("\" /></p>");
            out.println("<p><input type=\"submit\" name=\"action\" value=\"Save & Unlock\" />&nbsp;");
            out.println("<input type=\"submit\" name=\"action\" value=\"Cancel & Unlock\" /></p>");
            out.println("</form>");
        } else if ("variables".equals(cmd)) {
            out.println("<p>Application: " + process + "</p>");
            out.println("<p>Session: " + deploymentSession.getSessionID() + " : "
                    + deploymentSession.getCurrentPosition() + "</p>");
            out.println("<p>Select a variable to edit:</p><ul>");
            IVariableRegistry variables = deploymentSession.getVariableRegistry();
            String prefix = base + "edit&process=" + process + "&session=" + session + "&variable=";
            String[] variableNames = variables.getVariableNames();
            Arrays.sort(variableNames);
            for (String name : variableNames)
                examineVariable(out, prefix, name, variables.getVariable(name));
            out.println("</ul>");
        } else if ("sessions".equals(cmd)) {
            out.println("<p>Application: " + process + "</p>");
            out.println("<p>Select the session to examine:</p><ul>");
            for (DeploymentSession s : deployment.getActiveSessions()) {
                out.print("<li><a href=\"");
                out.print(base);
                out.print("variables&process=");
                out.print(process);
                out.print("&session=");
                out.print(s.getSessionID());
                out.print("\">");
                out.print(s.getSessionID());
                out.print(" : ");
                out.print(s.getCurrentPosition());
                out.println("</a></li>");
            }
            out.println("</ul>");
        } else {
            out.println("<p>Select the application to examine:</p><ul>");
            for (Object o : deploymentsByPath.keySet()) {
                out.print("<li><a href=\"");
                out.print(base);
                out.print("sessions&process=");
                out.print(o.toString());
                out.print("\">");
                out.print(o.toString());
                out.println("</a></li>");
            }
            out.println("</ul>");
        }
        out.println("</body></html>");
    }
}

From source file:eu.eidas.node.APSelectorServlet.java

/**
 * Prepares the citizen to be redirected to the AP.
 * @param request//from   w  w w. jav a2  s  . c o m
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        LOG.debug("**** EXECUTE : APSelectorServlet ****");

        APSelectorBean controllerService = (APSelectorBean) getApplicationContext()
                .getBean("springManagedAPSelector");

        validateSession(controllerService);

        // Prevent cookies from being accessed through client-side script.
        setHTTPOnlyHeader(request, response);

        final Map<String, Object> parameters = getHttpRequestParameters(request);

        IPersonalAttributeList attrList = (PersonalAttributeList) request
                .getAttribute(EIDASParameters.ATTRIBUTE_LIST.toString());

        String strAttrList = (String) parameters.get(SpecificParameterNames.STR_ATTR_LIST.toString());
        if (strAttrList == null) {
            strAttrList = (String) request.getAttribute(SpecificParameterNames.STR_ATTR_LIST.toString());
        }

        if (strAttrList != null) {
            LOG.debug("Setting AttributeList...");
            attrList = new PersonalAttributeList();
            attrList.populate(strAttrList);
            validateAttrList(controllerService, attrList);
        }

        if (controllerService.getNumberOfAps() > 0 && !checkAttributes(attrList)) {
            LOG.debug("Build parameter list");

            final String username = (String) controllerService.getSession()
                    .get(EIDASParameters.USERNAME.toString());
            EIDASUtil.validateParameter(APSelectorServlet.class.getCanonicalName(),
                    EIDASParameters.USERNAME.toString(), username);
            parameters.put(EIDASParameters.USERNAME.toString(), username);
            request.setAttribute(EIDASParameters.USERNAME.toString(), username);
            LOG.debug("Build username=" + username);

            if (controllerService.isExternalAP()) {
                LOG.debug("External AP configured");
                request.setAttribute(SpecificParameterNames.CALLBACK_URL.toString(),
                        encodeURL(controllerService.getCallbackURL(), request, response));
                final boolean retVal = controllerService.getSpecificEidasNode().prepareAPRedirect(attrList,
                        parameters, getHttpRequestAttributesHeaders(request), controllerService.getSession());
                if (retVal) {
                    request.setAttribute(EIDASParameters.AP_URL.toString(),
                            controllerService.getSession().get(EIDASParameters.AP_URL.toString()));
                    request.setAttribute(SpecificParameterNames.STR_ATTR_LIST.toString(), attrList.toString());
                    LOG.debug("[execute] external-ap");

                    RequestDispatcher dispatcher = getServletContext()
                            .getRequestDispatcher(response.encodeURL(SpecificViewNames.AP_REDIRECT.toString()));
                    dispatcher.forward(request, response);
                    return;
                }
            } else {
                controllerService.getSpecificEidasNode().getAttributesFromAttributeProviders(attrList,
                        parameters, getHttpRequestAttributesHeaders(request));
            }
        }

        final EIDASAuthnRequest authReq = (EIDASAuthnRequest) controllerService.getSession()
                .get(EIDASParameters.AUTH_REQUEST.toString());
        if (SAMLCore.EIDAS10_SAML_PREFIX.getValue().equalsIgnoreCase(authReq.getMessageFormatName())) {
            for (PersonalAttribute pa : attrList) {
                if (!pa.getValue().isEmpty() && !StringUtils.isEmpty(pa.getValue().get(0))
                        && StringUtils.isEmpty(pa.getStatus())) {
                    pa.setStatus(EIDASStatusCode.STATUS_AVAILABLE.toString());
                }
            }
        }

        if (authReq.getPersonalAttributeList().containsKey(controllerService.getAttribute())
                && controllerService.isSigModuleExists()) {
            final PersonalAttribute attr = authReq.getPersonalAttributeList()
                    .get(controllerService.getAttribute());
            if (!attr.isEmptyValue()) {
                LOG.debug("[execute] external-sig-module");
                final String signedDocValue = attr.getValue().get(0);
                request.setAttribute(SpecificParameterNames.DATA.toString(), signedDocValue);
                attrList.put(attr.getName(), attr);
                request.setAttribute(EIDASParameters.ATTRIBUTE_LIST.toString(), attrList);
                String dataURL = controllerService.getDataURL() + ";jsessionid=" + request.getSession().getId();
                request.setAttribute(SpecificParameterNames.DATA_URL.toString(), dataURL);
                controllerService.getSession().put(EIDASParameters.ATTRIBUTE_LIST.toString(), attrList);
                request.setAttribute(SpecificParameterNames.SIG_MODULE_CREATOR_URL.toString(),
                        controllerService.getSigCreatorModuleURL());

                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(
                        response.encodeURL(SpecificViewNames.EXTERNAL_SIG_MODULE_REDIRECT.toString()));
                dispatcher.forward(request, response);
                return;

            } else {
                LOG.info("ERROR : [execute] No " + controllerService.getAttribute() + " value found!");
            }
        }

        request.setAttribute(EIDASParameters.ATTRIBUTE_LIST.toString(), attrList);
        request.setAttribute(SpecificParameterNames.STR_ATTR_LIST.toString(), strAttrList);

        LOG.trace("[execute] internal-ap");
        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher(response.encodeURL(SpecificViewNames.AP_RESPONSE.toString()));
        dispatcher.forward(request, response);

    } catch (ServletException e) {
        LOG.info("ERROR : ", e.getMessage());
        LOG.debug("ERROR : ", e);
        throw e;
    } catch (IOException e) {
        LOG.info("ERROR : ", e.getMessage());
        LOG.debug("ERROR : ", e);
        throw e;
    } catch (AbstractEIDASException e) {
        LOG.info("ERROR : ", e.getErrorMessage());
        LOG.debug("ERROR : ", e);
        throw e;
    }

}

From source file:org.sakaiproject.portal.charon.CharonPortal.java

protected String getPlacement(HttpServletRequest req, HttpServletResponse res, Session session,
        String placementId, boolean doPage) throws ToolException {

    String siteId = req.getParameter(PARAM_SAKAI_SITE);
    if (siteId == null)
        return placementId; // Standard placement

    // find the site, for visiting
    // Sites like the !gateway site allow visits by anonymous
    Site site = null;/*www . j av  a 2  s.co  m*/
    try {
        site = SiteService.getSiteVisit(siteId);
    } catch (IdUnusedException e) {
        return placementId; // cannot resolve placement
    } catch (PermissionException e) {
        // If we are not logged in, try again after we log in, otherwise
        // punt
        if (session.getUserId() == null) {
            doLogin(req, res, session, URLUtils.getSafePathInfo(req) + "?sakai.site=" + res.encodeURL(siteId),
                    false);
            return null;
        }
        return placementId; // cannot resolve placement
    }

    if (site == null)
        return placementId;
    ToolConfiguration toolConfig = site.getToolForCommonId(placementId);
    if (toolConfig == null)
        return placementId;

    if (doPage) {
        return toolConfig.getPageId();
    } else {
        return toolConfig.getId();
    }

}

From source file:org.wings.session.PortletSessionServlet.java

/**
 * Verarbeitet Informationen vom Browser:
 * <UL>/* w w w  .  j  a  v a 2  s.  c  o m*/
 * <LI> setzt Locale
 * <LI> Dispatch Get Parameter
 * <LI> feuert Form Events
 * </UL>
 * Ist synchronized, damit nur ein Frame gleichzeitig bearbeitet
 * werden kann.
 */
public final synchronized void doGet(HttpServletRequest req, HttpServletResponse response) {
    // Special case: You double clicked i.e. a "logout button"
    // First request arrives, second is on hold. First invalidates session and sends redirect as response,
    // but browser ignores and expects response in second request. But second request has longer a valid session.
    if (session == null) {
        try {
            response.sendRedirect(exitSessionWorkaround != null ? exitSessionWorkaround : "");
            return;
        } catch (IOException e) {
            log.info("Session exit workaround failed to to IOException (triple click?)");
        }
    }

    SessionManager.setSession(session);
    session.setServletRequest(req);
    session.setServletResponse(response);

    session.fireRequestEvent(SRequestEvent.REQUEST_START);

    // in case, the previous thread did not clean up.
    SForm.clearArmedComponents();

    Device outputDevice = null;

    ReloadManager reloadManager = session.getReloadManager();

    try {
        /*
         * The tomcat 3.x has a bug, in that it does not encode the URL
         * sometimes. It does so, when there is a cookie, containing some
         * tomcat sessionid but that is invalid (because, for instance,
         * we restarted the tomcat in-between).
         * [I can't think of this being the correct behaviour, so I assume
         *  it is a bug. ]
         *
         * So we have to workaround this here: if we actually got the
         * session id from a cookie, but it is not valid, we don't do
         * the encodeURL() here: we just leave the requestURL as it is
         * in the properties .. and this is url-encoded, since
         * we had set it up in the very beginning of this session
         * with URL-encoding on  (see WingServlet::newSession()).
         *
         * Vice versa: if the requestedSessionId is valid, then we can
         * do the encoding (which then does URL-encoding or not, depending
         * whether the servlet engine detected a cookie).
         * (hen)
         */
        RequestURL portletRequestURL = null;
        // get the renderResponse
        RenderResponse renderResponse = (RenderResponse) req.getAttribute(Const.REQUEST_ATTR_RENDER_RESPONSE);
        if (renderResponse == null) {
            log.error("WingS-Portlet-Bridge: cant get the request attribute "
                    + Const.REQUEST_ATTR_RENDER_RESPONSE);
        }
        PortletURL actionURL = renderResponse.createActionURL();
        if (req.isRequestedSessionIdValid()) {
            portletRequestURL = new PortletRequestURL(actionURL.toString(),
                    response.encodeURL(actionURL.toString()));
            log.debug("WingS-Portlet-Bridge: created PortletRequestURL " + actionURL.toString());
            // this will fire an event, if the encoding has changed ..
            session.setProperty("request.url", portletRequestURL);
            session.setProperty(Const.WINGS_SESSION_PROPERTY_RENDER_RESPONSE, renderResponse);

            // get the RenderRequest
            RenderRequest renderRequest = (RenderRequest) req.getAttribute(Const.REQUEST_ATTR_RENDER_REQUEST);
            if (renderRequest == null) {
                log.error("WingS-Portlet-Bridge: cant get the request attribute "
                        + Const.REQUEST_ATTR_RENDER_REQUEST);
            }
            session.setProperty(Const.WINGS_SESSION_PROPERTY_RENDER_REQUEST, renderRequest);
        }

        if (log.isDebugEnabled()) {
            log.debug("Request URL: " + portletRequestURL);
            log.debug("HTTP header:");
            for (Enumeration en = req.getHeaderNames(); en.hasMoreElements();) {
                String header = (String) en.nextElement();
                log.debug("    " + header + ": " + req.getHeader(header));
            }
        }
        handleLocale(req);

        // WingS-Portlet-Bridge: get the Parameter from the map in the request
        // set by the portlet
        Map params = (Map) req.getAttribute(Const.REQUEST_ATTR_PARAMETERS_FROM_ACTION_MAP);

        // The externalizer is able to handle static and dynamic resources
        ExternalizeManager extManager = getSession().getExternalizeManager();
        //WingS-Portlet-Bridge:
        //String pathInfo = req.getPathInfo();                    // Note: Websphere returns <code>null</code> here!
        String pathInfo = null;
        if (params != null) {
            String[] path = (String[]) params.get(Const.REQUEST_PARAM_RESOURCE_AS_PARAM);
            if (path != null)
                pathInfo = path[0];
        }

        if (pathInfo != null && pathInfo.length() > 0) {
            // strip of leading /
            // WingS-Portlet-Bridge:
            // pathInfo = pathInfo.substring(1);
        }

        log.info("WingS-Portlet-Bridge: pathInfo: " + pathInfo);

        // If we have no path info, or the special '_' path info (that should be explained
        // somewhere, Holger), then we deliver the top-level frame of this application.
        String externalizeIdentifier = null;
        if (pathInfo == null || pathInfo.length() == 0 || "_".equals(pathInfo) || firstRequest) {
            externalizeIdentifier = retrieveCurrentRootFrameResource().getId();
            firstRequest = false;
        } else {
            externalizeIdentifier = pathInfo;
        }

        // Retrieve externalized resource
        ExternalizedResource extInfo = extManager.getExternalizedResource(externalizeIdentifier);

        // Special case handling: We request a .html resource of a session which is not accessible.
        // This happens some times and leads to a 404, though it should not be possible.
        if (extInfo == null && pathInfo != null && pathInfo.endsWith(".html")) {
            log.info("Found a request to an invalid .html during a valid session. Redirecting to root frame.");
            response.sendRedirect(retrieveCurrentRootFrameResource().getURL().toString());
            return;
        }

        if (extInfo != null && extInfo.getObject() instanceof UpdateResource) {
            reloadManager.setUpdateMode(true);
        } else {
            reloadManager.setUpdateMode(false);
        }

        // Prior to dispatching the actual events we have to detect
        // their epoch and inform the dispatcher which will then be
        // able to check if the request is valid and processed. If
        // this is not the case, we force a complete page reload.
        String ee = "";
        if (params != null) {
            String[] eeArray = (String[]) params.get("event_epoch");
            if (eeArray != null)
                ee = eeArray[0];
        }
        session.getDispatcher().setEventEpoch(ee);

        // WingS-Portlet-Bridge: Map for the parameters 
        // set by a SPortletAnchor or set in the Portlet
        Map portletParameters = new HashMap();

        // Enumeration en = req.getParameterNames();
        if (params != null) {
            Set paramNames = params.keySet();
            Iterator paramNamesIter = paramNames.iterator();

            Cookie[] cookies = req.getCookies();

            // are there parameters/low level events to dispatch
            if (paramNamesIter.hasNext()) {
                // only fire DISPATCH_START if we have parameters to dispatch
                session.fireRequestEvent(SRequestEvent.DISPATCH_START);

                if (cookies != null) {
                    //dispatch cookies
                    for (int i = 0; i < cookies.length; i++) {
                        Cookie cookie = cookies[i];
                        String paramName = cookie.getName();
                        String value = cookie.getValue();

                        if (log.isDebugEnabled())
                            log.debug("dispatching cookie " + paramName + " = " + value);

                        session.getDispatcher().dispatch(paramName, new String[] { value });
                    }
                }

                if (log.isDebugEnabled()) {
                    log.debug("Parameters:");
                    for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {
                        String paramName = (String) e.nextElement();
                        StringBuilder param = new StringBuilder();
                        param.append("    ").append(paramName).append(": ");
                        final String[] values = req.getParameterValues(paramName);
                        param.append(values != null ? Arrays.toString(values) : "null");
                        log.debug(param);
                    }
                }

                while (paramNamesIter.hasNext()) {
                    String paramName = (String) paramNamesIter.next();
                    String[] values = (String[]) params.get(paramName);

                    // We do not need to dispatch the event epoch and the XHR request ID
                    if (paramName.equals("event_epoch") || paramName.equals("_xhrID")) {
                        continue;
                    }

                    String value = values[0];

                    // Split the values of the event trigger
                    if (paramName.equals("event_trigger")) {
                        int pos = value.indexOf('|');
                        paramName = value.substring(0, pos);
                        values = new String[] { value.substring(pos + 1) };
                    }

                    // Handle form submit via default button
                    if (paramName.equals("default_button")) {
                        if (value.equals("undefined")) {
                            continue;
                        } else {
                            paramName = values[0];
                            values = new String[] { "1" };
                        }
                    }

                    // WingS-Portlet-Bridge: get the portlet parameters
                    if (paramName.startsWith(Const.WINGS_PORTLET_URL_CODE_STRING)) {
                        log.info("WingS-Portlet-Bridge: getting portlet parameter " + paramName + " = "
                                + Arrays.asList(values));
                        portletParameters.put(PortletParameterCodec.decode(paramName), values);
                    } else {
                        if (log.isDebugEnabled())
                            log.debug("dispatching " + paramName + " = " + Arrays.asList(values));
                        session.getDispatcher().dispatch(paramName, values);
                    }

                }

                SForm.fireEvents();

                // only fire DISPATCH DONE if we have parameters to dispatch
                session.fireRequestEvent(SRequestEvent.DISPATCH_DONE);
            }
        }

        //WingS-Portlet-Bridge: store the portlet parameters in the session
        session.setProperty(Const.WINGS_SESSION_PROPERTY_PORTLET_PARAMETER_MAP, portletParameters);

        session.fireRequestEvent(SRequestEvent.PROCESS_REQUEST);
        session.getDispatcher().invokeRunnables();

        // WingS-Portlet-Bridge: fires events if the window state has changed
        session.fireWindowStateEvents();
        // WingS-Portlet-Bridge: fires events for the new portlet parameters
        session.fireNewPortletParameters();

        // if the user chose to exit the session as a reaction on an
        // event, we got an URL to redirect after the session.
        /*
         * where is the right place?
         * The right place is
         *    - _after_ we processed the events
         *        (e.g. the 'Pressed Exit-Button'-event or gave
         *         the user the chance to exit this session in the custom
         *         processRequest())
         *    - but _before_ the rendering of the page,
         *      because otherwise an redirect won't work, since we must
         *      not have sent anything to the output stream).
         */
        if (session.getExitAddress() != null) {

            try {
                session.firePrepareExit();
                session.fireRequestEvent(SRequestEvent.REQUEST_END);

                String redirectAddress;
                if (session.getExitAddress().length() > 0) {
                    // redirect to user requested URL.
                    redirectAddress = session.getExitAddress();
                } else {
                    // redirect to a fresh session.
                    redirectAddress = req.getRequestURL().toString();
                }
                req.getSession().invalidate(); // calls destroy implicitly
                response.sendRedirect(redirectAddress);
                exitSessionWorkaround = redirectAddress;
                return;
            } catch (ExitVetoException ex) {
                session.exit(null);
            } // end of try-catch
        }

        if (session.getRedirectAddress() != null) {
            handleRedirect(response);
            return;
        }

        reloadManager.notifyCGs();
        reloadManager.invalidateFrames();

        // TODO ResourceMapper
        ResourceMapper mapper = session.getResourceMapper();
        if (extInfo == null && mapper != null) {
            //wings-Portlet-Bridge:
            //                Resource res = mapper.mapResource(req.getPathInfo());
            Resource res = mapper.mapResource(pathInfo);
            if (res != null) {
                extInfo = extManager.getExternalizedResource(res.getId());
            }
        }

        if (extInfo != null) {
            outputDevice = DeviceFactory.createDevice(extInfo);
            session.fireRequestEvent(SRequestEvent.DELIVER_START, extInfo);

            long startTime = System.currentTimeMillis();
            extManager.deliver(extInfo, response, outputDevice);
            long endTime = System.currentTimeMillis();
            log.debug("------------------------- Time needed for rendering: " + (endTime - startTime)
                    + " ms -------------------------\n");

            session.fireRequestEvent(SRequestEvent.DELIVER_DONE, extInfo);
        } else {
            handleUnknownResourceRequested(req, response);
        }

    } catch (Throwable e) {
        log.error("Uncaught Exception", e);
        handleException(response, e);
    } finally {
        if (session != null) {
            session.fireRequestEvent(SRequestEvent.REQUEST_END);
        }

        if (outputDevice != null) {
            try {
                outputDevice.close();
            } catch (Exception e) {
            }
        }

        /*
         * the session might be null due to destroy().
         */
        if (session != null) {
            reloadManager.clear();
            session.setServletRequest(null);
            session.setServletResponse(null);
        }

        // make sure that the session association to the thread is removed
        // from the SessionManager
        SessionManager.removeSession();
        SForm.clearArmedComponents();
    }
}

From source file:org.apache.struts2.views.util.UrlHelper.java

public static String buildUrl(String action, HttpServletRequest request, HttpServletResponse response,
        Map params, String scheme, boolean includeContext, boolean encodeResult,
        boolean forceAddSchemeHostAndPort, boolean escapeAmp) {
    StringBuilder link = new StringBuilder();

    boolean changedScheme = false;

    // FIXME: temporary hack until class is made a properly injected bean
    Container cont = ActionContext.getContext().getContainer();
    int httpPort = Integer.parseInt(cont.getInstance(String.class, StrutsConstants.STRUTS_URL_HTTP_PORT));
    int httpsPort = Integer.parseInt(cont.getInstance(String.class, StrutsConstants.STRUTS_URL_HTTPS_PORT));

    // only append scheme if it is different to the current scheme *OR*
    // if we explicity want it to be appended by having forceAddSchemeHostAndPort = true
    if (forceAddSchemeHostAndPort) {
        String reqScheme = request.getScheme();
        changedScheme = true;/*w w w  .j ava 2  s . c o m*/
        link.append(scheme != null ? scheme : reqScheme);
        link.append("://");
        link.append(request.getServerName());

        if (scheme != null) {
            // If switching schemes, use the configured port for the particular scheme.
            if (!scheme.equals(reqScheme)) {
                if ((scheme.equals("http") && (httpPort != DEFAULT_HTTP_PORT))
                        || (scheme.equals("https") && httpsPort != DEFAULT_HTTPS_PORT)) {
                    link.append(":");
                    link.append(scheme.equals("http") ? httpPort : httpsPort);
                }
                // Else use the port from the current request.
            } else {
                int reqPort = request.getServerPort();

                if ((scheme.equals("http") && (reqPort != DEFAULT_HTTP_PORT))
                        || (scheme.equals("https") && reqPort != DEFAULT_HTTPS_PORT)) {
                    link.append(":");
                    link.append(reqPort);
                }
            }
        }
    } else if ((scheme != null) && !scheme.equals(request.getScheme())) {
        changedScheme = true;
        link.append(scheme);
        link.append("://");
        link.append(request.getServerName());

        if ((scheme.equals("http") && (httpPort != DEFAULT_HTTP_PORT))
                || (scheme.equals("https") && httpsPort != DEFAULT_HTTPS_PORT)) {
            link.append(":");
            link.append(scheme.equals("http") ? httpPort : httpsPort);
        }
    }

    if (action != null) {
        // Check if context path needs to be added
        // Add path to absolute links
        if (action.startsWith("/") && includeContext) {
            String contextPath = request.getContextPath();
            if (!contextPath.equals("/")) {
                link.append(contextPath);
            }
        } else if (changedScheme) {

            // (Applicable to Servlet 2.4 containers)
            // If the request was forwarded, the attribute below will be set with the original URL
            String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");

            // If the attribute wasn't found, default to the value in the request object
            if (uri == null) {
                uri = request.getRequestURI();
            }

            link.append(uri.substring(0, uri.lastIndexOf('/') + 1));
        }

        // Add page
        link.append(action);
    } else {
        // Go to "same page"
        String requestURI = (String) request.getAttribute("struts.request_uri");

        // (Applicable to Servlet 2.4 containers)
        // If the request was forwarded, the attribute below will be set with the original URL
        if (requestURI == null) {
            requestURI = (String) request.getAttribute("javax.servlet.forward.request_uri");
        }

        // If neither request attributes were found, default to the value in the request object
        if (requestURI == null) {
            requestURI = request.getRequestURI();
        }

        link.append(requestURI);
    }

    //if the action was not explicitly set grab the params from the request
    if (escapeAmp) {
        buildParametersString(params, link);
    } else {
        buildParametersString(params, link, "&");
    }

    String result = link.toString();

    while (result.indexOf("<script>") > 0) {
        result = result.replaceAll("<script>", "script");
    }
    try {
        result = encodeResult ? response.encodeURL(result) : result;
    } catch (Exception ex) {
        // Could not encode the URL for some reason
        // Use it unchanged
        result = link.toString();
    }

    return result;
}

From source file:com.jaspersoft.jasperserver.war.tags.JasperViewerTag.java

public int doEndTag() throws JspException {
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();

    try {//from  www .j a v  a2s  .  com
        ReportUnitResult reportResult = getReportResult(request);
        JasperPrintAccessor printAccessor = reportResult.getJasperPrintAccessor();
        if (printAccessor == null) {
            log.error("There is no JasperPrint object cannot be accessed.");
            return EVAL_PAGE;
        }

        setReportContextAttributes(request, reportResult);

        Integer pageIndex = (Integer) request.getAttribute(getPageIndexAttribute());
        if (pageIndex == null) {
            pageIndex = new Integer(0);
        }

        ReportExecutionStatus reportStatus = printAccessor.getReportStatus();

        // get the status of the page, waiting for the page to be available in necessary
        ReportPageStatus pageStatus = printAccessor.pageStatus(pageIndex.intValue(), null);

        request.setAttribute("page", page);
        request.setAttribute("dataTimestamp", reportResult.getDataTimestamp());

        request.setAttribute(INNER_PAGINATION_ATTRIBUTE, innerPagination);
        request.setAttribute(IGNORE_PAGE_MARGINS, ignorePageMargins);

        Integer totalPageCount = reportStatus.getTotalPageCount();
        // set the total page count if known
        if (totalPageCount != null) {
            request.setAttribute("lastPageIndex", new Integer(totalPageCount - 1));

            //FIXME this duplicates logic in ReportExecutionController.viewReportPageUpdateCheck
            SnapshotSaveStatus snapshotSaveStatus = getDataCacheProvider()
                    .getSnapshotSaveStatus(reportResult.getReportContext());
            if (snapshotSaveStatus != null) {
                request.setAttribute("snapshotSaveStatus", snapshotSaveStatus.toString());
            }
        }

        // set the partial page count
        request.setAttribute("lastPartialPageIndex", new Integer(reportStatus.getCurrentPageCount() - 1));

        // if the page count is null, it means that the fill is not yet done but there is at least a page
        boolean emptyReport = totalPageCount != null && totalPageCount.intValue() == 0;
        request.setAttribute(EMPTY_REPORT_ATTRIBUTE, Boolean.valueOf(emptyReport));

        ApplicationContext applicationContext = getRequestContext().getWebApplicationContext();
        request.setAttribute(MESSAGE_SOURCE, applicationContext.getBean("messageSource"));

        if (!emptyReport) {
            if (!pageStatus.pageExists()) {
                // setting a header as there's no simple way currently to detect a specific exception in the client
                response.setHeader("reportPageNonExisting", "true");
                throw new JSException("jsexception.view.page.does.not.exist", new Object[] { pageIndex });
            }

            request.setAttribute("pageIndex", pageIndex);

            if (!pageStatus.isPageFinal()) {
                request.setAttribute("pageTimestamp", pageStatus.getTimestamp());
            }

            JasperReportsContext jasperReportsContext = getJasperReportsContext(applicationContext);

            AbstractHtmlExporter exporter = HtmlExportUtil.getHtmlExporter(jasperReportsContext);
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, printAccessor.getJasperPrint());
            exporter.setParameter(JRExporterParameter.PAGE_INDEX, pageIndex);
            exporter.setImageHandler(
                    new WebHtmlResourceHandler(response.encodeURL(imageServlet + "image={0}")));
            exporter.setResourceHandler(
                    new WebHtmlResourceHandler(response.encodeURL(resourceServlet + "/{0}")));
            exporter.setFontHandler(
                    new WebHtmlResourceHandler(response.encodeURL(resourceServlet + "&font={0}")));

            StringBuffer htmlHeader = new StringBuffer();
            String contextPath = request.getContextPath();

            // fix for Bug 26294 - [case #24473 +1] Problem with IE8 and IE9 when embedding app into iframe
            String referer = request.getHeader("Referer");
            referer = referer.substring(0, referer.indexOf(contextPath) + contextPath.length());
            // end fix
            exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, htmlHeader.toString());

            exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER, "");
            exporter.setParameter(JRHtmlExportUtils.PARAMETER_HTTP_REQUEST, request);
            exporter.setParameter(JRExporterParameter.IGNORE_PAGE_MARGINS, ignorePageMargins);
            WebflowReportContext webflowReportContext = getReportContextAccessor().getContext(request,
                    reportContextMap);
            webflowReportContext.setParameterValue("net.sf.jasperreports.web.app.context.path", contextPath);//FIXMEJIVE use constant
            //              webflowReportContext.setParameterValue(JRParameter.REPORT_CONTEXT, webflowReportContext);
            exporter.setReportContext(webflowReportContext);
            // hide the preview toolbar if view as dashboard frame
            if ((webflowReportContext.getParameterValue(ReportParametersAction.VIEW_AS_DASHBOARD_FRAME) != null)
                    && webflowReportContext.getParameterValue(ReportParametersAction.VIEW_AS_DASHBOARD_FRAME)
                            .toString().equalsIgnoreCase("true")) {
                request.setAttribute(ReportParametersAction.VIEW_AS_DASHBOARD_FRAME, "true");
            }
            HyperlinkProducerFactoryFlowFactory linkProducerFactory = (HyperlinkProducerFactoryFlowFactory) request
                    .getAttribute(getLinkProducerFactoryAttribute());
            if (linkProducerFactory != null) {
                JRHyperlinkProducerFactory hyperlinkProducerFactory = linkProducerFactory
                        .getHyperlinkProducerFactory(request, response);
                exporter.setParameter(JRExporterParameter.HYPERLINK_PRODUCER_FACTORY, hyperlinkProducerFactory);
            }

            /*
             * Future enhancement
             * 
             *             JRExporter exporter = (providedExporterClassName != null)
                   ? defaultExporter(jasperPrint, pageIndex) 
                   : providedExporter(jasperPrint, pageIndex);
                        setParameters(exporter);
            */
            request.setAttribute("exporter", exporter);

            boolean isComponentMetadataEmbedded = WebUtil.getInstance(jasperReportsContext)
                    .isComponentMetadataEmbedded();
            request.setAttribute("isComponentMetadataEmbedded", isComponentMetadataEmbedded);
            if (isComponentMetadataEmbedded) {
                JsonExporter jsonExporter = new JsonExporter(jasperReportsContext);
                jsonExporter.setReportContext(webflowReportContext);
                jsonExporter.setParameter(JRExporterParameter.JASPER_PRINT, printAccessor.getJasperPrint());
                request.setAttribute("jsonExporter", jsonExporter);
            }

            // set report status on response header
            LinkedHashMap<String, Object> result = new LinkedHashMap<String, Object>();
            result.put("reportStatus", reportStatus.getStatus().toString().toLowerCase());
            result.put("totalPages", reportStatus.getTotalPageCount());
            result.put("partialPageCount", reportStatus.getCurrentPageCount());
            result.put("pageFinal", pageStatus.isPageFinal());
            result.put("contextid", webflowReportContext.getId());
            result.put("isComponentMetadataEmbedded", isComponentMetadataEmbedded);
            result.put("jasperPrintName", request.getAttribute("jasperPrintName"));
            if (!pageStatus.isPageFinal()) {
                result.put("pageTimestamp", String.valueOf(pageStatus.getTimestamp()));
            }

            String defaultZoomProperty = printAccessor.getJasperPrint()
                    .getProperty("net.sf.jasperreports.viewer.zoom"); // FIXME: use constant
            if (defaultZoomProperty != null) {
                ZoomTypeEnum zoomType = ZoomTypeEnum.getByName(defaultZoomProperty);
                result.put("defaultZoom", zoomType != null ? zoomType.getHtmlValue() : defaultZoomProperty);
            }

            response.setHeader("jasperreports-report-status",
                    JacksonUtil.getInstance(jasperReportsContext).getJsonString(result));
        }

        BodyContent nestedContent = pageContext.pushBody();
        boolean popped = false;
        try {
            pageContext.include(getRenderJsp());
            popped = true;
            pageContext.popBody();
            nestedContent.writeOut(pageContext.getOut());
        } finally {
            if (!popped) {
                pageContext.popBody();
            }
        }

    } catch (Exception e) {
        if (e instanceof SessionAttribMissingException) {
            throw new SessionAttribMissingException(e.getMessage(),
                    ((SessionAttribMissingException) e).getArgs());
        } else {
            throw new JspException(e);
        }
    }

    return EVAL_PAGE;
}

From source file:org.esgf.globusonline.GOauthView1Controller.java

@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView doPost(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //grab the dataset name, file names and urls from the query string
    String dataset_name = request.getParameter("id");
    String[] file_names = request.getParameterValues("child_id");
    String[] file_urls = request.getParameterValues("child_url");
    String esg_user = "";
    String esg_password = "";
    //String e;/*w  w w . j av a  2 s . c  o  m*/
    //grab the credential string
    String credential = request.getParameter("credential");
    System.out.println("Starting GlobusOnline workflow");
    //System.out.println("\n\n\n\t\tGO Credential " + credential + "\n\n\n");

    StringBuffer currentURL = request.getRequestURL();
    String currentURI = request.getRequestURI();
    //System.out.println("current URL is: " + currentURL);
    //System.out.println("current URI is: " + currentURI);
    //System.out.println("index is: " + currentURL.lastIndexOf(currentURI));
    String BaseURL = currentURL.substring(0, currentURL.lastIndexOf(currentURI));
    //System.out.println("BaseURL string is: " + BaseURL );

    //Instantiate model object:
    Map<String, Object> model = new HashMap<String, Object>();

    //Bail out if no gsiftp URLs are in file_names
    if (file_names != null) {
        for (int i = 0; i < file_names.length; i++) {
            if (!(file_urls[i] == null) && (file_urls[i].contains("gsiftp"))) {
                break;
            } else {
                model.put(GOFORMVIEW_ERROR, "error");
                String error_msg = "Selected dataset " + dataset_name
                        + " contains no GridFTP URLS, and cannot be transferred with this transfer method.";
                model.put(GOFORMVIEW_ERROR_MSG, error_msg);
                return new ModelAndView("goauthview3", model);
            }
        }
    } else {
        System.out.println("file_urls itself was null\n");
        model.put(GOFORMVIEW_ERROR, "error");
        String error_msg = "Selected dataset(s) " + dataset_name
                + " contain no GridFTP URLS, and cannot be transferred with this transfer method.";
        model.put(GOFORMVIEW_ERROR_MSG, error_msg);
        return new ModelAndView("goauthview3", model);
    }
    //Create a session if it doesn't already exist, so we can save state.
    HttpSession session = request.getSession(true);
    if (session.isNew() == false) {
        session.invalidate();
        session = request.getSession(true);
    }

    //System.out.println("Auth1, session id is:" + session.getId());

    session.setAttribute("fileUrls", file_urls);
    session.setAttribute("fileNames", file_names);
    session.setAttribute("datasetName", dataset_name);
    session.setAttribute("baseurl", BaseURL);
    if (!(credential == null)) {
        session.setAttribute("usercertificatefile", credential);
    }

    Cookie[] cookies = request.getCookies();
    String openId = "";

    for (int i = 0; i < cookies.length; i++) {
        if (cookies[i].getName().equals("esgf.idp.cookie")) {
            openId = cookies[i].getValue();
        }
    }

    LOG.debug("Got User OpenID: " + openId);
    // Create the client
    Properties GOProperties = getGOProperties();
    String PortalID = (String) GOProperties.getProperty("GOesgfPortalID", "bogususer");
    String PortalPass = (String) GOProperties.getProperty("GOesgfPortalPassword", "boguspassword");

    String loginUri = "";
    try {
        GoauthClient cli = new GoauthClient("nexus.api.globusonline.org", "globusonline.org", PortalID,
                PortalPass);
        cli.setIgnoreCertErrors(true);

        // Redirect the user agent to the globusonline log in page
        loginUri = cli.getLoginUrl(response.encodeURL(BaseURL + "/esgf-web-fe/goauthview2"));

    } catch (NexusClientException e) {
        System.out.println("ERROR:  GOesgfPortalID and/or GOesgfPortalPassword wrong or not set.");
        //            e.printStackTrace();
        model.put(GOFORMVIEW_ERROR, "error");
        String error_msg = "GlobusOnline Configuration file not found. Please create /esg/config/globusonline.properties and populate it with GOesgfPortalID and GOesgfPortalPassword";
        model.put(GOFORMVIEW_ERROR_MSG, error_msg);
        return new ModelAndView("goauthview3", model);
    }
    String myproxyServerStr = null;

    return new ModelAndView("redirect:" + loginUri, model);
}

From source file:com.googlecode.vcsupdate.TeamCityController.java

private ModelAndView getModelAndView(HttpServletRequest request, HttpServletResponse response) {
    // Get all of the VCS roots specified in the request
    Set<SVcsRoot> roots = new LinkedHashSet<SVcsRoot>();

    // Start by getting any root names from the request
    String[] names = request.getParameterValues(NAME_PARAM);
    if (names != null) {
        for (String name : names) {
            SVcsRoot root = vcsManager.findRootByName(name);
            if (root != null)
                roots.add(root);/* ww w.  java2s  .c o  m*/
        }
    }

    // Then look for any root IDs
    String[] ids = request.getParameterValues(ID_PARAM);
    if (ids != null) {
        for (String id : ids) {
            try {
                SVcsRoot root = vcsManager.findRootById(Long.parseLong(id));
                if (root != null)
                    roots.add(root);
            } catch (NumberFormatException e) {
                // just move on to the next ID
            }
        }
    }

    // Finally, if the request is a POST but we've found no roots, it may be
    // due to bugs in some POST handling libraries. In this case, we'll
    // update all of the roots.
    if (names == null && ids == null && request.getMethod().equals("POST")) {
        roots.addAll(vcsManager.getAllRegisteredVcsRoots());
    }

    // Did we get a submitted form?
    if (!roots.isEmpty()) {
        List<String> forcedVcsRootNames = new ArrayList<String>();
        // Iterate through the roots
        for (SVcsRoot root : roots) {
            // Find the matching configurations
            List<SBuildType> builds = vcsManager.getAllConfigurationUsages(root);
            if (builds == null)
                continue;

            // Select the best configuration
            SBuildType selected = null;
            List<SVcsRoot> selectedRoots = null;
            for (SBuildType build : builds) {
                if (!build.isPaused() && !build.isPersonal()) {
                    List<SVcsRoot> buildRoots = build.getVcsRoots();
                    if (selected == null || buildRoots.size() < selectedRoots.size()) {
                        selected = build;
                        selectedRoots = buildRoots;
                    }
                }
            }

            // Did we find a match?
            if (selected == null)
                continue;

            // Kick off the modification check
            boolean defaultInterval = root.isUseDefaultModificationCheckInterval();
            int interval = (defaultInterval ? -1 : root.getModificationCheckInterval());
            root.setModificationCheckInterval(5);
            log("Forcing check for " + selected.getName());
            selected.forceCheckingForChanges();
            forcedVcsRootNames.add(root.getName());

            if (defaultInterval) {
                root.restoreDefaultModificationCheckInterval();
            } else {
                root.setModificationCheckInterval(interval);
            }
        }

        // Redirect to the done page
        String modelObject = forcedVcsRootNames.toString();
        return new ModelAndView(doneViewName, "updatedVCSRoots", modelObject);
    }

    // Build a sample URL
    StringBuilder sampleUrl = new StringBuilder();
    sampleUrl.append(request.getRequestURL()).append('?');
    boolean appendedRoot = false;

    // Append the list of available roots
    List<SVcsRoot> list = vcsManager.getAllRegisteredVcsRoots();
    if (list != null) {
        for (SVcsRoot root : list) {
            if (appendedRoot)
                sampleUrl.append('&');
            sampleUrl.append(NAME_PARAM).append('=').append(root.getName());
            appendedRoot = true;
        }
    }

    // If we didn't get any roots, use a sample name
    if (!appendedRoot) {
        sampleUrl.append(NAME_PARAM).append('=').append(SAMPLENAME);
    }

    // Return a simple view that explains how to use the tool
    String query = request.getQueryString();
    if (query != null)
        sampleUrl.append('&').append(query);

    String modelObject = response.encodeURL(sampleUrl.toString());
    log("Creating modelview. View: " + viewName + " and model: " + modelObject);
    return new ModelAndView(viewName, "sampleUrl", modelObject);
}