Example usage for java.util Collections list

List of usage examples for java.util Collections list

Introduction

In this page you can find the example usage for java.util Collections list.

Prototype

public static <T> ArrayList<T> list(Enumeration<T> e) 

Source Link

Document

Returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration.

Usage

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl.java

/**
 * Get all the aliases from the Keystore/Truststore or null if there was
 * some error while accessing it.//from  w w  w  . j a v  a  2  s  .  c  om
 */
@Override
public ArrayList<String> getAliases(KeystoreType ksType) throws CMException {
    // Need to make sure we are initialized before we do anything else
    // as Credential Manager can be created but not initialized
    initialize();

    try {
        switch (ksType) {
        case KEYSTORE:
            synchronized (keystore) {
                return Collections.list(keystore.aliases());
            }
        case TRUSTSTORE:
            synchronized (truststore) {
                return Collections.list(truststore.aliases());
            }
        default:
            return null;
        }
    } catch (Exception ex) {
        String exMessage = "failed to access the " + ksType + " to get the aliases";
        logger.error(exMessage, ex);
        throw new CMException(exMessage, ex);
    }
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java

/**
 * Get all the aliases from the Keystore/Truststore or null if there was
 * some error while accessing it.//from   w w  w  . ja v a2  s . c  o  m
 */
@Override
public ArrayList<String> getAliases(KeystoreType ksType) throws CMException {
    /*
     * Need to make sure we are initialized before we do anything else, as
     * the Credential Manager can be created but not initialized.
     */
    initialize();

    try {
        switch (ksType) {
        case KEYSTORE:
            synchronized (keystore) {
                return Collections.list(keystore.aliases());
            }
        case TRUSTSTORE:
            synchronized (truststore) {
                return Collections.list(truststore.aliases());
            }
        default:
            return null;
        }
    } catch (Exception ex) {
        String exMessage = "failed to access the " + ksType + " to get the aliases";
        logger.error(exMessage, ex);
        throw new CMException(exMessage, ex);
    }
}

From source file:org.xwoot.xwootApp.XWoot3.java

@SuppressWarnings("unchecked")
public Collection getNeighborsList() {
    return Collections.list(this.peer.getKnownDirectCommunicationPipeAdvertisements());
}

From source file:org.xwoot.xwootApp.XWoot3.java

@SuppressWarnings("unchecked")
public Collection getGroups() {
    return Collections.list(this.peer.getKnownGroups());
}

From source file:org.xwoot.jxta.JxtaPeer.java

/**
 * {@inheritDoc}//from  w w  w .ja v  a  2  s. c o m
 * <p/>
 * Make sure we never have duplicate direct communication channels (pipe advertisements) for one peer.
 **/
public void discoveryEvent(DiscoveryEvent event) {
    // FIXME: this only fixes the problem on the group RDV side and on the joining peer's side.
    // Existing group members still have this problem.      
    //  UPDATE: existing group members will update their local repo when a disconnected peer rejoins, but at least there will
    //  be no duplicates.
    // Existing group members need to be notified of disconnecting peers.

    DiscoveryResponseMsg response = event.getResponse();
    String queryAttribute = response.getQueryAttr();
    String queryValue = response.getQueryValue();
    String desiredQueryValue = this.getDirectCommunicationPipeNamePrefix() + "*";
    if (!this.isGroupRendezVous() && (response.getDiscoveryType() != DiscoveryService.ADV
            || !PipeAdvertisement.NameTag.equals(queryAttribute) || !desiredQueryValue.equals(queryValue))) {
        // Not interested in other advertisements, responses to other queries.
        return;
    }

    // A response to a direct communication channel advertisements discovery request or a remote publish by an EDGE peer when we are RDV.

    DiscoveryService disco = this.currentJoinedGroup.getDiscoveryService();

    Enumeration<Advertisement> receivedAdvertisements = response.getAdvertisements();
    while (receivedAdvertisements.hasMoreElements()) {
        Advertisement receivedAdvertisement = receivedAdvertisements.nextElement();
        // Make sure there aren't other types of advertisements.
        if (!(receivedAdvertisement instanceof PipeAdvertisement)) {
            // Not interested in other advertisements.
            continue;
        }

        PipeAdvertisement receivedPipeAdvertisement = (PipeAdvertisement) receivedAdvertisement;
        if (!receivedPipeAdvertisement.getName().startsWith(this.getDirectCommunicationPipeNamePrefix())) {
            // Not interested in other advertisements than direct communication channel advs.
            continue;
        }

        String receivedPipeName = receivedPipeAdvertisement.getName();
        ID receivedPipeId = receivedPipeAdvertisement.getPipeID();
        String receivedPeerId = JxtaPeer.getPeerIdFromBackChannelPipeName(receivedPipeName);
        long receivedCreationTime = 0;
        try {
            receivedCreationTime = Long
                    .parseLong(JxtaPeer.getCreationTimeFromBackChannelPipeName(receivedPipeName));
        } catch (Exception failedGetCreationTime) {
            this.logger.warn("Removing invalid received pipe advertisement named " + receivedPipeName,
                    failedGetCreationTime);
            try {
                disco.flushAdvertisement(receivedPipeAdvertisement);
            } catch (Exception failedFlushAdvertisement) {
                this.logger.warn(
                        "Failed to remove invalid received pipe advertisement named " + receivedPipeName,
                        failedFlushAdvertisement);
            }

            // Go to next received advertisement.
            continue;
        }

        // Get locally stored Pipe advertisements. 
        // Note: we don't use this.getKnownDirectCommunicationAdvertisements because we don`t want to trigger a new discovery event and enter an infinite loop.
        List<Advertisement> existingLocalAdvertisements = null;
        try {
            // get only existing direct communication channel advs.
            existingLocalAdvertisements = Collections.list(disco.getLocalAdvertisements(DiscoveryService.ADV,
                    PipeAdvertisement.NameTag, desiredQueryValue));
        } catch (Exception e) {
            logger.warn(
                    "Failed to get locally stored known advertisements while checking for duplicate direct communication advertisements.\n",
                    e);
            // hope others won't have this problem.
            return;
        }

        // Reset flag.
        boolean receivedFoundInExisting = false;

        // Search through the local direct communication advertisements if we already have an advertisement with the same pipeName of the new advertisement.
        for (Advertisement existingLocalAdvertisement : existingLocalAdvertisements) {
            // Make sure there aren't other types of advertisements.
            if (!(existingLocalAdvertisement instanceof PipeAdvertisement)) {
                // Not interested in other advertisements.
                continue;
            }

            PipeAdvertisement existingPipeAdvertisement = (PipeAdvertisement) existingLocalAdvertisement;
            String existingPipeName = existingPipeAdvertisement.getName();
            ID existingPipeId = existingPipeAdvertisement.getPipeID();
            String existingPeerId = JxtaPeer.getPeerIdFromBackChannelPipeName(existingPipeName);

            if (!existingPipeName.startsWith(this.getDirectCommunicationPipeNamePrefix())) {
                // Not interested in other pipe advertisements.
                continue;
            }

            if (receivedPipeId.equals(existingPipeId)) {
                if (receivedFoundInExisting) {
                    // Duplicate advertisement found. Deleting.
                    try {
                        disco.flushAdvertisement(existingPipeAdvertisement);
                    } catch (Exception failedFlushAdvertisement) {
                        this.logger.warn("Failed to remove duplicate existing pipe advertisement named "
                                + receivedPipeName, failedFlushAdvertisement);
                    }
                } else {
                    // Mark that we found the received advertisement trough the existing ones.
                    receivedFoundInExisting = true;
                }

                // Ignore retransmissions of the same advertisement.
                continue;
            }

            if (!receivedPeerId.equals(existingPeerId)) {
                // Ignore owning peer ID non-collisions. 
                continue;
            }

            // It's not the same advertisement retransmitted, but it's actually a new one, for the same owner(name collision)
            // Different pipeIDs but same owning peerId.

            long existingCreationTime = 0;
            try {
                existingCreationTime = Long
                        .parseLong(JxtaPeer.getCreationTimeFromBackChannelPipeName(existingPipeName));
            } catch (Exception failedGetCreationTime) {
                this.logger.warn("Removing invalid existing pipe advertisement named " + receivedPipeName,
                        failedGetCreationTime);
                try {
                    disco.flushAdvertisement(existingPipeAdvertisement);
                } catch (Exception failedFlushAdvertisement) {
                    this.logger.warn(
                            "Failed to remove invalid existing pipe advertisement named " + receivedPipeName,
                            failedFlushAdvertisement);
                }

                // Go to next existing advertisement.
                continue;
            }

            PipeAdvertisement toFlush = null;
            try {
                // update the communication channel for the owner by deleting the old and outdated one and keeping the new one.
                if (receivedCreationTime > existingCreationTime) {
                    toFlush = existingPipeAdvertisement;
                } else if (existingCreationTime > receivedCreationTime) {
                    toFlush = receivedPipeAdvertisement;
                }

                if (toFlush != null) {
                    this.logger.debug("Flushing outdated pipe advertisement by the name: " + toFlush.getName());
                    disco.flushAdvertisement(toFlush);
                }
            } catch (Exception e) {
                // Leave it as duplicate. The user will see the same peer twice but we hope that the next time it will be successfuly flushed.
                this.logger.warn(
                        "Failed to flush outdated pipe advertisement by the name: " + toFlush.getName() + "\n",
                        e);
            }

            // don't stop looking because we might have more outdated advertisements for the same peer (more collisions)
        }
    }
}

From source file:org.apache.openejb.config.DeploymentLoader.java

public static Map<String, URL> getWebDescriptors(final File warFile) throws IOException {
    final Map<String, URL> descriptors = new TreeMap<String, URL>();

    // xbean resource finder has a bug when you use any uri but "META-INF"
    // and the jar file does not contain a directory entry for the uri

    if (warFile.isFile()) { // only to discover module type so xml file filtering is enough
        final URL jarURL = new URL("jar", "", -1, warFile.toURI().toURL() + "!/");
        try {/*from   w w w  .ja  v a 2 s.  co m*/
            final JarFile jarFile = new JarFile(warFile);
            for (final JarEntry entry : Collections.list(jarFile.entries())) {
                final String entryName = entry.getName();
                if (!entry.isDirectory() && entryName.startsWith("WEB-INF/")
                        && (KNOWN_DESCRIPTORS.contains(entryName.substring("WEB-INF/".length()))
                                || entryName.endsWith(".xml"))) { // + web.xml, web-fragment.xml...
                    descriptors.put(entryName, new URL(jarURL, entry.getName()));
                }
            }
        } catch (final IOException e) {
            // most likely an invalid jar file
        }
    } else if (warFile.isDirectory()) {
        final File webInfDir = new File(warFile, "WEB-INF");
        if (webInfDir.isDirectory()) {
            final File[] files = webInfDir.listFiles();
            if (files != null) {
                for (final File file : files) {
                    if (!file.isDirectory()) {
                        descriptors.put(file.getName(), file.toURI().toURL());
                    }
                }
            }
        }

        // handle some few file(s) which can be in META-INF too
        final File webAppDdDir = new File(webInfDir, "classes/" + ddDir);
        if (webAppDdDir.isDirectory()) {
            final File[] files = webAppDdDir.listFiles();
            if (files != null) {
                for (final File file : files) {
                    final String name = file.getName();
                    if (!descriptors.containsKey(name)) {
                        descriptors.put(name, file.toURI().toURL());
                    } else {
                        logger.warning("Can't have a " + name
                                + " in WEB-INF and WEB-INF/classes/META-INF, second will be ignored");
                    }
                }
            }
        }
    }

    return descriptors;
}

From source file:org.sakaiproject.site.tool.SiteAction.java

/**
 * Build the context for each template using template_index parameter passed
 * in a form hidden field. Each case is associated with a template. (Not all
 * templates implemented). See String[] TEMPLATES.
 * /*from w w  w. ja v a  2 s.c  o m*/
 * @param index
 *            is the number contained in the template's template_index
 */

private String buildContextForTemplate(String preIndex, int index, VelocityPortlet portlet, Context context,
        RunData data, SessionState state) {
    String realmId = "";
    String site_type = "";
    String sortedBy = "";
    String sortedAsc = "";
    ParameterParser params = data.getParameters();
    context.put("tlang", rb);
    String alert = (String) state.getAttribute(STATE_MESSAGE);
    context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
    context.put("siteTextEdit", new SiteTextEditUtil());

    //SAK-29525 Open Template list by default when creating site
    context.put("isExpandTemplates",
            ServerConfigurationService.getBoolean("site.setup.creation.expand.template", false));

    // the last visited template index
    if (preIndex != null)
        context.put("backIndex", preIndex);

    // SAK-16600 adjust index for toolGroup mode 
    if (index == 3)
        index = 4;
    context.put("templateIndex", String.valueOf(index));

    // If cleanState() has removed SiteInfo, get a new instance into state
    SiteInfo siteInfo = new SiteInfo();
    if (state.getAttribute(STATE_SITE_INFO) != null) {
        siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
    } else {
        state.setAttribute(STATE_SITE_INFO, siteInfo);
    }
    // Lists used in more than one template

    // Access
    List roles = new Vector();

    // the hashtables for News and Web Content tools
    Hashtable newsTitles = new Hashtable();
    Hashtable newsUrls = new Hashtable();
    Hashtable wcTitles = new Hashtable();
    Hashtable wcUrls = new Hashtable();

    List toolRegistrationList = new Vector();
    List toolRegistrationSelectedList = new Vector();

    ResourceProperties siteProperties = null;

    // all site types
    context.put("courseSiteTypeStrings", SiteService.getSiteTypeStrings("course"));
    context.put("portfolioSiteTypeStrings", SiteService.getSiteTypeStrings("portfolio"));
    context.put("projectSiteTypeStrings", SiteService.getSiteTypeStrings("project"));

    //can the user create course sites?
    context.put(STATE_SITE_ADD_COURSE, SiteService.allowAddCourseSite());

    // can the user create portfolio sites?
    context.put("portfolioSiteType", STATE_PORTFOLIO_SITE_TYPE);
    context.put(STATE_SITE_ADD_PORTFOLIO, SiteService.allowAddPortfolioSite());

    // can the user create project sites?
    context.put("projectSiteType", STATE_PROJECT_SITE_TYPE);
    context.put(STATE_SITE_ADD_PROJECT, SiteService.allowAddProjectSite());

    // can the user user create sites from archives?
    context.put(STATE_SITE_IMPORT_ARCHIVE, SiteService.allowImportArchiveSite());

    Site site = getStateSite(state);

    List unJoinableSiteTypes = (List) state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);

    switch (index) {
    case 0:
        /*
         * buildContextForTemplate chef_site-list.vm
         * 
         */
        // site types
        List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);

        // make sure auto-updates are enabled
        Hashtable views = new Hashtable();

        // Allow a user to see their deleted sites.
        if (ServerConfigurationService.getBoolean("site.soft.deletion", false)) {
            views.put(SiteConstants.SITE_TYPE_DELETED, rb.getString("java.sites.deleted"));
            if (SiteConstants.SITE_TYPE_DELETED.equals((String) state.getAttribute(STATE_VIEW_SELECTED))) {
                context.put("canSeeSoftlyDeletedSites", true);
            }
        }

        // top menu bar
        Menu bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
        context.put("menu", bar);
        if (SiteService.allowAddSite(null)) {
            bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site"));
        }
        bar.add(new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site",
                "sitesForm"));
        bar.add(new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA,
                "doMenu_site_delete", "sitesForm"));

        // If we're in the restore view
        context.put("showRestore",
                SiteConstants.SITE_TYPE_DELETED.equals((String) state.getAttribute(STATE_VIEW_SELECTED)));

        if (SecurityService.isSuperUser()) {
            context.put("superUser", Boolean.TRUE);
        } else {
            context.put("superUser", Boolean.FALSE);
        }
        views.put(SiteConstants.SITE_TYPE_ALL, rb.getString("java.allmy"));
        views.put(SiteConstants.SITE_TYPE_MYWORKSPACE,
                rb.getFormattedMessage("java.sites", new Object[] { rb.getString("java.my") }));
        for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
            String type = (String) sTypes.get(sTypeIndex);
            views.put(type, rb.getFormattedMessage("java.sites", new Object[] { type }));
        }
        List<String> moreTypes = siteTypeProvider.getTypesForSiteList();
        if (!moreTypes.isEmpty()) {
            for (String mType : moreTypes) {
                views.put(mType, rb.getFormattedMessage("java.sites", new Object[] { mType }));
            }
        }
        // Allow SuperUser to see all deleted sites.
        if (ServerConfigurationService.getBoolean("site.soft.deletion", false)) {
            views.put(SiteConstants.SITE_TYPE_DELETED, rb.getString("java.sites.deleted"));
        }

        // default view
        if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
            state.setAttribute(STATE_VIEW_SELECTED, SiteConstants.SITE_TYPE_ALL);
        }

        if (ServerConfigurationService.getBoolean("sitesetup.show.unpublished", false)
                && !SecurityService.isSuperUser()) {
            views.put(SiteConstants.SITE_ACTIVE, rb.getString("java.myActive"));
            views.put(SiteConstants.SITE_INACTIVE, rb.getString("java.myInactive"));
        }

        // sort the keys in the views lookup
        List<String> viewKeys = Collections.list(views.keys());
        Collections.sort(viewKeys);
        context.put("viewKeys", viewKeys);
        context.put("views", views);

        if (state.getAttribute(STATE_VIEW_SELECTED) != null) {
            context.put("viewSelected", (String) state.getAttribute(STATE_VIEW_SELECTED));
        }

        //term filter:
        Hashtable termViews = new Hashtable();
        termViews.put(TERM_OPTION_ALL, rb.getString("list.allTerms"));

        // bjones86 - SAK-23256
        List<AcademicSession> aSessions = setTermListForContext(context, state, false, false);

        if (aSessions != null) {
            for (AcademicSession s : aSessions) {
                termViews.put(s.getTitle(), s.getTitle());
            }
        }

        // sort the keys in the termViews lookup
        List<String> termViewKeys = Collections.list(termViews.keys());
        Collections.sort(termViewKeys);
        context.put("termViewKeys", termViewKeys);
        context.put("termViews", termViews);

        // default term view
        if (state.getAttribute(STATE_TERM_VIEW_SELECTED) == null) {
            state.setAttribute(STATE_TERM_VIEW_SELECTED, TERM_OPTION_ALL);

            if (ServerConfigurationService.getBoolean(SAK_PROP_AUTO_FILTER_TERM, Boolean.FALSE)) {
                // SAK-28059 auto filter term to use the most current term
                List<AcademicSession> currentTerms = cms.getCurrentAcademicSessions();
                // current terms are sorted by start date we will just take the first
                if (!currentTerms.isEmpty()) {
                    int termIndex = termViewKeys.indexOf(currentTerms.get(0).getTitle());
                    if (termIndex > -1) {
                        state.setAttribute(STATE_TERM_VIEW_SELECTED, termViewKeys.get(termIndex));
                        context.put("viewTermSelected", termViewKeys.get(termIndex));
                    }
                }
            }
        } else {
            context.put("viewTermSelected", (String) state.getAttribute(STATE_TERM_VIEW_SELECTED));
        }

        if (termViews.size() == 1) {
            //this means the terms are empty, only the default option exist
            context.put("hideTermFilter", true);
        } else {
            context.put("hideTermFilter", false);
        }

        String search = (String) state.getAttribute(STATE_SEARCH);
        context.put("search_term", search);

        sortedBy = (String) state.getAttribute(SORTED_BY);
        if (sortedBy == null) {
            state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
            sortedBy = SortType.TITLE_ASC.toString();
        }

        sortedAsc = (String) state.getAttribute(SORTED_ASC);
        if (sortedAsc == null) {
            sortedAsc = Boolean.TRUE.toString();
            state.setAttribute(SORTED_ASC, sortedAsc);
        }
        if (sortedBy != null)
            context.put("currentSortedBy", sortedBy);
        if (sortedAsc != null)
            context.put("currentSortAsc", sortedAsc);

        String portalUrl = ServerConfigurationService.getPortalUrl();
        context.put("portalUrl", portalUrl);

        List<Site> allSites = prepPage(state);

        state.setAttribute(STATE_SITES, allSites);
        context.put("sites", allSites);

        context.put("totalPageNumber", Integer.valueOf(totalPageNumber(state)));
        context.put("searchString", state.getAttribute(STATE_SEARCH));
        context.put("form_search", FORM_SEARCH);
        context.put("formPageNumber", FORM_PAGE_NUMBER);
        context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS));
        context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS));
        context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));

        // put the service in the context (used for allow update calls on
        // each site)
        context.put("service", SiteService.getInstance());
        context.put("sortby_title", SortType.TITLE_ASC.toString());
        context.put("sortby_id", SortType.ID_ASC.toString());
        context.put("show_id_column",
                ServerConfigurationService.getBoolean("site.setup.showSiteIdColumn", false));
        context.put("sortby_type", SortType.TYPE_ASC.toString());
        context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
        context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
        context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
        context.put("sortby_softlydeleted", SortType.SOFTLY_DELETED_ASC.toString());

        // default to be no paging
        context.put("paged", Boolean.FALSE);

        Menu bar2 = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));

        // add the search commands
        addSearchMenus(bar2, state);
        context.put("menu2", bar2);

        pagingInfoToContext(state, context);

        //SAK-22438 if user can add one of these site types then they can see the link to add a new site
        boolean allowAddSite = false;
        if (SiteService.allowAddCourseSite()) {
            allowAddSite = true;
        } else if (SiteService.allowAddPortfolioSite()) {
            allowAddSite = true;
        } else if (SiteService.allowAddProjectSite()) {
            allowAddSite = true;
        }

        context.put("allowAddSite", allowAddSite);

        //SAK-23468 put create variables into context
        addSiteCreationValuesIntoContext(context, state);

        return (String) getContext(data).get("template") + TEMPLATE[0];
    case 1:
        /*
         * buildContextForTemplate chef_site-type.vm
         * 
         */
        List types = (List) state.getAttribute(STATE_SITE_TYPES);
        List<String> mTypes = siteTypeProvider.getTypesForSiteCreation();
        if (mTypes != null && !mTypes.isEmpty()) {
            types.addAll(mTypes);
        }
        context.put("siteTypes", types);
        context.put("templateControls", ServerConfigurationService.getString("templateControls", ""));
        // put selected/default site type into context
        String typeSelected = (String) state.getAttribute(STATE_TYPE_SELECTED);
        context.put("typeSelected",
                state.getAttribute(STATE_TYPE_SELECTED) != null ? state.getAttribute(STATE_TYPE_SELECTED)
                        : types.get(0));

        // bjones86 - SAK-23256
        Boolean hasTerms = Boolean.FALSE;
        List<AcademicSession> termList = setTermListForContext(context, state, true, true); // true => only
        if (termList != null && termList.size() > 0) {
            hasTerms = Boolean.TRUE;
        }
        context.put(CONTEXT_HAS_TERMS, hasTerms);

        // upcoming terms
        setSelectedTermForContext(context, state, STATE_TERM_SELECTED);

        // template site
        setTemplateListForContext(context, state);

        return (String) getContext(data).get("template") + TEMPLATE[1];
    case 4:
        /*
         * buildContextForTemplate chef_site-editToolGroups.vm
         * 
         */
        state.removeAttribute(STATE_TOOL_GROUP_LIST);

        String type = (String) state.getAttribute(STATE_SITE_TYPE);
        setTypeIntoContext(context, type);

        Map<String, List> groupTools = getTools(state, type, site);
        state.setAttribute(STATE_TOOL_GROUP_LIST, groupTools);

        // information related to LTI tools
        buildLTIToolContextForTemplate(context, state, site, true);

        if (SecurityService.isSuperUser()) {
            context.put("superUser", Boolean.TRUE);
        } else {
            context.put("superUser", Boolean.FALSE);
        }

        // save all lists to context         
        pageOrderToolTitleIntoContext(context, state, type, (site == null),
                site == null ? null
                        : site.getProperties()
                                .getProperty(SiteConstants.SITE_PROPERTY_OVERRIDE_HIDE_PAGEORDER_SITE_TYPES));
        Boolean checkToolGroupHome = (Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED);

        context.put("check_home", checkToolGroupHome);
        context.put("ltitool_id_prefix", LTITOOL_ID_PREFIX);
        context.put("serverName", ServerConfigurationService.getServerName());
        context.put("sites", SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
                null, null, null, SortType.TITLE_ASC, null));
        context.put("import", state.getAttribute(STATE_IMPORT));
        context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
        if (site != null) {
            MathJaxEnabler.addMathJaxSettingsToEditToolsContext(context, site, state); // SAK-22384
            context.put("SiteTitle", site.getTitle());
            context.put("existSite", Boolean.TRUE);
            context.put("backIndex", "12"); // back to site info list page
        } else {
            context.put("existSite", Boolean.FALSE);
            context.put("backIndex", "13"); // back to new site information page
        }
        context.put("homeToolId", TOOL_ID_HOME);
        context.put("toolsByGroup", (LinkedHashMap<String, List>) state.getAttribute(STATE_TOOL_GROUP_LIST));

        context.put("toolGroupMultiples",
                getToolGroupMultiples(state, (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST)));

        return (String) getContext(data).get("template") + TEMPLATE[4];

    case 8:
        /*
         * buildContextForTemplate chef_site-siteDeleteConfirm.vm
         * 
         */
        String site_title = NULL_STRING;
        String[] removals = (String[]) state.getAttribute(STATE_SITE_REMOVALS);
        List remove = new Vector();
        String user = SessionManager.getCurrentSessionUserId();
        String workspace = SiteService.getUserSiteId(user);
        // Are we attempting to softly delete a site.
        boolean softlyDeleting = ServerConfigurationService.getBoolean("site.soft.deletion", false);
        if (removals != null && removals.length != 0) {
            for (int i = 0; i < removals.length; i++) {
                String id = (String) removals[i];
                if (!(id.equals(workspace))) {
                    if (SiteService.allowRemoveSite(id)) {
                        try {
                            // check whether site exists
                            Site removeSite = SiteService.getSite(id);

                            //check site isn't already softly deleted
                            if (softlyDeleting && removeSite.isSoftlyDeleted()) {
                                softlyDeleting = false;
                            }
                            remove.add(removeSite);
                        } catch (IdUnusedException e) {
                            M_log.warn(this
                                    + "buildContextForTemplate chef_site-siteDeleteConfirm.vm - IdUnusedException "
                                    + id + e.getMessage());
                            addAlert(state, rb.getFormattedMessage("java.couldntlocate", new Object[] { id }));
                        }
                    } else {
                        addAlert(state, rb.getFormattedMessage("java.couldntdel", new Object[] { site_title }));
                    }
                } else {
                    addAlert(state, rb.getString("java.yourwork"));
                }
            }
            if (remove.size() == 0) {
                addAlert(state, rb.getString("java.click"));
            }
        }
        context.put("removals", remove);

        //check if hard deletes are wanted
        if (StringUtils.equalsIgnoreCase((String) state.getAttribute(STATE_HARD_DELETE),
                Boolean.TRUE.toString())) {
            context.put("hardDelete", true);
            //SAK-29678 - If it's hard deleted, it's not soft deleted.
            softlyDeleting = false;
        }

        //check if soft deletes are activated
        context.put("softDelete", softlyDeleting);

        return (String) getContext(data).get("template") + TEMPLATE[8];
    case 10:
        /*
         * buildContextForTemplate chef_site-newSiteConfirm.vm
         * 
         */
        siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
        String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
        if (SiteTypeUtil.isCourseSite(siteType)) {
            context.put("isCourseSite", Boolean.TRUE);
            context.put("disableCourseSelection",
                    ServerConfigurationService.getString("disable.course.site.skin.selection", "false")
                            .equals("true") ? Boolean.TRUE : Boolean.FALSE);
            context.put("isProjectSite", Boolean.FALSE);
            putSelectedProviderCourseIntoContext(context, state);
            if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
                context.put("selectedAuthorizerCourse", state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS));
            }
            if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
                context.put("selectedRequestedCourse", state.getAttribute(STATE_CM_REQUESTED_SECTIONS));
            }
            if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
                int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
                context.put("manualAddNumber", Integer.valueOf(number - 1));
                context.put("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
            } else if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
                context.put("manualAddNumber",
                        Integer.valueOf(((List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS)).size()));
            }

            context.put("skins", state.getAttribute(STATE_ICONS));
            if (StringUtils.trimToNull(siteInfo.getIconUrl()) != null) {
                context.put("selectedIcon", siteInfo.getIconUrl());
            }
        } else {
            context.put("isCourseSite", Boolean.FALSE);
            if (SiteTypeUtil.isProjectSite(siteType)) {
                context.put("isProjectSite", Boolean.TRUE);
            }

            if (StringUtils.trimToNull(siteInfo.iconUrl) != null) {
                context.put("iconUrl", siteInfo.iconUrl);
            }
        }

        context.put("siteUrls", getSiteUrlsForAliasIds(siteInfo.siteRefAliases));

        context.put("title", siteInfo.title);
        context.put("description", siteInfo.description);
        context.put("short_description", siteInfo.short_description);
        context.put("siteContactName", siteInfo.site_contact_name);
        context.put("siteContactEmail", siteInfo.site_contact_email);

        /// site language information

        String locale_string_selected = (String) state.getAttribute("locale_string");
        if (locale_string_selected == "" || locale_string_selected == null)
            context.put("locale_string_selected", "");
        else {
            Locale locale_selected = getLocaleFromString(locale_string_selected);
            context.put("locale_string_selected", locale_selected);
        }

        // put tool selection into context
        toolSelectionIntoContext(context, state, siteType, null,
                null/*site.getProperties().getProperty(SiteConstants.SITE_PROPERTY_OVERRIDE_HIDE_PAGEORDER_SITE_TYPES)*/);

        context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
        context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
        context.put("serverName", ServerConfigurationService.getServerName());
        context.put("include", Boolean.valueOf(siteInfo.include));
        context.put("published", Boolean.valueOf(siteInfo.published));
        context.put("joinable", Boolean.valueOf(siteInfo.joinable));
        context.put("joinerRole", siteInfo.joinerRole);
        context.put("additionalAccess", getAdditionRoles(siteInfo));

        // bjones86 - SAK-24423 - add joinable site settings to context
        JoinableSiteSettings.addJoinableSiteSettingsToNewSiteConfirmContext(context, siteInfo);

        context.put("importSiteTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
        context.put("siteService", SiteService.getInstance());

        // those manual inputs
        context.put("form_requiredFields", sectionFieldProvider.getRequiredFields());
        context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));

        context.put("fromArchive", state.getAttribute(STATE_UPLOADED_ARCHIVE_NAME));

        return (String) getContext(data).get("template") + TEMPLATE[10];
    case 12:
        /*
         * buildContextForTemplate chef_site-siteInfo-list.vm
         * 
         */
        // put the link for downloading participant
        putPrintParticipantLinkIntoContext(context, data, site);

        context.put("userDirectoryService", UserDirectoryService.getInstance());
        try {
            siteProperties = site.getProperties();
            siteType = site.getType();
            if (siteType != null) {
                state.setAttribute(STATE_SITE_TYPE, siteType);
            }

            if (site.getProviderGroupId() != null) {
                M_log.debug("site has provider");
                context.put("hasProviderSet", Boolean.TRUE);
            } else {
                M_log.debug("site has no provider");
                context.put("hasProviderSet", Boolean.FALSE);
            }
            boolean isMyWorkspace = false;
            if (SiteService.isUserSite(site.getId())) {
                if (SiteService.getSiteUserId(site.getId()).equals(SessionManager.getCurrentSessionUserId())) {
                    isMyWorkspace = true;
                    context.put("siteUserId", SiteService.getSiteUserId(site.getId()));
                }
            }
            context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));

            String siteId = site.getId();
            if (state.getAttribute(STATE_ICONS) != null) {
                List skins = (List) state.getAttribute(STATE_ICONS);
                for (int i = 0; i < skins.size(); i++) {
                    MyIcon s = (MyIcon) skins.get(i);
                    if (StringUtils.equals(s.getUrl(), site.getIconUrl())) {
                        context.put("siteUnit", s.getName());
                        break;
                    }
                }
            }

            context.put("siteFriendlyUrls", getSiteUrlsForSite(site));
            context.put("siteDefaultUrl", getDefaultSiteUrl(siteId));

            context.put("siteId", site.getId());
            context.put("siteIcon", site.getIconUrl());
            context.put("siteTitle", site.getTitle());
            context.put("siteDescription", site.getDescription());
            context.put("siteId", site.getId());
            if (unJoinableSiteTypes != null && !unJoinableSiteTypes.contains(siteType)) {
                context.put("siteJoinable", Boolean.valueOf(site.isJoinable()));
                context.put("allowUnjoin", SiteService.allowUnjoinSite(site.getId()));
            }

            // Is the current user a member
            context.put("siteUserMember",
                    site.getUserRole(UserDirectoryService.getCurrentUser().getId()) != null);

            if (site.isPublished()) {
                context.put("published", Boolean.TRUE);
            } else {
                context.put("published", Boolean.FALSE);
                context.put("owner", site.getCreatedBy().getSortName());
            }
            Time creationTime = site.getCreatedTime();
            if (creationTime != null) {
                context.put("siteCreationDate", creationTime.toStringLocalFull());
            }
            boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
            context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));

            boolean allowUpdateGroupMembership = SiteService.allowUpdateGroupMembership(siteId);
            context.put("allowUpdateGroupMembership", Boolean.valueOf(allowUpdateGroupMembership));

            boolean allowUpdateSiteMembership = SiteService.allowUpdateSiteMembership(siteId);
            context.put("allowUpdateSiteMembership", Boolean.valueOf(allowUpdateSiteMembership));

            context.put("additionalAccess", getAdditionRoles(site));

            Menu b = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
            if (allowUpdateSite) {
                // Site modified by information
                User siteModifiedBy = site.getModifiedBy();
                Time siteModifiedTime = site.getModifiedTime();
                if (siteModifiedBy != null) {
                    context.put("siteModifiedBy", siteModifiedBy.getSortName());
                }
                if (siteModifiedTime != null) {
                    context.put("siteModifiedTime", siteModifiedTime.toStringLocalFull());
                }

                // top menu bar
                if (!isMyWorkspace) {
                    b.add(new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info"));
                }
                b.add(new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools"));

                // if the page order helper is available, not
                // stealthed and not hidden, show the link
                if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) {

                    // in particular, need to check site types for showing the tool or not
                    if (isPageOrderAllowed(siteType, siteProperties
                            .getProperty(SiteConstants.SITE_PROPERTY_OVERRIDE_HIDE_PAGEORDER_SITE_TYPES))) {
                        b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper"));
                    }

                }

            }

            if (allowUpdateSiteMembership) {
                // show add participant menu
                if (!isMyWorkspace) {
                    // if the add participant helper is available, not
                    // stealthed and not hidden, show the link
                    if (notStealthOrHiddenTool("sakai-site-manage-participant-helper")) {
                        b.add(new MenuEntry(rb.getString("java.addp"), "doParticipantHelper"));
                    }

                    // show the Edit Class Roster menu
                    if (ServerConfigurationService.getBoolean("site.setup.allow.editRoster", true)
                            && siteType != null && SiteTypeUtil.isCourseSite(siteType)) {
                        b.add(new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass"));
                    }
                }
            }

            if (allowUpdateGroupMembership) {
                // show Manage Groups menu
                if (!isMyWorkspace && (ServerConfigurationService.getString("wsetup.group.support") == ""
                        || ServerConfigurationService.getString("wsetup.group.support")
                                .equalsIgnoreCase(Boolean.TRUE.toString()))) {
                    // show the group toolbar unless configured
                    // to not support group
                    // if the manage group helper is available, not
                    // stealthed and not hidden, show the link
                    // read the helper name from configuration variable: wsetup.group.helper.name
                    // the default value is: "sakai-site-manage-group-section-role-helper"
                    // the older version of group helper which is not section/role aware is named:"sakai-site-manage-group-helper"
                    String groupHelper = ServerConfigurationService.getString("wsetup.group.helper.name",
                            "sakai-site-manage-group-section-role-helper");
                    if (setHelper("wsetup.groupHelper", groupHelper, state, STATE_GROUP_HELPER_ID)) {
                        b.add(new MenuEntry(rb.getString("java.group"), "doManageGroupHelper"));
                    }
                }
            }

            if (allowUpdateSite) {
                // show add parent sites menu
                if (!isMyWorkspace) {
                    if (notStealthOrHiddenTool("sakai-site-manage-link-helper")) {
                        b.add(new MenuEntry(rb.getString("java.link"), "doLinkHelper"));
                    }

                    if (notStealthOrHiddenTool("sakai.basiclti.admin.helper")) {
                        b.add(new MenuEntry(rb.getString("java.external"), "doExternalHelper"));
                    }

                }
            }

            if (allowUpdateSite) {
                if (!isMyWorkspace) {
                    List<String> providedSiteTypes = siteTypeProvider.getTypes();
                    boolean isProvidedType = false;
                    if (siteType != null && providedSiteTypes.contains(siteType)) {
                        isProvidedType = true;
                    }
                    if (!isProvidedType) {
                        // hide site access for provided site types
                        // type of sites
                        b.add(new MenuEntry(rb.getString("java.siteaccess"), "doMenu_edit_site_access"));

                        // hide site duplicate and import
                        if (SiteService.allowAddSite(null) && ServerConfigurationService
                                .getBoolean("site.setup.allowDuplicateSite", true)) {
                            b.add(new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate"));
                        }

                        List updatableSites = SiteService.getSites(
                                org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null,
                                SortType.TITLE_ASC, null);

                        // import link should be visible even if only one
                        // site
                        if (updatableSites.size() > 0) {
                            //a configuration param for showing/hiding Import From Site with Clean Up
                            String importFromSite = ServerConfigurationService.getString("clean.import.site",
                                    Boolean.TRUE.toString());
                            if (importFromSite.equalsIgnoreCase("true")) {
                                b.add(new MenuEntry(rb.getString("java.import"),
                                        "doMenu_siteInfo_importSelection"));
                            } else {
                                b.add(new MenuEntry(rb.getString("java.import"), "doMenu_siteInfo_import"));
                            }
                            // a configuration param for
                            // showing/hiding import
                            // from file choice
                            String importFromFile = ServerConfigurationService
                                    .getString("site.setup.import.file", Boolean.TRUE.toString());
                            if (importFromFile.equalsIgnoreCase("true")) {
                                // htripath: June
                                // 4th added as per
                                // Kris and changed
                                // desc of above
                                b.add(new MenuEntry(rb.getString("java.importFile"),
                                        "doAttachmentsMtrlFrmFile"));
                            }
                        }
                    }
                }
            }

            if (allowUpdateSite) {
                // show add parent sites menu
                if (!isMyWorkspace) {
                    boolean eventLog = "true"
                            .equals(ServerConfigurationService.getString("user_audit_log_display", "true"));
                    if (notStealthOrHiddenTool("sakai.useraudit") && eventLog) {
                        b.add(new MenuEntry(rb.getString("java.userAuditEventLog"), "doUserAuditEventLog"));
                    }
                }
            }

            if (b.size() > 0) {
                // add the menus to vm
                context.put("menu", b);
            }

            if (state.getAttribute(IMPORT_QUEUED) != null) {
                context.put("importQueued", true);
                state.removeAttribute(IMPORT_QUEUED);
                if (StringUtils.isBlank(UserDirectoryService.getCurrentUser().getEmail())
                        || !ServerConfigurationService.getBoolean(SAK_PROP_IMPORT_NOTIFICATION, true)) {
                    context.put("importQueuedNoEmail", true);
                }
            }

            if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP)) {
                // editing from worksite setup tool
                context.put("fromWSetup", Boolean.TRUE);
                if (state.getAttribute(STATE_PREV_SITE) != null) {
                    context.put("prevSite", state.getAttribute(STATE_PREV_SITE));
                }
                if (state.getAttribute(STATE_NEXT_SITE) != null) {
                    context.put("nextSite", state.getAttribute(STATE_NEXT_SITE));
                }
            } else {
                context.put("fromWSetup", Boolean.FALSE);
            }
            // allow view roster?
            boolean allowViewRoster = SiteService.allowViewRoster(siteId);
            if (allowViewRoster) {
                context.put("viewRoster", Boolean.TRUE);
            } else {
                context.put("viewRoster", Boolean.FALSE);
            }
            // set participant list
            if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership) {
                Collection participantsCollection = getParticipantList(state);
                sortedBy = (String) state.getAttribute(SORTED_BY);
                sortedAsc = (String) state.getAttribute(SORTED_ASC);
                if (sortedBy == null) {
                    state.setAttribute(SORTED_BY, SiteConstants.SORTED_BY_PARTICIPANT_NAME);
                    sortedBy = SiteConstants.SORTED_BY_PARTICIPANT_NAME;
                }
                if (sortedAsc == null) {
                    sortedAsc = Boolean.TRUE.toString();
                    state.setAttribute(SORTED_ASC, sortedAsc);
                }
                if (sortedBy != null)
                    context.put("currentSortedBy", sortedBy);
                if (sortedAsc != null)
                    context.put("currentSortAsc", sortedAsc);
                context.put("participantListSize", Integer.valueOf(participantsCollection.size()));
                context.put("participantList", prepPage(state));
                pagingInfoToContext(state, context);
            }

            context.put("include", Boolean.valueOf(site.isPubView()));

            // site contact information
            String contactName = siteProperties.getProperty(Site.PROP_SITE_CONTACT_NAME);
            String contactEmail = siteProperties.getProperty(Site.PROP_SITE_CONTACT_EMAIL);
            if (contactName == null && contactEmail == null) {
                User u = site.getCreatedBy();
                String email = u.getEmail();
                if (email != null) {
                    contactEmail = u.getEmail();
                }
                contactName = u.getDisplayName();
            }
            if (contactName != null) {
                context.put("contactName", contactName);
            }
            if (contactEmail != null) {
                context.put("contactEmail", contactEmail);
            }

            if (SiteTypeUtil.isCourseSite(siteType)) {
                context.put("isCourseSite", Boolean.TRUE);

                coursesIntoContext(state, context, site);

                context.put("term", siteProperties.getProperty(Site.PROP_SITE_TERM));
            } else {
                context.put("isCourseSite", Boolean.FALSE);
            }

            Collection<Group> groups = null;
            if (ServerConfigurationService.getBoolean("wsetup.group.support.summary", true)) {
                if ((allowUpdateSite || allowUpdateGroupMembership) && (!isMyWorkspace
                        && ServerConfigurationService.getBoolean("wsetup.group.support", true))) {
                    // show all site groups
                    groups = site.getGroups();
                } else {
                    // show groups that the current user is member of
                    groups = site.getGroupsWithMember(UserDirectoryService.getCurrentUser().getId());
                }
            }
            if (groups != null) {
                // filter out only those groups that are manageable by site-info
                List<Group> filteredGroups = new ArrayList<Group>();
                List<Group> filteredSections = new ArrayList<Group>();
                Collection<String> viewMembershipGroups = new ArrayList<String>();
                Collection<String> unjoinableGroups = new ArrayList<String>();
                for (Group g : groups) {
                    Object gProp = g.getProperties().getProperty(g.GROUP_PROP_WSETUP_CREATED);
                    if (gProp != null && gProp.equals(Boolean.TRUE.toString())) {
                        filteredGroups.add(g);
                    } else {
                        filteredSections.add(g);
                    }
                    Object vProp = g.getProperties().getProperty(g.GROUP_PROP_VIEW_MEMBERS);
                    if (vProp != null && vProp.equals(Boolean.TRUE.toString())) {
                        viewMembershipGroups.add(g.getId());
                    }
                    Object joinableProp = g.getProperties().getProperty(g.GROUP_PROP_JOINABLE_SET);
                    Object unjoinableProp = g.getProperties().getProperty(g.GROUP_PROP_JOINABLE_UNJOINABLE);
                    if (joinableProp != null && !"".equals(joinableProp.toString()) && unjoinableProp != null
                            && unjoinableProp.equals(Boolean.TRUE.toString())
                            && g.getMember(UserDirectoryService.getCurrentUser().getId()) != null) {
                        unjoinableGroups.add(g.getId());
                    }
                }
                Collections.sort(filteredGroups, new Comparator<Group>() {
                    public int compare(Group o1, Group o2) {
                        return o1.getTitle().compareToIgnoreCase(o2.getTitle());
                    }
                });
                context.put("groups", filteredGroups);
                Collections.sort(filteredSections, new Comparator<Group>() {
                    public int compare(Group o1, Group o2) {
                        return o1.getTitle().compareToIgnoreCase(o2.getTitle());
                    }
                });
                context.put("sections", filteredSections);
                context.put("viewMembershipGroups", viewMembershipGroups);
                context.put("unjoinableGroups", unjoinableGroups);
            }

            //joinable groups:
            List<JoinableGroup> joinableGroups = new ArrayList<JoinableGroup>();
            if (site.getGroups() != null) {
                //find a list of joinable-sets this user is already a member of
                //in order to not display those groups as options
                Set<String> joinableSetsMember = new HashSet<String>();
                for (Group group : site.getGroupsWithMember(UserDirectoryService.getCurrentUser().getId())) {
                    String joinableSet = group.getProperties().getProperty(group.GROUP_PROP_JOINABLE_SET);
                    if (joinableSet != null && !"".equals(joinableSet.trim())) {
                        joinableSetsMember.add(joinableSet);
                    }
                }
                for (Group group : site.getGroups()) {
                    String joinableSet = group.getProperties().getProperty(group.GROUP_PROP_JOINABLE_SET);
                    if (joinableSet != null && !"".equals(joinableSet.trim())
                            && !joinableSetsMember.contains(joinableSet)) {
                        String reference = group.getReference();
                        String title = group.getTitle();
                        int max = 0;
                        try {
                            max = Integer.parseInt(
                                    group.getProperties().getProperty(group.GROUP_PROP_JOINABLE_SET_MAX));
                        } catch (Exception e) {
                        }
                        boolean preview = Boolean.valueOf(
                                group.getProperties().getProperty(group.GROUP_PROP_JOINABLE_SET_PREVIEW));
                        String groupMembers = "";
                        int size = 0;
                        try {
                            AuthzGroup g = authzGroupService.getAuthzGroup(group.getReference());
                            Collection<Member> gMembers = g != null ? g.getMembers() : new Vector<Member>();
                            size = gMembers.size();
                            if (size > 0) {
                                Set<String> hiddenUsers = new HashSet<String>();
                                boolean viewHidden = viewHidden = SecurityService.unlock("roster.viewHidden",
                                        site.getReference())
                                        || SecurityService.unlock("roster.viewHidden", g.getReference());
                                if (!SiteService.allowViewRoster(siteId) && !viewHidden) {
                                    //find hidden users in this group:
                                    //add hidden users to set so we can filter them out
                                    Set<String> memberIds = new HashSet<String>();
                                    for (Member member : gMembers) {
                                        memberIds.add(member.getUserId());
                                    }
                                    hiddenUsers = privacyManager.findHidden(site.getReference(), memberIds);
                                }
                                for (Iterator<Member> gItr = gMembers.iterator(); gItr.hasNext();) {
                                    Member p = (Member) gItr.next();

                                    // exclude those user with provided roles and rosters
                                    String userId = p.getUserId();
                                    if (!hiddenUsers.contains(userId)) {
                                        try {
                                            User u = UserDirectoryService.getUser(userId);
                                            if (!"".equals(groupMembers)) {
                                                groupMembers += ", ";
                                            }
                                            groupMembers += u.getDisplayName();
                                        } catch (Exception e) {
                                            M_log.debug(this + "joinablegroups: cannot find user with id "
                                                    + userId);
                                            // need to remove the group member
                                            size--;
                                        }
                                    }
                                }
                            }
                        } catch (GroupNotDefinedException e) {
                            M_log.debug(this + "joinablegroups: cannot find group " + group.getReference());
                        }
                        joinableGroups.add(new JoinableGroup(reference, title, joinableSet, size, max,
                                groupMembers, preview));
                    }
                }
                if (joinableGroups.size() > 0) {
                    Collections.sort(joinableGroups, new Comparator<JoinableGroup>() {
                        public int compare(JoinableGroup g1, JoinableGroup g2) {
                            return g1.getTitle().compareToIgnoreCase(g2.getTitle());
                        }
                    });
                    context.put("joinableGroups", joinableGroups);
                }
            }

        } catch (Exception e) {
            M_log.error(this + " buildContextForTemplate chef_site-siteInfo-list.vm ", e);
        }

        roles = getRoles(state);
        context.put("roles", roles);

        // SAK-23257 - add the allowed roles to the context for UI rendering
        context.put(VM_ALLOWED_ROLES_DROP_DOWN, SiteParticipantHelper.getAllowedRoles(site.getType(), roles));

        // will have the choice to active/inactive user or not
        String activeInactiveUser = ServerConfigurationService.getString("activeInactiveUser",
                Boolean.FALSE.toString());
        if (activeInactiveUser.equalsIgnoreCase("true")) {
            context.put("activeInactiveUser", Boolean.TRUE);
        } else {
            context.put("activeInactiveUser", Boolean.FALSE);
        }

        // UVa add realm object to context so we can provide last modified time
        realmId = SiteService.siteReference(site.getId());
        try {
            AuthzGroup realm = authzGroupService.getAuthzGroup(realmId);
            context.put("realmModifiedTime", realm.getModifiedTime().toStringLocalFullZ());
        } catch (GroupNotDefinedException e) {
            M_log.warn(this + "  IdUnusedException " + realmId);
        }

        // SAK-22384 mathjax support
        MathJaxEnabler.addMathJaxSettingsToSiteInfoContext(context, site, state);

        return (String) getContext(data).get("template") + TEMPLATE[12];

    case 13:
        /*
         * buildContextForTemplate chef_site-siteInfo-editInfo.vm
         * 
         */
        if (site != null) {
            // revising a existing site's tool
            context.put("existingSite", Boolean.TRUE);
            context.put("continue", "14");

            ResourcePropertiesEdit props = site.getPropertiesEdit();

            String locale_string = StringUtils.trimToEmpty(props.getProperty(PROP_SITE_LANGUAGE));
            context.put("locale_string", locale_string);
        } else {
            // new site
            context.put("existingSite", Boolean.FALSE);
            context.put("continue", "4");

            // get the system default as locale string
            context.put("locale_string", "");
        }

        boolean displaySiteAlias = displaySiteAlias();
        context.put("displaySiteAlias", Boolean.valueOf(displaySiteAlias));
        if (displaySiteAlias) {
            context.put(FORM_SITE_URL_BASE, getSiteBaseUrl());
            context.put(FORM_SITE_ALIAS, siteInfo.getFirstAlias());
        }

        siteType = (String) state.getAttribute(STATE_SITE_TYPE);
        context.put("type", siteType);
        context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, siteType)));
        context.put("titleMaxLength", state.getAttribute(STATE_SITE_TITLE_MAX));

        if (SiteTypeUtil.isCourseSite(siteType)) {
            context.put("isCourseSite", Boolean.TRUE);
            context.put("isProjectSite", Boolean.FALSE);

            boolean hasRosterAttached = putSelectedProviderCourseIntoContext(context, state);

            List<SectionObject> cmRequestedList = (List<SectionObject>) state
                    .getAttribute(STATE_CM_REQUESTED_SECTIONS);

            if (cmRequestedList != null) {
                context.put("cmRequestedSections", cmRequestedList);
                if (!hasRosterAttached && cmRequestedList.size() > 0) {
                    hasRosterAttached = true;
                }
            }

            List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state
                    .getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
            if (cmAuthorizerSectionList != null) {
                context.put("cmAuthorizerSections", cmAuthorizerSectionList);
                if (!hasRosterAttached && cmAuthorizerSectionList.size() > 0) {
                    hasRosterAttached = true;
                }
            }

            if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
                int number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
                context.put("manualAddNumber", Integer.valueOf(number - 1));
                context.put("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
                if (!hasRosterAttached) {
                    hasRosterAttached = true;
                }
            } else {
                if (site != null)
                    if (!hasRosterAttached) {
                        hasRosterAttached = coursesIntoContext(state, context, site);
                    } else {
                        coursesIntoContext(state, context, site);
                    }

                if (courseManagementIsImplemented()) {
                } else {
                    context.put("templateIndex", "37");
                }
            }
            context.put("hasRosterAttached", Boolean.valueOf(hasRosterAttached));

            if (StringUtils.trimToNull(siteInfo.term) == null) {
                if (site != null) {
                    // existing site
                    siteInfo.term = site.getProperties().getProperty(Site.PROP_SITE_TERM);
                } else {
                    // creating new site
                    AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
                    siteInfo.term = t != null ? t.getEid() : "";
                }
            }
            context.put("selectedTerm", siteInfo.term != null ? siteInfo.term : "");

        } else {
            context.put("isCourseSite", Boolean.FALSE);
            if (SiteTypeUtil.isProjectSite(siteType)) {
                context.put("isProjectSite", Boolean.TRUE);
            }

            if (StringUtils.trimToNull(siteInfo.iconUrl) != null) {
                context.put(FORM_ICON_URL, siteInfo.iconUrl);
            }
        }

        // about skin and icon selection
        skinIconSelection(context, state, SiteTypeUtil.isCourseSite(siteType), site, siteInfo);

        // those manual inputs
        context.put("form_requiredFields", sectionFieldProvider.getRequiredFields());
        context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));

        context.put("title", siteInfo.title);
        context.put(FORM_SITE_URL_BASE, getSiteBaseUrl());
        context.put(FORM_SITE_ALIAS, siteInfo.getFirstAlias());
        context.put("description", siteInfo.description);
        context.put("short_description", siteInfo.short_description);
        context.put("form_site_contact_name", siteInfo.site_contact_name);
        context.put("form_site_contact_email", siteInfo.site_contact_email);

        context.put("site_aliases", state.getAttribute(FORM_SITEINFO_ALIASES));
        context.put("site_url_base", state.getAttribute(FORM_SITEINFO_URL_BASE));
        context.put("site_aliases_editable", aliasesEditable(state, site == null ? null : site.getReference()));
        context.put("site_alias_assignable", aliasAssignmentForNewSitesEnabled(state));

        // available languages in sakai.properties
        List locales = getPrefLocales();
        context.put("locales", locales);

        // SAK-22384 mathjax support
        MathJaxEnabler.addMathJaxSettingsToSiteInfoContext(context, site, state);

        return (String) getContext(data).get("template") + TEMPLATE[13];
    case 14:
        /*
         * buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm
         * 
         */
        siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
        context.put("displaySiteAlias", Boolean.valueOf(displaySiteAlias()));
        siteProperties = site.getProperties();
        siteType = (String) state.getAttribute(STATE_SITE_TYPE);
        if (SiteTypeUtil.isCourseSite(siteType)) {
            context.put("isCourseSite", Boolean.TRUE);
            context.put("siteTerm", siteInfo.term);
        } else {
            context.put("isCourseSite", Boolean.FALSE);
        }
        // about skin and icon selection
        skinIconSelection(context, state, SiteTypeUtil.isCourseSite(siteType), site, siteInfo);

        context.put("oTitle", site.getTitle());
        context.put("title", siteInfo.title);

        // get updated language
        String new_locale_string = (String) state.getAttribute("locale_string");
        if (new_locale_string == "" || new_locale_string == null)
            context.put("new_locale", "");
        else {
            Locale new_locale = getLocaleFromString(new_locale_string);
            context.put("new_locale", new_locale);
        }

        // get site language saved
        ResourcePropertiesEdit props = site.getPropertiesEdit();
        String oLocale_string = props.getProperty(PROP_SITE_LANGUAGE);
        if (oLocale_string == "" || oLocale_string == null)
            context.put("oLocale", "");
        else {
            Locale oLocale = getLocaleFromString(oLocale_string);
            context.put("oLocale", oLocale);
        }

        context.put("description", siteInfo.description);
        context.put("oDescription", site.getDescription());
        context.put("short_description", siteInfo.short_description);
        context.put("oShort_description", site.getShortDescription());
        context.put("skin", siteInfo.iconUrl);
        context.put("oSkin", site.getIconUrl());
        context.put("skins", state.getAttribute(STATE_ICONS));
        context.put("oIcon", site.getIconUrl());
        context.put("icon", siteInfo.iconUrl);
        context.put("include", siteInfo.include);
        context.put("oInclude", Boolean.valueOf(site.isPubView()));
        context.put("name", siteInfo.site_contact_name);
        context.put("oName", siteProperties.getProperty(Site.PROP_SITE_CONTACT_NAME));
        context.put("email", siteInfo.site_contact_email);
        context.put("oEmail", siteProperties.getProperty(Site.PROP_SITE_CONTACT_EMAIL));
        context.put("siteUrls", getSiteUrlsForAliasIds(siteInfo.siteRefAliases));
        context.put("oSiteUrls", getSiteUrlsForSite(site));

        // SAK-22384 mathjax support
        MathJaxEnabler.addMathJaxSettingsToSiteInfoContext(context, site, state);

        return (String) getContext(data).get("template") + TEMPLATE[14];
    case 15:
        /*
         * buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm
         * 
         */
        context.put("title", site.getTitle());

        site_type = (String) state.getAttribute(STATE_SITE_TYPE);
        boolean myworkspace_site = false;
        if (SiteService.isUserSite(site.getId())) {
            if (SiteService.getSiteUserId(site.getId()).equals(SessionManager.getCurrentSessionUserId())) {
                myworkspace_site = true;
                site_type = "myworkspace";
            }
        }

        String overridePageOrderSiteTypes = site.getProperties()
                .getProperty(SiteConstants.SITE_PROPERTY_OVERRIDE_HIDE_PAGEORDER_SITE_TYPES);
        // put tool selection into context
        toolSelectionIntoContext(context, state, site_type, site.getId(), overridePageOrderSiteTypes);
        MathJaxEnabler.addMathJaxSettingsToEditToolsConfirmationContext(context, site, state,
                STATE_TOOL_REGISTRATION_TITLE_LIST); // SAK-22384            

        return (String) getContext(data).get("template") + TEMPLATE[15];
    case 18:
        /*
         * buildContextForTemplate chef_siteInfo-editAccess.vm
         * 
         */
        List publicChangeableSiteTypes = (List) state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);

        context.put("authAllowed", ServerConfigurationService.getBoolean("sitemanage.grant.auth", false));
        context.put("anonAllowed", ServerConfigurationService.getBoolean("sitemanage.grant.anon", false));

        if (site != null) {
            // editing existing site
            context.put("site", site);
            siteType = state.getAttribute(STATE_SITE_TYPE) != null
                    ? (String) state.getAttribute(STATE_SITE_TYPE)
                    : null;

            if (siteType != null && publicChangeableSiteTypes.contains(siteType)) {
                context.put("publicChangeable", Boolean.TRUE);
            } else {
                context.put("publicChangeable", Boolean.FALSE);
            }
            context.put("published", state.getAttribute(STATE_SITE_ACCESS_PUBLISH));
            context.put("include", state.getAttribute(STATE_SITE_ACCESS_INCLUDE));

            context.put("shoppingPeriodInstructorEditable", ServerConfigurationService
                    .getBoolean("delegatedaccess.shopping.instructorEditable", false));
            context.put("viewDelegatedAccessUsers", ServerConfigurationService
                    .getBoolean("delegatedaccess.siteaccess.instructorViewable", false));

            // bjones86 - SAK-24423 - add joinable site settings to context
            JoinableSiteSettings.addJoinableSiteSettingsToEditAccessContextWhenSiteIsNotNull(context, state,
                    site, !unJoinableSiteTypes.contains(siteType));

            if (siteType != null && !unJoinableSiteTypes.contains(siteType)) {
                // site can be set as joinable
                context.put("disableJoinable", Boolean.FALSE);
                if (state.getAttribute(STATE_JOINABLE) == null) {
                    state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site.isJoinable()));
                }

                if (state.getAttribute(STATE_JOINABLE) != null) {
                    context.put("joinable", state.getAttribute(STATE_JOINABLE));
                }
                if (state.getAttribute(STATE_JOINERROLE) != null) {
                    context.put("joinerRole", state.getAttribute(STATE_JOINERROLE));
                }
            } else {
                // site cannot be set as joinable
                context.put("disableJoinable", Boolean.TRUE);
            }

            Map<String, AdditionalRole> access = getAdditionalAccess(site);

            addAccess(context, access);

            // bjones86 - SAK-23257
            context.put("roles", getJoinerRoles(site.getReference(), state, site.getType()));
        } else {
            // In the site creation process...
            siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);

            if (siteInfo.site_type != null && publicChangeableSiteTypes.contains(siteInfo.site_type)) {
                context.put("publicChangeable", Boolean.TRUE);
            } else {
                context.put("publicChangeable", Boolean.FALSE);
            }
            context.put("include", Boolean.valueOf(siteInfo.getInclude()));
            context.put("published", Boolean.valueOf(siteInfo.getPublished()));

            if (siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type)) {
                // site can be set as joinable
                context.put("disableJoinable", Boolean.FALSE);
                context.put("joinable", Boolean.valueOf(siteInfo.joinable));
                context.put("joinerRole", siteInfo.joinerRole);
            } else {
                // site cannot be set as joinable
                context.put("disableJoinable", Boolean.TRUE);
            }

            // bjones86 - SAK-24423 - add joinable site settings to context
            JoinableSiteSettings.addJoinableSiteSettingsToEditAccessContextWhenSiteIsNull(context, siteInfo,
                    true);

            // the template site, if using one
            Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE);

            // use the type's template, if defined
            String realmTemplate = "!site.template";
            // if create based on template, use the roles from the template
            if (templateSite != null) {
                realmTemplate = SiteService.siteReference(templateSite.getId());
            } else if (siteInfo.site_type != null) {
                realmTemplate = realmTemplate + "." + siteInfo.site_type;
            }
            try {
                AuthzGroup r = authzGroupService.getAuthzGroup(realmTemplate);

                // bjones86 - SAK-23257
                context.put("roles", getJoinerRoles(r.getId(), state, null));
            } catch (GroupNotDefinedException e) {
                try {
                    AuthzGroup rr = authzGroupService.getAuthzGroup("!site.template");

                    // bjones86 - SAK-23257
                    context.put("roles", getJoinerRoles(rr.getId(), state, null));
                } catch (GroupNotDefinedException ee) {
                }
            }

            Map<String, AdditionalRole> additionalRoles = loadAdditionalRoles();
            for (AdditionalRole role : additionalRoles.values()) {
                if (siteInfo.additionalRoles.contains(role.getId())) {
                    role.granted = true;
                }
            }
            addAccess(context, additionalRoles);
            context.put("continue", "10");

            siteType = (String) state.getAttribute(STATE_SITE_TYPE);
            setTypeIntoContext(context, siteType);
        }
        return (String) getContext(data).get("template") + TEMPLATE[18];
    case 26:
        /*
         * buildContextForTemplate chef_site-modifyENW.vm
         * 
         */
        site_type = (String) state.getAttribute(STATE_SITE_TYPE);
        boolean existingSite = site != null ? true : false;
        if (existingSite) {
            // revising a existing site's tool
            context.put("existingSite", Boolean.TRUE);
            context.put("continue", "15");
        } else {
            // new site
            context.put("existingSite", Boolean.FALSE);
            context.put("continue", "18");
        }

        context.put(STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
        toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
        context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's

        // all info related to multiple tools
        multipleToolIntoContext(context, state);

        // put the lti tool selection into context
        if (state.getAttribute(STATE_LTITOOL_SELECTED_LIST) != null) {
            HashMap<String, Map<String, Object>> currentLtiTools = (HashMap<String, Map<String, Object>>) state
                    .getAttribute(STATE_LTITOOL_SELECTED_LIST);
            for (Map.Entry<String, Map<String, Object>> entry : currentLtiTools.entrySet()) {
                Map<String, Object> toolMap = entry.getValue();
                String toolId = entry.getKey();
                // get the proper html for tool input
                String ltiToolId = toolMap.get("id").toString();
                String[] contentToolModel = m_ltiService.getContentModel(Long.valueOf(ltiToolId));
                // attach the ltiToolId to each model attribute, so that we could have the tool configuration page for multiple tools
                for (int k = 0; k < contentToolModel.length; k++) {
                    contentToolModel[k] = ltiToolId + "_" + contentToolModel[k];
                }
                Map<String, Object> ltiTool = m_ltiService.getTool(Long.valueOf(ltiToolId));
                String formInput = m_ltiService.formInput(ltiTool, contentToolModel);
                toolMap.put("formInput", formInput);
                currentLtiTools.put(ltiToolId, toolMap);
            }
            context.put("ltiTools", currentLtiTools);
            context.put("ltiService", m_ltiService);
            context.put("oldLtiTools", state.getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST));
        }

        context.put("toolManager", ToolManager.getInstance());

        AcademicSession thisAcademicSession = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
        String emailId = null;

        boolean prePopulateEmail = ServerConfigurationService.getBoolean("wsetup.mailarchive.prepopulate.email",
                true);
        if (prePopulateEmail == true && state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) == null) {
            if (thisAcademicSession != null) {
                String siteTitle1 = siteInfo.title.replaceAll("[(].*[)]", "");
                siteTitle1 = siteTitle1.trim();
                siteTitle1 = siteTitle1.replaceAll(" ", "-");
                emailId = siteTitle1;
            } else {
                emailId = StringUtils.deleteWhitespace(siteInfo.title);
            }
        } else {
            emailId = (String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
        }

        if (emailId != null) {
            context.put("emailId", emailId);
        }

        context.put("serverName", ServerConfigurationService.getServerName());

        context.put("oldSelectedTools", state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));

        context.put("homeToolId", TOOL_ID_HOME);

        context.put("maxToolTitleLength", MAX_TOOL_TITLE_LENGTH);

        return (String) getContext(data).get("template") + TEMPLATE[26];
    case 27: {
        /*
         * buildContextForTemplate chef_site-importSites.vm
         * 
         * This is called before the list of tools to choose the content to import from (when merging) is presented.
         * This is also called in the new site workflow if re-using content from an existing site
         * 
         */
        existingSite = site != null ? true : false;
        site_type = (String) state.getAttribute(STATE_SITE_TYPE);

        // define the tools available for import. defaults to those tools in the 'destination' site
        List<String> importableToolsIdsInDestinationSite = (List) state
                .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
        if (existingSite) {
            // revising a existing site's tool
            context.put("continue", "12");
            context.put("step", "2");
            context.put("currentSite", site);

            // if the site exists, there may be other tools available for import
            importableToolsIdsInDestinationSite = getToolsAvailableForImport(state,
                    importableToolsIdsInDestinationSite);

        } else {
            // new site, go to edit access page
            if (fromENWModifyView(state)) {
                context.put("continue", "26");
            } else {
                context.put("continue", "18");
            }
        }

        // list of all tools that participate in the archive/merge process that are in the site selected to import from
        List<Site> importSites = new ArrayList<Site>(
                ((Hashtable) state.getAttribute(STATE_IMPORT_SITES)).keySet());
        List<String> allImportableToolIdsInOriginalSites = getToolsInSitesAvailableForImport(importSites);

        context.put("existingSite", Boolean.valueOf(existingSite));

        //sort the list of all tools by title and extract into a list of toolIds
        //we then use this as the basis for sorting the other toolId lists
        List<MyTool> allTools = (List<MyTool>) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);

        Collections.sort(allTools, new Comparator<MyTool>() {
            public int compare(MyTool t1, MyTool t2) {
                return t1.getTitle().compareTo(t2.getTitle());
            }
        });

        final List<String> sortedToolIds = new ArrayList<String>();
        for (MyTool m : allTools) {
            sortedToolIds.add(m.getId());
        }

        //use the above sorted list as the basis to sort the following two toolId lists
        Collections.sort(allImportableToolIdsInOriginalSites, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return Integer.compare(sortedToolIds.indexOf(s1), sortedToolIds.indexOf(s2));
            }
        });

        Collections.sort(importableToolsIdsInDestinationSite, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return Integer.compare(sortedToolIds.indexOf(s1), sortedToolIds.indexOf(s2));
            }
        });

        context.put(STATE_TOOL_REGISTRATION_LIST, allTools);

        //if option is enabled, show the import for all tools in the original site, not just the ones in this site
        //otherwise, only import content for the tools that already exist in the 'destination' site
        boolean addMissingTools = isAddMissingToolsOnImportEnabled();

        //helper var to hold the list we use for the selectedTools context variable, as we use it for the alternate toolnames too
        List<String> selectedTools = new ArrayList<>();

        if (addMissingTools) {
            selectedTools = allImportableToolIdsInOriginalSites;
            context.put("selectedTools", selectedTools);
            //set tools in destination site into context so we can markup the lists and show which ones are new
            context.put("toolsInDestinationSite", importableToolsIdsInDestinationSite);
        } else {
            //just just the ones in the destination site
            selectedTools = importableToolsIdsInDestinationSite;
            context.put("selectedTools", selectedTools);
        }

        //get all known tool names from the sites selected to import from (importSites) and the selectedTools list
        Map<String, Set<String>> toolNames = this.getToolNames(selectedTools, importSites);

        //filter this list so its just the alternate ones and turn it into a string for the UI
        Map<String, String> alternateToolTitles = new HashMap<>();
        for (MyTool myTool : allTools) {
            String toolId = myTool.getId();
            String toolTitle = myTool.getTitle();
            Set<String> allToolNames = toolNames.get(toolId);
            if (allToolNames != null) {
                allToolNames.remove(toolTitle);

                //if we have something left then we have alternates, so process them
                if (!allToolNames.isEmpty()) {
                    alternateToolTitles.put(toolId, StringUtils.join(allToolNames, ", "));
                }
            }
        }
        context.put("alternateToolTitlesMap", alternateToolTitles);

        //build a map of sites and tools in those sites that have content
        Map<String, Set<String>> siteToolsWithContent = this.getSiteImportToolsWithContent(importSites,
                selectedTools);
        context.put("siteToolsWithContent", siteToolsWithContent);

        // set the flag for the UI
        context.put("addMissingTools", addMissingTools);

        context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
        context.put("importSitesTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
        context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
        context.put("importSupportedTools", allImportableToolIdsInOriginalSites);
        context.put("hideImportedContent",
                ServerConfigurationService.getBoolean("content.import.hidden", false));

        if (ServerConfigurationService.getBoolean("site-manage.importoption.siteinfo", false)) {
            try {
                String siteInfoToolTitle = ToolManager.getTool(SITE_INFO_TOOL_ID).getTitle();
                context.put("siteInfoToolTitle", siteInfoToolTitle);
            } catch (Exception e) {

            }
        }

        return (String) getContext(data).get("template") + TEMPLATE[27];
    }
    case 60: {
        /*
         * buildContextForTemplate chef_site-importSitesMigrate.vm
         * 
         * This is called before the list of tools to choose the content to import from (when replacing) is presented.
         * 
         */
        existingSite = site != null ? true : false;
        site_type = (String) state.getAttribute(STATE_SITE_TYPE);

        // define the tools available for import. defaults to those tools in the 'destination' site
        List<String> importableToolsIdsInDestinationSite = (List) state
                .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);

        if (existingSite) {
            // revising a existing site's tool
            context.put("continue", "12");
            context.put("back", "28");
            context.put("step", "2");
            context.put("currentSite", site);

            // if the site exists, there may be other tools available for import
            importableToolsIdsInDestinationSite = getToolsAvailableForImport(state,
                    importableToolsIdsInDestinationSite);

        } else {
            // new site, go to edit access page
            context.put("back", "4");
            if (fromENWModifyView(state)) {
                context.put("continue", "26");
            } else {
                context.put("continue", "18");
            }

            //use the toolId list for the new site we are creating
            importableToolsIdsInDestinationSite = (List<String>) state
                    .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
        }

        // list of all tools that participate in the archive/merge process that are in the site selected to import from
        List<Site> importSites = new ArrayList<Site>(
                ((Hashtable) state.getAttribute(STATE_IMPORT_SITES)).keySet());
        List<String> allImportableToolIdsInOriginalSites = getToolsInSitesAvailableForImport(importSites);

        //sort the list of all tools by title and extract into a list of toolIds
        //we then use this as the basis for sorting the other toolId lists
        List<MyTool> allTools = (List<MyTool>) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);

        Collections.sort(allTools, new Comparator<MyTool>() {
            public int compare(MyTool t1, MyTool t2) {
                return t1.getTitle().compareTo(t2.getTitle());
            }
        });

        final List<String> sortedToolIds = new ArrayList<String>();
        for (MyTool m : allTools) {
            sortedToolIds.add(m.getId());
        }

        //use the above sorted list as the basis to sort the following two toolId lists
        Collections.sort(allImportableToolIdsInOriginalSites, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return Integer.compare(sortedToolIds.indexOf(s1), sortedToolIds.indexOf(s2));
            }
        });

        Collections.sort(importableToolsIdsInDestinationSite, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return Integer.compare(sortedToolIds.indexOf(s1), sortedToolIds.indexOf(s2));
            }
        });

        //ensure this is the original tool list and set the sorted list back into context.
        context.put(STATE_TOOL_REGISTRATION_LIST, allTools);
        state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST,
                state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST));

        //if option is enabled, import into ALL tools, not just the ones in this site
        //otherwise, only import content for the tools that already exist in the 'destination' site
        boolean addMissingTools = isAddMissingToolsOnImportEnabled();

        //helper var to hold the list we use for the selectedTools context variable, as we use it for the alternate toolnames too
        List<String> selectedTools = new ArrayList<>();

        if (addMissingTools) {

            selectedTools = allImportableToolIdsInOriginalSites;

            context.put("selectedTools", selectedTools);
            //set tools in destination site into context so we can markup the lists and show which ones are new
            context.put("toolsInDestinationSite", importableToolsIdsInDestinationSite);

        } else {

            selectedTools = importableToolsIdsInDestinationSite;

            //just just the ones in the destination site
            context.put("selectedTools", selectedTools);
        }

        //get all known tool names from the sites selected to import from (importSites) and the selectedTools list
        Map<String, Set<String>> toolNames = this.getToolNames(selectedTools, importSites);

        //filter this list so its just the alternate ones and turn it into a string for the UI
        Map<String, String> alternateToolTitles = new HashMap<>();
        for (MyTool myTool : allTools) {
            String toolId = myTool.getId();
            String toolTitle = myTool.getTitle();
            Set<String> allToolNames = toolNames.get(toolId);
            if (allToolNames != null) {
                allToolNames.remove(toolTitle);

                //if we have something left then we have alternates, so process them
                if (!allToolNames.isEmpty()) {
                    alternateToolTitles.put(toolId, StringUtils.join(allToolNames, ", "));
                }
            }
        }
        context.put("alternateToolTitlesMap", alternateToolTitles);

        //build a map of sites and tools in those sites that have content
        Map<String, Set<String>> siteToolsWithContent = this.getSiteImportToolsWithContent(importSites,
                selectedTools);
        context.put("siteToolsWithContent", siteToolsWithContent);

        // set the flag for the UI
        context.put("addMissingTools", addMissingTools);

        context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
        context.put("importSitesTools", state.getAttribute(STATE_IMPORT_SITE_TOOL));
        context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
        context.put("importSupportedTools", allImportableToolIdsInOriginalSites);

        return (String) getContext(data).get("template") + TEMPLATE[60];
    }
    case 28:
        /*
         * buildContextForTemplate chef_siteinfo-import.vm
         * 
         * This is called before the list of sites to import from is presented
         * 
         */
        putImportSitesInfoIntoContext(context, site, state, false);
        return (String) getContext(data).get("template") + TEMPLATE[28];
    case 58:
        /*
         * buildContextForTemplate chef_siteinfo-importSelection.vm
         * 
         */
        putImportSitesInfoIntoContext(context, site, state, false);
        return (String) getContext(data).get("template") + TEMPLATE[58];
    case 59:
        /*
         * buildContextForTemplate chef_siteinfo-importMigrate.vm
         * 
         */
        putImportSitesInfoIntoContext(context, site, state, false);
        return (String) getContext(data).get("template") + TEMPLATE[59];

    case 29:
        /*
         * buildContextForTemplate chef_siteinfo-duplicate.vm
         * 
         */
        context.put("siteTitle", site.getTitle());
        String sType = site.getType();
        if (sType != null && SiteTypeUtil.isCourseSite(sType)) {
            context.put("isCourseSite", Boolean.TRUE);
            context.put("currentTermId", site.getProperties().getProperty(Site.PROP_SITE_TERM));

            // bjones86 - SAK-23256
            setTermListForContext(context, state, true, false); // true upcoming only
        } else {
            context.put("isCourseSite", Boolean.FALSE);
        }
        if (state.getAttribute(SITE_DUPLICATED) == null) {
            context.put("siteDuplicated", Boolean.FALSE);
        } else {
            context.put("siteDuplicated", Boolean.TRUE);
            context.put("duplicatedName", state.getAttribute(SITE_DUPLICATED_NAME));
        }

        // SAK-20797 - display checkboxes only if sitespecific value exists
        long quota = getSiteSpecificQuota(site);
        if (quota > 0) {
            context.put("hasSiteSpecificQuota", true);
            context.put("quotaSize", formatSize(quota * 1024));
        } else {
            context.put("hasSiteSpecificQuota", false);
        }

        context.put("titleMaxLength", state.getAttribute(STATE_SITE_TITLE_MAX));
        return (String) getContext(data).get("template") + TEMPLATE[29];
    case 36:
        /*
         * buildContextForTemplate chef_site-newSiteCourse.vm
         */
        // SAK-9824
        Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser",
                Boolean.FALSE);
        context.put("enableCourseCreationForUser", enableCourseCreationForUser);

        if (site != null) {
            context.put("site", site);
            context.put("siteTitle", site.getTitle());

            List providerCourseList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
            coursesIntoContext(state, context, site);

            // bjones86 - SAK-23256
            List<AcademicSession> terms = setTermListForContext(context, state, true, true); // true -> upcoming only

            AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);

            if (terms != null && terms.size() > 0) {
                boolean foundTerm = false;
                for (AcademicSession testTerm : terms) {
                    if (t != null && testTerm.getEid().equals(t.getEid())) {
                        foundTerm = true;
                        break;
                    }
                }
                if (!foundTerm) {
                    // if the term is no longer listed in the term list, choose the first term in the list instead
                    t = terms.get(0);
                }
            }
            context.put("term", t);
            if (t != null) {
                String userId = UserDirectoryService.getCurrentUser().getEid();
                List courses = prepareCourseAndSectionListing(userId, t.getEid(), state);
                if (courses != null && courses.size() > 0) {
                    Vector notIncludedCourse = new Vector();

                    // remove included sites
                    for (Iterator i = courses.iterator(); i.hasNext();) {
                        CourseObject c = (CourseObject) i.next();
                        if (providerCourseList == null || !providerCourseList.contains(c.getEid())) {
                            notIncludedCourse.add(c);
                        }
                    }
                    state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse);
                } else {
                    state.removeAttribute(STATE_TERM_COURSE_LIST);
                }
            }
        } else {
            // need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS
            // contains sections that doens't belongs to current user and
            // STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does -
            // v2.4 daisyf
            if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null
                    || state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {

                putSelectedProviderCourseIntoContext(context, state);

                List<SectionObject> authorizerSectionList = (List<SectionObject>) state
                        .getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
                if (authorizerSectionList != null) {
                    List authorizerList = (List) state.getAttribute(STATE_CM_AUTHORIZER_LIST);
                    //authorizerList is a list of SectionObject
                    /*
                    String userId = null;
                    if (authorizerList != null) {
                       userId = (String) authorizerList.get(0);
                    }
                    List list2 = prepareSectionObject(
                          authorizerSectionList, userId);
                          */
                    ArrayList list2 = new ArrayList();
                    for (int i = 0; i < authorizerSectionList.size(); i++) {
                        SectionObject so = (SectionObject) authorizerSectionList.get(i);
                        list2.add(so.getEid());
                    }
                    context.put("selectedAuthorizerCourse", list2);
                }
            }

            if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
                context.put("selectedManualCourse", Boolean.TRUE);
            }
            context.put("term", (AcademicSession) state.getAttribute(STATE_TERM_SELECTED));
            context.put("currentUserId", (String) state.getAttribute(STATE_CM_CURRENT_USERID));
            context.put("form_additional", (String) state.getAttribute(FORM_ADDITIONAL));
            context.put("authorizers", getAuthorizers(state, STATE_CM_AUTHORIZER_LIST));
        }
        if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP)) {
            context.put("backIndex", "1");
        } else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) {
            context.put("backIndex", "");
        }
        List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST);
        context.put("termCourseList", state.getAttribute(STATE_TERM_COURSE_LIST));

        // SAK-29000
        Boolean isAuthorizationRequired = ServerConfigurationService.getBoolean(SAK_PROP_REQUIRE_AUTHORIZER,
                Boolean.TRUE);
        context.put(VM_ADD_ROSTER_AUTH_REQUIRED, isAuthorizationRequired);

        // added for 2.4 -daisyf
        context.put("campusDirectory", getCampusDirectory());
        context.put("userId",
                state.getAttribute(STATE_INSTRUCTOR_SELECTED) != null
                        ? (String) state.getAttribute(STATE_INSTRUCTOR_SELECTED)
                        : UserDirectoryService.getCurrentUser().getId());
        /*
         * for measuring how long it takes to load sections java.util.Date
         * date = new java.util.Date(); M_log.debug("***2. finish at:
         * "+date); M_log.debug("***3. userId:"+(String) state
         * .getAttribute(STATE_INSTRUCTOR_SELECTED));
         */

        context.put("basedOnTemplate",
                state.getAttribute(STATE_TEMPLATE_SITE) != null ? Boolean.TRUE : Boolean.FALSE);
        context.put("publishTemplate", (Boolean) state.getAttribute(STATE_TEMPLATE_PUBLISH));

        // bjones86 - SAK-21706
        context.put(CONTEXT_SKIP_COURSE_SECTION_SELECTION,
                ServerConfigurationService.getBoolean(SAK_PROP_SKIP_COURSE_SECTION_SELECTION, Boolean.FALSE));
        context.put(CONTEXT_SKIP_MANUAL_COURSE_CREATION,
                ServerConfigurationService.getBoolean(SAK_PROP_SKIP_MANUAL_COURSE_CREATION, Boolean.FALSE));

        context.put("siteType", state.getAttribute(STATE_TYPE_SELECTED));

        // SAK-28990 remove continue with no roster
        if ("true".equalsIgnoreCase(
                ServerConfigurationService.getString(SAK_PROP_CONT_NO_ROSTER_ENABLED, "true"))) {
            context.put(VM_CONT_NO_ROSTER_ENABLED, Boolean.TRUE);
        } else {
            context.put(VM_CONT_NO_ROSTER_ENABLED, Boolean.FALSE);
        }

        return (String) getContext(data).get("template") + TEMPLATE[36];
    case 37:
        /*
         * buildContextForTemplate chef_site-newSiteCourseManual.vm
         */
        if (site != null) {
            context.put("site", site);
            context.put("siteTitle", site.getTitle());
            coursesIntoContext(state, context, site);
        }
        buildInstructorSectionsList(state, params, context);
        context.put("form_requiredFields", sectionFieldProvider.getRequiredFields());
        context.put("form_additional", siteInfo.additional);
        context.put("form_title", siteInfo.title);
        context.put("form_description", siteInfo.description);
        context.put("officialAccountName", ServerConfigurationService.getString("officialAccountName", ""));
        if (state.getAttribute(STATE_SITE_QUEST_UNIQNAME) == null) {
            context.put("value_uniqname", getAuthorizers(state, STATE_SITE_QUEST_UNIQNAME));
        }
        int number = 1;
        if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
            number = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
            context.put("currentNumber", Integer.valueOf(number));
        }
        context.put("currentNumber", Integer.valueOf(number));
        context.put("listSize", number > 0 ? Integer.valueOf(number - 1) : 0);
        if (state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null
                && ((List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)).size() > 0) {
            context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
        }

        putSelectedProviderCourseIntoContext(context, state);

        if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
            List l = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS);
            context.put("cmRequestedSections", l);
        }

        if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) {
            context.put("editSite", Boolean.TRUE);
            context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
        }

        if (site == null) {
            if (state.getAttribute(STATE_AUTO_ADD) != null) {
                context.put("autoAdd", Boolean.TRUE);
            }
        }

        isFutureTermSelected(state);
        context.put("isFutureTerm", state.getAttribute(STATE_FUTURE_TERM_SELECTED));
        context.put("weeksAhead",
                ServerConfigurationService.getString("roster.available.weeks.before.term.start", "0"));

        context.put("basedOnTemplate",
                state.getAttribute(STATE_TEMPLATE_SITE) != null ? Boolean.TRUE : Boolean.FALSE);
        context.put("publishTemplate", (Boolean) state.getAttribute(STATE_TEMPLATE_PUBLISH));

        context.put("requireAuthorizer",
                ServerConfigurationService.getString(SAK_PROP_REQUIRE_AUTHORIZER, "true").equals("true")
                        ? Boolean.TRUE
                        : Boolean.FALSE);

        // bjones86 - SAK-21706/SAK-23255
        context.put(CONTEXT_IS_ADMIN, SecurityService.isSuperUser());
        context.put(CONTEXT_SKIP_COURSE_SECTION_SELECTION,
                ServerConfigurationService.getBoolean(SAK_PROP_SKIP_COURSE_SECTION_SELECTION, Boolean.FALSE));
        context.put(CONTEXT_FILTER_TERMS,
                ServerConfigurationService.getBoolean(SAK_PROP_FILTER_TERMS, Boolean.FALSE));

        return (String) getContext(data).get("template") + TEMPLATE[37];
    case 42:
        /*
         * buildContextForTemplate chef_site-type-confirm.vm
         * 
         */
        siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
        context.put("title", siteInfo.title);
        context.put("description", siteInfo.description);
        context.put("short_description", siteInfo.short_description);
        toolRegistrationList = (Vector) state.getAttribute(STATE_PROJECT_TOOL_LIST);
        toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
        context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's
        context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%%
        // use
        // Tool
        context.put("check_home", state.getAttribute(STATE_TOOL_HOME_SELECTED));
        context.put("emailId", state.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
        context.put("serverName", ServerConfigurationService.getServerName());
        context.put("include", Boolean.valueOf(siteInfo.include));
        return (String) getContext(data).get("template") + TEMPLATE[42];
    case 43:
        /*
         * buildContextForTemplate chef_siteInfo-editClass.vm
         * 
         */
        bar = new MenuImpl(portlet, data, (String) state.getAttribute(STATE_ACTION));
        if (SiteService.allowAddSite(null)) {
            bar.add(new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass"));
        }
        context.put("menu", bar);

        context.put("siteTitle", site.getTitle());
        coursesIntoContext(state, context, site);

        return (String) getContext(data).get("template") + TEMPLATE[43];
    case 44:
        /*
         * buildContextForTemplate chef_siteInfo-addCourseConfirm.vm
         * 
         */

        context.put("siteTitle", site.getTitle());

        coursesIntoContext(state, context, site);

        putSelectedProviderCourseIntoContext(context, state);

        if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) {
            context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
        }
        if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
            context.put("cmRequestedSections", state.getAttribute(STATE_CM_REQUESTED_SECTIONS));
        }
        if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
            int addNumber = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue() - 1;
            context.put("manualAddNumber", Integer.valueOf(addNumber));
            context.put("requestFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
            context.put("backIndex", "37");
        } else {
            context.put("backIndex", "36");
        }
        // those manual inputs
        context.put("form_requiredFields", sectionFieldProvider.getRequiredFields());
        context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));

        return (String) getContext(data).get("template") + TEMPLATE[44];

    // htripath - import materials from classic
    case 45:
        /*
         * buildContextForTemplate chef_siteInfo-importMtrlMaster.vm
         * 
         */
        return (String) getContext(data).get("template") + TEMPLATE[45];

    case 46:
        /*
         * buildContextForTemplate chef_siteInfo-importMtrlCopy.vm
         * 
         */
        // this is for list display in listbox
        context.put("allZipSites", state.getAttribute(ALL_ZIP_IMPORT_SITES));

        context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
        // zip file
        // context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME));

        return (String) getContext(data).get("template") + TEMPLATE[46];

    case 47:
        /*
         * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
         * 
         */
        context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));

        return (String) getContext(data).get("template") + TEMPLATE[47];

    case 48:
        /*
         * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
         * 
         */
        context.put("finalZipSites", state.getAttribute(FINAL_ZIP_IMPORT_SITES));
        return (String) getContext(data).get("template") + TEMPLATE[48];
    // case 49, 50, 51 have been implemented in helper mode
    case 53: {
        /*
         * build context for chef_site-findCourse.vm
         */

        AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);

        List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS),
                selections = (List) state.getAttribute(STATE_CM_LEVEL_SELECTIONS);

        if (cmLevels == null) {
            cmLevels = getCMLevelLabels(state);
        }

        List<SectionObject> selectedSect = (List<SectionObject>) state.getAttribute(STATE_CM_SELECTED_SECTION);
        List<SectionObject> requestedSections = (List<SectionObject>) state
                .getAttribute(STATE_CM_REQUESTED_SECTIONS);

        if (courseManagementIsImplemented() && cms != null) {
            context.put("cmsAvailable", Boolean.valueOf(true));
        }

        int cmLevelSize = 0;

        if (cms == null || !courseManagementIsImplemented() || cmLevels == null || cmLevels.size() < 1) {
            // TODO: redirect to manual entry: case #37
        } else {
            cmLevelSize = cmLevels.size();
            Object levelOpts[] = state.getAttribute(STATE_CM_LEVEL_OPTS) == null ? new Object[cmLevelSize]
                    : (Object[]) state.getAttribute(STATE_CM_LEVEL_OPTS);
            int numSelections = 0;

            if (selections != null) {
                numSelections = selections.size();
            }

            if (numSelections != 0) {
                // execution will fall through these statements based on number of selections already made
                if (numSelections == cmLevelSize - 1) {
                    levelOpts[numSelections] = getCMSections((String) selections.get(numSelections - 1));
                } else if (numSelections == cmLevelSize - 2) {
                    levelOpts[numSelections] = getCMCourseOfferings(
                            getSelectionString(selections, numSelections), t.getEid());
                } else if (numSelections < cmLevelSize) {
                    levelOpts[numSelections] = sortCourseSets(
                            cms.findCourseSets(getSelectionString(selections, numSelections)));
                }
            }
            // always set the top level
            Set<CourseSet> courseSets = filterCourseSetList(getCourseSet(state));
            levelOpts[0] = sortCourseSets(courseSets);

            // clean further element inside the array
            for (int i = numSelections + 1; i < cmLevelSize; i++) {
                levelOpts[i] = null;
            }

            context.put("cmLevelOptions", Arrays.asList(levelOpts));
            context.put("cmBaseCourseSetLevel",
                    Integer.valueOf((levelOpts.length - 3) >= 0 ? (levelOpts.length - 3) : 0)); // staring from that selection level, the lookup will be for CourseSet, CourseOffering, and Section
            context.put("maxSelectionDepth", Integer.valueOf(levelOpts.length - 1));
            state.setAttribute(STATE_CM_LEVEL_OPTS, levelOpts);
        }

        putSelectedProviderCourseIntoContext(context, state);

        if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
            int courseInd = ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
            context.put("manualAddNumber", Integer.valueOf(courseInd - 1));
            context.put("manualAddFields", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
        }

        context.put("term", (AcademicSession) state.getAttribute(STATE_TERM_SELECTED));

        context.put("cmLevels", cmLevels);
        context.put("cmLevelSelections", selections);
        context.put("selectedCourse", selectedSect);
        context.put("cmRequestedSections", requestedSections);
        if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) {
            context.put("editSite", Boolean.TRUE);
            context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
        }
        if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP)) {
            if (state.getAttribute(STATE_TERM_COURSE_LIST) != null) {
                context.put("backIndex", "36");
            } else {
                context.put("backIndex", "1");
            }
        } else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) {
            context.put("backIndex", "36");
        }

        context.put("authzGroupService", authzGroupService);

        if (selectedSect != null && !selectedSect.isEmpty()
                && state.getAttribute(STATE_SITE_QUEST_UNIQNAME) == null) {
            context.put("value_uniqname", selectedSect.get(0).getAuthorizerString());
        }
        context.put("value_uniqname", state.getAttribute(STATE_SITE_QUEST_UNIQNAME));
        context.put("basedOnTemplate",
                state.getAttribute(STATE_TEMPLATE_SITE) != null ? Boolean.TRUE : Boolean.FALSE);
        context.put("requireAuthorizer",
                ServerConfigurationService.getString(SAK_PROP_REQUIRE_AUTHORIZER, "true").equals("true")
                        ? Boolean.TRUE
                        : Boolean.FALSE);

        // bjones86 - SAK-21706/SAK-23255
        context.put(CONTEXT_IS_ADMIN, SecurityService.isSuperUser());
        context.put(CONTEXT_SKIP_MANUAL_COURSE_CREATION,
                ServerConfigurationService.getBoolean(SAK_PROP_SKIP_MANUAL_COURSE_CREATION, Boolean.FALSE));
        context.put(CONTEXT_FILTER_TERMS,
                ServerConfigurationService.getBoolean(SAK_PROP_FILTER_TERMS, Boolean.FALSE));

        return (String) getContext(data).get("template") + TEMPLATE[53];
    }
    case 54:
        /*
         * build context for chef_site-questions.vm
         */
        SiteTypeQuestions siteTypeQuestions = questionService
                .getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE));
        if (siteTypeQuestions != null) {
            context.put("questionSet", siteTypeQuestions);
            context.put("userAnswers", state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER));
        }
        context.put("continueIndex", state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE));
        return (String) getContext(data).get("template") + TEMPLATE[54];

    case 61:
        /*
         * build context for chef_site-importUser.vm
         */
        context.put("toIndex", "12");
        // only show those sites with same site type
        putImportSitesInfoIntoContext(context, site, state, true);
        return (String) getContext(data).get("template") + TEMPLATE[61];

    case 62:
        /*
         * build context for chef_site-uploadArchive.vm
         */

        //back to access, continue to confirm
        context.put("back", "18");

        //now go to uploadArchive template
        return (String) getContext(data).get("template") + TEMPLATE[62];
    }

    // should never be reached
    return (String) getContext(data).get("template") + TEMPLATE[0];
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static void handleUploadPart(HttpServletRequest request, HttpServletResponse response, InputStream is,
        BlobStore blobStore, String containerName, String blobName, String uploadId)
        throws IOException, S3Exception {
    // TODO: duplicated from handlePutBlob
    String contentLengthString = null;
    String decodedContentLengthString = null;
    String contentMD5String = null;
    for (String headerName : Collections.list(request.getHeaderNames())) {
        String headerValue = Strings.nullToEmpty(request.getHeader(headerName));
        if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) {
            contentLengthString = headerValue;
        } else if (headerName.equalsIgnoreCase("x-amz-decoded-content-length")) {
            decodedContentLengthString = headerValue;
        } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_MD5)) {
            contentMD5String = headerValue;
        }/*ww w .ja  va  2  s  . c om*/
    }
    if (decodedContentLengthString != null) {
        contentLengthString = decodedContentLengthString;
    }

    HashCode contentMD5 = null;
    if (contentMD5String != null) {
        try {
            contentMD5 = HashCode.fromBytes(BaseEncoding.base64().decode(contentMD5String));
        } catch (IllegalArgumentException iae) {
            throw new S3Exception(S3ErrorCode.INVALID_DIGEST, iae);
        }
        if (contentMD5.bits() != Hashing.md5().bits()) {
            throw new S3Exception(S3ErrorCode.INVALID_DIGEST);
        }
    }

    if (contentLengthString == null) {
        throw new S3Exception(S3ErrorCode.MISSING_CONTENT_LENGTH);
    }
    long contentLength;
    try {
        contentLength = Long.parseLong(contentLengthString);
    } catch (NumberFormatException nfe) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT, nfe);
    }
    if (contentLength < 0) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT);
    }

    String partNumberString = request.getParameter("partNumber");
    if (partNumberString == null) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT);
    }
    int partNumber;
    try {
        partNumber = Integer.parseInt(partNumberString);
    } catch (NumberFormatException nfe) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT,
                "Part number must be an integer between 1 and 10000" + ", inclusive", nfe,
                ImmutableMap.of("ArgumentName", "partNumber", "ArgumentValue", partNumberString));
    }
    if (partNumber < 1 || partNumber > 10_000) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT,
                "Part number must be an integer between 1 and 10000" + ", inclusive", (Throwable) null,
                ImmutableMap.of("ArgumentName", "partNumber", "ArgumentValue", partNumberString));
    }

    // TODO: how to reconstruct original mpu?
    MultipartUpload mpu = MultipartUpload.create(containerName, blobName, uploadId,
            createFakeBlobMetadata(blobStore), new PutOptions());

    if (getBlobStoreType(blobStore).equals("azureblob")) {
        // Azure has a maximum part size of 4 MB while S3 has a minimum
        // part size of 5 MB and a maximum of 5 GB.  Split a single S3
        // part multiple Azure parts.
        long azureMaximumMultipartPartSize = blobStore.getMaximumMultipartPartSize();
        HashingInputStream his = new HashingInputStream(Hashing.md5(), is);
        for (int offset = 0, subPartNumber = 0; offset < contentLength; offset += azureMaximumMultipartPartSize, ++subPartNumber) {
            Payload payload = Payloads
                    .newInputStreamPayload(ByteStreams.limit(his, azureMaximumMultipartPartSize));
            payload.getContentMetadata()
                    .setContentLength(Math.min(azureMaximumMultipartPartSize, contentLength - offset));
            blobStore.uploadMultipartPart(mpu, 10_000 * partNumber + subPartNumber, payload);
        }
        response.addHeader(HttpHeaders.ETAG,
                maybeQuoteETag(BaseEncoding.base16().lowerCase().encode(his.hash().asBytes())));
    } else {
        MultipartPart part;
        Payload payload = Payloads.newInputStreamPayload(is);
        payload.getContentMetadata().setContentLength(contentLength);
        if (contentMD5 != null) {
            payload.getContentMetadata().setContentMD5(contentMD5);
        }

        part = blobStore.uploadMultipartPart(mpu, partNumber, payload);

        if (part.partETag() != null) {
            response.addHeader(HttpHeaders.ETAG, maybeQuoteETag(part.partETag()));
        }
    }
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

