Example usage for java.util Hashtable size

List of usage examples for java.util Hashtable size

Introduction

In this page you can find the example usage for java.util Hashtable size.

Prototype

public synchronized int size() 

Source Link

Document

Returns the number of keys in this hashtable.

Usage

From source file:edu.ku.brc.specify.web.SpecifyExplorer.java

/**
 * @param clazz//w  w w .  j  ava2s . c  o  m
 * @param fieldName
 */
public void doAlphaIndexPageSQL(final PrintWriter out, final String className, final String letter,
        final int numLetters, final UIFieldFormatterIFace fmt, final String sql) {
    boolean isNumeric = fmt != null && fmt.isNumeric();
    int inx = template.indexOf(contentTag);
    String subContent = template.substring(0, inx);

    out.println(StringUtils.replace(subContent, "<!-- Title -->", className));

    ClassDisplayInfo cdi = classHash.get(className);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
    boolean useLetter = true;

    Connection connection = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        connection = DBConnection.getInstance().createConnection();
        stmt = connection.createStatement();
        rs = stmt.executeQuery(sql);

        Vector<NameId> alphaList = new Vector<NameId>();
        Hashtable<String, NameId> alphaHash = new Hashtable<String, NameId>();

        boolean doingIndex = StringUtils.isEmpty(letter);
        System.out.println("\n\ndoingIndex " + doingIndex + " letter[" + letter + "]");

        int numMin = Integer.MAX_VALUE;
        int numMax = Integer.MIN_VALUE;
        int cnt = 0;

        while (rs.next()) {
            String name;
            int id = rs.getInt(1);

            if (isNumeric) {

                name = rs.getString(2);
                name = (String) fmt.formatToUI(name);
                Integer numAsInt = null;
                Integer floor = null;
                try {
                    numAsInt = Integer.parseInt(name);
                    floor = Integer.parseInt(letter);

                } catch (Exception ex) {
                }

                numMin = Math.min(numMin, numAsInt);
                numMax = Math.min(numMax, numAsInt);

                if (doingIndex) {
                    int numSegment = numAsInt / 1000;
                    String c = Integer.toString(numSegment);
                    NameId nis = alphaHash.get(c);
                    if (nis == null) {
                        nis = new NameId(c, 0, numSegment);
                        alphaHash.put(c, nis);
                    }
                    nis.add();

                } else {
                    if (numAsInt >= floor && numAsInt < (floor + 1000)) {
                        alphaList.add(new NameId(name, id, numAsInt));
                    }
                }

            } else {

                name = rs.getString(2);
                if (StringUtils.isEmpty(name)) {
                    name = rs.getString(1);
                }

                if (cdi.isUseIdentityTitle()) {
                    DataProviderSessionIFace session = null;
                    try {
                        session = DataProviderFactory.getInstance().createSession();
                        FormDataObjIFace fdi = (FormDataObjIFace) session
                                .createQuery("from " + className + " where id = " + id, false).list().get(0);
                        if (fdi != null) {
                            String title = fdi.getIdentityTitle();
                            if (StringUtils.isNotEmpty(title)) {
                                name = title;
                            }
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        //log.error(ex);

                    } finally {
                        session.close();
                    }

                } else if (cdi.getIndexClass() != null) {
                    if (cdi.getIndexClass() == Calendar.class) {
                        Date date = rs.getDate(2);
                        if (date != null) {
                            name = sdf.format(date);
                        } else {
                            name = "0000";
                        }
                        useLetter = false;
                    }
                }

                int len = Math.min(numLetters, name.length());
                if (doingIndex) {
                    String c = useLetter ? name.substring(0, len).toLowerCase() : name;
                    NameId nis = alphaHash.get(c);
                    if (nis == null) {
                        nis = new NameId(c, 0);
                        alphaHash.put(c, nis);
                    }
                    nis.add();

                } else {
                    if ((useLetter && name.substring(0, len).toUpperCase().equals(letter))
                            || (!useLetter && name.equals(letter))) {
                        alphaList.add(new NameId(name, id));
                    }
                }
            }

            cnt++;
        }

        System.out.println("alphaHash.size: " + alphaHash.size());
        if (doingIndex) {
            alphaList = new Vector<NameId>(alphaHash.values());
        }

        Collections.sort(alphaList);

        System.out.println("alphaList.size: " + alphaList.size());

        if (doingIndex) {
            DBTableInfo ti = DBTableIdMgr.getInstance().getByShortClassName(className);

            out.println("<center><br/><span style=\"font-size: 14pt;\">Index For " + ti.getTitle()
                    + "</span><br/>");
            out.println("<table class=\"brdr\" border=\"0\" cellpadding=\"4\" cellspacing=\"0\">\n");
            out.println("<tr><th class=\"brdr\" align=\"center\" nowrap=\"nowrap\">Index</th>");
            out.println("<th class=\"brdr\" align=\"center\" nowrap=\"nowrap\">Count</th></tr>\n");
            int i = 0;
            for (NameId nis : alphaList) {
                String ltrStr = nis.getNum() != null ? Integer.toString(nis.getNum() * 1000)
                        : nis.getName().toUpperCase();
                out.println("<tr>");
                out.println("<td nowrap=\"nowrap\" class=\"brdr" + (((i + 1) % 2 == 0) ? "even" : "odd")
                        + "\" align=\"center\">&nbsp;&nbsp;<a href=\"" + servletURL + "?cls=" + className
                        + "&ltr=" + ltrStr + "\">" + ltrStr + "</a>&nbsp;&nbsp;</td>\n");
                out.println("<td nowrap=\"nowrap\" class=\"brdr" + (((i + 1) % 2 == 0) ? "even" : "odd")
                        + "\"  align=\"center\"><a href=\"" + servletURL + "?cls=" + className + "&ltr="
                        + ltrStr + "\">" + nis.getId() + "</a></td>\n");
                out.println("</tr>");
                i++;
            }
            out.println("</table></center>\n");
        } else {
            if (alphaList.size() > 0) {
                if (useLetter) {
                    out.println("<br/>" + alphaList.get(0).getName().charAt(0) + "<br/>\n");
                }
                out.println("<table class=\"brdr\" border=\"0\" cellpadding=\4\" cellspacing=\"0\">\n");
                int i = 1;
                for (NameId nis : alphaList) {
                    out.println("<tr>");
                    out.println("<td nowrap=\"nowrap\" class=\"brdr" + (((i + 1) % 2 == 0) ? "even" : "odd")
                            + "\" >");
                    out.println("<a href=\"" + servletURL + "?cls=" + className + "&id=" + nis.getId() + "\">"
                            + nis.getName() + "</a>");
                    out.println("</td></tr>\n");
                    i++;
                }
                out.println("</table>\n");
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    out.println(template.substring(inx + contentTag.length() + 1, template.length()));

    log.info("Done");
}

From source file:edu.ku.brc.specify.web.SpecifyExplorer.java

/**
 * @param out/*  w ww.ja  v  a 2s.co m*/
 * @param pointsStr
 * @param sortByCE
 */
protected void createMap(final PrintWriter out, final String pointsStr, final boolean sortByCE) {
    DataProviderSessionIFace session = null;
    try {
        session = DataProviderFactory.getInstance().createSession();

        String mapTemplate = "";
        try {
            File templateFile = new File(
                    UIRegistry.getDefaultWorkingPath() + File.separator + "site/map_template.html");
            mapTemplate = FileUtils.readFileToString(templateFile);

        } catch (IOException ex) {
            ex.printStackTrace();
            out.println(ex.toString());
        }

        if (StringUtils.isEmpty(template)) {
            out.println("The template file is empty!");
        }

        int inx = mapTemplate.indexOf(contentTag);
        String subContent = mapTemplate.substring(0, inx);
        out.println(StringUtils.replace(subContent, "<!-- Title -->", "Mapping Collection Objects"));

        String[] points = StringUtils.splitPreserveAllTokens(pointsStr, ';');
        /*System.out.println("["+pointsStr+"]");
        for (int i=0;i<points.length;i++)
        {
        System.out.println("i["+i+"]Loc["+points[i]+"] CO["+points[i+1]+"]");
        i++;
        }*/

        double maxLat = Double.MIN_VALUE;
        double minLat = Double.MAX_VALUE;

        double maxLon = Double.MIN_VALUE;
        double minLon = Double.MAX_VALUE;

        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Hashtable<Locality, CollectingEvent> locToCE = new Hashtable<Locality, CollectingEvent>();

        boolean drawLines = false;

        Hashtable<CollectingEvent, CEForPoly> hash = new Hashtable<CollectingEvent, CEForPoly>();
        StringBuilder locStr = new StringBuilder();

        int locCnt = 0;
        for (int i = 0; i < points.length; i++) {
            //System.out.println("i["+i+"]Loc["+points[i]+"]");
            if (StringUtils.isEmpty(points[i])) {
                break;
            }

            //String title = "";
            Locality locality = (Locality) session.createQuery("from Locality WHERE id = " + points[i], false)
                    .list().get(0);
            if (locality != null) {
                StringBuilder sb = new StringBuilder();
                String[] colObjsIds = StringUtils.splitPreserveAllTokens(points[i + 1], ',');
                for (String id : colObjsIds) {
                    //System.out.println("co["+id+"]");
                    if (StringUtils.isNotEmpty(id)) {
                        CollectionObject co = (CollectionObject) session
                                .createQuery("from CollectionObject WHERE id = " + id, false).list().get(0);
                        if (co != null) {
                            CollectingEvent ce = co.getCollectingEvent();
                            if (ce != null) {
                                CollectingEvent colEv = locToCE.get(locality);
                                if (colEv == null) {
                                    locToCE.put(locality, ce);

                                } else if (!ce.getCollectingEventId().equals(colEv.getCollectingEventId())) {
                                    drawLines = false;
                                }
                                //sb.append("<h3>"+sdf.format(ce.getStartDate().getTime())+"</h3>");
                                Locality loc = ce.getLocality();
                                if (loc != null && loc.getLatitude1() != null && loc.getLongitude1() != null) {
                                    CEForPoly cep = hash.get(ce);
                                    if (cep == null) {
                                        cep = new CEForPoly(ce.getStartDate(), loc.getLatitude1().doubleValue(),
                                                loc.getLongitude1().doubleValue(), "");
                                        hash.put(ce, cep);
                                    }
                                    cep.getColObjs().add(co);
                                }
                            }
                            for (Determination det : co.getDeterminations()) {
                                if (det.isCurrentDet()) {
                                    Taxon txn = det.getPreferredTaxon();
                                    if (txn != null) {
                                        sb.append("<a href='SpecifyExplorer?cls=CollectionObject&id="
                                                + co.getCollectionObjectId() + "'>" + txn.getFullName()
                                                + "</a>");
                                        sb.append("<br/>");
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }

                if (locality.getLatitude1() != null && locality.getLongitude1() != null) {
                    if (locCnt == 0) {
                        maxLat = locality.getLatitude1().doubleValue();
                        minLat = maxLat;

                        maxLon = locality.getLongitude1().doubleValue();
                        minLon = maxLon;

                    } else {
                        maxLat = Math.max(maxLat, locality.getLatitude1().doubleValue());
                        minLat = Math.min(minLat, locality.getLatitude1().doubleValue());

                        maxLon = Math.max(maxLon, locality.getLongitude1().doubleValue());
                        minLon = Math.min(minLon, locality.getLongitude1().doubleValue());
                    }

                    locStr.append("var point = new GLatLng(" + locality.getLatitude1() + ","
                            + locality.getLongitude1() + ");\n");
                    locStr.append("var marker = createMarker(point,\"" + locality.getLocalityName() + "\",\""
                            + sb.toString() + "\");\n");
                    locStr.append("map.addOverlay(marker);\n");
                    locCnt++;
                }

            }
            i++;
        }

        System.out.println("maxLat: " + maxLat);
        System.out.println("minLat: " + minLat);
        System.out.println("maxLon: " + maxLon);
        System.out.println("minLon: " + minLon);

        double halfLat = (maxLat - minLat) / 2;
        double halfLon = (maxLon - minLon) / 2;
        System.out.println("halfLat: " + halfLat);
        System.out.println("halfLon: " + halfLon);

        int zoom = 2;
        if (halfLat == 0.0 && halfLon == 0.0) {
            zoom = 12;

        } else if (halfLat < 0.5 && halfLon < 0.5) {
            zoom = 10;

        } else if (halfLat < 2.0 && halfLon < 2.0) {
            zoom = 8;

        } else if (halfLat < 7.0 && halfLon < 7.0) {
            zoom = 6;
        }

        out.println("        map.setCenter(new GLatLng( " + (minLat + halfLat) + "," + (minLon + halfLon)
                + "), " + zoom + ");\n");

        out.println(locStr.toString());

        if (drawLines) {
            if (hash.size() > 0) {
                out.println("var polyline = new GPolyline([");
                for (CEForPoly cep : hash.values()) {
                    out.println("new GLatLng(" + cep.getLat() + ", " + cep.getLon() + "),\n");
                }
            }
            out.println("], \"#FF0000\", 5);\n");
            out.println("map.addOverlay(polyline);\n");

        }

        if (false) {
            out.println("var polygon = new GPolygon([");
            for (CEForPoly cep : hash.values()) {
                out.println("new GLatLng(" + cep.getLat() + ", " + cep.getLon() + "),\n");
            }
            out.println("], \"#ff0000\", 5, 0.7, \"#0000ff\", 0.4);\n");
            out.println("map.addOverlay(polygon);\n");
        }

        out.println(mapTemplate.substring(inx + contentTag.length() + 1, mapTemplate.length()));

    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:edu.ku.brc.specify.conversion.GenericDBConversion.java

/**
 * @param rsmd/*  w w  w.  ja  v a2s .  com*/
 * @param map
 * @param tableNames
 * @throws SQLException
 */
protected void buildIndexMapFromMetaData(final ResultSetMetaData rsmd, final Hashtable<String, Integer> map,
        final String[] tableNames) throws SQLException {
    map.clear();

    // Find the missing table name by figuring our which one isn't used.
    Hashtable<String, Boolean> existsMap = new Hashtable<String, Boolean>();
    for (String tblName : tableNames) {
        existsMap.put(tblName, true);
        log.debug("[" + tblName + "]");
    }
    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
        String tableName = rsmd.getTableName(i);
        // log.info("["+tableName+"]");
        if (isNotEmpty(tableName)) {
            if (existsMap.get(tableName) != null) {
                existsMap.remove(tableName);
                log.info("Removing Table Name[" + tableName + "]");
            }
        }
    }

    String missingTableName = null;
    if (existsMap.size() == 1) {
        missingTableName = existsMap.keys().nextElement();
        log.info("Missing Table Name[" + missingTableName + "]");

    } else if (existsMap.size() > 1) {
        throw new RuntimeException("ExistsMap cannot have more than one name in it!");
    } else {
        log.info("No Missing Table Names.");
    }

    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
        strBuf.setLength(0);
        String tableName = rsmd.getTableName(i);
        strBuf.append(isNotEmpty(tableName) ? tableName : missingTableName);
        strBuf.append(".");
        strBuf.append(rsmd.getColumnName(i));
        map.put(strBuf.toString(), i);
    }
}

From source file:org.adl.sequencer.impl.ADLSequencer.java

/**
 * Initiates deterministic rollup from the target activity and any other
 * activities that may have been affected. <br>
 * <b>Internal Sequencing Process</b><br>
 * <br>//from   w w w  . j a v  a 2  s .c  o m
 * 
 * @param ioTarget
 *            Identifies the activity where rollup is applied.
 * 
 * @param iWriteObjIDs
 *            Identifies the set of objective IDs that are affected by this
 *            invokation; or <code>null</code> if none.
 */
private void invokeRollup(SeqActivity ioTarget, List<String> iWriteObjIDs) {

    if (_Debug) {
        System.out.println("  :: ADLSequencer --> BEGIN - invokeRollup");
        System.out.println("  ::-->  Start: " + ioTarget.getID());
    }

    Hashtable<String, Integer> rollupSet = new Hashtable<String, Integer>();

    // Case #1 -- Rollup applies along the active path
    if (ioTarget == mSeqTree.getCurrentActivity()) {

        if (_Debug) {
            System.out.println("  ::--> CASE #1 Rollup");
        }

        SeqActivity walk = ioTarget;

        // Walk from the target to the root, apply rollup rules at each step
        while (walk != null) {

            if (_Debug) {
                System.out.println("  ::--> Adding :: " + walk.getID());
            }

            rollupSet.put(walk.getID(), Integer.valueOf(walk.getDepth()));

            List<String> writeObjIDs = walk.getObjIDs(null, false);

            if (writeObjIDs != null) {
                for (int i = 0; i < writeObjIDs.size(); i++) {
                    String objID = writeObjIDs.get(i);

                    if (_Debug) {
                        System.out.println("  ::--> Rolling up Obj -- " + objID);
                    }

                    // Need to identify all activity's that 'read' this
                    // objective
                    // into their primary objective -- those activities need
                    // to be
                    // included in the rollup set
                    List<String> acts = mSeqTree.getObjMap(objID);

                    if (_Debug) {
                        System.out.println("  ACTS == " + acts);
                    }

                    if (acts != null) {
                        for (int j = 0; j < acts.size(); j++) {
                            SeqActivity act = getActivity(acts.get(j));

                            if (_Debug) {
                                System.out.println("  *+> " + j + " <+*  :: " + act.getID());
                            }

                            // Only rollup at the parent of the affected
                            // activity
                            act = act.getParent();

                            if (act != null) {
                                // Only add if the activity is selected
                                if (act.getIsSelected()) {
                                    if (_Debug) {
                                        System.out.println("  ::--> Adding :: " + act.getID());
                                    }

                                    rollupSet.put(act.getID(), Integer.valueOf(act.getDepth()));
                                }
                            }
                        }
                    }
                }
            }

            walk = walk.getParent();
        }

        // Remove the Current Activity from the rollup set
        rollupSet.remove(ioTarget.getID());

    }

    // Case #2 -- Rollup applies when the state of a global shared objective
    // is written to...
    if (iWriteObjIDs != null) {

        if (_Debug) {
            System.out.println("  ::--> CASE #2 Rollup");
        }

        for (int i = 0; i < iWriteObjIDs.size(); i++) {
            String objID = iWriteObjIDs.get(i);

            if (_Debug) {
                System.out.println("  ::--> Rolling up Obj -- " + objID);
            }

            // Need to identify all activity's that 'read' this objective
            // into their primary objective -- those activities need to be
            // included in the rollup set
            List<String> acts = mSeqTree.getObjMap(objID);

            if (_Debug) {
                System.out.println("  ACTS == " + acts);
            }

            if (acts != null) {
                for (int j = 0; j < acts.size(); j++) {
                    SeqActivity act = getActivity(acts.get(j));

                    if (_Debug) {
                        System.out.println("  *+> " + j + " <+*  :: " + act.getID());
                    }

                    // Only rollup at the parent of the affected activity
                    act = act.getParent();

                    if (act != null) {
                        // Only add if the activity is selected
                        if (act.getIsSelected()) {
                            if (_Debug) {
                                System.out.println("  ::--> Adding :: " + act.getID());
                            }

                            rollupSet.put(act.getID(), Integer.valueOf(act.getDepth()));
                        }
                    }
                }
            }
        }
    }

    // Perform the deterministic rollup extension
    while (rollupSet.size() != 0) {
        if (_Debug) {
            System.out.println("  ::--> Rollup Set Size == " + rollupSet.size());

            for (Entry<String, Integer> entry : rollupSet.entrySet()) {
                System.out.println("  ::-->  " + entry.getKey() + "  //  " + entry.getValue());
            }
        }

        // Find the deepest activity
        SeqActivity deepest = null;
        int depth = -1;

        for (Entry<String, Integer> entry : rollupSet.entrySet()) {
            String key = entry.getKey();
            int thisDepth = entry.getValue();

            if (depth == -1) {
                depth = thisDepth;
                deepest = getActivity(key);
            } else if (thisDepth > depth) {
                depth = thisDepth;
                deepest = getActivity(key);
            }
        }

        if (deepest != null) {
            doOverallRollup(deepest, rollupSet);

            // If rollup was performed on the root, set the course's status
            if (deepest == mSeqTree.getRoot()) {
                @SuppressWarnings("unused")
                String completed = "unknown";
                if (deepest.getObjStatus(false)) {
                    completed = (deepest.getObjSatisfied(false)) ? "satisfied" : "notSatisfied";
                }

                if (deepest.getObjMeasureStatus(false)) {
                    completed = (new Double(deepest.getObjMeasure(false))).toString();
                }

                if (deepest.getProgressStatus(false)) {
                    completed = (deepest.getAttemptCompleted(false)) ? "completed" : "incomplete";
                }

                //ADLSeqUtilities.setCourseStatus(mSeqTree.getCourseID(),
                //      mSeqTree.getLearnerID(), satisfied, measure,
                //      completed);
            }

        } else {
            if (_Debug) {
                System.out.println("  :: ERROR :: No activity found");
            }
        }
    }

    if (_Debug) {
        System.out.println("  :: ADLSequencer --> END   - invokeRollup");
    }
}

From source file:org.unitime.timetable.solver.TimetableDatabaseSaver.java

private Long[] save(org.hibernate.Session hibSession) throws Exception {

    if (iStudentSectioning)
        getModel().switchStudents(getAssignment());

    iProgress.setStatus("Saving solution ...");

    if (iSolverGroupId == null || iSolverGroupId.length == 0) {
        iProgress.fatal("No solver group loaded.");
        return null;
    }/*from  www. j av a2 s . c  o  m*/

    Hashtable solverGroups = new Hashtable();
    for (int i = 0; i < iSolverGroupId.length; i++) {
        SolverGroup solverGroup = SolverGroupDAO.getInstance().get(iSolverGroupId[i], hibSession);
        if (solverGroup == null) {
            iProgress.fatal("Unable to load solver group " + iSolverGroupId[i] + ".");
            return null;
        }
        solverGroups.put(solverGroup.getUniqueId(), solverGroup);
        iProgress.debug("solver group [" + (i + 1) + "]: " + solverGroup.getName());
    }

    iSolutions = new Hashtable();
    if (!iCreateNew && iSolutionId != null && iSolutionId.length >= 0) {
        for (int i = 0; i < iSolverGroupId.length; i++) {
            if (i < iSolutionId.length && iSolutionId[i] != null) {
                Solution solution = (new SolutionDAO()).get(iSolutionId[i], hibSession);
                if (solution == null) {
                    iProgress.warn("Unable to load solution " + iSolutionId[i]);
                    continue;
                }
                if (!solverGroups.containsKey(solution.getOwner().getUniqueId())) {
                    iProgress.warn("Solution " + iSolutionId[i]
                            + " ignored -- it does not match with the owner(s) of the problem");
                    continue;
                }
                if (solution.isCommited().booleanValue()) {
                    solution.uncommitSolution(hibSession,
                            getModel().getProperties().getProperty("General.OwnerPuid"));
                    if (!iCommitSolution) {
                        String className = ApplicationProperty.ExternalActionSolutionCommit.value();
                        if (className != null && className.trim().length() > 0) {
                            HashSet<Solution> touchedSolutions = new HashSet<Solution>();
                            touchedSolutions.add(solution);
                            ExternalSolutionCommitAction commitAction = (ExternalSolutionCommitAction) (Class
                                    .forName(className).newInstance());
                            commitAction.performExternalSolutionCommitAction(touchedSolutions, hibSession);
                        }

                    }
                }
                solution.empty(hibSession, getFileProxy());
                iSolutions.put(solution.getOwner().getUniqueId(), solution);
            }
        }
    }

    Session session = SessionDAO.getInstance().get(iSessionId, hibSession);
    if (session == null) {
        iProgress.fatal("No session loaded.");
        return null;
    }
    iProgress.debug("session: " + session.getLabel());

    for (Enumeration e = solverGroups.elements(); e.hasMoreElements();) {
        SolverGroup solverGroup = (SolverGroup) e.nextElement();
        Solution solution = (Solution) iSolutions.get(solverGroup.getUniqueId());
        if (solution == null) {
            solution = new Solution();
            iSolutions.put(solverGroup.getUniqueId(), solution);
        }
        solution.setCommitDate(null);
        solution.setCreated(new Timestamp((new Date()).getTime()));
        solution.setCreator(Test.getVersionString());
        solution.setNote(getModel().getProperties().getProperty("General.Note"));
        solution.setOwner(solverGroup);
        solverGroup.getSolutions().add(solution);
        solution.setValid(Boolean.TRUE);
        solution.setCommited(Boolean.FALSE);

        iProgress.setPhase("Saving solver parameters ...", getModel().getProperties().size());
        HashSet params = new HashSet();
        for (Iterator i1 = getModel().getProperties().entrySet().iterator(); i1.hasNext();) {
            Map.Entry entry = (Map.Entry) i1.next();
            String name = (String) entry.getKey();
            String value = (String) entry.getValue();
            SolverParameterDef def = SolverParameterDef.findByNameType(hibSession, name,
                    SolverParameterGroup.sTypeCourse);
            if (def != null) {
                iProgress.trace("save " + name + "=" + value);
                SolverParameter param = new SolverParameter();
                param.setDefinition(def);
                param.setValue(value);
                hibSession.save(param);
                params.add(param);
            }
            iProgress.incProgress();
        }
        solution.setParameters(params);

        hibSession.saveOrUpdate(solution);
    }

    hibSession.flush();
    hibSession.clear();
    int batchIdx = 0;

    iProgress.setPhase("Saving assignments ...", getModel().variables().size());
    for (Lecture lecture : getModel().variables()) {
        Placement placement = getAssignment().getValue(lecture);
        if (placement != null) {
            iProgress.trace("save " + lecture.getName() + " " + placement.getName());
            Class_ clazz = (new Class_DAO()).get(lecture.getClassId(), hibSession);
            if (clazz == null) {
                iProgress.warn("Unable to save assignment for class " + lecture + " ("
                        + placement.getLongName(iUseAmPm) + ") -- class (id:" + lecture.getClassId()
                        + ") does not exist.");
                continue;
            }
            HashSet rooms = new HashSet();
            if (placement.isMultiRoom()) {
                for (RoomLocation r : placement.getRoomLocations()) {
                    Location room = (new LocationDAO()).get(r.getId(), hibSession);
                    if (room == null) {
                        iProgress.warn("Unable to save assignment for class " + lecture + " ("
                                + placement.getLongName(iUseAmPm) + ") -- room (id:" + r.getId()
                                + ") does not exist.");
                        continue;
                    }
                    rooms.add(room);
                }
                if (rooms.size() != placement.getRoomLocations().size())
                    continue;
            } else {
                Location room = (new LocationDAO()).get(placement.getRoomLocation().getId(), hibSession);
                if (room == null) {
                    iProgress.warn("Unable to save assignment for class " + lecture + " ("
                            + placement.getLongName(iUseAmPm) + ") -- room (id:"
                            + placement.getRoomLocation().getId() + ") does not exist.");
                    continue;
                }
                rooms.add(room);
            }

            HashSet instructors = new HashSet();
            for (InstructorConstraint ic : lecture.getInstructorConstraints()) {
                DepartmentalInstructor instructor = null;
                if (ic.getPuid() != null && ic.getPuid().length() > 0) {
                    instructor = DepartmentalInstructor.findByPuidDepartmentId(ic.getPuid(),
                            clazz.getControllingDept().getUniqueId());
                } else if (ic.getResourceId() != null) {
                    instructor = (new DepartmentalInstructorDAO()).get(ic.getResourceId(), hibSession);
                }
                if (instructor != null)
                    instructors.add(instructor);
            }

            TimePattern pattern = (new TimePatternDAO()).get(placement.getTimeLocation().getTimePatternId(),
                    hibSession);
            if (pattern == null) {
                iProgress.warn("Unable to save assignment for class " + lecture + " ("
                        + placement.getLongName(iUseAmPm) + ") -- time pattern (id:"
                        + placement.getTimeLocation().getTimePatternId() + ") does not exist.");
                continue;
            }
            Solution solution = getSolution(lecture, hibSession);
            if (solution == null) {
                iProgress.warn("Unable to save assignment for class " + lecture + " ("
                        + placement.getLongName(iUseAmPm)
                        + ") -- none or wrong solution group assigned to the class");
                continue;
            }
            Assignment assignment = new Assignment();
            assignment.setClazz(clazz);
            assignment.setClassId(clazz.getUniqueId());
            assignment.setClassName(lecture.getName());
            assignment.setDays(new Integer(placement.getTimeLocation().getDayCode()));
            assignment.setStartSlot(new Integer(placement.getTimeLocation().getStartSlot()));
            assignment.setTimePattern(pattern);
            if (placement.getTimeLocation().getDatePatternId() != null)
                assignment.setDatePattern(DatePatternDAO.getInstance()
                        .get(placement.getTimeLocation().getDatePatternId(), hibSession));
            assignment.setRooms(rooms);
            assignment.setInstructors(instructors);
            assignment.setSolution(solution);
            hibSession.save(assignment);
            iAssignments.put(lecture.getClassId(), assignment);
            if (++batchIdx % BATCH_SIZE == 0) {
                hibSession.flush();
                hibSession.clear();
            }
        }
        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    if (getModel().getProperties().getPropertyBoolean("General.SaveStudentEnrollments", true)) {
        iProgress.setPhase("Saving student enrollments ...", getModel().variables().size());
        for (Lecture lecture : getModel().variables()) {
            Class_ clazz = (new Class_DAO()).get(lecture.getClassId(), hibSession);
            if (clazz == null)
                continue;
            iProgress.trace("save " + lecture.getName());
            Solution solution = getSolution(lecture, hibSession);
            if (solution == null) {
                iProgress.warn("Unable to save student enrollments for class " + lecture
                        + "  -- none or wrong solution group assigned to the class");
                continue;
            }

            for (Iterator i2 = lecture.students().iterator(); i2.hasNext();) {
                Student student = (Student) i2.next();
                StudentEnrollment enrl = new StudentEnrollment();
                enrl.setStudentId(student.getId());
                enrl.setClazz(clazz);
                enrl.setSolution(solution);
                hibSession.save(enrl);
                if (++batchIdx % BATCH_SIZE == 0) {
                    hibSession.flush();
                    hibSession.clear();
                }
            }

            iProgress.incProgress();
        }

        hibSession.flush();
        hibSession.clear();
        batchIdx = 0;
    }

    /**  // is this needed?
    iProgress.setPhase("Saving joint enrollments ...", getModel().getJenrlConstraints().size());
    for (Enumeration e1=getModel().getJenrlConstraints().elements();e1.hasMoreElements();) {
     JenrlConstraint jenrlConstraint = (JenrlConstraint)e1.nextElement();
             
     Class_ clazz1 = (new Class_DAO()).get(((Lecture)jenrlConstraint.first()).getClassId());
     Class_ clazz2 = (new Class_DAO()).get(((Lecture)jenrlConstraint.second()).getClassId());
             
     JointEnrollment jenrl = new JointEnrollment();
     jenrl.setJenrl(new Double(jenrlConstraint.getJenrl()));
     jenrl.setClass1(clazz1);
     jenrl.setClass2(clazz2);
     jenrl.setSolution(solution);
     hibSession.save(jenrl);
             
     iProgress.incProgress();
    }
    */

    SolverInfoDef defGlobalInfo = SolverInfoDef.findByName(hibSession, "GlobalInfo");
    if (defGlobalInfo == null)
        iProgress.warn("Global info is not registered.");
    SolverInfoDef defCbsInfo = SolverInfoDef.findByName(hibSession, "CBSInfo");
    if (defCbsInfo == null)
        iProgress.warn("Constraint-based statistics info is not registered.");
    SolverInfoDef defAssignmentInfo = SolverInfoDef.findByName(hibSession, "AssignmentInfo");
    if (defAssignmentInfo == null)
        iProgress.warn("Assignment info is not registered.");
    SolverInfoDef defDistributionInfo = SolverInfoDef.findByName(hibSession, "DistributionInfo");
    if (defDistributionInfo == null)
        iProgress.warn("Distribution constraint info is not registered.");
    SolverInfoDef defJenrlInfo = SolverInfoDef.findByName(hibSession, "JenrlInfo");
    if (defJenrlInfo == null)
        iProgress.warn("Joint enrollments info is not registered.");
    SolverInfoDef defLogInfo = SolverInfoDef.findByName(hibSession, "LogInfo");
    if (defLogInfo == null)
        iProgress.warn("Solver log info is not registered.");
    SolverInfoDef defBtbInstrInfo = SolverInfoDef.findByName(hibSession, "BtbInstructorInfo");
    if (defBtbInstrInfo == null)
        iProgress.warn("Back-to-back instructor info is not registered.");

    Hashtable<Solution, List<Lecture>> lectures4solution = new Hashtable<Solution, List<Lecture>>();
    for (Lecture lecture : getModel().variables()) {
        Solution s = getSolution(lecture, hibSession);
        if (s == null)
            continue;
        List<Lecture> lectures = lectures4solution.get(s);
        if (lectures == null) {
            lectures = new ArrayList<Lecture>();
            lectures4solution.put(s, lectures);
        }
        lectures.add(lecture);
    }

    iProgress.setPhase("Saving global info ...", solverGroups.size());
    for (Enumeration e = solverGroups.elements(); e.hasMoreElements();) {
        SolverGroup solverGroup = (SolverGroup) e.nextElement();
        Solution solution = (Solution) iSolutions.get(solverGroup.getUniqueId());
        List<Lecture> lectures = lectures4solution.get(solution);
        if (lectures == null)
            lectures = new ArrayList<Lecture>(0);
        SolutionInfo solutionInfo = new SolutionInfo();
        solutionInfo.setDefinition(defGlobalInfo);
        solutionInfo.setOpt(null);
        solutionInfo.setSolution(solution);
        solutionInfo.setInfo(new PropertiesInfo(getSolution().getInfo(lectures)), getFileProxy());
        hibSession.save(solutionInfo);
        solution.setGlobalInfo(solutionInfo);
        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    ConflictStatistics cbs = null;
    for (Extension ext : getSolver().getExtensions()) {
        if (ext instanceof ConflictStatistics) {
            cbs = (ConflictStatistics) ext;
            break;
        }
    }
    if (cbs != null && cbs.getNoGoods() != null) {
        ConflictStatisticsInfo cbsInfo = new ConflictStatisticsInfo();
        cbsInfo.load(getSolver(), cbs);
        iProgress.setPhase("Saving conflict-based statistics ...", 1);
        for (Enumeration e = iSolutions.elements(); e.hasMoreElements();) {
            Solution solution = (Solution) e.nextElement();
            List<Lecture> lectures = lectures4solution.get(solution);
            if (lectures == null)
                lectures = new ArrayList<Lecture>(0);
            SolutionInfo cbsSolutionInfo = new SolutionInfo();
            cbsSolutionInfo.setDefinition(defCbsInfo);
            cbsSolutionInfo.setOpt(null);
            cbsSolutionInfo.setSolution(solution);
            cbsSolutionInfo.setInfo(cbsInfo.getConflictStatisticsSubInfo(lectures), getFileProxy());
            hibSession.save(cbsSolutionInfo);
            if (++batchIdx % BATCH_SIZE == 0) {
                hibSession.flush();
                hibSession.clear();
            }
        }
        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving variable infos ...", getModel().variables().size());
    for (Lecture lecture : getModel().variables()) {
        Placement placement = getAssignment().getValue(lecture);
        if (placement != null) {
            Assignment assignment = (Assignment) iAssignments.get(lecture.getClassId());
            AssignmentInfo assignmentInfo = new AssignmentInfo();
            assignmentInfo.setAssignment(assignment);
            assignmentInfo.setDefinition(defAssignmentInfo);
            assignmentInfo.setOpt(null);
            assignmentInfo.setInfo(new AssignmentPreferenceInfo(getSolver(), placement, true, true),
                    getFileProxy());
            hibSession.save(assignmentInfo);
            if (++batchIdx % BATCH_SIZE == 0) {
                hibSession.flush();
                hibSession.clear();
            }
        }
        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving btb instructor infos ...", getModel().variables().size());
    for (Lecture lecture1 : getModel().variables()) {
        Placement placement1 = (Placement) getAssignment().getValue(lecture1);
        iProgress.incProgress();
        if (placement1 == null)
            continue;
        for (InstructorConstraint ic : lecture1.getInstructorConstraints()) {
            for (Lecture lecture2 : ic.variables()) {
                Placement placement2 = (Placement) getAssignment().getValue(lecture2);
                if (placement2 == null || lecture2.getClassId().compareTo(lecture1.getClassId()) <= 0)
                    continue;
                int pref = ic.getDistancePreference(placement1, placement2);
                if (pref == PreferenceLevel.sIntLevelNeutral)
                    continue;
                iProgress.trace("Back-to-back instructor constraint (" + pref + ") between " + placement1
                        + " and " + placement2);
                BtbInstructorConstraintInfo biInfo = new BtbInstructorConstraintInfo();
                biInfo.setPreference(pref);
                biInfo.setInstructorId(ic.getResourceId());
                ConstraintInfo constraintInfo = new ConstraintInfo();
                constraintInfo.setDefinition(defBtbInstrInfo);
                constraintInfo.setOpt(String.valueOf(ic.getResourceId()));
                HashSet biAssignments = new HashSet();
                Assignment assignment = (Assignment) iAssignments.get(lecture1.getClassId());
                if (assignment != null)
                    biAssignments.add(assignment);
                assignment = (Assignment) iAssignments.get(lecture2.getClassId());
                if (assignment != null)
                    biAssignments.add(assignment);
                if (!biAssignments.isEmpty()) {
                    constraintInfo.setAssignments(biAssignments);
                    constraintInfo.setInfo(biInfo, getFileProxy());
                    hibSession.save(constraintInfo);
                    if (++batchIdx % BATCH_SIZE == 0) {
                        hibSession.flush();
                        hibSession.clear();
                    }
                } else {
                    iProgress.trace("   NO ASSIGNMENTS !!!");
                }
            }
        }
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving group constraint infos ...", getModel().getGroupConstraints().size());
    for (GroupConstraint gc : getModel().getGroupConstraints()) {
        GroupConstraintInfo gcInfo = new GroupConstraintInfo(getAssignment(), gc);
        ConstraintInfo constraintInfo = new ConstraintInfo();
        constraintInfo.setDefinition(defDistributionInfo);
        constraintInfo.setOpt(gcInfo.isSatisfied() ? "1" : "0");
        iProgress.trace("Distribution constraint " + gcInfo.getName() + " (p:" + gcInfo.getPreference() + ", s:"
                + gcInfo.isSatisfied() + ") between");
        HashSet gcAssignments = new HashSet();
        for (Lecture lecture : gc.variables()) {
            Assignment assignment = (Assignment) iAssignments.get(lecture.getClassId());
            iProgress.trace("  " + getAssignment().getValue(lecture));
            if (assignment != null)
                gcAssignments.add(assignment);
        }

        if (!gcAssignments.isEmpty()) {
            constraintInfo.setAssignments(gcAssignments);
            constraintInfo.setInfo(gcInfo, getFileProxy());
            hibSession.save(constraintInfo);
            if (++batchIdx % BATCH_SIZE == 0) {
                hibSession.flush();
                hibSession.clear();
            }
        } else {
            iProgress.trace("   NO ASSIGNMENTS !!!");
        }

        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving student enrollment infos ...", getModel().getJenrlConstraints().size());
    for (JenrlConstraint jc : getModel().getJenrlConstraints()) {
        if (!jc.isInConflict(getAssignment()) || !jc.isOfTheSameProblem()) {
            iProgress.incProgress();
            continue;
        }
        JenrlInfo jInfo = new JenrlInfo(getSolver(), jc);
        ConstraintInfo constraintInfo = new ConstraintInfo();
        constraintInfo.setDefinition(defJenrlInfo);
        constraintInfo.setOpt((jInfo.isSatisfied() ? "S" : "") + (jInfo.isHard() ? "H" : "")
                + (jInfo.isDistance() ? "D" : "") + (jInfo.isFixed() ? "F" : "")
                + (jInfo.isImportant() ? "I" : "") + (jInfo.isInstructor() ? "X" : ""));
        Assignment firstAssignment = (Assignment) iAssignments.get(((Lecture) jc.first()).getClassId());
        Assignment secondAssignment = (Assignment) iAssignments.get(((Lecture) jc.second()).getClassId());
        if (firstAssignment == null || secondAssignment == null)
            continue;
        HashSet jAssignments = new HashSet();
        jAssignments.add(firstAssignment);
        jAssignments.add(secondAssignment);
        constraintInfo.setAssignments(jAssignments);
        constraintInfo.setInfo(jInfo, getFileProxy());
        hibSession.save(constraintInfo);
        if (++batchIdx % BATCH_SIZE == 0) {
            hibSession.flush();
            hibSession.clear();
        }

        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving committed student enrollment infos ...", iSolutions.size());
    for (Enumeration e = iSolutions.elements(); e.hasMoreElements();) {
        Solution solution = (Solution) e.nextElement();
        solution.updateCommittedStudentEnrollmentInfos(hibSession);
        iProgress.incProgress();
    }
    iProgress.incProgress();

    /*
    iProgress.setPhase("Saving committed student enrollment infos ...", getModel().assignedVariables().size());
    for (Enumeration e1=getModel().assignedVariables().elements();e1.hasMoreElements();) {
     Lecture lecture = (Lecture)e1.nextElement();
     Assignment assignment = (Assignment)iAssignments.get(lecture.getClassId());
    if (assignment==null) continue;
    Hashtable infos = JenrlInfo.getCommitedJenrlInfos(lecture);
     for (Iterator i2=infos.entrySet().iterator();i2.hasNext();) {
        Map.Entry entry = (Map.Entry)i2.next();
        Integer assignmentId = (Integer)entry.getKey();
        JenrlInfo jInfo = (JenrlInfo)entry.getValue();
        Assignment other = (new AssignmentDAO()).get(assignmentId,hibSession);
        if (other==null) continue;
         ConstraintInfo constraintInfo = new ConstraintInfo();
         constraintInfo.setDefinition(defJenrlInfo);
         constraintInfo.setOpt("C"+(jInfo.isSatisfied()?"S":"")+(jInfo.isHard()?"H":"")+(jInfo.isDistance()?"D":"")+(jInfo.isFixed()?"F":""));
         HashSet jAssignments = new HashSet();
         jAssignments.add(assignment);
         jAssignments.add(other);
         constraintInfo.setAssignments(jAssignments);
         constraintInfo.setInfo(jInfo,getFileProxy());
         hibSession.save(constraintInfo);
        if (++batchIdx % BATCH_SIZE == 0) {
           hibSession.flush(); hibSession.clear();
        }
     }
     iProgress.incProgress();
    }
    */

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Done", 1);
    iProgress.incProgress();

    Long ret[] = new Long[iSolutions.size()];
    int idx = 0;
    for (Enumeration e = iSolutions.elements(); e.hasMoreElements();)
        ret[idx++] = ((Solution) e.nextElement()).getUniqueId();

    return ret;
}

From source file:com.globalsight.webservices.Ambassador.java

private void changeFileListByXliff(String p_filename, String p_targetLocale, FileProfile p_fileProfile,
        Vector p_fileProfileList, Vector p_fileList, Vector p_afterTargetLocales) {
    Hashtable<String, FileProfile> splitFiles = new Hashtable<String, FileProfile>();
    XliffFileUtil.processMultipleFileTags(splitFiles, p_filename, p_fileProfile);
    if (splitFiles != null && splitFiles.size() > 0) {
        for (Iterator<String> iterator = splitFiles.keySet().iterator(); iterator.hasNext();) {
            String tmp = iterator.next();
            p_fileList.add(new File(AmbFileStoragePathUtils.getCxeDocDir(), tmp));
            p_fileProfileList.add(p_fileProfile);
            p_afterTargetLocales.add(p_targetLocale);
        }/*from  ww w . ja  va2s . c o  m*/
    }
}

From source file:com.globalsight.webservices.Ambassador.java

/**
 * Generate workflow info in xml format//from   w ww.  j a  v  a 2 s  .c o m
 * 
 * @param workflow
 *            workflow object
 * @param tab
 *            Tab string as prefix, such as '\t\t'
 * @return String workflow info in xml format
 */
private String getWorkflowInfo(Workflow workflow, String tab) {
    StringBuilder xml = new StringBuilder();
    TaskInstance taskInstance = null;

    // workflow
    xml.append(tab).append("<workflow>\r\n");
    // workflow id
    xml.append(tab).append("\t<workflow_id>").append(workflow.getId()).append("</workflow_id>\r\n");
    // workflow state
    xml.append(tab).append("\t<workflow_state>").append(workflow.getState()).append("</workflow_state>\r\n");

    xml.append(tab).append("\t<target_locale>").append(workflow.getTargetLocale())
            .append("</target_locale>\r\n");
    xml.append(tab).append("\t<dispatch_date>")
            .append(workflow.getDispatchedDate() == null ? ""
                    : DateHelper.getFormattedDateAndTime(workflow.getDispatchedDate(), null))
            .append("</dispatch_date>\r\n");
    // tasks
    Hashtable<Long, Task> tasks = (Hashtable<Long, Task>) workflow.getTasks();
    Rate rate = null;
    if (tasks == null || tasks.size() == 0) {
        xml.append(tab).append("\t<tasks>\r\n").append(tab).append("\t</tasks>\r\n");
    } else {
        xml.append(tab).append("\t<tasks>\r\n");

        // each task
        Long taskId = null;
        Task task = null;
        String tmp = "";
        for (Iterator<Long> ids = tasks.keySet().iterator(); ids.hasNext();) {
            taskId = ids.next();
            // task = tasks.get(taskId);
            try {
                task = ServerProxy.getTaskManager().getTask(taskId);
            } catch (Exception e) {
            }

            tmp = getTaskInfo(task, tab + "\t\t");
            xml.append(tmp);
        }

        xml.append(tab).append("\t</tasks>\r\n");
    }

    // current activity
    taskInstance = WorkflowManagerLocal.getCurrentTask(workflow.getId());
    String currentTaskName = "";
    if (taskInstance != null) {
        currentTaskName = TaskJbpmUtil.getTaskDisplayName(taskInstance.getName());
        xml.append(tab).append("\t<current_activity>").append(currentTaskName)
                .append("</current_activity>\r\n");
    }

    /** Wordcount Summary */
    xml.append(tab).append("\t<word_counts>\r\n");
    // leverageOption
    String leverageOption = "unknown";
    boolean isInContextMatch = false;
    try {
        Job job = workflow.getJob();
        if (PageHandler.isInContextMatch(job)) {
            isInContextMatch = true;
        }

        if (isInContextMatch) {
            leverageOption = "Leverage in context matches";
        } else {
            leverageOption = "100% match only";
        }
    } catch (Exception e) {

    }
    xml.append(tab).append("\t\t<leverage_option>").append(leverageOption).append("</leverage_option>\r\n");
    // 100%
    int wc = 0;
    if (isInContextMatch) {
        wc = workflow.getSegmentTmWordCount();
    } else {
        wc = workflow.getTotalExactMatchWordCount();
    }
    xml.append(tab).append("\t\t<match_100_percent>").append(wc).append("</match_100_percent>\r\n");
    // 95%-99%
    xml.append(tab).append("\t\t<match_95_percent-99_percent>").append(workflow.getThresholdHiFuzzyWordCount())
            .append("</match_95_percent-99_percent>\r\n");
    // 85%-94%
    xml.append(tab).append("\t\t<match_85_percent-94_percent>")
            .append(workflow.getThresholdMedHiFuzzyWordCount()).append("</match_85_percent-94_percent>\r\n");
    // 75%-84%
    xml.append(tab).append("\t\t<match_75_percent-84_percent>").append(workflow.getThresholdMedFuzzyWordCount())
            .append("</match_75_percent-84_percent>\r\n");
    // noMatch (50%-74%)
    xml.append(tab).append("\t\t<no_match>")
            .append(workflow.getThresholdNoMatchWordCount() + workflow.getThresholdLowFuzzyWordCount())
            .append("</no_match>\r\n");
    // Repetitions
    xml.append(tab).append("\t\t<repetitions>").append(workflow.getRepetitionWordCount())
            .append("</repetitions>\r\n");
    // In Context Matches
    if (isInContextMatch) {
        xml.append(tab).append("\t\t<in_context_matches>").append(workflow.getInContextMatchWordCount())
                .append("</in_context_matches>\r\n");
    }
    // total
    xml.append(tab).append("\t\t<total>").append(workflow.getTotalWordCount()).append("</total>\r\n");
    xml.append(tab).append("\t</word_counts>\r\n");

    if (workflow.getCompletedDate() != null) {
        xml.append(tab).append("\t<complete_date>")
                .append(DateHelper.getFormattedDateAndTime(workflow.getCompletedDate(), null))
                .append("</complete_date>\r\n");
    }

    xml.append(tab).append("</workflow>\r\n");

    return xml.toString();
}

From source file:be.ibridge.kettle.trans.TransMeta.java

/**
     * Checks all the steps and fills a List of (CheckResult) remarks.
     *//from   w w w.ja  v a  2s. c  o m
     * @param remarks The remarks list to add to.
     * @param only_selected Check only the selected steps.
     * @param monitor The progress monitor to use, null if not used
     */
    public void checkSteps(ArrayList remarks, boolean only_selected, IProgressMonitor monitor) {
        try {
            remarks.clear(); // Start with a clean slate...

            Hashtable values = new Hashtable();
            String stepnames[];
            StepMeta steps[];
            if (!only_selected || nrSelectedSteps() == 0) {
                stepnames = getStepNames();
                steps = getStepsArray();
            } else {
                stepnames = getSelectedStepNames();
                steps = getSelectedSteps();
            }

            boolean stop_checking = false;

            if (monitor != null)
                monitor.beginTask(Messages.getString("TransMeta.Monitor.VerifyingThisTransformationTask.Title"), //$NON-NLS-1$
                        steps.length + 2);

            for (int i = 0; i < steps.length && !stop_checking; i++) {
                if (monitor != null)
                    monitor.subTask(Messages.getString("TransMeta.Monitor.VerifyingStepTask.Title", stepnames[i])); //$NON-NLS-1$ //$NON-NLS-2$

                StepMeta stepMeta = steps[i];

                int nrinfo = findNrInfoSteps(stepMeta);
                StepMeta[] infostep = null;
                if (nrinfo > 0) {
                    infostep = getInfoStep(stepMeta);
                }

                Row info = null;
                if (infostep != null) {
                    try {
                        info = getStepFields(infostep);
                    } catch (KettleStepException kse) {
                        info = null;
                        CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString(
                                "TransMeta.CheckResult.TypeResultError.ErrorOccurredGettingStepInfoFields.Description", //$NON-NLS-1$
                                "" + stepMeta, Const.CR + kse.getMessage()), stepMeta);
                        remarks.add(cr);
                    }
                }

                // The previous fields from non-informative steps:
                Row prev = null;
                try {
                    prev = getPrevStepFields(stepMeta);
                } catch (KettleStepException kse) {
                    CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString(
                            "TransMeta.CheckResult.TypeResultError.ErrorOccurredGettingInputFields.Description",
                            "" + stepMeta, Const.CR + kse.getMessage()), stepMeta); //$NON-NLS-1$
                    remarks.add(cr);
                    // This is a severe error: stop checking...
                    // Otherwise we wind up checking time & time again because nothing gets put in the database
                    // cache, the timeout of certain databases is very long... (Oracle)
                    stop_checking = true;
                }

                if (isStepUsedInTransHops(stepMeta)) {
                    // Get the input & output steps!
                    // Copy to arrays:
                    String input[] = getPrevStepNames(stepMeta);
                    String output[] = getPrevStepNames(stepMeta);

                    // Check step specific info...
                    stepMeta.check(remarks, prev, input, output, info);

                    // See if illegal characters etc. were used in field-names...
                    if (prev != null) {
                        for (int x = 0; x < prev.size(); x++) {
                            Value v = prev.getValue(x);
                            String name = v.getName();
                            if (name == null)
                                values.put(v, Messages.getString(
                                        "TransMeta.Value.CheckingFieldName.FieldNameIsEmpty.Description")); //$NON-NLS-1$
                            else if (name.indexOf(' ') >= 0)
                                values.put(v, Messages.getString(
                                        "TransMeta.Value.CheckingFieldName.FieldNameContainsSpaces.Description")); //$NON-NLS-1$
                            else {
                                char list[] = new char[] { '.', ',', '-', '/', '+', '*', '\'', '\t', '"', '|', '@',
                                        '(', ')', '{', '}', '!', '^' };
                                for (int c = 0; c < list.length; c++) {
                                    if (name.indexOf(list[c]) >= 0)
                                        values.put(v, Messages.getString(
                                                "TransMeta.Value.CheckingFieldName.FieldNameContainsUnfriendlyCodes.Description", //$NON-NLS-1$
                                                String.valueOf(list[c]))); //$NON-NLS-2$
                                }
                            }
                        }

                        // Check if 2 steps with the same name are entering the step...
                        if (prev.size() > 1) {
                            String fieldNames[] = prev.getFieldNames();
                            String sortedNames[] = Const.sortStrings(fieldNames);

                            String prevName = sortedNames[0];
                            for (int x = 1; x < sortedNames.length; x++) {
                                // Checking for doubles
                                if (prevName.equalsIgnoreCase(sortedNames[x])) {
                                    // Give a warning!!
                                    CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_WARNING,
                                            Messages.getString(
                                                    "TransMeta.CheckResult.TypeResultWarning.HaveTheSameNameField.Description", //$NON-NLS-1$
                                                    prevName),
                                            stepMeta); //$NON-NLS-2$
                                    remarks.add(cr);
                                } else {
                                    prevName = sortedNames[x];
                                }
                            }
                        }
                    } else {
                        CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString(
                                "TransMeta.CheckResult.TypeResultError.CannotFindPreviousFields.Description") //$NON-NLS-1$
                                + stepMeta.getName(), stepMeta);
                        remarks.add(cr);
                    }
                } else {
                    CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_WARNING,
                            Messages.getString("TransMeta.CheckResult.TypeResultWarning.StepIsNotUsed.Description"), //$NON-NLS-1$
                            stepMeta);
                    remarks.add(cr);
                }

                if (monitor != null) {
                    monitor.worked(1); // progress bar...
                    if (monitor.isCanceled())
                        stop_checking = true;
                }
            }

            // Also, check the logging table of the transformation...
            if (monitor == null || !monitor.isCanceled()) {
                if (monitor != null)
                    monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingTheLoggingTableTask.Title")); //$NON-NLS-1$
                if (getLogConnection() != null) {
                    Database logdb = new Database(getLogConnection());
                    try {
                        logdb.connect();
                        CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_OK,
                                Messages.getString(
                                        "TransMeta.CheckResult.TypeResultOK.ConnectingWorks.Description"), //$NON-NLS-1$
                                null);
                        remarks.add(cr);

                        if (getLogTable() != null) {
                            if (logdb.checkTableExists(getLogTable())) {
                                cr = new CheckResult(CheckResult.TYPE_RESULT_OK,
                                        Messages.getString(
                                                "TransMeta.CheckResult.TypeResultOK.LoggingTableExists.Description", //$NON-NLS-1$
                                                getLogTable()),
                                        null); //$NON-NLS-2$
                                remarks.add(cr);

                                Row fields = Database.getTransLogrecordFields(isBatchIdUsed(), isLogfieldUsed());
                                String sql = logdb.getDDL(getLogTable(), fields);
                                if (sql == null || sql.length() == 0) {
                                    cr = new CheckResult(CheckResult.TYPE_RESULT_OK,
                                            Messages.getString(
                                                    "TransMeta.CheckResult.TypeResultOK.CorrectLayout.Description"), //$NON-NLS-1$
                                            null);
                                    remarks.add(cr);
                                } else {
                                    cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString(
                                            "TransMeta.CheckResult.TypeResultError.LoggingTableNeedsAdjustments.Description") //$NON-NLS-1$
                                            + Const.CR + sql, null);
                                    remarks.add(cr);
                                }

                            } else {
                                cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString(
                                        "TransMeta.CheckResult.TypeResultError.LoggingTableDoesNotExist.Description"), //$NON-NLS-1$
                                        null);
                                remarks.add(cr);
                            }
                        } else {
                            cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString(
                                    "TransMeta.CheckResult.TypeResultError.LogTableNotSpecified.Description"), //$NON-NLS-1$
                                    null);
                            remarks.add(cr);
                        }
                    } catch (KettleDatabaseException dbe) {

                    } finally {
                        logdb.disconnect();
                    }
                }
                if (monitor != null)
                    monitor.worked(1);

            }

            if (monitor != null)
                monitor.subTask(Messages.getString(
                        "TransMeta.Monitor.CheckingForDatabaseUnfriendlyCharactersInFieldNamesTask.Title")); //$NON-NLS-1$
            if (values.size() > 0) {
                Enumeration keys = values.keys();
                while (keys.hasMoreElements()) {
                    Value v = (Value) keys.nextElement();
                    String message = (String) values.get(v);
                    CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_WARNING,
                            Messages.getString("TransMeta.CheckResult.TypeResultWarning.Description", v.getName(), //$NON-NLS-1$
                                    message, v.getOrigin()),
                            findStep(v.getOrigin()));
                    remarks.add(cr);
                }
            } else {
                CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_OK,
                        Messages.getString("TransMeta.CheckResult.TypeResultOK.Description"), null); //$NON-NLS-1$
                remarks.add(cr);
            }
            if (monitor != null)
                monitor.worked(1);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

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  ww .j a  va  2s  .co 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:com.afunms.report.abstraction.ExcelReport1.java

public void createReport_hostall(String filename) {
    if (impReport.getTable() == null) {
        fileName = null;//from w w  w  .java2  s  .  c o m
        return;
    }
    WritableWorkbook wb = null;
    try {
        // fileName = ResourceCenter.getInstance().getSysPath() +
        // "temp\\dhcnms_report.xls";
        fileName = ResourceCenter.getInstance().getSysPath() + filename;
        wb = Workbook.createWorkbook(new File(fileName));
        Hashtable allreporthash = new Hashtable();
        allreporthash = reportHash;
        if (allreporthash != null && allreporthash.size() > 0) {
            Iterator keys = allreporthash.keySet().iterator();
            String ip = "";
            int sheetNum = 0;
            while (keys.hasNext()) {
                ip = keys.next().toString();
                Hashtable report_has = (Hashtable) allreporthash.get(ip);
                String hostname = (String) report_has.get("equipname");
                WritableSheet sheet = wb.createSheet(hostname + "", sheetNum);
                this.createReportTitle(sheet, report_has);
                this.createPingAndCpu(sheet, ip, report_has);
                this.createMemory(sheet, ip, report_has);
                this.createDisk(sheet, ip, report_has);
                sheetNum++;
            }
            wb.write();
        }

    } catch (Exception e) {
        // SysLogger.error("Error in ExcelReport.createReport()",e);
        SysLogger.error("", e);
    } finally {
        try {
            if (wb != null)
                wb.close();
        } catch (Exception e) {
        }
    }
}