Example usage for java.lang StringBuffer indexOf

List of usage examples for java.lang StringBuffer indexOf

Introduction

In this page you can find the example usage for java.lang StringBuffer indexOf.

Prototype

@Override
public int indexOf(String str) 

Source Link

Usage

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

public String getAdminLoginURL(HttpServletRequest req, String sourceURL)
        throws UnsupportedEncodingException, URIException {

    StringBuffer loginURL = new StringBuffer();
    loginURL.append(getPublisherURL(req)).append("/login.jsp");

    String parameterIntroducor = "?";
    if (loginURL.indexOf("?") != -1) {
        parameterIntroducor = "&";
    }/*from w  ww. j a v  a 2  s.com*/

    loginURL.append(parameterIntroducor).append("domain=").append(WGACore.DOMAIN_ADMINLOGINS)
            .append("&redirect=").append(getCore().getURLEncoder().encodeQueryPart(sourceURL));

    return loginURL.toString();

}

From source file:ubc.pavlab.aspiredb.server.service.ProjectServiceImpl.java

@Override
@RemoteMethod// w  ww .  j  a  va 2s  .com
public String addSubjectVariantsPhenotypeToProject(final String variantFilename, final String phenotypeFilename,
        final boolean createProject, final String projectName, final String variantType, final boolean dryRun) {

    // Run the upload task on a separate thread so we don't block the current thread and return a proxy error on the
    // front end
    class ProjectUploadThread extends Thread {

        SecurityContext context;

        public ProjectUploadThread(SecurityContext context) {
            this.context = context;
        }

        @Override
        public void run() {

            SecurityContextHolder.setContext(this.context);

            StopWatch timer = new StopWatch();
            timer.start();

            StringBuffer returnMsg = new StringBuffer();
            StringBuffer errMsg = new StringBuffer();

            VariantUploadServiceResult variantResult = null;
            Collection<Variant2VariantOverlap> overlap = null;
            PhenotypeUploadServiceResult phenResult = null;

            final String STR_FMT = "%35s: %5s\n";

            returnMsg.append(String.format(STR_FMT, "Project", projectName) + "\n");

            if (variantFilename.length() > 0) {

                try {
                    variantResult = addSubjectVariantsToProject(variantFilename, createProject, projectName,
                            variantType, dryRun);
                    returnMsg.append(
                            String.format(STR_FMT, "Number of Subjects", getSubjects(projectName).size()));
                    returnMsg.append(String.format(STR_FMT, "Number of Variants",
                            variantResult.getVariantsToAdd().size()));
                    for (String err : variantResult.getErrorMessages()) {
                        errMsg.append(err + "\n");
                    }

                    if (!dryRun) {
                        // only run SpecialProject overlap if projectName is not a special project
                        try {
                            SpecialProject.valueOf(projectName);
                        } catch (IllegalArgumentException argEx) {
                            for (Project specialProject : projectDao.getSpecialOverlapProjects()) {
                                try {
                                    overlap = projectManager.populateProjectToProjectOverlap(projectName,
                                            specialProject.getName(), variantResult.getVariantsToAdd());
                                    returnMsg.append(String.format(STR_FMT,
                                            "Number of Overlaps with " + specialProject.getName(),
                                            overlap.size()));
                                } catch (Exception e) {
                                    log.error(e.getLocalizedMessage(), e);
                                    errMsg.append(e.getLocalizedMessage() + "\n");
                                }
                            }
                        }
                    }

                } catch (Exception e) {
                    log.error(e.getLocalizedMessage(), e);
                    errMsg.append(e.getLocalizedMessage() + "\n");
                }
            }

            if (phenotypeFilename.length() > 0) {
                try {
                    phenResult = addSubjectPhenotypeToProject(phenotypeFilename, createProject, projectName,
                            dryRun);
                    if (returnMsg.indexOf("Number of Subjects") == -1) {
                        returnMsg.append(
                                String.format(STR_FMT, "Number of Subjects", getSubjects(projectName).size()));
                    }
                    returnMsg.append(String.format(STR_FMT, "Number of Phenotypes",
                            phenResult.getPhenotypesToAdd().size()));
                    for (String err : phenResult.getErrorMessages()) {
                        errMsg.append(err + "\n");
                    }
                } catch (Exception e) {
                    log.error(e.getLocalizedMessage(), e);
                    errMsg.append(e.getLocalizedMessage() + "\n");
                }
            }

            log.info("Uploading took " + timer.getTime() + " ms");

            // trim errorMssage
            final int ERRMSG_LIMIT = 500;
            if (errMsg.length() > ERRMSG_LIMIT) {
                errMsg.delete(ERRMSG_LIMIT, errMsg.length() - 1);
                errMsg.append("\n...\n");
            }

            String returnStr = returnMsg.toString();
            returnStr += errMsg.length() > 0 ? "\nExceptions\n" + errMsg : "";

            log.info(returnStr);

            if (!dryRun) {
                // email users that the upload has finished

                // if ( timer.getTime() > ConfigUtils.getLong( "aspiredb.uploadTimeThreshold", 60000 ) ) {
                emailUploadFinished(projectName, returnStr);
                // }
            }

        }
    }

    ProjectUploadThread thread = new ProjectUploadThread(SecurityContextHolder.getContext());
    thread.setName(ProjectUploadThread.class.getName() + "_" + projectName + "_load_thread_"
            + RandomStringUtils.randomAlphanumeric(5));
    // To prevent VM from waiting on this thread to shutdown (if shutting down).
    thread.setDaemon(true);
    thread.start();

    return thread.getName();
}

From source file:org.pentaho.di.core.database.DatabaseMeta.java

public String getURL(String partitionId) throws KettleDatabaseException {
    // First see if we're not doing any JNDI...
    // //from   ww  w. j a va2  s. c om
    if (getAccessType() == TYPE_ACCESS_JNDI) {
        // We can't really determine the URL here.
        //
        //
    }

    String baseUrl;
    if (isPartitioned() && !Const.isEmpty(partitionId)) {
        // Get the cluster information...
        PartitionDatabaseMeta partition = getPartitionMeta(partitionId);
        String hostname = partition.getHostname();
        String port = partition.getPort();
        String databaseName = partition.getDatabaseName();

        baseUrl = databaseInterface.getURL(hostname, port, databaseName);
    } else {
        baseUrl = databaseInterface.getURL(getHostname(), getDatabasePortNumberString(), getDatabaseName());
    }
    StringBuffer url = new StringBuffer(environmentSubstitute(baseUrl));

    if (databaseInterface.supportsOptionsInURL()) {
        // OK, now add all the options...
        String optionIndicator = getExtraOptionIndicator();
        String optionSeparator = getExtraOptionSeparator();
        String valueSeparator = getExtraOptionValueSeparator();

        Map<String, String> map = getExtraOptions();
        if (map.size() > 0) {
            Iterator<String> iterator = map.keySet().iterator();
            boolean first = true;
            while (iterator.hasNext()) {
                String typedParameter = (String) iterator.next();
                int dotIndex = typedParameter.indexOf('.');
                if (dotIndex >= 0) {
                    String typeCode = typedParameter.substring(0, dotIndex);
                    String parameter = typedParameter.substring(dotIndex + 1);
                    String value = map.get(typedParameter);

                    // Only add to the URL if it's the same database type code...
                    //
                    if (databaseInterface.getPluginId().equals(typeCode)) {
                        if (first && url.indexOf(valueSeparator) == -1) {
                            url.append(optionIndicator);
                        } else {
                            url.append(optionSeparator);
                        }

                        url.append(parameter);
                        if (!Const.isEmpty(value) && !value.equals(EMPTY_OPTIONS_STRING)) {
                            url.append(valueSeparator).append(value);
                        }
                        first = false;
                    }
                }
            }
        }
    } else {
        // We need to put all these options in a Properties file later (Oracle & Co.)
        // This happens at connect time...
    }

    return url.toString();
}

From source file:com.stratelia.webactiv.kmelia.servlets.KmeliaRequestRouter.java

/**
 * This method has to be implemented by the component request rooter it has to compute a
 * destination page/*from  w  ww  .j a  v  a2s  . c  o m*/
 *
 *
 * @param function The entering request function ( : "Main.jsp")
 * @param kmelia The component Session Control, build and initialised.
 * @param request The entering request. The request rooter need it to get parameters
 * @return The complete destination URL for a forward (ex :
 * "/almanach/jsp/almanach.jsp?flag=user")
 */