/**
 * Create Amazon V2 signature.  Reference:
 * http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html
 *//*from  w  w  w .j  a v a 2 s .  co  m*/
private static String createAuthorizationSignature(HttpServletRequest request, String uri, String credential) {
    // sort Amazon headers
    SortedSetMultimap<String, String> canonicalizedHeaders = TreeMultimap.create();
    for (String headerName : Collections.list(request.getHeaderNames())) {
        Collection<String> headerValues = Collections.list(request.getHeaders(headerName));
        headerName = headerName.toLowerCase();
        if (!headerName.startsWith("x-amz-")) {
            continue;
        }
        if (headerValues.isEmpty()) {
            canonicalizedHeaders.put(headerName, "");
        }
        for (String headerValue : headerValues) {
            canonicalizedHeaders.put(headerName, Strings.nullToEmpty(headerValue));
        }
    }

    // build string to sign
    StringBuilder builder = new StringBuilder().append(request.getMethod()).append('\n')
            .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_MD5))).append('\n')
            .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_TYPE))).append('\n');
    String expires = request.getParameter("Expires");
    if (expires != null) {
        builder.append(expires);
    } else if (!canonicalizedHeaders.containsKey("x-amz-date")) {
        builder.append(request.getHeader(HttpHeaders.DATE));
    }
    builder.append('\n');
    for (Map.Entry<String, String> entry : canonicalizedHeaders.entries()) {
        builder.append(entry.getKey()).append(':').append(entry.getValue()).append('\n');
    }
    builder.append(uri);

    char separator = '?';
    List<String> subresources = Collections.list(request.getParameterNames());
    Collections.sort(subresources);
    for (String subresource : subresources) {
        if (SIGNED_SUBRESOURCES.contains(subresource)) {
            builder.append(separator).append(subresource);

            String value = request.getParameter(subresource);
            if (!"".equals(value)) {
                builder.append('=').append(value);
            }
            separator = '&';
        }
    }

    String stringToSign = builder.toString();
    logger.trace("stringToSign: {}", stringToSign);

    // sign string
    Mac mac;
    try {
        mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(credential.getBytes(StandardCharsets.UTF_8), "HmacSHA1"));
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    return BaseEncoding.base64().encode(mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)));
}