@Override
public String getDestination(String function, KmeliaSessionController kmelia, HttpRequest request) {
    SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
            "function = " + function);
    String destination = "";
    String rootDestination = "/kmelia/jsp/";
    boolean profileError = false;
    boolean kmaxMode = false;
    boolean toolboxMode;
    try {
        SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                "getComponentRootName() = " + kmelia.getComponentRootName());
        if ("kmax".equals(kmelia.getComponentRootName())) {
            kmaxMode = true;
            kmelia.isKmaxMode = true;
        }
        request.setAttribute("KmaxMode", kmaxMode);

        toolboxMode = KmeliaHelper.isToolbox(kmelia.getComponentId());

        // Set language choosen by the user
        setLanguage(request, kmelia);

        if (function.startsWith("Main")) {
            resetWizard(kmelia);
            if (kmaxMode) {
                destination = getDestination("KmaxMain", kmelia, request);
                kmelia.setSessionTopic(null);
                kmelia.setSessionPath("");
            } else {
                destination = getDestination("GoToTopic", kmelia, request);
            }
        } else if (function.startsWith("validateClassification")) {
            String[] publicationIds = request.getParameterValues("pubid");
            Collection<KmeliaPublication> publications = kmelia
                    .getPublications(asPks(kmelia.getComponentId(), publicationIds));
            request.setAttribute("Context", URLManager.getApplicationURL());
            request.setAttribute("PublicationsDetails", publications);
            destination = rootDestination + "validateImportedFilesClassification.jsp";
        } else if (function.startsWith("portlet")) {
            kmelia.setSessionPublication(null);
            String flag = kmelia.getUserRoleLevel();
            if (kmaxMode) {
                destination = rootDestination + "kmax_portlet.jsp?Profile=" + flag;
            } else {
                destination = rootDestination + "portlet.jsp?Profile=user";
            }
        } else if (function.equals("FlushTrashCan")) {
            kmelia.flushTrashCan();
            if (kmaxMode) {
                destination = getDestination("KmaxMain", kmelia, request);
            } else {
                destination = getDestination("GoToCurrentTopic", kmelia, request);
            }
        } else if (function.equals("GoToDirectory")) {
            String topicId = request.getParameter("Id");

            String path;
            if (StringUtil.isDefined(topicId)) {
                NodeDetail topic = kmelia.getNodeHeader(topicId);
                path = topic.getPath();
            } else {
                path = request.getParameter("Path");
            }

            FileFolder folder = new FileFolder(path);
            request.setAttribute("Directory", folder);
            request.setAttribute("LinkedPathString", kmelia.getSessionPath());

            destination = rootDestination + "repository.jsp";
        } else if ("GoToTopic".equals(function)) {
            String topicId = (String) request.getAttribute("Id");
            if (!StringUtil.isDefined(topicId)) {
                topicId = request.getParameter("Id");
                if (!StringUtil.isDefined(topicId)) {
                    topicId = NodePK.ROOT_NODE_ID;
                }
            }
            kmelia.setCurrentFolderId(topicId, true);
            resetWizard(kmelia);
            request.setAttribute("CurrentFolderId", topicId);
            request.setAttribute("DisplayNBPublis", kmelia.displayNbPublis());
            request.setAttribute("DisplaySearch", kmelia.isSearchOnTopicsEnabled());

            // rechercher si le theme a un descripteur
            request.setAttribute("HaveDescriptor", kmelia.isTopicHaveUpdateChainDescriptor());

            request.setAttribute("Profile", kmelia.getUserTopicProfile(topicId));
            request.setAttribute("IsGuest", kmelia.getUserDetail().isAccessGuest());
            request.setAttribute("RightsOnTopicsEnabled", kmelia.isRightsOnTopicsEnabled());
            request.setAttribute("WysiwygDescription", kmelia.getWysiwygOnTopic());
            request.setAttribute("PageIndex", kmelia.getIndexOfFirstPubToDisplay());

            if (kmelia.isTreeviewUsed()) {
                destination = rootDestination + "treeview.jsp";
            } else if (kmelia.isTreeStructure()) {
                destination = rootDestination + "oneLevel.jsp";
            } else {
                destination = rootDestination + "simpleListOfPublications.jsp";
            }
        } else if ("GoToCurrentTopic".equals(function)) {
            if (!NodePK.ROOT_NODE_ID.equals(kmelia.getCurrentFolderId())) {
                request.setAttribute("Id", kmelia.getCurrentFolderId());
                destination = getDestination("GoToTopic", kmelia, request);
            } else {
                destination = getDestination("Main", kmelia, request);
            }
        } else if (function.equals("GoToBasket")) {
            destination = rootDestination + "basket.jsp";
        } else if (function.equals("ViewPublicationsToValidate")) {
            destination = rootDestination + "publicationsToValidate.jsp";
        } else if ("GoBackToResults".equals(function)) {
            request.setAttribute("SearchContext", kmelia.getSearchContext());
            destination = getDestination("GoToCurrentTopic", kmelia, request);
        } else if (function.startsWith("searchResult")) {
            resetWizard(kmelia);
            String id = request.getParameter("Id");
            String type = request.getParameter("Type");
            String fileAlreadyOpened = request.getParameter("FileOpened");
            String from = request.getParameter("From");
            if ("Search".equals(from)) {
                // identify clearly access from global search
                // because same URL is used from portlet, permalink...
                request.setAttribute("SearchScope", SearchContext.GLOBAL);
            }

            if (type != null && ("Publication".equals(type)
                    || "com.stratelia.webactiv.calendar.backbone.TodoDetail".equals(type)
                    || "Attachment".equals(type) || "Document".equals(type) || type.startsWith("Comment"))) {
                KmeliaSecurity security = new KmeliaSecurity(kmelia.getOrganisationController());
                try {
                    boolean accessAuthorized = security.isAccessAuthorized(kmelia.getComponentId(),
                            kmelia.getUserId(), id, "Publication");
                    if (accessAuthorized) {
                        processPath(kmelia, id);
                        if ("Attachment".equals(type)) {
                            String attachmentId = request.getParameter("AttachmentId");
                            request.setAttribute("AttachmentId", attachmentId);
                            destination = getDestination("ViewPublication", kmelia, request);
                        } else if ("Document".equals(type)) {
                            String documentId = request.getParameter("DocumentId");
                            request.setAttribute("DocumentId", documentId);
                            destination = getDestination("ViewPublication", kmelia, request);
                        } else {
                            if (kmaxMode) {
                                request.setAttribute("FileAlreadyOpened", fileAlreadyOpened);
                                destination = getDestination("ViewPublication", kmelia, request);
                            } else if (toolboxMode) {
                                // we have to find which page contains the right publication
                                List<KmeliaPublication> publications = kmelia.getSessionPublicationsList();
                                int pubIndex = -1;
                                for (int p = 0; p < publications.size() && pubIndex == -1; p++) {
                                    KmeliaPublication publication = publications.get(p);
                                    if (id.equals(publication.getDetail().getPK().getId())) {
                                        pubIndex = p;
                                    }
                                }
                                int nbPubliPerPage = kmelia.getNbPublicationsPerPage();
                                if (nbPubliPerPage == 0) {
                                    nbPubliPerPage = pubIndex;
                                }
                                int ipage = pubIndex / nbPubliPerPage;
                                kmelia.setIndexOfFirstPubToDisplay(Integer.toString(ipage * nbPubliPerPage));
                                request.setAttribute("PubIdToHighlight", id);
                                request.setAttribute("Id", kmelia.getCurrentFolderId());
                                destination = getDestination("GoToTopic", kmelia, request);
                            } else {
                                request.setAttribute("FileAlreadyOpened", fileAlreadyOpened);
                                destination = getDestination("ViewPublication", kmelia, request);
                            }
                        }
                    } else {
                        destination = "/admin/jsp/accessForbidden.jsp";
                    }
                } catch (Exception e) {
                    SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()",
                            "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e);
                    destination = getDocumentNotFoundDestination(kmelia, request);
                }
            } else if ("Node".equals(type)) {
                if (kmaxMode) {
                    // Simuler l'action d'un utilisateur ayant slectionn la valeur id d'un axe
                    // SearchCombination est un chemin /0/4/i
                    NodeDetail node = kmelia.getNodeHeader(id);
                    String path = node.getPath() + id;
                    request.setAttribute("SearchCombination", path);
                    destination = getDestination("KmaxSearch", kmelia, request);
                } else {
                    try {
                        request.setAttribute("Id", id);
                        destination = getDestination("GoToTopic", kmelia, request);
                    } catch (Exception e) {
                        SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()",
                                "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e);
                        destination = getDocumentNotFoundDestination(kmelia, request);
                    }
                }
            } else if ("Wysiwyg".equals(type)) {
                if (id.startsWith("Node")) {
                    id = id.substring("Node_".length(), id.length());
                    request.setAttribute("Id", id);
                    destination = getDestination("GoToTopic", kmelia, request);
                } else {
                    destination = getDestination("ViewPublication", kmelia, request);
                }
            } else {
                request.setAttribute("Id", NodePK.ROOT_NODE_ID);
                destination = getDestination("GoToTopic", kmelia, request);
            }
        } else if (function.startsWith("GoToFilesTab")) {
            String id = request.getParameter("Id");
            try {
                processPath(kmelia, id);
                if (toolboxMode) {
                    KmeliaPublication kmeliaPublication = kmelia.getPublication(id);
                    kmelia.setSessionPublication(kmeliaPublication);
                    kmelia.setSessionOwner(true);
                    destination = getDestination("ViewAttachments", kmelia, request);
                } else {
                    destination = getDestination("ViewPublication", kmelia, request);
                }
            } catch (Exception e) {
                SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                        "Document Not Found = " + e.getMessage(), e);
                destination = getDocumentNotFoundDestination(kmelia, request);
            }
        } else if ("ToUpdatePublicationHeader".equals(function)) {
            request.setAttribute("Action", "UpdateView");
            destination = getDestination("publicationManager.jsp", kmelia, request);
        } else if ("publicationManager.jsp".equals(function)) {
            String action = (String) request.getAttribute("Action");
            if ("UpdateView".equals(action)) {
                request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK());
                request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK());
                request.setAttribute("Publication", kmelia.getSessionPubliOrClone());
            } else if ("New".equals(action)) {
                request.setAttribute("TaxonomyOK", true);
                request.setAttribute("ValidatorsOK", true);
            }

            request.setAttribute("Wizard", kmelia.getWizard());
            request.setAttribute("Path", kmelia.getTopicPath(kmelia.getCurrentFolderId()));
            request.setAttribute("Profile", kmelia.getProfile());

            destination = rootDestination + "publicationManager.jsp";
            // thumbnail error for front explication
            if (request.getParameter("errorThumbnail") != null) {
                destination = destination + "&resultThumbnail=" + request.getParameter("errorThumbnail");
            }
        } else if (function.equals("ToAddTopic")) {
            String topicId = request.getParameter("Id");
            if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(topicId))) {
                destination = "/admin/jsp/accessForbidden.jsp";
            } else {
                String isLink = request.getParameter("IsLink");
                if (StringUtil.isDefined(isLink)) {
                    request.setAttribute("IsLink", Boolean.TRUE);
                }

                List<NodeDetail> path = kmelia.getTopicPath(topicId);
                request.setAttribute("Path", kmelia.displayPath(path, false, 3));
                request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3));
                request.setAttribute("Translation", kmelia.getCurrentLanguage());
                request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed());
                request.setAttribute("Parent", kmelia.getNodeHeader(topicId));

                if (kmelia.isRightsOnTopicsEnabled()) {
                    request.setAttribute("Profiles", kmelia.getTopicProfiles());

                    // Rights of the component
                    request.setAttribute("RightsDependsOn", "ThisComponent");
                }

                destination = rootDestination + "addTopic.jsp";
            }
        } else if ("ToUpdateTopic".equals(function)) {
            String id = request.getParameter("Id");
            NodeDetail node = kmelia.getSubTopicDetail(id);
            if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))
                    && !SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(node.getFatherPK().getId()))) {
                destination = "/admin/jsp/accessForbidden.jsp";
            } else {
                request.setAttribute("NodeDetail", node);

                List<NodeDetail> path = kmelia.getTopicPath(id);
                request.setAttribute("Path", kmelia.displayPath(path, false, 3));
                request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3));
                request.setAttribute("Translation", kmelia.getCurrentLanguage());
                request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed());

                if (kmelia.isRightsOnTopicsEnabled()) {
                    request.setAttribute("Profiles", kmelia.getTopicProfiles(id));

                    if (node.haveInheritedRights()) {
                        request.setAttribute("RightsDependsOn", "AnotherTopic");
                    } else if (node.haveLocalRights()) {
                        request.setAttribute("RightsDependsOn", "ThisTopic");
                    } else {
                        // Rights of the component
                        request.setAttribute("RightsDependsOn", "ThisComponent");
                    }
                }

                destination = rootDestination + "updateTopicNew.jsp";
            }
        } else if (function.equals("AddTopic")) {
            String name = request.getParameter("Name");
            String description = request.getParameter("Description");
            String alertType = request.getParameter("AlertType");
            if (!StringUtil.isDefined(alertType)) {
                alertType = "None";
            }
            String rightsUsed = request.getParameter("RightsUsed");
            String path = request.getParameter("Path");
            String parentId = request.getParameter("ParentId");

            NodeDetail topic = new NodeDetail("-1", name, description, null, null, null, "0", "X");
            I18NHelper.setI18NInfo(topic, request);

            if (StringUtil.isDefined(path)) {
                topic.setType(NodeDetail.FILE_LINK_TYPE);
                topic.setPath(path);
            }

            int rightsDependsOn = -1;
            if (StringUtil.isDefined(rightsUsed)) {
                if ("father".equalsIgnoreCase(rightsUsed)) {
                    NodeDetail father = kmelia.getCurrentFolder();
                    rightsDependsOn = father.getRightsDependsOn();
                } else {
                    rightsDependsOn = 0;
                }
                topic.setRightsDependsOn(rightsDependsOn);
            }
            NodePK nodePK = kmelia.addSubTopic(topic, alertType, parentId);
            if (kmelia.isRightsOnTopicsEnabled()) {
                if (rightsDependsOn == 0) {
                    request.setAttribute("NodeId", nodePK.getId());
                    destination = getDestination("ViewTopicProfiles", kmelia, request);
                } else {
                    destination = getDestination("GoToCurrentTopic", kmelia, request);
                }
            } else {
                destination = getDestination("GoToCurrentTopic", kmelia, request);
            }
        } else if ("UpdateTopic".equals(function)) {
            String name = request.getParameter("Name");
            String description = request.getParameter("Description");
            String alertType = request.getParameter("AlertType");
            if (!StringUtil.isDefined(alertType)) {
                alertType = "None";
            }
            String id = request.getParameter("ChildId");
            String path = request.getParameter("Path");
            NodeDetail topic = new NodeDetail(id, name, description, null, null, null, "0", "X");
            I18NHelper.setI18NInfo(topic, request);
            if (StringUtil.isDefined(path)) {
                topic.setType(NodeDetail.FILE_LINK_TYPE);
                topic.setPath(path);
            }
            boolean goToProfilesDefinition = false;
            if (kmelia.isRightsOnTopicsEnabled()) {
                int rightsUsed = Integer.parseInt(request.getParameter("RightsUsed"));
                topic.setRightsDependsOn(rightsUsed);

                // process destination
                NodeDetail oldTopic = kmelia.getNodeHeader(id);
                if (oldTopic.getRightsDependsOn() != rightsUsed) {
                    // rights dependency have changed
                    if (rightsUsed != -1) {
                        // folder uses its own rights
                        goToProfilesDefinition = true;
                    }
                }
            }
            kmelia.updateTopicHeader(topic, alertType);

            if (goToProfilesDefinition) {
                request.setAttribute("NodeId", id);
                destination = getDestination("ViewTopicProfiles", kmelia, request);
            } else {
                destination = getDestination("GoToCurrentTopic", kmelia, request);
            }
        } else if (function.equals("DeleteTopic")) {
            String id = request.getParameter("Id");
            kmelia.deleteTopic(id);
            destination = getDestination("GoToCurrentTopic", kmelia, request);
        } else if (function.equals("ViewClone")) {
            PublicationDetail pubDetail = kmelia.getSessionPublication().getDetail();

            // Reload clone and put it into session
            String cloneId = pubDetail.getCloneId();
            KmeliaPublication kmeliaPublication = kmelia.getPublication(cloneId);
            kmelia.setSessionClone(kmeliaPublication);

            request.setAttribute("Publication", kmeliaPublication);
            request.setAttribute("Profile", kmelia.getProfile());
            request.setAttribute("VisiblePublicationId", pubDetail.getPK().getId());
            request.setAttribute("UserCanValidate", kmelia.isUserCanValidatePublication());
            request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK());
            request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK());

            putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), kmelia, request);

            // Attachments area must be displayed or not ?
            request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled());

            destination = rootDestination + "clone.jsp";
        } else if ("ViewPublication".equals(function)) {
            String id = request.getParameter("PubId");
            if (!StringUtil.isDefined(id)) {
                id = request.getParameter("Id");
                if (!StringUtil.isDefined(id)) {
                    id = (String) request.getAttribute("PubId");
                }
            }

            if (!kmaxMode) {
                boolean checkPath = StringUtil.getBooleanValue(request.getParameter("CheckPath"));
                if (checkPath || KmeliaHelper.isToValidateFolder(kmelia.getCurrentFolderId())) {
                    processPath(kmelia, id);
                } else {
                    processPath(kmelia, null);
                }
            }

            // view publication from global search ?
            Integer searchScope = (Integer) request.getAttribute("SearchScope");
            if (searchScope == null) {
                if (kmelia.getSearchContext() != null) {
                    request.setAttribute("SearchScope", SearchContext.LOCAL);
                } else {
                    request.setAttribute("SearchScope", SearchContext.NONE);
                }
            }

            KmeliaPublication kmeliaPublication;
            if (StringUtil.isDefined(id)) {
                kmeliaPublication = kmelia.getPublication(id, true);
                kmelia.setSessionPublication(kmeliaPublication);

                PublicationDetail pubDetail = kmeliaPublication.getDetail();
                if (pubDetail.haveGotClone()) {
                    KmeliaPublication clone = kmelia.getPublication(pubDetail.getCloneId());
                    kmelia.setSessionClone(clone);
                }
            } else {
                kmeliaPublication = kmelia.getSessionPublication();
                id = kmeliaPublication.getDetail().getPK().getId();
            }
            if (toolboxMode) {
                destination = getDestination("ToUpdatePublicationHeader", kmelia, request);
            } else {
                List<String> publicationLanguages = kmelia.getPublicationLanguages(); // languages of
                // publication
                // header and attachments
                if (publicationLanguages.contains(kmelia.getCurrentLanguage())) {
                    request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage());
                } else {
                    request.setAttribute("ContentLanguage",
                            checkLanguage(kmelia, kmeliaPublication.getDetail()));
                }
                request.setAttribute("Languages", publicationLanguages);

                // see also management
                Collection<ForeignPK> links = kmeliaPublication.getCompleteDetail().getLinkList();
                HashSet<String> linkedList = new HashSet<String>(links.size());
                for (ForeignPK link : links) {
                    linkedList.add(link.getId() + "-" + link.getInstanceId());
                }
                // put into session the current list of selected publications (see also)
                request.getSession().setAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY, linkedList);

                request.setAttribute("Publication", kmeliaPublication);
                request.setAttribute("PubId", id);
                request.setAttribute("UserCanValidate",
                        kmelia.isUserCanValidatePublication() && kmelia.getSessionClone() == null);
                request.setAttribute("ValidationStep", kmelia.getValidationStep());
                request.setAttribute("ValidationType", kmelia.getValidationType());

                // check if user is writer with approval right (versioning case)
                request.setAttribute("WriterApproval", kmelia.isWriterApproval(id));
                request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed());

                // check is requested publication is an alias
                checkAlias(kmelia, kmeliaPublication);

                if (kmeliaPublication.isAlias()) {
                    request.setAttribute("Profile", "user");
                    request.setAttribute("TaxonomyOK", false);
                    request.setAttribute("ValidatorsOK", false);
                    request.setAttribute("IsAlias", "1");
                } else {
                    request.setAttribute("Profile", kmelia.getProfile());
                    request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK());
                    request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK());
                }

                request.setAttribute("Wizard", kmelia.getWizard());

                request.setAttribute("Rang", kmelia.getRang());
                if (kmelia.getSessionPublicationsList() != null) {
                    request.setAttribute("NbPublis", kmelia.getSessionPublicationsList().size());
                } else {
                    request.setAttribute("NbPublis", 1);
                }
                putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), kmelia, request);
                String fileAlreadyOpened = (String) request.getAttribute("FileAlreadyOpened");
                boolean alreadyOpened = "1".equals(fileAlreadyOpened);
                String attachmentId = (String) request.getAttribute("AttachmentId");
                String documentId = (String) request.getAttribute("DocumentId");
                if (!alreadyOpened && kmelia.openSingleAttachmentAutomatically()
                        && !kmelia.isCurrentPublicationHaveContent()) {
                    request.setAttribute("SingleAttachmentURL",
                            kmelia.getFirstAttachmentURLOfCurrentPublication());
                } else if (!alreadyOpened && attachmentId != null) {
                    request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(attachmentId));
                } else if (!alreadyOpened && documentId != null) {
                    request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(documentId));
                }

                // Attachments area must be displayed or not ?
                request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled());

                // option Actualits dcentralises
                request.setAttribute("NewsManage", kmelia.isNewsManage());
                if (kmelia.isNewsManage()) {
                    request.setAttribute("DelegatedNews", kmelia.getDelegatedNews(id));
                    request.setAttribute("IsBasket", NodePK.BIN_NODE_ID.equals(kmelia.getCurrentFolderId()));
                }

                request.setAttribute("LastAccess", kmelia.getLastAccess(kmeliaPublication.getPk()));
                request.setAttribute("PublicationRatingsAllowed", kmelia.isPublicationRatingAllowed());

                destination = rootDestination + "publication.jsp";
            }
        } else if (function.equals("PreviousPublication")) {
            // rcupration de la publication prcdente
            String pubId = kmelia.getPrevious();
            request.setAttribute("PubId", pubId);
            destination = getDestination("ViewPublication", kmelia, request);
        } else if (function.equals("NextPublication")) {
            // rcupration de la publication suivante
            String pubId = kmelia.getNext();
            request.setAttribute("PubId", pubId);
            destination = getDestination("ViewPublication", kmelia, request);
        } else if (function.startsWith("copy")) {
            String objectType = request.getParameter("Object");
            String objectId = request.getParameter("Id");
            if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) {
                kmelia.copyTopic(objectId);
            } else {
                kmelia.copyPublication(objectId);
            }

            destination = URLManager.getURL(URLManager.CMP_CLIPBOARD, null, null)
                    + "Idle.jsp?message=REFRESHCLIPBOARD";
        } else if (function.startsWith("cut")) {
            String objectType = request.getParameter("Object");
            String objectId = request.getParameter("Id");
            if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) {
                kmelia.cutTopic(objectId);
            } else {
                kmelia.cutPublication(objectId);
            }

            destination = URLManager.getURL(URLManager.CMP_CLIPBOARD, null, null)
                    + "Idle.jsp?message=REFRESHCLIPBOARD";
        } else if (function.startsWith("paste")) {
            kmelia.paste();
            destination = URLManager.getURL(URLManager.CMP_CLIPBOARD, null, null) + "Idle.jsp";
        } else if (function.startsWith("ToAlertUserAttachment")) { // utilisation de alertUser et
            // alertUserPeas
            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "ToAlertUserAttachment: function = " + function + " spaceId=" + kmelia.getSpaceId()
                            + " componentId=" + kmelia.getComponentId());
            try {
                String attachmentId = request.getParameter("AttachmentOrDocumentId");
                destination = kmelia.initAlertUserAttachment(attachmentId);
            } catch (Exception e) {
                SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED",
                        "function = " + function, e);
            }
            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "ToAlertUserAttachment: function = " + function + "=> destination=" + destination);
        } else if (function.startsWith("ToAlertUserDocument")) { // utilisation de alertUser et
            // alertUserPeas
            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "ToAlertUserDocument: function = " + function + " spaceId=" + kmelia.getSpaceId()
                            + " componentId=" + kmelia.getComponentId());
            try {
                String documentId = request.getParameter("AttachmentOrDocumentId");
                destination = kmelia.initAlertUserAttachment(documentId);
            } catch (Exception e) {
                SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED",
                        "function = " + function, e);
            }
            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "ToAlertUserDocument: function = " + function + "=> destination=" + destination);
        } else if (function.startsWith("ToAlertUser")) { // utilisation de alertUser et alertUserPeas
            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "ToAlertUser: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId="
                            + kmelia.getComponentId());
            try {
                destination = kmelia.initAlertUser();
            } catch (Exception e) {
                SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED",
                        "function = " + function, e);
            }
            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "ToAlertUser: function = " + function + "=> destination=" + destination);
        } else if (function.equals("ReadingControl")) {
            PublicationDetail publication = kmelia.getSessionPublication().getDetail();
            request.setAttribute("LinkedPathString", kmelia.getSessionPath());
            request.setAttribute("Publication", publication);
            request.setAttribute("UserIds", kmelia.getUserIdsOfTopic());

            // paramtre du wizard
            request.setAttribute("Wizard", kmelia.getWizard());

            destination = rootDestination + "readingControlManager.jsp";
        } else if (function.startsWith("ViewAttachments")) {
            String flag = kmelia.getProfile();

            // Versioning is out of "Always visible publication" mode
            if (kmelia.isCloneNeeded() && !kmelia.isVersionControlled()) {
                kmelia.clonePublication();
            }

            // put current publication
            if (!kmelia.isVersionControlled()) {
                request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone().getDetail());
            } else {
                request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication().getDetail());
            }
            // Paramtres du wizard
            setWizardParams(request, kmelia);

            // Paramtres de i18n
            List<String> attachmentLanguages = kmelia.getAttachmentLanguages();
            if (attachmentLanguages.contains(kmelia.getCurrentLanguage())) {
                request.setAttribute("Language", kmelia.getCurrentLanguage());
            } else {
                request.setAttribute("Language", checkLanguage(kmelia));
            }
            request.setAttribute("Languages", attachmentLanguages);

            request.setAttribute("XmlFormForFiles", kmelia.getXmlFormForFiles());

            destination = rootDestination + "attachmentManager.jsp?profile=" + flag;
        } else if (function.equals("DeletePublication")) {
            String pubId = request.getParameter("PubId");
            kmelia.deletePublication(pubId);

            if (kmaxMode) {
                destination = getDestination("Main", kmelia, request);
            } else {
                destination = getDestination("GoToCurrentTopic", kmelia, request);
            }
        } else if (function.equals("DeleteClone")) {
            kmelia.deleteClone();

            destination = getDestination("ViewPublication", kmelia, request);
        } else if (function.equals("ViewValidationSteps")) {
            request.setAttribute("LinkedPathString", kmelia.getSessionPath());
            request.setAttribute("Publication", kmelia.getSessionPubliOrClone().getDetail());
            request.setAttribute("ValidationSteps", kmelia.getValidationSteps());

            request.setAttribute("Role", kmelia.getProfile());

            destination = rootDestination + "validationSteps.jsp";
        } else if ("ValidatePublication".equals(function)) {
            String pubId = kmelia.getSessionPublication().getDetail().getPK().getId();

            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "function = " + function + " pubId=" + pubId);

            boolean validationComplete = kmelia.validatePublication(pubId);
            if (validationComplete) {
                request.setAttribute("Action", "ValidationComplete");
                destination = getDestination("ViewPublication", kmelia, request);
            } else {
                request.setAttribute("Action", "ValidationInProgress");
                if (kmelia.getSessionClone() != null) {
                    destination = getDestination("ViewClone", kmelia, request);
                } else {
                    destination = getDestination("ViewPublication", kmelia, request);
                }
            }
        } else if (function.equals("ForceValidatePublication")) {
            String pubId = kmelia.getSessionPublication().getDetail().getPK().getId();
            kmelia.forcePublicationValidation(pubId);
            request.setAttribute("Action", "ValidationComplete");

            request.setAttribute("PubId", pubId);
            destination = getDestination("ViewPublication", kmelia, request);
        } else if ("Unvalidate".equals(function)) {
            String motive = request.getParameter("Motive");
            String pubId = kmelia.getSessionPublication().getDetail().getPK().getId();

            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "function = " + function + " pubId=" + pubId);

            kmelia.unvalidatePublication(pubId, motive);

            request.setAttribute("Action", "Unvalidate");

            if (kmelia.getSessionClone() != null) {
                destination = getDestination("ViewClone", kmelia, request);
            } else {
                destination = getDestination("ViewPublication", kmelia, request);
            }
        } else if (function.equals("WantToSuspendPubli")) {
            String pubId = request.getParameter("PubId");

            PublicationDetail pubDetail = kmelia.getPublicationDetail(pubId);

            request.setAttribute("PublicationToSuspend", pubDetail);

            destination = rootDestination + "defermentMotive.jsp";
        } else if (function.equals("SuspendPublication")) {
            String motive = request.getParameter("Motive");
            String pubId = request.getParameter("PubId");

            kmelia.suspendPublication(pubId, motive);

            request.setAttribute("Action", "Suspend");

            destination = getDestination("ViewPublication", kmelia, request);
        } else if (function.equals("DraftIn")) {
            kmelia.draftInPublication();
            if (kmelia.getSessionClone() != null) {
                // draft have generate a clone
                destination = getDestination("ViewClone", kmelia, request);
            } else {
                String from = request.getParameter("From");
                if (StringUtil.isDefined(from)) {
                    destination = getDestination(from, kmelia, request);
                } else {
                    destination = getDestination("ToUpdatePublicationHeader", kmelia, request);
                }
            }
        } else if (function.equals("DraftOut")) {
            kmelia.draftOutPublication();

            destination = getDestination("ViewPublication", kmelia, request);
        } else if (function.equals("ToTopicWysiwyg")) {
            String topicId = request.getParameter("Id");
            String subTopicId = request.getParameter("ChildId");
            String flag = kmelia.getProfile();

            NodeDetail topic = kmelia.getSubTopicDetail(subTopicId);

            request.setAttribute("SpaceId", kmelia.getSpaceId());
            request.setAttribute("SpaceName", URLEncoder.encode(kmelia.getSpaceLabel(), CharEncoding.UTF_8));
            request.setAttribute("ComponentId", kmelia.getComponentId());
            request.setAttribute("ComponentName",
                    URLEncoder.encode(kmelia.getComponentLabel(), CharEncoding.UTF_8));
            String browseInfo = kmelia.getSessionPathString();
            if (browseInfo != null && !browseInfo.contains(topic.getName())) {
                browseInfo += topic.getName();
            }
            if (!StringUtil.isDefined(browseInfo)) {
                browseInfo = kmelia.getString("TopicWysiwyg");
            } else {
                browseInfo += " > " + kmelia.getString("TopicWysiwyg");
            }
            request.setAttribute("BrowseInfo", browseInfo);
            request.setAttribute("ObjectId", "Node_" + subTopicId);
            request.setAttribute("Language", kmelia.getLanguage());
            request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage());
            request.setAttribute("ReturnUrl",
                    URLManager.getApplicationURL()
                            + URLManager.getURL(kmelia.getSpaceId(), kmelia.getComponentId())
                            + "FromTopicWysiwyg?Action=Search&Id=" + topicId + "&ChildId=" + subTopicId
                            + "&Profile=" + flag);
            destination = "/wysiwyg/jsp/htmlEditor.jsp";
        } else if (function.equals("FromTopicWysiwyg")) {
            String subTopicId = request.getParameter("ChildId");

            kmelia.processTopicWysiwyg(subTopicId);

            destination = getDestination("GoToCurrentTopic", kmelia, request);
        } else if (function.equals("ChangeTopicStatus")) {
            String subTopicId = request.getParameter("ChildId");
            String newStatus = request.getParameter("Status");
            String recursive = request.getParameter("Recursive");

            if (recursive != null && recursive.equals("1")) {
                kmelia.changeTopicStatus(newStatus, subTopicId, true);
            } else {
                kmelia.changeTopicStatus(newStatus, subTopicId, false);
            }

            destination = getDestination("GoToCurrentTopic", kmelia, request);
        } else if (function.equals("ViewOnly")) {
            String id = request.getParameter("Id");
            destination = rootDestination + "publicationViewOnly.jsp?Id=" + id;
        } else if (function.equals("SeeAlso")) {
            String action = request.getParameter("Action");
            if (!StringUtil.isDefined(action)) {
                action = "LinkAuthorView";
            }

            request.setAttribute("Action", action);

            // check if requested publication is an alias
            String pubId = request.getParameter("PubId");
            KmeliaPublication kmeliaPublication = kmelia.getSessionPublication();
            if (StringUtil.isDefined(pubId)) {
                kmeliaPublication = kmelia.getPublication(pubId);
                kmelia.setSessionPublication(kmeliaPublication);
            }
            checkAlias(kmelia, kmeliaPublication);

            if (kmeliaPublication.isAlias()) {
                request.setAttribute("Profile", "user");
                request.setAttribute("IsAlias", "1");
            } else {
                request.setAttribute("Profile", kmelia.getProfile());
            }

            // paramtres du wizard
            request.setAttribute("Wizard", kmelia.getWizard());

            destination = rootDestination + "seeAlso.jsp";
        } else if (function.equals("DeleteSeeAlso")) {
            String[] pubIds = request.getParameterValues("PubIds");

            if (pubIds != null) {
                List<ForeignPK> infoLinks = new ArrayList<ForeignPK>();
                for (String pubId : pubIds) {
                    StringTokenizer tokens = new StringTokenizer(pubId, "-");
                    infoLinks.add(new ForeignPK(tokens.nextToken(), tokens.nextToken()));

                    // removing deleted pks from session
                    Set<String> list = (Set<String>) request.getSession()
                            .getAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY);
                    if (list != null) {
                        list.remove(pubId);
                    }
                }

                if (!infoLinks.isEmpty()) {
                    kmelia.deleteInfoLinks(kmelia.getSessionPublication().getId(), infoLinks);
                }
            }

            destination = getDestination("SeeAlso", kmelia, request);
        } else if (function.equals("ImportFileUpload")) {
            destination = processFormUpload(kmelia, request, rootDestination, false);
        } else if (function.equals("ImportFilesUpload")) {
            destination = processFormUpload(kmelia, request, rootDestination, true);
        } else if (function.equals("ExportAttachementsToPDF")) {
            String topicId = request.getParameter("TopicId");
            // build an exploitable list by importExportPeas
            SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()",
                    "root.MSG_PARAM_VALUE", "topicId =" + topicId);
            List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId);
            request.setAttribute("selectedResultsWa", publicationsIds);
            request.setAttribute("RootPK", new NodePK(topicId, kmelia.getComponentId()));
            // Go to importExportPeas
            destination = "/RimportExportPeas/jsp/ExportPDF";
        } else if (function.equals("NewPublication")) {
            request.setAttribute("Action", "New");
            destination = getDestination("publicationManager.jsp", kmelia, request);
        } else if (function.equals("ManageSubscriptions")) {
            destination = kmelia.manageSubscriptions();
        } else if (function.equals("AddPublication")) {
            List<FileItem> parameters = request.getFileItems();

            // create publication
            String positions = FileUploadUtil.getParameter(parameters, "Positions");
            PdcClassificationEntity withClassification = PdcClassificationEntity.undefinedClassification();
            if (StringUtil.isDefined(positions)) {
                withClassification = PdcClassificationEntity.fromJSON(positions);
            }
            PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia);
            String newPubId = kmelia.createPublication(pubDetail, withClassification);
            // create thumbnail if exists
            boolean newThumbnail = ThumbnailController.processThumbnail(
                    new ForeignPK(newPubId, kmelia.getComponentId()), PublicationDetail.getResourceType(),
                    parameters);
            // force indexation to taking into account new thumbnail
            if (newThumbnail && pubDetail.isIndexable()) {
                kmelia.getPublicationBm().createIndex(pubDetail.getPK());
            }
            request.setAttribute("PubId", newPubId);
            processPath(kmelia, newPubId);
            String wizard = kmelia.getWizard();
            if ("progress".equals(wizard)) {
                KmeliaPublication kmeliaPublication = kmelia.getPublication(newPubId);
                kmelia.setSessionPublication(kmeliaPublication);
                String position = FileUploadUtil.getParameter(parameters, "Position");
                setWizardParams(request, kmelia);
                request.setAttribute("Position", position);
                request.setAttribute("Publication", kmeliaPublication);
                request.setAttribute("Profile", kmelia.getProfile());
                destination = getDestination("WizardNext", kmelia, request);
            } else {
                StringBuffer requestURI = request.getRequestURL();
                destination = requestURI.substring(0, requestURI.indexOf("AddPublication"))
                        + "ViewPublication?PubId=" + newPubId;
            }
        } else if ("UpdatePublication".equals(function)) {
            List<FileItem> parameters = request.getFileItems();

            PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia);
            String id = pubDetail.getPK().getId();
            ThumbnailController.processThumbnail(new ForeignPK(id, kmelia.getComponentId()),
                    PublicationDetail.getResourceType(), parameters);

            kmelia.updatePublication(pubDetail);

            String wizard = kmelia.getWizard();
            if (wizard.equals("progress")) {
                KmeliaPublication kmeliaPublication = kmelia.getPublication(id);
                String position = FileUploadUtil.getParameter(parameters, "Position");
                setWizardParams(request, kmelia);
                request.setAttribute("Position", position);
                request.setAttribute("Publication", kmeliaPublication);
                request.setAttribute("Profile", kmelia.getProfile());
                destination = getDestination("WizardNext", kmelia, request);
            } else {
                if (kmelia.getSessionClone() != null) {
                    destination = getDestination("ViewClone", kmelia, request);
                } else {
                    request.setAttribute("PubId", id);
                    request.setAttribute("CheckPath", "1");
                    destination = getDestination("ViewPublication", kmelia, request);
                }
            }
        } else if (function.equals("SelectValidator")) {
            destination = kmelia.initUPToSelectValidator("");
        } else if (function.equals("PublicationPaths")) {
            // paramtre du wizard
            request.setAttribute("Wizard", kmelia.getWizard());

            PublicationDetail publication = kmelia.getSessionPublication().getDetail();
            String pubId = publication.getPK().getId();
            request.setAttribute("Publication", publication);
            request.setAttribute("LinkedPathString", kmelia.getSessionPath());
            request.setAttribute("PathList", kmelia.getPublicationFathers(pubId));

            if (toolboxMode) {
                request.setAttribute("Topics", kmelia.getAllTopics());
            } else {
                List<Alias> aliases = kmelia.getAliases();
                request.setAttribute("Aliases", aliases);
                request.setAttribute("Components", kmelia.getComponents(aliases));
            }

            destination = rootDestination + "publicationPaths.jsp";
        } else if (function.equals("SetPath")) {
            String[] topics = request.getParameterValues("topicChoice");
            String loadedComponentIds = request.getParameter("LoadedComponentIds");

            Alias alias;
            List<Alias> aliases = new ArrayList<Alias>();
            for (int i = 0; topics != null && i < topics.length; i++) {
                String topicId = topics[i];
                SilverTrace.debug("kmelia", "KmeliaRequestRouter.setPath()", "root.MSG_GEN_PARAM_VALUE",
                        "topicId = " + topicId);
                StringTokenizer tokenizer = new StringTokenizer(topicId, ",");
                String nodeId = tokenizer.nextToken();
                String instanceId = tokenizer.nextToken();

                alias = new Alias(nodeId, instanceId);
                alias.setUserId(kmelia.getUserId());
                aliases.add(alias);
            }

            // Tous les composants ayant un alias n'ont pas forcment t chargs
            List<Alias> oldAliases = kmelia.getAliases();
            for (Alias oldAlias : oldAliases) {
                if (!loadedComponentIds.contains(oldAlias.getInstanceId())) {
                    // le composant de l'alias n'a pas t charg
                    aliases.add(oldAlias);
                }
            }

            kmelia.setAliases(aliases);

            destination = getDestination("ViewPublication", kmelia, request);
        } else if (function.equals("ShowAliasTree")) {
            String componentId = request.getParameter("ComponentId");

            request.setAttribute("Tree", kmelia.getAliasTreeview(componentId));
            request.setAttribute("Aliases", kmelia.getAliases());

            destination = rootDestination + "treeview4PublicationPaths.jsp";
        } else if (function.equals("AddLinksToPublication")) {
            String id = request.getParameter("PubId");
            String topicId = request.getParameter("TopicId");
            //noinspection unchecked
            HashSet<String> list = (HashSet) request.getSession()
                    .getAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY);

            int nb = kmelia.addPublicationsToLink(id, list);

            request.setAttribute("NbLinks", Integer.toString(nb));

            destination = rootDestination + "publicationLinksManager.jsp?Action=Add&Id=" + topicId;
        } else if (function.equals("ExportTopic")) {
            String topicId = request.getParameter("TopicId");
            boolean exportFullApp = !StringUtil.isDefined(topicId) || NodePK.ROOT_NODE_ID.equals(topicId);
            if (kmaxMode) {
                if (exportFullApp) {
                    destination = getDestination("KmaxExportComponent", kmelia, request);
                } else {
                    destination = getDestination("KmaxExportPublications", kmelia, request);
                }
            } else {
                // build an exploitable list by importExportPeas
                SilverTrace.info("kmelia", "KmeliaRequestRouter.ExportTopic", "root.MSG_PARAM_VALUE",
                        "topicId =" + topicId);
                final List<WAAttributeValuePair> publicationsIds;
                if (exportFullApp) {
                    publicationsIds = kmelia.getAllVisiblePublications();
                } else {
                    publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId);
                }
                request.setAttribute("selectedResultsWa", publicationsIds);
                request.setAttribute("RootPK", new NodePK(topicId, kmelia.getComponentId()));
                // Go to importExportPeas
                destination = "/RimportExportPeas/jsp/SelectExportMode";
            }
        } else if (function.equals("ExportPublications")) {
            String selectedIds = request.getParameter("SelectedIds");
            String notSelectedIds = request.getParameter("NotSelectedIds");
            List<PublicationPK> pks = kmelia.processSelectedPublicationIds(selectedIds, notSelectedIds);

            List<WAAttributeValuePair> publicationIds = new ArrayList<WAAttributeValuePair>();
            for (PublicationPK pk : pks) {
                publicationIds.add(new WAAttributeValuePair(pk.getId(), pk.getInstanceId()));
            }
            request.setAttribute("selectedResultsWa", publicationIds);
            request.setAttribute("RootPK", new NodePK(kmelia.getCurrentFolderId(), kmelia.getComponentId()));
            kmelia.resetSelectedPublicationPKs();
            // Go to importExportPeas
            destination = "/RimportExportPeas/jsp/SelectExportMode";
        } else if (function.equals("ToPubliContent")) {
            CompletePublication completePublication = kmelia.getSessionPubliOrClone().getCompleteDetail();
            if (completePublication.getModelDetail() != null) {
                destination = getDestination("ToDBModel", kmelia, request);
            } else if (WysiwygController.haveGotWysiwyg(kmelia.getComponentId(),
                    completePublication.getPublicationDetail().getPK().getId(), kmelia.getCurrentLanguage())) {

                destination = getDestination("ToWysiwyg", kmelia, request);
            } else {
                String infoId = completePublication.getPublicationDetail().getInfoId();
                if (infoId == null || "0".equals(infoId)) {
                    List<String> usedModels = (List<String>) kmelia.getModelUsed();
                    if (usedModels.size() == 1) {
                        String modelId = usedModels.get(0);
                        if ("WYSIWYG".equals(modelId)) {
                            // Wysiwyg content
                            destination = getDestination("ToWysiwyg", kmelia, request);
                        } else if (StringUtil.isInteger(modelId)) {
                            // DB template
                            ModelDetail model = kmelia.getModelDetail(modelId);
                            request.setAttribute("ModelDetail", model);
                            destination = getDestination("ToDBModel", kmelia, request);
                        } else {
                            // XML template
                            request.setAttribute("Name", modelId);
                            destination = getDestination("GoToXMLForm", kmelia, request);
                        }
                    } else {
                        destination = getDestination("ListModels", kmelia, request);
                    }
                } else {
                    destination = getDestination("GoToXMLForm", kmelia, request);
                }
            }
        } else if (function.equals("ListModels")) {
            setTemplatesUsedIntoRequest(kmelia, request);

            // put current publication
            request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication().getDetail());

            // Paramtres du wizard
            setWizardParams(request, kmelia);
            destination = rootDestination + "modelsList.jsp";
        } else if (function.equals("ModelUsed")) {
            request.setAttribute("XMLForms", kmelia.getForms());
            // put dbForms
            Collection<ModelDetail> dbForms = kmelia.getAllModels();
            request.setAttribute("DBForms", dbForms);

            Collection<String> modelUsed = kmelia.getModelUsed();
            request.setAttribute("ModelUsed", modelUsed);

            destination = rootDestination + "modelUsedList.jsp";
        } else if (function.equals("SelectModel")) {
            Object o = request.getParameterValues("modelChoice");
            if (o != null) {
                kmelia.addModelUsed((String[]) o);
            }
            destination = getDestination("GoToCurrentTopic", kmelia, request);
        } else if ("ChangeTemplate".equals(function)) {
            kmelia.removePublicationContent();
            destination = getDestination("ToPubliContent", kmelia, request);
        } else if ("ToWysiwyg".equals(function)) {
            if (kmelia.isCloneNeeded()) {
                kmelia.clonePublication();
            }
            // put current publication
            PublicationDetail publication = kmelia.getSessionPubliOrClone().getDetail();

            // Parametres du Wizard
            setWizardParams(request, kmelia);
            request.setAttribute("SpaceId", kmelia.getSpaceId());
            request.setAttribute("SpaceName", URLEncoder.encode(kmelia.getSpaceLabel(), CharEncoding.UTF_8));
            request.setAttribute("ComponentId", kmelia.getComponentId());
            request.setAttribute("ComponentName",
                    URLEncoder.encode(kmelia.getComponentLabel(), CharEncoding.UTF_8));
            if (kmaxMode) {
                request.setAttribute("BrowseInfo", publication.getName());
            } else {
                request.setAttribute("BrowseInfo",
                        kmelia.getSessionPathString() + " > " + publication.getName());
            }
            request.setAttribute("ObjectId", publication.getId());
            request.setAttribute("Language", kmelia.getLanguage());
            request.setAttribute("ContentLanguage", checkLanguage(kmelia, publication));
            request.setAttribute("ReturnUrl", URLManager.getApplicationURL() + kmelia.getComponentUrl()
                    + "FromWysiwyg?PubId=" + publication.getId());
            request.setAttribute("UserId", kmelia.getUserId());
            request.setAttribute("IndexIt", "false");

            destination = "/wysiwyg/jsp/htmlEditor.jsp";
        } else if ("FromWysiwyg".equals(function)) {
            String id = request.getParameter("PubId");

            // Parametres du Wizard
            String wizard = kmelia.getWizard();
            setWizardParams(request, kmelia);
            if (wizard.equals("progress")) {
                request.setAttribute("Position", "Content");
                destination = getDestination("WizardNext", kmelia, request);
            } else {
                if (kmelia.getSessionClone() != null
                        && id.equals(kmelia.getSessionClone().getDetail().getPK().getId())) {
                    destination = getDestination("ViewClone", kmelia, request);
                } else {
                    destination = getDestination("ViewPublication", kmelia, request);
                }
            }
        } else if (function.equals("ToDBModel")) {
            String modelId = request.getParameter("ModelId");
            if (StringUtil.isDefined(modelId)) {
                ModelDetail model = kmelia.getModelDetail(modelId);
                request.setAttribute("ModelDetail", model);
            }

            // put current publication
            request.setAttribute("CompletePublication", kmelia.getSessionPubliOrClone().getCompleteDetail());
            request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed());

            // Paramtres du wizard
            setWizardParams(request, kmelia);

            destination = rootDestination + "modelManager.jsp";
        } else if (function.equals("UpdateDBModelContent")) {
            ResourceLocator publicationSettings = kmelia.getPublicationSettings();

            List<InfoTextDetail> textDetails = new ArrayList<InfoTextDetail>();
            List<InfoImageDetail> imageDetails = new ArrayList<InfoImageDetail>();
            int imageOrder = 0;
            boolean imageTrouble = false;
            List<FileItem> parameters = request.getFileItems();
            String modelId = FileUploadUtil.getParameter(parameters, "ModelId");
            // Parametres du Wizard
            setWizardParams(request, kmelia);

            for (FileItem item : parameters) {
                if (item.isFormField() && item.getFieldName().startsWith("WATXTVAR")) {
                    String theText = item.getString();
                    int textOrder = Integer
                            .parseInt(item.getFieldName().substring(8, item.getFieldName().length()));
                    textDetails.add(new InfoTextDetail(null, Integer.toString(textOrder), null, theText));
                } else if (!item.isFormField()) {
                    String logicalName = item.getName();
                    if (logicalName != null && logicalName.length() > 0) {
                        if (!FileUtil.isWindows()) {
                            logicalName = logicalName.replace('\\', File.separatorChar);
                            SilverTrace.info("kmelia", "KmeliaRequestRouter.UpdateDBModelContent",
                                    "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName);
                        }
                        logicalName = FilenameUtils.getName(logicalName);
                        String physicalName = Long.toString(System.currentTimeMillis()) + "."
                                + FilenameUtils.getExtension(logicalName);
                        String mimeType = item.getContentType();
                        long size = item.getSize();

                        File dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId())
                                + publicationSettings.getString("imagesSubDirectory") + File.separatorChar
                                + physicalName);
                        if (FileUtil.isImage(logicalName)) {
                            item.write(dir);
                            imageOrder++;
                            if (size > 0L) {
                                imageDetails.add(new InfoImageDetail(null, Integer.toString(imageOrder), null,
                                        physicalName, logicalName, "", mimeType, size));
                                imageTrouble = false;
                            } else {
                                imageTrouble = true;
                            }
                        } else {
                            imageTrouble = true;
                        }
                    } else {
                        // the field did not contain a file
                    }
                }
            }

            InfoDetail infos = new InfoDetail(null, textDetails, imageDetails, null, "");
            CompletePublication completePub = kmelia.getSessionPubliOrClone().getCompleteDetail();
            if (completePub.getModelDetail() == null) {
                kmelia.createInfoModelDetail("useless", modelId, infos);
            } else {
                kmelia.updateInfoDetail("useless", infos);
            }
            if (imageTrouble) {
                request.setAttribute("ImageTrouble", Boolean.TRUE);
            }

            String wizard = kmelia.getWizard();
            if (wizard.equals("progress")) {
                request.setAttribute("Position", "Content");
                destination = getDestination("WizardNext", kmelia, request);
            } else {
                destination = getDestination("ToDBModel", kmelia, request);
            }
        } else if (function.equals("GoToXMLForm")) {
            String xmlFormName = request.getParameter("Name");
            if (!StringUtil.isDefined(xmlFormName)) {
                xmlFormName = (String) request.getAttribute("Name");
            }
            setXMLForm(request, kmelia, xmlFormName);
            // put current publication
            request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone().getDetail());
            // Parametres du Wizard
            setWizardParams(request, kmelia);
            // template can be changed only if current topic is using at least two templates
            setTemplatesUsedIntoRequest(kmelia, request);
            @SuppressWarnings("unchecked")
            Collection<PublicationTemplate> templates = (Collection<PublicationTemplate>) request
                    .getAttribute("XMLForms");
            boolean wysiwygUsable = (Boolean) request.getAttribute("WysiwygValid");
            request.setAttribute("IsChangingTemplateAllowed",
                    templates.size() >= 2 || (!templates.isEmpty() && wysiwygUsable));

            destination = rootDestination + "xmlForm.jsp";
        } else if (function.equals("UpdateXMLForm")) {
            if (kmelia.isCloneNeeded()) {
                kmelia.clonePublication();
            }

            if (!StringUtil.isDefined(request.getCharacterEncoding())) {
                request.setCharacterEncoding("UTF-8");
            }
            String encoding = request.getCharacterEncoding();
            List<FileItem> items = request.getFileItems();

            PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getDetail();

            String xmlFormShortName;

            // Is it the creation of the content or an update ?
            String infoId = pubDetail.getInfoId();
            if (infoId == null || "0".equals(infoId)) {
                String xmlFormName = FileUploadUtil.getParameter(items, "Name", null, encoding);

                // The publication have no content
                // We have to register xmlForm to publication
                xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf('/') + 1,
                        xmlFormName.indexOf('.'));
                pubDetail.setInfoId(xmlFormShortName);
                kmelia.updatePublication(pubDetail);
            } else {
                xmlFormShortName = pubDetail.getInfoId();
            }
            String pubId = pubDetail.getPK().getId();
            PublicationTemplate pub = getPublicationTemplateManager()
                    .getPublicationTemplate(kmelia.getComponentId() + ":" + xmlFormShortName);
            RecordSet set = pub.getRecordSet();
            Form form = pub.getUpdateForm();
            String language = checkLanguage(kmelia, pubDetail);
            DataRecord data = set.getRecord(pubId, language);
            if (data == null) {
                data = set.getEmptyRecord();
                data.setId(pubId);
                data.setLanguage(language);
            }
            PagesContext context = new PagesContext("myForm", "3", kmelia.getLanguage(), false,
                    kmelia.getComponentId(), kmelia.getUserId());
            context.setEncoding(CharEncoding.UTF_8);
            if (!kmaxMode) {
                context.setNodeId(kmelia.getCurrentFolderId());
            }
            context.setObjectId(pubId);
            context.setContentLanguage(kmelia.getCurrentLanguage());

            form.update(items, data, context);
            set.save(data);

            // update publication to change updateDate and updaterId
            kmelia.updatePublication(pubDetail);

            // Parametres du Wizard
            setWizardParams(request, kmelia);

            if (kmelia.getWizard().equals("progress")) {
                // on est en mode Wizard
                request.setAttribute("Position", "Content");
                destination = getDestination("WizardNext", kmelia, request);
            } else {
                if (kmelia.getSessionClone() != null) {
                    destination = getDestination("ViewClone", kmelia, request);
                } else if (kmaxMode) {
                    destination = getDestination("ViewAttachments", kmelia, request);
                } else {
                    destination = getDestination("ViewPublication", kmelia, request);
                }
            }
        } else if (function.startsWith("ToOrderPublications")) {
            List<KmeliaPublication> publications = kmelia.getSessionPublicationsList();

            request.setAttribute("Publications", publications);
            request.setAttribute("Path", kmelia.getSessionPath());

            destination = rootDestination + "orderPublications.jsp";
        } else if (function.startsWith("OrderPublications")) {
            String sortedIds = request.getParameter("sortedIds");

            StringTokenizer tokenizer = new StringTokenizer(sortedIds, ",");
            List<String> ids = new ArrayList<String>();
            while (tokenizer.hasMoreTokens()) {
                ids.add(tokenizer.nextToken());
            }
            kmelia.orderPublications(ids);

            destination = getDestination("GoToCurrentTopic", kmelia, request);
        } else if (function.equals("ToOrderTopics")) {
            String id = request.getParameter("Id");
            if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))) {
                destination = "/admin/jsp/accessForbidden.jsp";
            } else {
                TopicDetail topic = kmelia.getTopic(id);
                request.setAttribute("Nodes", topic.getNodeDetail().getChildrenDetails());
                destination = rootDestination + "orderTopics.jsp";
            }
        } else if (function.startsWith("Wizard")) {
            destination = processWizard(function, kmelia, request, rootDestination);
        } else if ("ViewTopicProfiles".equals(function)) {
            String role = request.getParameter("Role");
            if (!StringUtil.isDefined(role)) {
                role = SilverpeasRole.admin.toString();
            }

            String id = request.getParameter("NodeId");
            if (!StringUtil.isDefined(id)) {
                id = (String) request.getAttribute("NodeId");
            }
            request.setAttribute("Profiles", kmelia.getTopicProfiles(id));
            NodeDetail topic = kmelia.getNodeHeader(id);
            ProfileInst profile;
            if (topic.haveInheritedRights()) {
                profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn()));

                request.setAttribute("RightsDependsOn", "AnotherTopic");
            } else if (topic.haveLocalRights()) {
                profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn()));

                request.setAttribute("RightsDependsOn", "ThisTopic");
            } else {
                profile = kmelia.getProfile(role);
                // Rights of the component
                request.setAttribute("RightsDependsOn", "ThisComponent");
            }

            request.setAttribute("CurrentProfile", profile);
            request.setAttribute("Groups", kmelia.groupIds2Groups(profile.getAllGroups()));
            request.setAttribute("Users", kmelia.userIds2Users(profile.getAllUsers()));
            List<NodeDetail> path = kmelia.getTopicPath(id);
            request.setAttribute("Path", kmelia.displayPath(path, true, 3));
            request.setAttribute("NodeDetail", topic);

            destination = rootDestination + "topicProfiles.jsp";
        } else if (function.equals("TopicProfileSelection")) {
            String role = request.getParameter("Role");
            String nodeId = request.getParameter("NodeId");
            try {
                kmelia.initUserPanelForTopicProfile(role, nodeId);
            } catch (Exception e) {
                SilverTrace.warn("jobStartPagePeas", "JobStartPagePeasRequestRouter.getDestination()",
                        "root.EX_USERPANEL_FAILED", "function = " + function, e);
            }
            destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS);
        } else if (function.equals("TopicProfileSetUsersAndGroups")) {
            String role = request.getParameter("Role");
            String nodeId = request.getParameter("NodeId");

            kmelia.updateTopicRole(role, nodeId);

            request.setAttribute("urlToReload", "ViewTopicProfiles?Role=" + role + "&NodeId=" + nodeId);
            destination = rootDestination + "closeWindow.jsp";
        } else if (function.equals("TopicProfileRemove")) {
            String profileId = request.getParameter("Id");

            kmelia.deleteTopicRole(profileId);

            destination = getDestination("ViewTopicProfiles", kmelia, request);
        } else if (function.equals("CloseWindow")) {
            destination = rootDestination + "closeWindow.jsp";
        } else if (function.startsWith("UpdateChain")) {
            destination = processUpdateChainOperation(rootDestination, function, kmelia, request);
        } else if (function.equals("SuggestDelegatedNews")) {

            String pubId = kmelia.addDelegatedNews();

            request.setAttribute("PubId", pubId);
            destination = getDestination("ViewPublication", kmelia, request);
        } /**
          * *************************
          * Kmax mode ***********************
          */
        else if (function.equals("KmaxMain")) {
            destination = rootDestination + "kmax.jsp?Action=KmaxView&Profile=" + kmelia.getProfile();
        } else if (function.equals("KmaxAxisManager")) {
            destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxViewAxis&Profile="
                    + kmelia.getProfile();
        } else if (function.equals("KmaxAddAxis")) {
            String newAxisName = request.getParameter("Name");
            String newAxisDescription = request.getParameter("Description");
            NodeDetail axis = new NodeDetail("-1", newAxisName, newAxisDescription, DateUtil.today2SQLDate(),
                    kmelia.getUserId(), null, "0", "X");
            // I18N
            I18NHelper.setI18NInfo(axis, request);
            kmelia.addAxis(axis);

            request.setAttribute("urlToReload", "KmaxAxisManager");
            destination = rootDestination + "closeWindow.jsp";
        } else if (function.equals("KmaxUpdateAxis")) {
            String axisId = request.getParameter("AxisId");
            String newAxisName = request.getParameter("AxisName");
            String newAxisDescription = request.getParameter("AxisDescription");
            NodeDetail axis = new NodeDetail(axisId, newAxisName, newAxisDescription, null, null, null, "0",
                    "X");
            // I18N
            I18NHelper.setI18NInfo(axis, request);
            kmelia.updateAxis(axis);
            destination = getDestination("KmaxAxisManager", kmelia, request);
        } else if (function.equals("KmaxDeleteAxis")) {
            String axisId = request.getParameter("AxisId");
            kmelia.deleteAxis(axisId);
            destination = getDestination("KmaxAxisManager", kmelia, request);
        } else if (function.equals("KmaxManageAxis")) {
            String axisId = request.getParameter("AxisId");
            String translation = request.getParameter("Translation");
            request.setAttribute("Translation", translation);
            destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManageAxis&Profile="
                    + kmelia.getProfile() + "&AxisId=" + axisId;
        } else if (function.equals("KmaxManagePosition")) {
            String positionId = request.getParameter("PositionId");
            String translation = request.getParameter("Translation");
            request.setAttribute("Translation", translation);
            destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManagePosition&Profile="
                    + kmelia.getProfile() + "&PositionId=" + positionId;
        } else if (function.equals("KmaxAddPosition")) {
            String axisId = request.getParameter("AxisId");
            String newPositionName = request.getParameter("Name");
            String newPositionDescription = request.getParameter("Description");
            String translation = request.getParameter("Translation");
            NodeDetail position = new NodeDetail("toDefine", newPositionName, newPositionDescription, null,
                    null, null, "0", "X");
            // I18N
            I18NHelper.setI18NInfo(position, request);
            kmelia.addPosition(axisId, position);
            request.setAttribute("AxisId", axisId);
            request.setAttribute("Translation", translation);
            destination = getDestination("KmaxManageAxis", kmelia, request);
        } else if (function.equals("KmaxUpdatePosition")) {
            String positionId = request.getParameter("PositionId");
            String positionName = request.getParameter("PositionName");
            String positionDescription = request.getParameter("PositionDescription");
            NodeDetail position = new NodeDetail(positionId, positionName, positionDescription, null, null,
                    null, "0", "X");
            // I18N
            I18NHelper.setI18NInfo(position, request);
            kmelia.updatePosition(position);
            destination = getDestination("KmaxAxisManager", kmelia, request);
        } else if (function.equals("KmaxDeletePosition")) {
            String positionId = request.getParameter("PositionId");
            kmelia.deletePosition(positionId);
            destination = getDestination("KmaxAxisManager", kmelia, request);
        } else if (function.equals("KmaxViewUnbalanced")) {
            List<KmeliaPublication> publications = kmelia.getUnbalancedPublications();
            kmelia.setSessionPublicationsList(publications);
            kmelia.orderPubs();

            destination = rootDestination + "kmax.jsp?Action=KmaxViewUnbalanced&Profile=" + kmelia.getProfile();
        } else if (function.equals("KmaxViewBasket")) {
            TopicDetail basket = kmelia.getTopic("1");
            List<KmeliaPublication> publications = (List<KmeliaPublication>) basket.getKmeliaPublications();
            kmelia.setSessionPublicationsList(publications);
            kmelia.orderPubs();

            destination = rootDestination + "kmax.jsp?Action=KmaxViewBasket&Profile=" + kmelia.getProfile();

        } else if (function.equals("KmaxViewToValidate")) {
            destination = rootDestination + "kmax.jsp?Action=KmaxViewToValidate&Profile=" + kmelia.getProfile();
        } else if (function.equals("KmaxSearch")) {
            String axisValuesStr = request.getParameter("SearchCombination");
            if (!StringUtil.isDefined(axisValuesStr)) {
                axisValuesStr = (String) request.getAttribute("SearchCombination");
            }
            String timeCriteria = request.getParameter("TimeCriteria");

            SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "axisValuesStr = " + axisValuesStr + " timeCriteria=" + timeCriteria);
            List<String> combination = kmelia.getCombination(axisValuesStr);
            List<KmeliaPublication> publications;
            if (StringUtil.isDefined(timeCriteria) && !"X".equals(timeCriteria)) {
                publications = kmelia.search(combination, Integer.parseInt(timeCriteria));
            } else {
                publications = kmelia.search(combination);
            }
            SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "publications = " + publications + " Combination=" + combination + " timeCriteria="
                            + timeCriteria);

            kmelia.setIndexOfFirstPubToDisplay("0");
            kmelia.orderPubs();
            kmelia.setSessionCombination(combination);
            kmelia.setSessionTimeCriteria(timeCriteria);

            destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile();
        } else if (function.equals("KmaxSearchResult")) {
            if (kmelia.getSessionCombination() == null) {
                destination = getDestination("KmaxMain", kmelia, request);
            } else {
                destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile="
                        + kmelia.getProfile();
            }
        } else if (function.equals("KmaxViewCombination")) {
            setWizardParams(request, kmelia);

            request.setAttribute("CurrentCombination", kmelia.getCurrentCombination());
            destination = rootDestination + "kmax_viewCombination.jsp?Profile=" + kmelia.getProfile();
        } else if (function.equals("KmaxAddCoordinate")) {
            String pubId = request.getParameter("PubId");
            String axisValuesStr = request.getParameter("SearchCombination");
            StringTokenizer st = new StringTokenizer(axisValuesStr, ",");
            List<String> combination = new ArrayList<String>();
            String axisValue;
            while (st.hasMoreTokens()) {
                axisValue = st.nextToken();
                // axisValue is xx/xx/xx where xx are nodeId
                axisValue = axisValue.substring(axisValue.lastIndexOf('/') + 1, axisValue.length());
                combination.add(axisValue);
            }
            kmelia.addPublicationToCombination(pubId, combination);
            // Store current combination
            kmelia.setCurrentCombination(kmelia.getCombination(axisValuesStr));
            destination = getDestination("KmaxViewCombination", kmelia, request);
        } else if (function.equals("KmaxDeleteCoordinate")) {
            String coordinateId = request.getParameter("CoordinateId");
            String pubId = request.getParameter("PubId");
            SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "coordinateId = " + coordinateId + " PubId=" + pubId);
            kmelia.deletePublicationFromCombination(pubId, coordinateId);
            destination = getDestination("KmaxViewCombination", kmelia, request);
        } else if (function.equals("KmaxExportComponent")) {
            // build an exploitable list by importExportPeas
            List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications();
            request.setAttribute("selectedResultsWa", publicationsIds);

            // Go to importExportPeas
            destination = "/RimportExportPeas/jsp/KmaxExportComponent";
        } else if (function.equals("KmaxExportPublications")) {
            // build an exploitable list by importExportPeas
            List<WAAttributeValuePair> publicationsIds = kmelia.getCurrentPublicationsList();
            List<String> combination = kmelia.getSessionCombination();
            // get the time axis
            String timeCriteria = null;
            if (kmelia.isTimeAxisUsed() && StringUtil.isDefined(kmelia.getSessionTimeCriteria())) {
                ResourceLocator timeSettings = new ResourceLocator(
                        "org.silverpeas.kmelia.multilang.timeAxisBundle", kmelia.getLanguage());
                if (kmelia.getSessionTimeCriteria().equals("X")) {
                    timeCriteria = null;
                } else {
                    timeCriteria = "<b>" + kmelia.getString("TimeAxis") + "</b> > "
                            + timeSettings.getString(kmelia.getSessionTimeCriteria(), "");
                }
            }
            request.setAttribute("selectedResultsWa", publicationsIds);
            request.setAttribute("Combination", combination);
            request.setAttribute("TimeCriteria", timeCriteria);
            // Go to importExportPeas
            destination = "/RimportExportPeas/jsp/KmaxExportPublications";
        } else if ("statistics".equals(function)) {
            destination = rootDestination + statisticRequestHandler.handleRequest(request, function, kmelia);
        } else if ("statSelectionGroup".equals(function)) {
            destination = statisticRequestHandler.handleRequest(request, function, kmelia);
        } else if ("SetPublicationValidator".equals(function)) {
            String userIds = request.getParameter("ValideurId");
            kmelia.setPublicationValidator(userIds);
            destination = getDestination("ViewPublication", kmelia, request);
        } else {
            destination = rootDestination + function;
        }

        if (profileError) {
            destination = GeneralPropertiesManager.getString("sessionTimeout");
        }
        SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                "destination = " + destination);
    } catch (Exception exce_all) {
        request.setAttribute("javax.servlet.jsp.jspException", exce_all);
        return "/admin/jsp/errorpageMain.jsp";
    }
    return destination;
}

From source file:com.krawler.common.notification.handlers.NotificationExtractorManager.java

public void replacePlaceholders(StringBuffer htmlMsg, NotificationRequest notificationReqObj,
        User recipientUser, DateFormat df) {
    try {//  w  ww  .java  2s  .co  m
        // e.g 
        // First Type of placeholder => #reftype1:oppmainowner.firstName#
        // Second Type of placeholder => #reftype1:oppname#
        java.lang.reflect.Method objMethod;
        String expr = "[#]{1}[a-zA-Z0-9]+[:]{1}[a-zA-Z0-9]+(\\.){0,1}[a-zA-Z0-9]*[#]{1}";
        Pattern p = Pattern.compile(expr);
        Matcher m = p.matcher(htmlMsg);
        while (m.find()) {
            String table = m.group();
            String woHash = table.substring(1, table.length() - 1);
            String[] sp = woHash.split(":");
            if (!StringUtil.isNullOrEmpty(sp[0])) { // sp[0] having reftype1 which holds placeholder class path
                Class cl = notificationReqObj.getClass();
                String methodStr = sp[0].substring(0, 1).toUpperCase() + sp[0].substring(1); // Make first letter of operand capital.
                String methodGetIdStr = methodStr.replace("type", "id");
                objMethod = cl.getMethod("get" + methodStr + ""); // Gets the value of the operand
                String classPath = (String) objMethod.invoke(notificationReqObj);
                objMethod = cl.getMethod("get" + methodGetIdStr + ""); //refid1 which holds placeholder class object primary id
                String classObjectId = (String) objMethod.invoke(notificationReqObj);

                // Placeholder Class
                String value = "-";
                Object invoker = commonTablesDAOObj.getObject(classPath, classObjectId); // load placeholder class
                Class placeHolderClass = invoker.getClass();
                String[] operator = sp[1].split("\\.");
                // 
                if (operator.length > 1) { // if having oppmainowner.firstName
                    methodStr = operator[0].substring(0, 1).toUpperCase() + operator[0].substring(1); // Make first letter of operand capital.
                    objMethod = placeHolderClass.getMethod("get" + methodStr + "");
                    Object innerClassObject = objMethod.invoke(invoker); // get oppmainowner object
                    if (!StringUtil.isNullObject(innerClassObject)) {
                        placeHolderClass = innerClassObject.getClass();
                        methodStr = operator[1].substring(0, 1).toUpperCase() + operator[1].substring(1); // Make first letter of operand capital.
                        objMethod = placeHolderClass.getMethod("get" + methodStr + "");// get oppmainowner's firstName field
                        value = String.valueOf(objMethod.invoke(innerClassObject));
                    }
                } else if (operator.length == 1) { // if having oppname
                    methodStr = operator[0].substring(0, 1).toUpperCase() + operator[0].substring(1); // Make first letter of operand capital.
                    objMethod = placeHolderClass.getMethod("get" + methodStr + "");
                    java.util.Date.class.isAssignableFrom(objMethod.getReturnType());
                    if (java.util.Date.class.isAssignableFrom(objMethod.getReturnType()))
                        value = df.format(((java.util.Date) objMethod.invoke(invoker)));
                    else if ((methodStr.equals("Startdate")
                            && java.lang.Long.class.isAssignableFrom(objMethod.getReturnType()))
                            || (methodStr.equals("Enddate")
                                    && java.lang.Long.class.isAssignableFrom(objMethod.getReturnType()))) {
                        value = df.format(new java.util.Date((java.lang.Long) objMethod.invoke(invoker)));
                    } else
                        value = String.valueOf(objMethod.invoke(invoker));
                } else {
                    value = table.replaceAll("#", "@~@~");
                }

                int i1 = htmlMsg.indexOf(table);
                int i2 = htmlMsg.indexOf(table) + table.length();
                if (StringUtil.isNullOrEmpty(value)) {
                    value = "";
                }
                if (i1 >= 0) {
                    htmlMsg.replace(i1, i2, value);
                }
            }
            m = p.matcher(htmlMsg);
        }

        // replace receiver placeholders
        expr = "[$]{1}recipient[:]{1}[a-zA-Z0-9]+(\\.){0,1}[a-zA-Z0-9]*[$]{1}"; //$recipient:firstName$ $recipient:lastName$
        p = Pattern.compile(expr);
        m = p.matcher(htmlMsg);
        while (m.find()) {
            String table = m.group();
            String woHash = table.substring(1, table.length() - 1);
            String[] sp = woHash.split(":");
            String value = "-";
            if (!StringUtil.isNullOrEmpty(sp[0])) { // sp[0] having recipient which holds placeholder class path
                Class placeHolderClass = recipientUser.getClass();
                String[] operator = sp[1].split("\\.");
                if (operator.length > 1) { // if having oppmainowner.firstName
                    String methodStr = operator[0].substring(0, 1).toUpperCase() + operator[0].substring(1); // Make first letter of operand capital.
                    objMethod = placeHolderClass.getMethod("get" + methodStr + "");
                    Object innerClassObject = objMethod.invoke(recipientUser); // get oppmainowner object
                    if (!StringUtil.isNullObject(innerClassObject)) {
                        placeHolderClass = innerClassObject.getClass();
                        methodStr = operator[1].substring(0, 1).toUpperCase() + operator[1].substring(1); // Make first letter of operand capital.
                        objMethod = placeHolderClass.getMethod("get" + methodStr + "");// get oppmainowner's firstName field
                        value = (String) objMethod.invoke(innerClassObject);
                    }
                } else if (operator.length == 1) { // if having oppname
                    String methodStr = operator[0].substring(0, 1).toUpperCase() + operator[0].substring(1); // Make first letter of operand capital.
                    objMethod = placeHolderClass.getMethod("get" + methodStr + "");
                    java.util.Date.class.isAssignableFrom(objMethod.getReturnType());
                    if (java.util.Date.class.isAssignableFrom(objMethod.getReturnType()))
                        value = df.format(((java.util.Date) objMethod.invoke(recipientUser)));
                    else
                        value = (String) objMethod.invoke(recipientUser);
                } else {
                    value = table.replaceAll("$", "@~@~");
                }

                int i1 = htmlMsg.indexOf(table);
                int i2 = htmlMsg.indexOf(table) + table.length();
                if (StringUtil.isNullOrEmpty(value)) {
                    value = "";
                }
                if (i1 >= 0) {
                    htmlMsg.replace(i1, i2, value);
                }
            }
            m = p.matcher(htmlMsg);
        }
    } catch (IllegalAccessException ex) {
        LOG.info(ex.getMessage(), ex);
        ex.printStackTrace();
    } catch (IllegalArgumentException ex) {
        LOG.info(ex.getMessage(), ex);
        ex.printStackTrace();
    } catch (InvocationTargetException ex) {
        LOG.info(ex.getMessage(), ex);
        ex.printStackTrace();
    } catch (NoSuchMethodException ex) {
        LOG.info(ex.getMessage(), ex);
        ex.printStackTrace();
    } catch (ServiceException ex) {
        LOG.info(ex.getMessage(), ex);
        ex.printStackTrace();
    }

}

From source file:org.talend.mdm.webapp.browserecords.server.actions.BrowseRecordsActionTest.java

/**
 * the code comes from//w w  w .j  a v a  2s .c  o m
 * org.talend.mdm.webapp.browserecords.server.actions.BrowseRecordsAction.builderNode(Map<String, Integer>, Element,
 * EntityModel, String, String, boolean, StringBuffer, boolean, String) <li>change findTypeModelByTypePath to
 * DataModelHelper.findTypeModelByTypePath(metaDataTypes, typePath) <li>change getForeignKeyDesc to
 * mock_getForeignKeyDesc
 */
private ItemNodeModel builderNode(Map<String, Integer> multiNodeIndex, Element el, EntityModel entity,
        String baseXpath, String xpath, boolean isPolyType, StringBuffer foreignKeyDeleteMessage,
        boolean isCreate, String language) throws Exception {
    Map<String, TypeModel> metaDataTypes = entity.getMetaDataTypes();
    String realType = el.getAttribute("xsi:type"); //$NON-NLS-1$
    if (isPolyType) {
        xpath += ("".equals(xpath) ? el.getNodeName() : "/" + el.getNodeName()); //$NON-NLS-1$//$NON-NLS-2$
        if (realType != null && realType.trim().length() > 0) {
            xpath += ":" + realType; //$NON-NLS-1$
        }
    } else {
        xpath += ("".equals(xpath) ? el.getNodeName() : "/" + el.getNodeName()); //$NON-NLS-1$//$NON-NLS-2$
    }
    String typePath;
    if ("".equals(baseXpath)) { //$NON-NLS-1$
        typePath = xpath.replaceAll("\\[\\d+\\]", ""); //$NON-NLS-1$//$NON-NLS-2$
    } else {
        typePath = (baseXpath + "/" + xpath).replaceAll("\\[\\d+\\]", ""); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
    }
    typePath = typePath.replaceAll(":" + realType + "$", ""); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
    ItemNodeModel nodeModel = new ItemNodeModel(el.getNodeName());

    TypeModel model = DataModelHelper.findTypeModelByTypePath(metaDataTypes, typePath);
    nodeModel.setTypePath(model.getTypePath());
    nodeModel.setHasVisiblueRule(model.isHasVisibleRule());
    String realXPath = xpath;
    if (isPolyType) {
        realXPath = realXPath.replaceAll(":\\w+", ""); //$NON-NLS-1$//$NON-NLS-2$
    }

    if (model.getMaxOccurs() > 1 || model.getMaxOccurs() == -1) {

        Integer index = multiNodeIndex.get(realXPath);
        if (index == null) {
            nodeModel.setIndex(1);
            multiNodeIndex.put(realXPath, new Integer(1));
        } else {
            nodeModel.setIndex(index + 1);
            multiNodeIndex.put(realXPath, nodeModel.getIndex());
        }
    }

    if (realType != null && realType.trim().length() > 0) {
        nodeModel.setRealType(el.getAttribute("xsi:type")); //$NON-NLS-1$
    }
    nodeModel.setLabel(model.getLabel(language));
    nodeModel.setDescription(model.getDescriptionMap().get(language));
    nodeModel.setName(el.getNodeName());
    if (model.getMinOccurs() == 1 && model.getMaxOccurs() == 1) {
        nodeModel.setMandatory(true);
    }
    String foreignKey = model.getForeignkey();
    if (foreignKey != null && foreignKey.trim().length() > 0) {
        // set foreignKeyBean
        model.setRetrieveFKinfos(true);
        String modelType = el.getAttribute("tmdm:type"); //$NON-NLS-1$
        if (modelType != null && modelType.trim().length() > 0) {
            nodeModel.setTypeName(modelType);
        }
        ForeignKeyBean fkBean = mock_getForeignKeyDesc(model, el.getTextContent(), true, modelType);
        if (fkBean != null) {
            String fkNotFoundMessage = fkBean.get("foreignKeyDeleteMessage"); //$NON-NLS-1$
            if (fkNotFoundMessage != null) {// fix bug TMDM-2757
                if (foreignKeyDeleteMessage.indexOf(fkNotFoundMessage) == -1) {
                    foreignKeyDeleteMessage.append(fkNotFoundMessage + "\r\n"); //$NON-NLS-1$
                }
                return nodeModel;
            }
            nodeModel.setObjectValue(fkBean);
        }
    } else if (model.isSimpleType()) {
        nodeModel.setObjectValue(el.getTextContent());
    }
    if (isCreate && model.getDefaultValueExpression() != null
            && model.getDefaultValueExpression().trim().length() > 0) {
        nodeModel.setChangeValue(true);
    }

    NodeList children = el.getChildNodes();
    if (children != null && !model.isSimpleType()) {
        List<TypeModel> childModels = null;
        if (nodeModel.getRealType() != null && nodeModel.getRealType().trim().length() > 0) {
            childModels = ((ComplexTypeModel) model).getRealType(nodeModel.getRealType()).getSubTypes();
        } else {
            childModels = ((ComplexTypeModel) model).getSubTypes();
        }
        for (TypeModel typeModel : childModels) { // display tree node according to the studio default configuration
            boolean existNodeFlag = false;
            for (int i = 0; i < children.getLength(); i++) {
                Node child = children.item(i);
                if (child.getNodeType() == Node.ELEMENT_NODE) {
                    String tem_typePath;
                    if (realType != null && realType.trim().length() > 0) {
                        tem_typePath = typePath + ":" + realType + "/" + child.getNodeName(); //$NON-NLS-1$ //$NON-NLS-2$
                    } else {
                        tem_typePath = typePath + "/" + child.getNodeName(); //$NON-NLS-1$
                    }

                    if (typeModel.getTypePath().equals(tem_typePath) || (typeModel.getTypePathObject() != null
                            && typeModel.getTypePathObject().getAllAliasXpaths() != null
                            && typeModel.getTypePathObject().getAllAliasXpaths().contains(tem_typePath))) {
                        ItemNodeModel childNode = builderNode(multiNodeIndex, (Element) child, entity,
                                baseXpath, xpath, isPolyType, foreignKeyDeleteMessage, isCreate, language);
                        nodeModel.add(childNode);
                        existNodeFlag = true;
                        if (typeModel.getMaxOccurs() < 0 || typeModel.getMaxOccurs() > 1) {
                            continue;
                        } else {
                            break;
                        }
                    }
                }
            }
            if (!existNodeFlag) { // add default tree node when the node has not been saved in DB.
                nodeModel.add(org.talend.mdm.webapp.browserecords.server.util.CommonUtil
                        .getDefaultTreeModel(typeModel, isCreate, language).get(0));
            }
        }

    }
    for (String key : entity.getKeys()) {
        if (key.equals(realXPath)) {
            nodeModel.setKey(true);
        }
    }
    return nodeModel;

}

From source file:org.openhealthtools.mdht.uml.cda.core.util.CDAModelUtil.java

public static String computeConformanceMessage(Constraint constraint, boolean markup) {
    StringBuffer message = new StringBuffer();
    String strucTextBody = null;//from w ww . jav  a  2 s  . co m
    String analysisBody = null;
    Map<String, String> langBodyMap = new HashMap<String, String>();

    ValueSpecification spec = constraint.getSpecification();
    if (spec instanceof OpaqueExpression) {
        for (int i = 0; i < ((OpaqueExpression) spec).getLanguages().size(); i++) {
            String lang = ((OpaqueExpression) spec).getLanguages().get(i);
            String body = ((OpaqueExpression) spec).getBodies().get(i);

            if ("StrucText".equals(lang)) {
                strucTextBody = body;
            } else if ("Analysis".equals(lang)) {
                analysisBody = body;
            } else {
                langBodyMap.put(lang, body);
            }
        }
    }

    String displayBody = null;
    if (strucTextBody != null && strucTextBody.trim().length() > 0) {
        // TODO if markup, parse strucTextBody and insert DITA markup
        displayBody = strucTextBody;
    } else if (analysisBody != null && analysisBody.trim().length() > 0) {
        if (markup) {
            // escape non-dita markup in analysis text
            displayBody = escapeMarkupCharacters(analysisBody);
            // change severity words to bold text
            displayBody = replaceSeverityWithBold(displayBody);
        } else {
            displayBody = analysisBody;
        }
    }

    if (!markup) {
        message.append(getPrefixedSplitName(constraint.getContext())).append(" ");
    }

    if (displayBody == null || !containsSeverityWord(displayBody)) {
        String keyword = getValidationKeyword(constraint);
        if (keyword == null) {
            keyword = "SHALL";
        }

        message.append(markup ? "<b>" : "");
        message.append(keyword);
        message.append(markup ? "</b>" : "");
        message.append(" satisfy: ");
    }

    if (displayBody == null) {
        message.append(constraint.getName());
    } else {
        message.append(displayBody);
    }
    appendConformanceRuleIds(constraint, message, markup);

    // include comment text only in markup output
    if (false && markup && constraint.getOwnedComments().size() > 0) {
        message.append("<ul>");
        for (Comment comment : constraint.getOwnedComments()) {
            message.append("<li>");
            message.append(fixNonXMLCharacters(comment.getBody()));
            message.append("</li>");
        }
        message.append("</ul>");
    }

    // Include other constraint languages, e.g. OCL or XPath
    if (false && langBodyMap.size() > 0) {
        message.append("<ul>");
        for (String lang : langBodyMap.keySet()) {
            message.append("<li>");
            message.append("<codeblock>[" + lang + "]: ");
            message.append(escapeMarkupCharacters(langBodyMap.get(lang)));
            message.append("</codeblock>");
            message.append("</li>");
        }
        message.append("</ul>");
    }

    if (!markup) {
        // remove line feeds
        int index;
        while ((index = message.indexOf("\r")) >= 0) {
            message.deleteCharAt(index);
        }
        while ((index = message.indexOf("\n")) >= 0) {
            message.deleteCharAt(index);
            if (message.charAt(index) != ' ') {
                message.insert(index, " ");
            }
        }
    }

    return message.toString();
}

From source file:com.google.enterprise.connector.sharepoint.spiimpl.SharepointConnectorType.java

/**
 * Validates all the patterns under included / excluded to check if any of
 * them is not a valid pattern.//from w ww  .  j av  a2  s. c o m
 *
 * @param patterns
 *          The pattern to be validated
 * @return the set of wrong patterns, if any. Otherwise returns null
 */
private Set<String> validatePatterns(final String patterns) {
    LOGGER.info("validating patterns [ " + patterns + " ]. ");
    String[] patternsList = null;
    if ((patterns != null) && (patterns.trim().length() != 0)) {
        patternsList = patterns.split(SPConstants.SEPARATOR);
    }
    if (patternsList == null) {
        return null;
    }

    final Set<String> invalidPatterns = new HashSet<String>();

    for (final String pattern : patternsList) {
        if (pattern.startsWith(SPConstants.HASH) || pattern.startsWith(SPConstants.MINUS)) {
            continue;
        }
        if (pattern.startsWith(SPConstants.CONTAINS)) {
            final StringBuffer tempBuffer = new StringBuffer(pattern);
            if (tempBuffer == null) {
                invalidPatterns.add(pattern);
            }
            final String strContainKey = new String(tempBuffer.delete(0, SPConstants.CONTAINS.length()));
            try {
                new RE(strContainKey); // with case
            } catch (final Exception e) {
                invalidPatterns.add(pattern);
            }
            continue;
        }

        if (pattern.startsWith(SPConstants.REGEXP)) {
            final StringBuffer tempBuffer = new StringBuffer(pattern);
            if (tempBuffer == null) {
                invalidPatterns.add(pattern);
            }
            final String strRegexPattrn = new String(tempBuffer.delete(0, SPConstants.REGEXP.length()));
            try {
                new RE(strRegexPattrn);
            } catch (final Exception e) {
                invalidPatterns.add(pattern);
            }
            continue;
        }

        if (pattern.startsWith(SPConstants.REGEXP_CASE)) {
            final StringBuffer tempBuffer = new StringBuffer(pattern);
            if (tempBuffer == null) {
                invalidPatterns.add(pattern);
            }
            final String strRegexCasePattrn = new String(
                    tempBuffer.delete(0, SPConstants.REGEXP_CASE.length()));
            try {
                new RE(strRegexCasePattrn);
            } catch (final Exception e) {
                invalidPatterns.add(pattern);
            }
            continue;
        }

        if (pattern.startsWith(SPConstants.REGEXP_IGNORE_CASE)) {
            final StringBuffer tempBuffer = new StringBuffer(pattern);
            if (tempBuffer == null) {
                invalidPatterns.add(pattern);
            }
            final String strRegexIgnoreCasePattrn = new String(
                    tempBuffer.delete(0, SPConstants.REGEXP_IGNORE_CASE.length()));
            try {
                new RE(strRegexIgnoreCasePattrn, RE.REG_ICASE); // ignore
                // case
            } catch (final Exception e) {
                invalidPatterns.add(pattern);
            }
            continue;
        }

        if (pattern.startsWith(SPConstants.CARET) || pattern.endsWith(SPConstants.DOLLAR)) {
            StringBuffer tempBuffer = new StringBuffer(pattern);
            boolean bDollar = false;
            if (pattern.startsWith(SPConstants.CARET)) {
                tempBuffer = new StringBuffer(pattern);
                final int indexOfStar = tempBuffer.indexOf("*");
                if (indexOfStar != -1) {
                    tempBuffer.replace(indexOfStar, indexOfStar + "*".length(), "[0-9].*");
                } else {
                    tempBuffer.delete(0, "^".length());
                    if (pattern.endsWith(SPConstants.DOLLAR)) {
                        bDollar = true;
                        tempBuffer.delete(tempBuffer.length() - SPConstants.DOLLAR.length(),
                                tempBuffer.length());
                    }
                    try {
                        final URL urlPatt = new URL(tempBuffer.toString());
                        final int port = urlPatt.getPort();
                        final String strHost = urlPatt.getHost().toString();
                        if ((port == -1) && (strHost != null) && (strHost.length() != 0)) {
                            tempBuffer = new StringBuffer("^" + urlPatt.getProtocol() + SPConstants.URL_SEP
                                    + urlPatt.getHost() + ":[0-9].*" + urlPatt.getPath());
                        }
                        if (bDollar) {
                            tempBuffer.append(SPConstants.DOLLAR);
                        }
                    } catch (final Exception e) {
                        tempBuffer = new StringBuffer(pattern);
                    }
                }
            }

            try {
                new RE(tempBuffer);
            } catch (final Exception e) {
                invalidPatterns.add(pattern);
            }
            continue;
        }

        String patternDecoded = pattern;
        try {
            patternDecoded = URLDecoder.decode(pattern, "UTF-8");
        } catch (final Exception e) {
            // eatup exception. use the original value
            patternDecoded = pattern;
        }

        if (patternDecoded == null) {
            invalidPatterns.add(pattern);
        }

        boolean containProtocol = false;
        try {
            final RE re = new RE(SPConstants.URL_SEP);
            final REMatch reMatch = re.getMatch(patternDecoded);
            if (reMatch != null) {
                containProtocol = true; // protocol is present
            }

        } catch (final Exception e) {
            containProtocol = false;
        }

        if (containProtocol) {
            String urlPatt1stPart = null;
            String urlPatt2ndPart = null;
            boolean bPortStar = false;
            try {
                final URL urlPatt = new URL(patternDecoded);
                final int port = urlPatt.getPort();
                String strPort = "";
                if (port == -1) {
                    strPort = "[0-9].*";
                } else {
                    strPort = port + "";
                }
                urlPatt1stPart = "^" + urlPatt.getProtocol() + SPConstants.URL_SEP + urlPatt.getHost()
                        + SPConstants.COLON + strPort;
                if (!(urlPatt.getFile()).startsWith(SPConstants.SLASH)) { // The pattern must have "/" 
                                                                          // after the port
                    invalidPatterns.add(pattern);
                }
                urlPatt2ndPart = "^" + urlPatt.getFile();
            } catch (final Exception e) {
                bPortStar = true;
            }

            if (bPortStar) {
                final int indexOfStar = patternDecoded.indexOf("*");
                if (indexOfStar != -1) {
                    urlPatt1stPart = "^" + patternDecoded.substring(0, indexOfStar) + "[0-9].*";
                    if (!(patternDecoded.substring(indexOfStar + 1)).startsWith(SPConstants.SLASH)) {
                        invalidPatterns.add(pattern);
                    }
                    urlPatt2ndPart = "^" + patternDecoded.substring(indexOfStar + 1);
                }
            }

            try {
                new RE(urlPatt1stPart);
                new RE(urlPatt2ndPart);
            } catch (final Exception e) {
                invalidPatterns.add(pattern);
            }
        } else {
            String urlPatt1stPart = null;
            String urlPatt2ndPart = null;
            if (patternDecoded.indexOf(SPConstants.SLASH) != -1) {
                if (patternDecoded.indexOf(SPConstants.COLON) == -1) {
                    urlPatt1stPart = patternDecoded.substring(0, patternDecoded.indexOf(SPConstants.SLASH))
                            + ":[0-9].*";
                } else {
                    urlPatt1stPart = patternDecoded.substring(0, patternDecoded.indexOf(SPConstants.SLASH));
                }
                urlPatt2ndPart = patternDecoded.substring(patternDecoded.indexOf(SPConstants.SLASH));
            } else {
                invalidPatterns.add(pattern);
            }

            urlPatt1stPart = "^.*://.*" + urlPatt1stPart;
            urlPatt2ndPart = "^" + urlPatt2ndPart;
            try {
                new RE(urlPatt1stPart);
                new RE(urlPatt2ndPart);
            } catch (final Exception e) {
                invalidPatterns.add(pattern);
            }
        }
    }
    if (invalidPatterns.size() == 0) {
        return null;
    } else {
        return invalidPatterns;
    }
}

From source file:org.eclipse.mdht.uml.cda.core.util.CDAModelUtil.java

private static String computeCustomConformanceMessage(Constraint constraint, boolean markup) {
    StringBuffer message = new StringBuffer();
    String strucTextBody = null;/*from w  w w  . j  a  va  2 s. c  om*/
    String analysisBody = null;
    Map<String, String> langBodyMap = new HashMap<String, String>();

    CDAProfileUtil.getLogicalConstraint(constraint);

    ValueSpecification spec = constraint.getSpecification();
    if (spec instanceof OpaqueExpression) {
        for (int i = 0; i < ((OpaqueExpression) spec).getLanguages().size(); i++) {
            String lang = ((OpaqueExpression) spec).getLanguages().get(i);
            String body = ((OpaqueExpression) spec).getBodies().get(i);

            if ("StrucText".equals(lang)) {
                strucTextBody = body;
            } else if ("Analysis".equals(lang)) {
                analysisBody = body;
            } else {
                langBodyMap.put(lang, body);
            }
        }
    }

    String displayBody = null;
    if (strucTextBody != null && strucTextBody.trim().length() > 0) {
        // TODO if markup, parse strucTextBody and insert DITA markup
        displayBody = strucTextBody;
    } else if (analysisBody != null && analysisBody.trim().length() > 0) {
        Boolean ditaEnabled = false;
        try {
            Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(constraint,
                    ICDAProfileConstants.CONSTRAINT_VALIDATION);
            ditaEnabled = (Boolean) constraint.getValue(stereotype,
                    ICDAProfileConstants.CONSTRAINT_DITA_ENABLED);
        } catch (IllegalArgumentException e) { /* Swallow this */
        }
        if (markup && !ditaEnabled) {
            // escape non-dita markup in analysis text
            displayBody = escapeMarkupCharacters(analysisBody);
            // change severity words to bold text
            displayBody = replaceSeverityWithBold(displayBody);
        } else {
            displayBody = analysisBody;
        }
    }

    if (displayBody == null) {
        List<Stereotype> stereotypes = constraint.getAppliedStereotypes();
        if (stereotypes.isEmpty()) {
            // This should never happen but in case it does we deal with it appropriately
            // by bypassing custom constraint message additions
            return "";
        }
    }

    if (!markup) {
        message.append(getPrefixedSplitName(constraint.getContext())).append(" ");
    }

    if (displayBody == null || !containsSeverityWord(displayBody)) {
        String keyword = getValidationKeyword(constraint);
        if (keyword == null) {
            keyword = "SHALL";
        }

        message.append(markup ? "<b>" : "");
        message.append(keyword);
        message.append(markup ? "</b>" : "");
        message.append(" satisfy: ");
    }

    if (displayBody == null) {
        message.append(constraint.getName());
    } else {
        message.append(displayBody);
    }
    appendConformanceRuleIds(constraint, message, markup);

    if (!markup) {
        // remove line feeds
        int index;
        while ((index = message.indexOf("\r")) >= 0) {
            message.deleteCharAt(index);
        }
        while ((index = message.indexOf("\n")) >= 0) {
            message.deleteCharAt(index);
            if (message.charAt(index) != ' ') {
                message.insert(index, " ");
            }
        }
    }

    return message.toString();
}

From source file:org.infoglue.deliver.invokers.DecoratedComponentBasedHTMLPageInvoker.java

/**
 * This method adds the necessary html to a template to make it right-clickable.
 */// w  w w  . j a  v a 2  s. c  o m

private String decorateTemplate(TemplateController templateController, String template,
        DeliveryContext deliveryContext, InfoGlueComponent component) {
    Timer timer = new Timer();
    timer.setActive(false);

    String decoratedTemplate = template;

    try {
        String cmsBaseUrl = CmsPropertyHandler.getCmsBaseUrl();
        String componentEditorUrl = CmsPropertyHandler.getComponentEditorUrl();

        InfoGluePrincipal principal = templateController.getPrincipal();
        String cmsUserName = (String) templateController.getHttpServletRequest().getSession()
                .getAttribute("cmsUserName");
        if (cmsUserName != null && !CmsPropertyHandler.getAnonymousUser().equalsIgnoreCase(cmsUserName)) {
            InfoGluePrincipal newPrincipal = templateController.getPrincipal(cmsUserName);
            if (newPrincipal != null)
                principal = newPrincipal;
        }

        Locale locale = templateController.getLocaleAvailableInTool(principal);

        boolean hasAccessToAccessRights = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.ChangeSlotAccess", "");
        boolean hasAccessToAddComponent = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.AddComponent",
                "" + component.getContentId() + "_" + component.getCleanedSlotName());
        boolean hasAccessToDeleteComponent = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.DeleteComponent",
                "" + component.getContentId() + "_" + component.getCleanedSlotName());
        boolean hasAccessToChangeComponent = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.ChangeComponent",
                "" + component.getContentId() + "_" + component.getCleanedSlotName());
        boolean hasSaveTemplateAccess = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.SavePageTemplate", true, false,
                true);
        boolean hasSubmitToPublishAccess = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.SubmitToPublish", true, false,
                true);
        boolean hasPageStructureAccess = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.PageStructure", true, false,
                true);
        boolean hasOpenInNewWindowAccess = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.OpenInNewWindow", true, false,
                true);
        boolean hasViewSourceAccess = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.ViewSource", true, false, true);

        boolean showNotifyUserOfPage = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.NotifyUserOfPage", true, false,
                true);
        boolean showContentNotifications = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.ContentNotifications", true,
                false, true);
        boolean showPageNotifications = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.PageNotifications", true, false,
                true);

        boolean showW3CValidator = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.W3CValidator", true, false, true);
        boolean showLanguageMenu = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.ShowLanguageMenu", true, false,
                true);

        boolean showHomeButton = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.ShowHomeButton", true, false,
                true);
        boolean showMySettingsButton = AccessRightController.getController().getIsPrincipalAuthorized(
                templateController.getDatabase(), principal, "ComponentEditor.ShowMySettingsButton", true,
                false, true);

        String useApprovalFlow = CmsPropertyHandler.getUseApprovalFlow();
        String autoShowApprovalButtons = CmsPropertyHandler.getAutoShowApprovalButtons();

        String extraHeader = FileHelper.getFileAsString(new File(CmsPropertyHandler.getContextDiskPath()
                + (CmsPropertyHandler.getContextDiskPath().endsWith("/") ? "" : "/")
                + "preview/pageComponentEditorHeader.vm"), "iso-8859-1");
        String extraBody = FileHelper.getFileAsString(new File(CmsPropertyHandler.getContextDiskPath()
                + (CmsPropertyHandler.getContextDiskPath().endsWith("/") ? "" : "/")
                + "preview/pageComponentEditorBody.vm"), "iso-8859-1");
        boolean oldUseFullUrl = this.getTemplateController().getDeliveryContext().getUseFullUrl();
        this.getTemplateController().getDeliveryContext().setUseFullUrl(true);

        String parameters = "repositoryId=" + templateController.getSiteNode().getRepositoryId()
                + "&siteNodeId=" + templateController.getSiteNodeId() + "&languageId="
                + templateController.getLanguageId() + "&contentId=" + templateController.getContentId()
                + "&componentId=" + this.getRequest().getParameter("activatedComponentId")
                + "&componentContentId=" + this.getRequest().getParameter("componentContentId")
                + "&showSimple=false&showLegend=false&originalUrl="
                + URLEncoder.encode(this.getTemplateController().getCurrentPageUrl(), "UTF-8");

        String WYSIWYGEditorFile = "ckeditor/ckeditor.js";
        if (!CmsPropertyHandler.getPrefferedWYSIWYG().equals("ckeditor4"))
            WYSIWYGEditorFile = "FCKEditor/fckeditor.js";

        StringBuffer path = getPagePathAsCommaseparatedIds(templateController);

        extraHeader = extraHeader.replaceAll("\\$\\{focusElementId\\}",
                "" + this.getRequest().getParameter("focusElementId"));
        extraHeader = extraHeader.replaceAll("\\$\\{cmsBaseUrl\\}", cmsBaseUrl);
        extraHeader = extraHeader.replaceAll("\\$\\{contextName\\}", this.getRequest().getContextPath());
        extraHeader = extraHeader.replaceAll("\\$\\{componentEditorUrl\\}", componentEditorUrl);
        if (principal.getName().equalsIgnoreCase(CmsPropertyHandler.getAnonymousUser()))
            extraHeader = extraHeader.replaceAll("\\$\\{limitedUserWarning\\}",
                    "alert('Your session must have expired as you are now in decorated mode as "
                            + principal.getName() + ". Please close browser and login again.');");
        else
            extraHeader = extraHeader.replaceAll("\\$\\{limitedUserWarning\\}", "");
        //extraHeader = extraHeader.replaceAll("\\$\\{currentUrl\\}", URLEncoder.encode(this.getTemplateController().getCurrentPageUrl(), "UTF-8"));
        extraHeader = extraHeader.replaceAll("\\$\\{currentUrl\\}",
                URLEncoder.encode(this.getTemplateController().getOriginalFullURL(), "UTF-8"));
        extraHeader = extraHeader.replaceAll("\\$\\{activatedComponentId\\}",
                "" + this.getRequest().getParameter("activatedComponentId"));
        extraHeader = extraHeader.replaceAll("\\$\\{parameters\\}", parameters);
        extraHeader = extraHeader.replaceAll("\\$\\{siteNodeId\\}", "" + templateController.getSiteNodeId());
        extraHeader = extraHeader.replaceAll("\\$\\{languageId\\}", "" + templateController.getLanguageId());
        extraHeader = extraHeader.replaceAll("\\$\\{contentId\\}", "" + templateController.getContentId());
        extraHeader = extraHeader.replaceAll("\\$\\{metaInfoContentId\\}",
                "" + templateController.getMetaInformationContentId());
        extraHeader = extraHeader.replaceAll("\\$\\{parentSiteNodeId\\}",
                "" + templateController.getSiteNode().getParentSiteNodeId());
        extraHeader = extraHeader.replaceAll("\\$\\{repositoryId\\}",
                "" + templateController.getSiteNode().getRepositoryId());
        extraHeader = extraHeader.replaceAll("\\$\\{path\\}", "" + path.substring(1));
        extraHeader = extraHeader.replaceAll("\\$\\{userPrefferredLanguageCode\\}",
                "" + CmsPropertyHandler.getPreferredLanguageCode(principal.getName()));
        extraHeader = extraHeader.replaceAll("\\$\\{userPrefferredWYSIWYG\\}",
                "" + CmsPropertyHandler.getPrefferedWYSIWYG());
        extraHeader = extraHeader.replaceAll("\\$\\{WYSIWYGEditorJS\\}", WYSIWYGEditorFile);

        extraHeader = extraHeader.replaceAll("\\$\\{publishedLabel\\}",
                getLocalizedString(locale, "tool.contenttool.state.published"));

        if (CmsPropertyHandler.getPersonalDisableEditOnSightToolbar(principal.getName())) {
            extraHeader = extraHeader.replaceAll("\\$\\{editOnSightFooterToolbarIsActive\\}", "false");
            extraHeader = extraHeader.replaceAll("\\$\\{editOnSightFooterToolbarOverideCSS\\}",
                    ".editOnSightFooterToolbar{display:none}");
        } else {
            extraHeader = extraHeader.replaceAll("\\$\\{editOnSightFooterToolbarIsActive\\}", "true");
            extraHeader = extraHeader.replaceAll("\\$\\{editOnSightFooterToolbarOverideCSS\\}", "");
        }

        if (CmsPropertyHandler.getShowInlinePropertiesIcon().equalsIgnoreCase("false")) {
            extraHeader = extraHeader.replaceAll("\\$\\{useInlinePropertiesIcon\\}", "false");
        } else {
            extraHeader = extraHeader.replaceAll("\\$\\{useInlinePropertiesIcon\\}", "true");
        }

        if (getRequest().getParameter("approveEntityName") != null
                && !getRequest().getParameter("approveEntityName").equals("")
                && getRequest().getParameter("approveEntityId") != null
                && !getRequest().getParameter("approveEntityId").equals("")) {
            extraHeader = extraHeader.replaceAll("\\$\\{approveEntityName\\}",
                    "" + getRequest().getParameter("approveEntityName"));
            extraHeader = extraHeader.replaceAll("\\$\\{approveEntityId\\}",
                    "" + getRequest().getParameter("approveEntityId"));
            extraHeader = extraHeader.replaceAll("\\$\\{publishingEventId\\}",
                    "" + getRequest().getParameter("publishingEventId"));
        } else {
            extraHeader = extraHeader.replaceAll("\\$\\{approveEntityName\\}", "");
            extraHeader = extraHeader.replaceAll("\\$\\{approveEntityId\\}", "");
            extraHeader = extraHeader.replaceAll("\\$\\{publishingEventId\\}", "");
        }

        StringBuffer skinCSS = new StringBuffer();

        String theme = CmsPropertyHandler.getTheme(principal.getName());
        if (!theme.equalsIgnoreCase("Default")) {
            skinCSS.append("<link rel=\"stylesheet\" type=\"text/css\" href=\""
                    + this.getRequest().getContextPath() + "/css/skins/" + theme + "/componentEditor.css\" />");
            String themeFileJQueryUI = CmsPropertyHandler.getThemeFile(theme, "jquery-ui.css");
            if (themeFileJQueryUI != null)
                skinCSS.append("<link rel=\"stylesheet\" type=\"text/css\" href=\""
                        + this.getRequest().getContextPath() + "/css/skins/" + theme + "/jquery-ui.css\" />");
            else
                skinCSS.append(
                        "<link rel=\"stylesheet\" type=\"text/css\" href=\"script/jqueryplugins-latest/ui/css/jquery-ui.css\" />");
        } else {
            skinCSS.append(
                    "<link rel=\"stylesheet\" type=\"text/css\" href=\"script/jqueryplugins-latest/ui/css/jquery-ui.css\" />");
        }
        extraHeader = extraHeader.replaceAll("\\$\\{skinDeliveryCSS\\}", skinCSS.toString());

        String sortBaseUrl = componentEditorUrl + "ViewSiteNodePageComponents!moveComponent.action?siteNodeId="
                + templateController.getSiteNodeId() + "&languageId=" + templateController.getLanguageId()
                + "&contentId=" + templateController.getContentId() + "&showSimple="
                + this.getTemplateController().getDeliveryContext().getShowSimple() + "";
        extraHeader = extraHeader.replaceAll("\\$\\{sortBaseUrl\\}", sortBaseUrl);

        this.getTemplateController().getDeliveryContext().setUseFullUrl(oldUseFullUrl);

        String changeUrl = componentEditorUrl
                + "ViewSiteNodePageComponents!listComponentsForChange.action?siteNodeId="
                + templateController.getSiteNodeId() + "&amp;languageId=" + templateController.getLanguageId()
                + "&amp;contentId=" + templateController.getContentId() + "&amp;componentId="
                + component.getId() + "&amp;slotId=base&amp;showSimple="
                + this.getTemplateController().getDeliveryContext().getShowSimple();
        extraBody = extraBody
                + "<script type=\"text/javascript\">$(function() { initializeComponentEventHandler('base0_"
                + component.getId() + "Comp', '" + component.getId() + "', '', '" + componentEditorUrl
                + "ViewSiteNodePageComponents!deleteComponent.action?siteNodeId="
                + templateController.getSiteNodeId() + "&amp;languageId=" + templateController.getLanguageId()
                + "&amp;contentId=" + templateController.getContentId() + "&amp;componentId="
                + component.getId() + "&amp;slotId=base&amp;showSimple="
                + this.getTemplateController().getDeliveryContext().getShowSimple() + "','" + changeUrl
                + "'); }); </script>";

        String submitToPublishHTML = getLocalizedString(locale, "deliver.editOnSight.submitToPublish");
        String addComponentHTML = getLocalizedString(locale, "deliver.editOnSight.addComponentHTML");
        String deleteComponentHTML = getLocalizedString(locale, "deliver.editOnSight.deleteComponentHTML");
        String changeComponentHTML = getLocalizedString(locale, "deliver.editOnSight.changeComponentHTML");
        String accessRightsHTML = getLocalizedString(locale, "deliver.editOnSight.accessRightsHTML");
        String pageComponentsHTML = getLocalizedString(locale, "deliver.editOnSight.pageComponentsHTML");
        String viewSourceHTML = getLocalizedString(locale, "deliver.editOnSight.viewSourceHTML");
        String componentEditorInNewWindowHTML = getLocalizedString(locale,
                "deliver.editOnSight.componentEditorInNewWindowHTML");
        String savePageTemplateHTML = getLocalizedString(locale, "deliver.editOnSight.savePageTemplateHTML");
        String savePagePartTemplateHTML = getLocalizedString(locale,
                "deliver.editOnSight.savePagePartTemplateHTML");
        String editHTML = getLocalizedString(locale, "deliver.editOnSight.editHTML");
        String editInlineHTML = getLocalizedString(locale, "deliver.editOnSight.editContentInlineLabel");
        String propertiesHTML = getLocalizedString(locale, "deliver.editOnSight.propertiesHTML");
        String favouriteComponentsHeader = getLocalizedString(locale, "tool.common.favouriteComponentsHeader");
        String noActionAvailableHTML = getLocalizedString(locale, "deliver.editOnSight.noActionAvailableHTML");

        String notifyLabel = getLocalizedString(locale, "deliver.editOnSight.notifyLabel");
        String subscribeToContentLabel = getLocalizedString(locale,
                "deliver.editOnSight.subscribeToContentLabel");
        String subscribeToPageLabel = getLocalizedString(locale, "deliver.editOnSight.subscribeToPageLabel");
        String translateContentLabel = getLocalizedString(locale, "deliver.editOnSight.translateContentLabel");

        String confirmDeleteLabel = getLocalizedString(locale, "deliver.editOnSight.confirmDeleteLabel");
        String leaveWarningOnDirtyPageText = getLocalizedString(locale,
                "deliver.editOnSight.leaveWarningOnDirtyPage.text");

        String saveTemplateUrl = "saveComponentStructure('" + componentEditorUrl
                + "CreatePageTemplate!input.action?contentId="
                + templateController.getSiteNode(deliveryContext.getSiteNodeId()).getMetaInfoContentId()
                + "');";
        String savePartTemplateUrl = "savePartComponentStructure('" + componentEditorUrl
                + "CreatePageTemplate!input.action?contentId="
                + templateController.getSiteNode(deliveryContext.getSiteNodeId()).getMetaInfoContentId()
                + "');";
        if (!hasSaveTemplateAccess) {
            saveTemplateUrl = "alert('Not authorized to save template');";
            savePartTemplateUrl = "alert('Not authorized to save part template');";
        }

        String personalStartUrl = "/";
        String repositoryId = CmsPropertyHandler.getPreferredRepositoryId(principal.getName());
        logger.info("repositoryId: " + repositoryId);
        if (repositoryId == null) {
            List<RepositoryVO> repos = RepositoryController.getController()
                    .getAuthorizedRepositoryVOList(principal, false);
            if (repos.size() > 0)
                repositoryId = "" + repos.get(0).getId();
        }
        if (repositoryId != null) {
            SiteNodeVO siteNodeVO = SiteNodeController.getController()
                    .getRootSiteNodeVO(new Integer(repositoryId), templateController.getDatabase());
            personalStartUrl = "ViewPage!renderDecoratedPage.action?siteNodeId=" + siteNodeVO.getId();
        }

        String returnAddress = "" + componentEditorUrl + "ViewInlineOperationMessages.action";

        String notifyUrl = componentEditorUrl
                + "CreateEmail!inputChooseRecipientsV3.action?enableUsers=true&originalUrl="
                + URLEncoder.encode(templateController.getOriginalFullURL().replaceFirst("cmsUserName=.*?", ""),
                        "utf-8")
                + "&amp;returnAddress=" + URLEncoder.encode(returnAddress, "utf-8")
                + "&amp;extraTextProperty=tool.managementtool.createEmailNotificationPageExtraText.text";
        String pageSubscriptionUrl = componentEditorUrl
                + "Subscriptions!input.action?interceptionPointCategory=SiteNodeVersion&amp;entityName="
                + SiteNode.class.getName() + "&amp;entityId=" + templateController.getSiteNodeId()
                + "&amp;returnAddress=" + URLEncoder.encode(returnAddress, "utf-8");

        extraBody = extraBody.replaceAll("\\$siteNodeId", "" + templateController.getSiteNodeId());
        extraBody = extraBody.replaceAll("\\$languageId", "" + templateController.getLanguageId());
        extraBody = extraBody.replaceAll("\\$repositoryId",
                "" + templateController.getSiteNode().getRepositoryId());
        extraBody = extraBody.replaceAll("\\$originalFullURL",
                URLEncoder.encode(templateController.getOriginalFullURL(), "UTF-8"));
        extraBody = extraBody.replaceAll("\\$notifyUrl", notifyUrl);
        extraBody = extraBody.replaceAll("\\$pageSubscriptionUrl", pageSubscriptionUrl);

        extraBody = extraBody.replaceAll("\\$editHTML", editHTML);
        extraBody = extraBody.replaceAll("\\$submitToPublishHTML", submitToPublishHTML);

        extraBody = extraBody.replaceAll("\\$confirmDeleteLabel", confirmDeleteLabel);
        extraBody = extraBody.replaceAll("\\$\\{leaveWarningOnDirtyPageText\\}", leaveWarningOnDirtyPageText);

        extraBody = extraBody.replaceAll("\\$notifyHTML", notifyLabel);
        extraBody = extraBody.replaceAll("\\$subscribeToContentHTML", subscribeToContentLabel);
        extraBody = extraBody.replaceAll("\\$subscribeToPageHTML", subscribeToPageLabel);

        extraBody = extraBody.replaceAll("\\$addComponentHTML", addComponentHTML);
        extraBody = extraBody.replaceAll("\\$deleteComponentHTML", deleteComponentHTML);
        extraBody = extraBody.replaceAll("\\$changeComponentHTML", changeComponentHTML);
        extraBody = extraBody.replaceAll("\\$accessRightsHTML", accessRightsHTML);

        extraBody = extraBody.replaceAll("\\$pageComponents", pageComponentsHTML);
        extraBody = extraBody.replaceAll("\\$componentEditorInNewWindowHTML", componentEditorInNewWindowHTML);
        extraBody = extraBody.replaceAll("\\$savePageTemplateHTML", savePageTemplateHTML);
        extraBody = extraBody.replaceAll("\\$savePagePartTemplateHTML", savePagePartTemplateHTML);
        extraBody = extraBody.replaceAll("\\$saveTemplateUrl", saveTemplateUrl);
        extraBody = extraBody.replaceAll("\\$savePartTemplateUrl", savePartTemplateUrl);
        extraBody = extraBody.replaceAll("\\$viewSource", viewSourceHTML);
        extraBody = extraBody.replaceAll("\\$propertiesHTML", propertiesHTML);
        extraBody = extraBody.replaceAll("\\$favouriteComponentsHeader", favouriteComponentsHeader);
        extraBody = extraBody.replaceAll("\\$noActionAvailableHTML", noActionAvailableHTML);

        extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.pendingPageApproval.title\\}",
                getLocalizedString(locale, "deliver.editOnSight.pendingPageApproval.title"));
        extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.pendingContentApproval.title\\}",
                getLocalizedString(locale, "deliver.editOnSight.pendingContentApproval.title"));
        extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarInlineEditing.title\\}",
                getLocalizedString(locale, "deliver.editOnSight.toolbarInlineEditing.title"));
        extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarState.title\\}",
                getLocalizedString(locale, "deliver.editOnSight.toolbarState.title"));
        extraBody = extraBody.replaceAll("\\$\\{tool.contenttool.approve.label\\}",
                getLocalizedString(locale, "tool.contenttool.approve.label"));
        extraBody = extraBody.replaceAll("\\$\\{tool.contenttool.deny.label\\}",
                getLocalizedString(locale, "tool.contenttool.deny.label"));

        extraBody = extraBody.replaceAll("\\$\\{tool.common.saveButton.label\\}",
                getLocalizedString(locale, "tool.common.saveButton.label"));
        extraBody = extraBody.replaceAll("\\$\\{tool.common.cancelButton.label\\}",
                getLocalizedString(locale, "tool.common.cancelButton.label"));
        extraBody = extraBody.replaceAll("\\$\\{tool.common.publishing.publishButtonLabel\\}",
                getLocalizedString(locale, "tool.common.publishing.publishButtonLabel"));
        extraBody = extraBody.replaceAll("\\$\\{tool.structuretool.toolbarV3.previewPageLabel\\}",
                getLocalizedString(locale, "tool.structuretool.toolbarV3.previewPageLabel"));
        extraBody = extraBody.replaceAll("\\$\\{tool.structuretool.toolbarV3.previewMediumScreenPageLabel\\}",
                getLocalizedString(locale, "tool.structuretool.toolbarV3.previewMediumScreenPageLabel"));
        extraBody = extraBody.replaceAll("\\$\\{tool.structuretool.toolbarV3.previewSmallScreenPageLabel\\}",
                getLocalizedString(locale, "tool.structuretool.toolbarV3.previewSmallScreenPageLabel"));

        extraBody = extraBody.replaceAll("\\$\\{tool.structuretool.toolbarV3.disableEditmodeNotAllowed\\}",
                getLocalizedString(locale, "tool.structuretool.toolbarV3.disableEditmodeNotAllowed"));

        extraBody = extraBody.replaceAll("\\$\\{homeURL\\}", personalStartUrl);

        extraBody = extraBody.replaceAll("\\$\\{currentLanguageCode\\}", "" + templateController
                .getLanguageCode(templateController.getLanguageId()).getLanguage().toUpperCase());
        extraBody = extraBody.replaceAll("\\$\\{currentLanguageName\\}", templateController
                .getLanguageCode(templateController.getLanguageId()).getDisplayName().toUpperCase());

        StringBuffer languagesSB = new StringBuffer();
        List<LanguageVO> languages = templateController.getAvailableLanguages();
        for (LanguageVO language : languages) {
            if (language.getId() != templateController.getLanguageId())
                languagesSB.append("<li style=\"margin-bottom: 6px;\"><a style=\"color: black;\" href=\""
                        + templateController.getCurrentPageUrl().replaceAll(
                                "languageId=" + templateController.getLanguageId(),
                                "languageId=" + language.getId())
                        + "\">" + language.getLanguageCode().toUpperCase() + "</a></li>");
        }
        extraBody = extraBody.replaceAll("\\$\\{languageList\\}", languagesSB.toString());

        extraBody = extraBody.replaceAll("\\$addComponentJavascript",
                "window.hasAccessToAddComponent" + component.getId() + "_" + component.getCleanedSlotName()
                        + " = " + hasAccessToAddComponent + ";");
        extraBody = extraBody.replaceAll("\\$deleteComponentJavascript",
                "window.hasAccessToDeleteComponent" + component.getId() + "_" + component.getCleanedSlotName()
                        + " = " + hasAccessToDeleteComponent + ";");
        extraBody = extraBody.replaceAll("\\$changeComponentJavascript",
                "window.hasAccessToChangeComponent" + component.getId() + "_" + component.getCleanedSlotName()
                        + " = " + hasAccessToChangeComponent + ";");
        extraBody = extraBody.replaceAll("\\$changeAccessJavascript",
                "window.hasAccessToAccessRights" + " = " + hasAccessToAccessRights + ";");

        extraBody = extraBody.replaceAll("\\$submitToPublishJavascript",
                "window.hasAccessToSubmitToPublish = " + hasSubmitToPublishAccess + ";");
        extraBody = extraBody.replaceAll("\\$pageStructureJavascript",
                "window.hasPageStructureAccess = " + hasPageStructureAccess + ";");
        extraBody = extraBody.replaceAll("\\$openInNewWindowJavascript",
                "window.hasOpenInNewWindowAccess = " + hasOpenInNewWindowAccess + ";");
        extraBody = extraBody.replaceAll("\\$allowViewSourceJavascript",
                "window.hasAccessToViewSource = " + hasViewSourceAccess + ";");
        extraBody = extraBody.replaceAll("\\$allowSavePageTemplateJavascript",
                "window.hasAccessToSavePageTemplate = " + hasSaveTemplateAccess + ";");

        extraBody = extraBody.replaceAll("\\$submitToNotifyJavascript",
                "window.hasAccessToNotifyUserOfPage = " + showNotifyUserOfPage + ";");
        extraBody = extraBody.replaceAll("\\$contentNotificationsJavascript",
                "window.hasAccessToContentNotifications = " + showContentNotifications + ";");
        extraBody = extraBody.replaceAll("\\$pageNotificationsJavascript",
                "window.hasAccessToPageNotifications = " + showPageNotifications + ";");

        extraBody = extraBody.replaceAll("\\$W3CValidatorJavascript",
                "window.hasAccessToW3CValidator = " + showW3CValidator + ";");
        extraBody = extraBody.replaceAll("\\$ShowLanguageMenuJavascript",
                "window.hasAccessToShowLanguageMenu = " + showLanguageMenu + ";");
        extraBody = extraBody.replaceAll("\\$ShowApproveButtonsJavascript",
                "window.useApprovalFlow = " + useApprovalFlow + ";");
        extraBody = extraBody.replaceAll("\\$autoShowApprovalButtonsJavascript",
                "window.autoShowApprovalButtons = " + autoShowApprovalButtons + ";");
        extraBody = extraBody.replaceAll("\\$useDoubleClickOnTextToInlineEdit",
                "" + CmsPropertyHandler.getUseDoubleClickOnTextToInlineEdit());

        extraBody = extraBody.replaceAll("\\$showHomeButtonJavascript",
                "window.showHomeButton = " + showHomeButton + ";");
        extraBody = extraBody.replaceAll("\\$showMySettingsButtonJavascript",
                "window.showMySettingsButton = " + showMySettingsButton + ";");

        extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarHomeButton.title\\}",
                getLocalizedString(new Locale(CmsPropertyHandler.getPreferredLanguageCode(principal.getName())),
                        "deliver.editOnSight.toolbarHomeButton.title"));
        extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarValidateW3CButton.title\\}",
                getLocalizedString(new Locale(CmsPropertyHandler.getPreferredLanguageCode(principal.getName())),
                        "deliver.editOnSight.toolbarValidateW3CButton.title"));
        extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarNewWindowButton.title\\}",
                getLocalizedString(new Locale(CmsPropertyHandler.getPreferredLanguageCode(principal.getName())),
                        "deliver.editOnSight.toolbarNewWindowButton.title"));
        extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarMySettingsButton.title\\}",
                getLocalizedString(new Locale(CmsPropertyHandler.getPreferredLanguageCode(principal.getName())),
                        "deliver.editOnSight.toolbarMySettingsButton.title"));
        extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarValidateW3CErrorsQuestion.label\\}",
                getLocalizedString(new Locale(CmsPropertyHandler.getPreferredLanguageCode(principal.getName())),
                        "deliver.editOnSight.toolbarValidateW3CErrorsQuestion.label"));
        extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarValidateW3CNoErrors.label\\}",
                getLocalizedString(new Locale(CmsPropertyHandler.getPreferredLanguageCode(principal.getName())),
                        "deliver.editOnSight.toolbarValidateW3CNoErrors.label"));

        StringBuffer userDefinedButtonsSB = new StringBuffer();
        List<ToolbarButton> buttons = AdminToolbarService.getService().getFooterToolbarButtons(
                "tool.deliver.editOnSight.toolbarRight", principal, locale,
                templateController.getHttpServletRequest(), true);

        for (ToolbarButton button : buttons) {
            try {
                if (button.getCustomMarkup() == null) {
                    userDefinedButtonsSB
                            .append("<div id=\"" + button.getId() + "\" class=\"right editOnSightToolbarButton "
                                    + button.getCssClass() + "\" title=\"" + button.getTitle() + "\" onclick=\""
                                    + button.getActionURL() + "\"></div>");
                } else {
                    if (button.getCustomMarkupPlacement().equals("before"))
                        userDefinedButtonsSB.append("" + button.getCustomMarkup());

                    userDefinedButtonsSB
                            .append("<div id=\"" + button.getId() + "\" class=\"right editOnSightToolbarButton "
                                    + button.getCssClass() + "\" title=\"" + button.getTitle() + "\" onclick=\""
                                    + button.getActionURL() + "\">"
                                    + (button.getCustomMarkupPlacement().equals("inside")
                                            ? button.getCustomMarkup()
                                            : "")
                                    + "</div>");

                    if (button.getCustomMarkupPlacement().equals("after"))
                        userDefinedButtonsSB.append("" + button.getCustomMarkup());
                }
            } catch (Exception e) {
                logger.warn("Problem adding custome EOS button: " + e.getMessage(), e);
            }
        }
        extraBody = extraBody.replaceAll("\\$\\{userDefinedButtons\\}", userDefinedButtonsSB.toString());

        //List tasks = getTasks();
        //component.setTasks(tasks);

        //String tasks = templateController.getContentAttribute(component.getContentId(), "ComponentTasks", true);

        /*
        Map context = new HashMap();
        context.put("templateLogic", templateController);
        StringWriter cacheString = new StringWriter();
        PrintWriter cachedStream = new PrintWriter(cacheString);
        new VelocityTemplateProcessor().renderTemplate(context, cachedStream, extraBody);
        extraBody = cacheString.toString();
        */

        //extraHeader.replaceAll()

        timer.printElapsedTime("Read files");

        StringBuffer modifiedTemplate = new StringBuffer(template);

        //Adding stuff in the header
        int indexOfHeadEndTag = modifiedTemplate.indexOf("</head");
        if (indexOfHeadEndTag == -1)
            indexOfHeadEndTag = modifiedTemplate.indexOf("</HEAD");

        if (indexOfHeadEndTag > -1) {
            modifiedTemplate = modifiedTemplate.replace(indexOfHeadEndTag,
                    modifiedTemplate.indexOf(">", indexOfHeadEndTag) + 1, extraHeader);
        } else {
            int indexOfHTMLStartTag = modifiedTemplate.indexOf("<html");
            if (indexOfHTMLStartTag == -1) {
                indexOfHTMLStartTag = modifiedTemplate.indexOf("<HTML");
            }
            if (indexOfHTMLStartTag > -1) {
                modifiedTemplate = modifiedTemplate
                        .insert(modifiedTemplate.indexOf(">", indexOfHTMLStartTag) + 1, "<head>" + extraHeader);
            } else {
                logger.info(
                        "The current template is not a valid document. It does not comply with the simplest standards such as having a correct header.");
            }
        }

        timer.printElapsedTime("Header handled");

        //Adding stuff in the body   
        int indexOfBodyStartTag = modifiedTemplate.indexOf("<body");
        if (indexOfBodyStartTag == -1)
            indexOfBodyStartTag = modifiedTemplate.indexOf("<BODY");

        if (indexOfBodyStartTag > -1) {
            //String pageComponentStructureDiv = "";
            String pageComponentStructureDiv = getPageComponentStructureDiv(templateController,
                    deliveryContext.getSiteNodeId(), deliveryContext.getLanguageId(), component);
            timer.printElapsedTime("pageComponentStructureDiv");
            String componentPaletteDiv = getComponentPaletteDiv(deliveryContext.getSiteNodeId(),
                    deliveryContext.getLanguageId(), templateController);
            //String componentPaletteDiv = "";
            timer.printElapsedTime("componentPaletteDiv");
            modifiedTemplate = modifiedTemplate.insert(modifiedTemplate.indexOf(">", indexOfBodyStartTag) + 1,
                    extraBody + pageComponentStructureDiv + componentPaletteDiv);
        } else {
            logger.info(
                    "The current template is not a valid document. It does not comply with the simplest standards such as having a correct body.");
        }

        timer.printElapsedTime("Body handled");

        decoratedTemplate = modifiedTemplate.toString();
    } catch (Exception e) {
        e.printStackTrace();
        logger.warn(
                "An error occurred when deliver tried to decorate your template to enable onSiteEditing. Reason "
                        + e.getMessage(),
                e);
    }

    return decoratedTemplate;
}