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:es.pode.catalogadorWeb.presentacion.categoriasAvanzado.clasificacion.detalleClasificacion.DetalleClasificacionControllerImpl.java

private void cambioFormulario(HttpServletRequest request, int longitudTextosDesc, int[] longitudTextosPCla,
        int longitudPalabrasClave, int longitudRutasTax, int[] longiTextosFuente, int[] longiTaxones,
        Object formRequestSession) throws Exception {

    descripcion = new DescripcionVO();
    palabrasClave = new PalabraClaveVO[longitudPalabrasClave];
    rutasTaxonomicas = new RutaTaxonomicaVO[longitudRutasTax];

    String[] textoDescripcion = new String[longitudTextosDesc];
    String[] idiomaDescripcion = new String[longitudTextosDesc];
    ArrayList[] textoPalabrasClave = new ArrayList[longitudPalabrasClave];
    ArrayList[] idiomaPalabrasClave = new ArrayList[longitudPalabrasClave];
    ArrayList[] textoRutasTaxFuente = new ArrayList[longitudRutasTax];
    ArrayList textoRutasTaxTaxones = new ArrayList();
    Hashtable hDatos = new Hashtable();

    for (Enumeration names = request.getParameterNames(); names.hasMoreElements();) {
        String name = String.valueOf(names.nextElement());

        if (name.startsWith("Des")) { //Descripciones
            if (name.startsWith("DesTex")) {
                int i = Integer.parseInt(name.substring(6, name.length()));
                textoDescripcion[i] = request.getParameter(name);
            }// w  w  w.ja  v a2s.  c  o  m
            if (name.startsWith("DesIdio")) {
                int i = Integer.parseInt(name.substring(7, name.length()));
                idiomaDescripcion[i] = request.getParameter(name);
            }
        } else if (name.startsWith("Pcla")) {//Palabras Clave
            String[] namePartido = name.split("_");
            int i = Integer.parseInt(namePartido[0].substring(4, namePartido[0].length()));
            if (namePartido[1].startsWith("Tex")) {
                int j = Integer.parseInt(namePartido[1].substring(3, namePartido[1].length()));
                ArrayList lPCla = textoPalabrasClave[i];
                if (lPCla == null) {
                    lPCla = new ArrayList();
                    for (int k = 0; k < longitudTextosPCla[i]; k++)
                        lPCla.add("");
                }

                lPCla.set(j, request.getParameter(name));
                textoPalabrasClave[i] = lPCla;
            } else {//Idio
                int j = Integer.parseInt(namePartido[1].substring(4, namePartido[1].length()));
                ArrayList lPCla = idiomaPalabrasClave[i];
                if (lPCla == null) {
                    lPCla = new ArrayList();
                    for (int k = 0; k < longitudTextosPCla[i]; k++)
                        lPCla.add("");
                }

                lPCla.set(j, request.getParameter(name));
                idiomaPalabrasClave[i] = lPCla;
            }
        } else if (name.startsWith("rutaTax")) {
            //              rutaTax${i }_source, rutaTax${i}_taxon${t}_Id${u }//rutaTax${i}_taxon${t}_EntryTex${u} //rutaTax${i}_taxon${t}_EntryIdio${u}
            hDatos.put(name, request.getParameter(name));
        } else if (name.startsWith("razon")) {
            razon = request.getParameter(name);
        }
    }

    if (hDatos.size() > 0) {
        ArrayList arrRutaTax = new ArrayList();
        for (int i = 0; i < longitudRutasTax; i++) {
            RutaTaxonomicaVO rutavo = new RutaTaxonomicaVO();
            //rellenams fuentes
            //               String source= hDatos.get("rutaTax" + i + "_source").toString();
            String source = hDatos.get("rutaTax" + i + "_source") != null
                    ? hDatos.get("rutaTax" + i + "_source").toString()
                    : "";
            //               String idio= hDatos.get("rutaTax" + i + "_idio").toString();
            String idio = hDatos.get("rutaTax" + i + "_idio") != null
                    ? hDatos.get("rutaTax" + i + "_idio").toString()
                    : "";
            LangStringVO textFuente = new LangStringVO();
            textFuente.setTexto(source);
            textFuente.setIdioma(idio);
            FuenteVO fuente = new FuenteVO();
            LangStringVO[] textosFuentes = new LangStringVO[1];
            textosFuentes[0] = textFuente;
            fuente.setTextos(textosFuentes);//metidas las fuentes de una RutaTaxonomica

            //rutasTaxonomicas[i].setFuente(fuente);
            //ahora metemos los taxones para esa fuente
            ArrayList taxones = new ArrayList();
            for (int j = 0; j < longiTaxones[i]; j++) {
                ArrayList taxonij = new ArrayList();
                TaxonVO tax = new TaxonVO();
                EntryVO entry = new EntryVO();
                ArrayList lans = new ArrayList();

                String textoId = "";
                if (hDatos.get("rutaTax" + i + "_taxon" + j + "_Id" + 0) != null)
                    textoId = hDatos.get("rutaTax" + i + "_taxon" + j + "_Id" + 0).toString();

                IdVO id = new IdVO();
                id.setTexto(textoId);
                for (int u = 0; u < hDatos.size(); u++) {
                    LangStringVO lanvo = new LangStringVO();
                    if (hDatos.containsKey("rutaTax" + i + "_taxon" + j + "_EntryTex" + u)) {
                        String textoTax = "";
                        if (hDatos.get("rutaTax" + i + "_taxon" + j + "_EntryTex" + u) != null)
                            textoTax = hDatos.get("rutaTax" + i + "_taxon" + j + "_EntryTex" + u).toString();
                        lanvo.setTexto(textoTax);
                        String idioTax = "";
                        if (hDatos.get("rutaTax" + i + "_taxon" + j + "_EntryIdio" + u) != null)
                            idioTax = hDatos.get("rutaTax" + i + "_taxon" + j + "_EntryIdio" + u).toString();
                        lanvo.setIdioma(idioTax);
                        lans.add(lanvo); //array d langs para entryvo
                    }
                }
                //*****************
                if (lans.size() == 0) {
                    LangStringVO lanvo = new LangStringVO();
                    lanvo.setIdioma("");
                    lanvo.setTexto("");
                    lans.add(lanvo);
                }
                //*****************
                LangStringVO[] textosEnt = (LangStringVO[]) lans.toArray(new LangStringVO[lans.size()]);
                entry.setTextos(textosEnt);

                tax.setId(id);
                tax.setEntry(entry); //un Taxon
                taxones.add(tax);
            }
            TaxonVO[] rutaTaxones = (TaxonVO[]) taxones.toArray(new TaxonVO[taxones.size()]);
            rutavo.setFuente(fuente);
            rutavo.setTaxones(rutaTaxones);//tenemos una RutaTaxonomica
            arrRutaTax.add(rutavo);
        }
        rutasTaxonomicas = (RutaTaxonomicaVO[]) arrRutaTax.toArray(new RutaTaxonomicaVO[arrRutaTax.size()]);
        RutaTaxonomicaVO[] rutasTaxonomicas2 = rutaLimpia(rutasTaxonomicas);
        rutasTaxonomicas = new RutaTaxonomicaVO[rutasTaxonomicas2.length];
        rutasTaxonomicas = rutasTaxonomicas2;
    }

    //descripcion
    DescripcionVO descVO = new DescripcionVO();
    LangStringVO[] aLangDescripciones = new LangStringVO[textoDescripcion.length];
    for (int i = 0; i < textoDescripcion.length; i++) {
        LangStringVO langDescripciones = new LangStringVO();
        langDescripciones.setTexto(textoDescripcion[i]);
        langDescripciones.setIdioma(idiomaDescripcion[i]);
        aLangDescripciones[i] = langDescripciones;
    }
    descVO.setTextos(aLangDescripciones);
    descripcion = descVO;

    //palabras clave
    for (int i = 0; i < textoPalabrasClave.length; i++) {
        PalabraClaveVO pClaVO = new PalabraClaveVO();
        if (textoPalabrasClave[i] != null) {
            LangStringVO[] aLangPCla = new LangStringVO[textoPalabrasClave[i].size()];
            for (int j = 0; j < textoPalabrasClave[i].size(); j++) {
                LangStringVO langPCla = new LangStringVO();
                langPCla.setTexto(textoPalabrasClave[i].get(j).toString());
                langPCla.setIdioma(idiomaPalabrasClave[i].get(j).toString());
                aLangPCla[j] = langPCla;
            }
            pClaVO.setTextos(aLangPCla);
        } else {
            LangStringVO[] aLangString = new LangStringVO[1];
            LangStringVO langString = new LangStringVO();
            langString.setIdioma("");
            langString.setTexto("");
            aLangString[0] = langString;
            pClaVO.setTextos(aLangString);
        }
        palabrasClave[i] = pClaVO;
    }

}

From source file:gov.nih.nci.security.dao.AuthorizationDAOImpl.java

public List getObjects(SearchCriteria searchCriteria) {
    Session s = null;// w w  w.  j av a  2s  . c o  m
    List result = new ArrayList();
    try {

        s = HibernateSessionFactoryHelper.getAuditSession(sf);
        Criteria criteria = s.createCriteria(searchCriteria.getObjectType());
        Hashtable fieldValues = searchCriteria.getFieldAndValues();
        Enumeration enKeys = fieldValues.keys();
        while (enKeys.hasMoreElements()) {
            String fieldKey = (String) enKeys.nextElement();
            String fieldValue = (String) fieldValues.get(fieldKey);
            String fieldValue_ = StringUtilities.replaceInString(fieldValue.trim(), "*", "%");
            int i = fieldValue_.indexOf("%");
            if (i != -1) {
                criteria.add(Restrictions.like(fieldKey, fieldValue_));
            } else {
                criteria.add(Restrictions.eq(fieldKey, fieldValue_));
            }
        }
        if (fieldValues.size() == 0) {
            criteria.add(Restrictions.eqProperty("1", "1"));
        }
        log.debug("Message from debug: ObjectType=" + searchCriteria.getObjectType().getName());

        if (!(searchCriteria.getObjectType().getName()
                .equalsIgnoreCase("gov.nih.nci.security.authorization.domainobjects.User")
                || searchCriteria.getObjectType().getName()
                        .equalsIgnoreCase("gov.nih.nci.security.authorization.domainobjects.Privilege")
                || searchCriteria.getObjectType().getName()
                        .equalsIgnoreCase("gov.nih.nci.security.authorization.domainobjects.Application")
                || searchCriteria.getObjectType().getName().equalsIgnoreCase(
                        "gov.nih.nci.security.authorization.domainobjects.ConfigurationProperties")

        )) {
            criteria.add(Restrictions.eq("application", this.application));
        }

        List list = new ArrayList();
        list = criteria.list();
        if (searchCriteria.getObjectType().getName()
                .equalsIgnoreCase("gov.nih.nci.security.authorization.domainobjects.User")) {
            list = decryptUserInformation(list);
        }
        Collections.sort(list);
        result.clear();
        result.addAll(list);

    } catch (Exception ex) {
        ex.printStackTrace();
        if (log.isDebugEnabled())
            log.debug("Authorization|||getObjects|Failure|Error in Obtaining Search Objects from Database |"
                    + ex.getMessage());
    } finally {
        try {
            s.close();
        } catch (Exception ex2) {
            if (log.isDebugEnabled())
                log.debug("Authorization|||getObjects|Failure|Error in Closing Session |" + ex2.getMessage());
        }
    }
    if (log.isDebugEnabled())
        log.debug("Authorization|||getObjects|Success|Successful in Searching objects from the database |");
    return result;
}

From source file:gov.nih.nci.security.dao.AuthorizationDAOImpl.java

private List getObjects(Session s, SearchCriteria searchCriteria) {
    List result = new ArrayList();
    try {//  w  w w  .  j  a va2 s . c  o  m

        Criteria criteria = s.createCriteria(searchCriteria.getObjectType());
        Hashtable fieldValues = searchCriteria.getFieldAndValues();
        Enumeration en = fieldValues.keys();
        while (en.hasMoreElements()) {
            String str = (String) en.nextElement();
            String fieldValue = (String) fieldValues.get(str);
            String fieldValue_ = StringUtilities.replaceInString(fieldValue, "*", "%");
            //int i = ((String) fieldValues.get(str)).indexOf("%");
            int i = fieldValue_.indexOf("%");
            if (i != -1) {
                //criteria.add(Restrictions.like(str, fieldValues.get(str)));
                criteria.add(Restrictions.like(str, fieldValue_));
            } else {
                //criteria.add(Restrictions.eq(str, fieldValues.get(str)));
                criteria.add(Restrictions.eq(str, fieldValue_));
            }
        }
        if (fieldValues.size() == 0) {
            criteria.add(Restrictions.eqProperty("1", "1"));
        }
        log.debug("Message from debug: ObjectType=" + searchCriteria.getObjectType().getName());

        //boolean t =
        // searchCriteria.getObjectType().getName().equalsIgnoreCase("gov.nih.nci.security.authorization.domainobjects.User")||searchCriteria.getObjectType().getName().equalsIgnoreCase("gov.nih.nci.security.authorization.domainobjects.Privilege");

        //log.debug("Test:"+t);

        //if(!t){
        //   criteria.add(Restrictions.eq("application", this.application));
        //}

        if (!(searchCriteria.getObjectType().getName()
                .equalsIgnoreCase("gov.nih.nci.security.authorization.domainobjects.User")
                || searchCriteria.getObjectType().getName()
                        .equalsIgnoreCase("gov.nih.nci.security.authorization.domainobjects.Privilege")
                || searchCriteria.getObjectType().getName()
                        .equalsIgnoreCase("gov.nih.nci.security.authorization.domainobjects.Application"))) {
            criteria.add(Restrictions.eq("application", this.application));
        }

        result = criteria.list();
        Collections.sort(result);

    } catch (Exception ex) {
        ex.printStackTrace();
        if (log.isDebugEnabled())
            log.debug("Authorization|||getObjects|Failure|Error in Obtaining Search Objects from Database |"
                    + ex.getMessage());
    }
    if (log.isDebugEnabled())
        log.debug("Authorization|||getObjects|Success|Successful in Searching objects from the database |");
    return result;
}

From source file:com.crushpaper.Servlet.java

/**
 * Helper method. Adds the Markdown for an entry to an export.
 *//*www . j a  v  a 2 s .c o  m*/
private void addEntryMarkdownToExport(Entry entry, StringBuilder result, SourcesHashList sources,
        boolean includeQuotations, boolean includeReferencesSection, boolean skipThisLevel) throws IOException {

    if (!skipThisLevel) {
        final Entry source = dbLogic.getEntryById(entry.getSourceId());
        int sourceId = 0;
        if (source != null) {
            sourceId = sources.add(source);
        }

        if (includeQuotations && entry.hasQuotation()) {
            result.append(markdownBlockquote(entry.getQuotation("")));
            if (includeReferencesSection) {
                if (sourceId != 0) {
                    result.append(" [Reference" + sourceId + "] [Reference" + sourceId + "]");
                }
            }
            result.append("\n\n");
        }

        if (entry.hasNote()) {
            result.append(entry.getNote("").replace("\n", "  \n") + "\n\n");
        }
    }

    List<?> childrenFromDb = dbLogic.getEntriesByParentId(entry.getId());

    if (!childrenFromDb.isEmpty()) {
        final Hashtable<String, Entry> children = new Hashtable<String, Entry>();
        Entry first = null;
        for (final Object childObject : childrenFromDb) {
            final Entry child = (Entry) childObject;
            children.put(child.getId(), child);
            if (!child.hasPreviousSiblingId()) {
                first = child;
            }
        }

        if (first != null) {
            // This is the code path if there is no DB corruption.
            Entry child = first;
            for (int i = 0; i < children.size(); ++i) {
                if (child == null) {
                    break;
                }

                addEntryMarkdownToExport(child, result, sources, includeQuotations, includeReferencesSection,
                        false);

                if (!child.hasNextSiblingId()) {
                    break;
                }

                final String nextId = child.getNextSiblingId();
                child = children.get(nextId);
            }
        } else {
            // This is an error code path. It should only happen if there is
            // DB corruption.
            final Iterator<Map.Entry<String, Entry>> iterator = children.entrySet().iterator();
            while (iterator.hasNext()) {
                final Map.Entry<String, Entry> mapEntry = iterator.next();
                final Entry child = mapEntry.getValue();

                addEntryMarkdownToExport(child, result, sources, includeQuotations, includeReferencesSection,
                        false);
            }
        }
    }
}

From source file:com.crushpaper.Servlet.java

/**
 * Helper method. Adds the RTF for an entry to an export.
 *///ww w.  j av  a2s  .  c o m
private void addEntryRtfToExport(Entry entry, StringBuilder result, SourcesHashList sources,
        boolean includeQuotations, boolean includeReferencesSection, boolean skipThisLevel) throws IOException {

    if (!skipThisLevel) {
        final Entry source = dbLogic.getEntryById(entry.getSourceId());
        int sourceId = 0;
        if (source != null) {
            sourceId = sources.add(source);
        }

        if (includeQuotations && entry.hasQuotation()) {
            appendRtfString(result, entry.getQuotation(""));
            result.append("\\par\n");
            if (includeReferencesSection) {
                if (sourceId != 0) {
                    result.append("[Reference " + sourceId + "]\\par\n");
                }
            }
            result.append("\\par\n");
        }

        if (entry.hasNote()) {
            appendRtfString(result, entry.getNote(""));
            result.append("\\par\n\\par\n");
        }
    }

    List<?> childrenFromDb = dbLogic.getEntriesByParentId(entry.getId());

    if (!childrenFromDb.isEmpty()) {
        final Hashtable<String, Entry> children = new Hashtable<String, Entry>();
        Entry first = null;
        for (final Object childObject : childrenFromDb) {
            final Entry child = (Entry) childObject;
            children.put(child.getId(), child);
            if (!child.hasPreviousSiblingId()) {
                first = child;
            }
        }

        if (first != null) {
            // This is the code path if there is no DB corruption.
            Entry child = first;
            for (int i = 0; i < children.size(); ++i) {
                if (child == null) {
                    break;
                }

                addEntryRtfToExport(child, result, sources, includeQuotations, includeReferencesSection, false);

                if (!child.hasNextSiblingId()) {
                    break;
                }

                final String nextId = child.getNextSiblingId();
                child = children.get(nextId);
            }
        } else {
            // This is an error code path. It should only happen if there is
            // DB corruption.
            final Iterator<Map.Entry<String, Entry>> iterator = children.entrySet().iterator();
            while (iterator.hasNext()) {
                final Map.Entry<String, Entry> mapEntry = iterator.next();
                final Entry child = mapEntry.getValue();

                addEntryRtfToExport(child, result, sources, includeQuotations, includeReferencesSection, false);
            }
        }
    }
}

From source file:com.crushpaper.Servlet.java

/**
 * Helper method. Adds the HTML for an entry to an export.
 *///  www  . ja v  a2 s.  c  om
private void addEntryHtmlToExport(Entry entry, StringBuilder result, SourcesHashList sources,
        boolean asNestedLists, boolean includeQuotations, boolean includeReferencesSection,
        boolean skipThisLevel) throws IOException {

    if (!skipThisLevel) {
        if (asNestedLists) {
            result.append("<div class=\"noteAndQuotation\">\n");
        }

        final Entry source = dbLogic.getEntryById(entry.getSourceId());
        int sourceId = 0;
        if (source != null) {
            sourceId = sources.add(source);
        }

        if (includeQuotations && entry.hasQuotation()) {
            result.append("<p class=\"quotation\">");
            result.append(textToPreishHtml(entry.getQuotation(), false));

            if (includeReferencesSection) {
                if (sourceId != 0) {
                    result.append(" <a href=\"#reference" + sourceId + "\">[" + sourceId + "]</a>");
                }
            }

            result.append("</p>\n");
        }

        if (entry.hasNote()) {
            String noteHtml = textToPreishHtml(entry.getNote(), false);
            if (!noteHtml.isEmpty()) {
                result.append("<p class=\"note\">");
                result.append(noteHtml);
                result.append("</p>\n");
            }
        }
    }

    List<?> childrenFromDb = dbLogic.getEntriesByParentId(entry.getId());

    if (!childrenFromDb.isEmpty()) {
        if (asNestedLists) {
            result.append("<ol class=\"subnotes\">\n");
        }

        final Hashtable<String, Entry> children = new Hashtable<String, Entry>();
        Entry first = null;
        for (final Object childObject : childrenFromDb) {
            final Entry child = (Entry) childObject;
            children.put(child.getId(), child);
            if (!child.hasPreviousSiblingId()) {
                first = child;
            }
        }

        if (first != null) {
            // This is the code path if there is no DB corruption.
            Entry child = first;
            for (int i = 0; i < children.size(); ++i) {
                if (child == null) {
                    break;
                }

                if (asNestedLists) {
                    result.append("<li>\n");
                }

                addEntryHtmlToExport(child, result, sources, asNestedLists, includeQuotations,
                        includeReferencesSection, false);

                if (asNestedLists) {
                    result.append("</li>\n");
                }

                if (!child.hasNextSiblingId()) {
                    break;
                }

                final String nextId = child.getNextSiblingId();
                child = children.get(nextId);
            }
        } else {
            // This is an error code path. It should only happen if there is
            // DB corruption.
            final Iterator<Map.Entry<String, Entry>> iterator = children.entrySet().iterator();
            while (iterator.hasNext()) {
                final Map.Entry<String, Entry> mapEntry = iterator.next();
                final Entry child = mapEntry.getValue();

                if (asNestedLists) {
                    result.append("<li>\n");
                }

                addEntryHtmlToExport(child, result, sources, asNestedLists, includeQuotations,
                        includeReferencesSection, false);

                if (asNestedLists) {
                    result.append("</li>\n");
                }
            }
        }

        if (asNestedLists) {
            result.append("</ol>\n");
        }
    }

    if (!skipThisLevel && asNestedLists) {
        result.append("</div>\n");
    }
}

From source file:ome.formats.OMEROMetadataStoreClient.java

/**
 * Creates a temporary file on disk containing all metadata in the
 * Bio-Formats metadata hash table for the current series.
 * @param suffix String that will be appended to the end of the temporary
 * file path./*from ww  w .ja  v a2  s .  c  o  m*/
 * @return Temporary file created.
 */
private File createSeriesMetadataFile(String suffix) {
    Hashtable<?, ?> globalMetadata = reader.getGlobalMetadata();
    Hashtable<?, ?> seriesMetadata = reader.getSeriesMetadata();
    if (globalMetadata.size() == 0 && seriesMetadata.size() == 0) {
        return null;
    }
    FileOutputStream stream = null;
    OutputStreamWriter writer = null;
    try {
        File metadataFile = TempFileManager.createTempFile(ORIGINAL_METADATA_KEY, suffix);
        stream = new FileOutputStream(metadataFile);
        writer = new OutputStreamWriter(stream);
        metadataFile.deleteOnExit();
        writer.write("[GlobalMetadata]\n");
        for (Object key : globalMetadata.keySet()) {
            String s = key.toString() + "=" + globalMetadata.get(key).toString() + "\n";
            writer.write(s);
        }
        writer.write("[SeriesMetadata]\n");
        for (Object key : seriesMetadata.keySet()) {
            String s = key.toString() + "=" + seriesMetadata.get(key).toString() + "\n";
            writer.write(s);
        }
        return metadataFile;
    } catch (IOException e) {
        log.error("Unable to create series metadata file.", e);
        return null;
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
            if (stream != null) {
                stream.close();
            }
        } catch (IOException e) {
            log.error("Unable to close writer or stream.", e);
        }
    }
}

From source file:com.crushpaper.Servlet.java

/**
 * Helper method. Adds the HTML for an entry to a tree.
 */// w  w w .  j ava2  s .  com
private int addEntryHtmlToTree(Entry entry, StringBuilder result, List<EntryInfo> entryInfoList,
        int levelsOfChildrenToInclude, boolean onlyChildren, String idOfEntryToSkip,
        boolean includeRootInEntryInfoList, boolean showCheckboxes) throws IOException {
    if (!onlyChildren) {
        result.append("<div class=\"subtree\">");

        result.append("<div class=\"alone " + entry.getId() + "\" id=\"alone_" + entry.getId()
                + "\" ondragover=\"onDragOverAloneEl(event)\" ondrop=\"onDropAloneEl(event)\">");

        result.append(
                "<table class=\"nopadding alonetd\"><tr><td onmousedown=\"triangleOnMouseDown(event); return false;\" class=\"triTd justDrag\">"
                        + "<div></div></td><td>"
                        + "<table class=\"nopadding\"><tr><td class=\"nowords\"><img onmouseover=\"plusOnMouseOver(event);\" onmouseout=\"plusOnMouseOut(event);\" alt=\"plus\" title=\""
                        + servletText.plusTooltip()
                        + "\" class=\"justDrag plusOrMinus\" onmousedown=\"plusOnMouseDown(event); return false;\" src=\"/images/plus.png\"></td></tr>"
                        + "<tr><td class=\"nowords\"><img onmouseover=\"minusOnMouseOver(event);\" onmouseout=\"minusOnMouseOut(event);\" alt=\"minus\" title=\""
                        + servletText.minusTooltip()
                        + "\" class=\"justDrag plusOrMinus\" onmousedown=\"minusOnMouseDown(event); return false;\" src=\"/images/minus.png\"></td></tr></table>"
                        + "</td>");

        if (showCheckboxes) {
            result.append(
                    "<td><input type=\"checkbox\" class=\"justDrag aloneCheckbox mousetrap\" onclick=\"checkboxOnClick(event); return true;\"></td>");
        }

        result.append("<td class=\"content\">");

        if (entry.hasQuotation()) {
            result.append("<div class=\"quotation\">");
            result.append(getQuotationHtml(entry, true));
            result.append("</div><br>");
        }

        String noteHtml = getNoteHtml(entry, false, entry.hasQuotation(), true);
        if (!noteHtml.isEmpty()) {
            result.append("<div class=\"note mousetrap\">");
            result.append(noteHtml);
            result.append("</div>");
        }

        result.append("<span class=\"entryDaytime\">" + servletText.fragmentLastModified() + " "
                + "<span class=\"modTime\">" + formatDateAndTime(entry.getModTime())
                + "<span class=\"rawDateTime\">" + entry.getModTime() + "</span></span></span>");

        final Entry source = dbLogic.getEntryById(entry.getSourceId());
        if (source != null) {
            addSourceHtml(source, result, SourceEmbedContext.InQuotation, null, -1, null);
        }

        // Good for debugging.
        if (false) {
            result.append("<br>id: " + entry.getId());
            result.append("<br>parent: " + entry.getParentId(""));
            result.append("<br>first child: " + entry.getFirstChildId(""));
            result.append("<br>last child: " + entry.getLastChildId(""));
            result.append("<br>previous sibling: " + entry.getPreviousSiblingId(""));
            result.append("<br>next sibling: " + entry.getNextSiblingId(""));
        }

        result.append("</td></tr></table></div>");
        result.append("<div class=\"justchildren\">");
    }

    if (includeRootInEntryInfoList) {
        addEntryToInfoList(entry, entryInfoList);
    }

    int indexOfEntryToSkip = -1;
    if (levelsOfChildrenToInclude > 0) {
        --levelsOfChildrenToInclude;

        final Hashtable<String, Entry> children = new Hashtable<String, Entry>();
        Entry first = null;
        for (final Object childObject : dbLogic.getEntriesByParentId(entry.getId())) {
            final Entry child = (Entry) childObject;
            children.put(child.getId(), child);
            if (!child.hasPreviousSiblingId()) {
                first = child;
            }
        }

        if (first != null) {
            // This is the code path if there is no DB corruption.
            Entry child = first;
            for (int i = 0; i < children.size(); ++i) {
                if (child == null) {
                    break;
                }

                if (idOfEntryToSkip != null && idOfEntryToSkip.equals(child.getId())) {
                    indexOfEntryToSkip = i;
                } else {
                    addEntryHtmlToTree(child, result, entryInfoList, levelsOfChildrenToInclude, false, null,
                            true, showCheckboxes);
                }

                if (!child.hasNextSiblingId()) {
                    break;
                }

                final String nextId = child.getNextSiblingId();
                child = children.get(nextId);
            }
        } else {
            // This is an error code path. It should only happen if there is
            // DB corruption.
            final Iterator<Map.Entry<String, Entry>> iterator = children.entrySet().iterator();
            int i = 0;
            while (iterator.hasNext()) {
                final Map.Entry<String, Entry> mapEntry = iterator.next();
                final Entry child = mapEntry.getValue();

                if (idOfEntryToSkip != null && idOfEntryToSkip.equals(child.getId())) {
                    indexOfEntryToSkip = i;
                } else {
                    addEntryHtmlToTree(child, result, entryInfoList, levelsOfChildrenToInclude, false, null,
                            true, showCheckboxes);
                }

                ++i;
            }
        }
    }

    if (!onlyChildren) {
        result.append("</div>");
        result.append("</div>");
    }

    return indexOfEntryToSkip;
}

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

private void load(org.hibernate.Session hibSession) throws Exception {
    iProgress.setStatus("Loading input data ...");

    TravelTime.populateTravelTimes(getModel().getDistanceMetric(), iSessionId, hibSession);

    iSolverGroup = null;//from  w w w.  j  a v a2s.c o  m
    iSession = null;

    if (iSolverGroup == null) {
        iSolverGroup = new SolverGroup[iSolverGroupId.length];
        for (int i = 0; i < iSolverGroupId.length; i++) {
            iSolverGroup[i] = SolverGroupDAO.getInstance().get(iSolverGroupId[i], hibSession);
            if (iSolverGroup[i] == null) {
                iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL),
                        "Unable to load solver group " + iSolverGroupId[i] + ".");
                return;
            }
            iProgress.debug("solver group[" + (i + 1) + "]: " + iSolverGroup[i].getName());
        }
    }
    if (iSolverGroup == null || iSolverGroup.length == 0) {
        iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "No solver group loaded.");
        return;
    }

    iDepartmentIds = "";
    for (int j = 0; j < iSolverGroup.length; j++) {
        for (Iterator i = iSolverGroup[j].getDepartments().iterator(); i.hasNext();) {
            Department d = (Department) i.next();
            if (iDepartmentIds.length() > 0)
                iDepartmentIds += ",";
            iDepartmentIds += d.getUniqueId().toString();
        }
    }
    getModel().getProperties().setProperty("General.DepartmentIds", iDepartmentIds);

    Hashtable<Long, Solution> solutions = null;
    if (iSolutionId != null && iSolutionId.length > 0) {
        solutions = new Hashtable<Long, Solution>();
        String note = "";
        for (int i = 0; i < iSolutionId.length; i++) {
            Solution solution = (new SolutionDAO()).get(iSolutionId[i], hibSession);
            if (solution == null) {
                iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL),
                        "Unable to load solution " + iSolutionId[i] + ".");
                return;
            }
            iProgress.debug("solution[" + (i + 1) + "] version: " + solution.getUniqueId() + " (created "
                    + solution.getCreated() + ", solver group " + solution.getOwner().getName() + ")");
            if (solution.getNote() != null) {
                if (note.length() > 0)
                    note += "\n";
                note += solution.getNote();
            }
            solutions.put(solution.getOwner().getUniqueId(), solution);
        }
        getModel().getProperties().setProperty("General.Note", note);
        String solutionIdStr = "";
        for (int i = 0; i < iSolverGroupId.length; i++) {
            Solution solution = solutions.get(iSolverGroupId[i]);
            if (solution != null) {
                if (solutionIdStr.length() > 0)
                    solutionIdStr += ",";
                solutionIdStr += solution.getUniqueId().toString();
            }
        }
        getModel().getProperties().setProperty("General.SolutionId", solutionIdStr);
    }

    if (iSession == null)
        iSession = (new SessionDAO()).get(iSessionId, hibSession);
    if (iSession == null) {
        iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "No session loaded.");
        return;
    }
    iProgress.debug("session: " + iSession.getLabel());

    getModel().getProperties().setProperty("Data.Term", iSession.getAcademicYearTerm());
    getModel().getProperties().setProperty("Data.Initiative", iSession.getAcademicInitiative());
    getModel().setYear(iSession.getSessionStartYear());
    getModel().getProperties().setProperty("DatePattern.DayOfWeekOffset", String.valueOf(Constants.getDayOfWeek(
            DateUtils.getDate(1, iSession.getPatternStartMonth(), iSession.getSessionStartYear()))));
    if (iSession.getDefaultDatePattern() != null) {
        BitSet pattern = iSession.getDefaultDatePattern().getPatternBitSet();
        String patternStr = "";
        for (int i = 0; i < pattern.length(); i++)
            patternStr += (pattern.get(i) ? "1" : "0");
        getModel().getProperties().setProperty("DatePattern.Default", patternStr);
    }

    iAllClasses = new TreeSet(new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY));
    for (int i = 0; i < iSolverGroup.length; i++) {
        for (Iterator j = iSolverGroup[i].getDepartments().iterator(); j.hasNext();) {
            Department d = (Department) j.next();
            iAllClasses.addAll(d.getClassesFetchWithStructure());
        }
    }
    if (iAllClasses == null || iAllClasses.isEmpty()) {
        iProgress.message(msglevel("noClasses", Progress.MSGLEVEL_FATAL), "No classes to load.");
        return;
    }
    iProgress.debug("classes to load: " + iAllClasses.size());

    iProgress.setPhase("Loading classes ...", iAllClasses.size());
    int ord = 0;
    HashSet<SchedulingSubpart> subparts = new HashSet<SchedulingSubpart>();
    for (Iterator i1 = iAllClasses.iterator(); i1.hasNext();) {
        Class_ clazz = (Class_) i1.next();
        Lecture lecture = loadClass(clazz, hibSession);
        subparts.add(clazz.getSchedulingSubpart());
        if (lecture != null)
            lecture.setOrd(ord++);
        iClasses.put(clazz.getUniqueId(), clazz);
        iProgress.incProgress();
    }

    loadInstructorAvailabilities(hibSession);

    loadRoomAvailabilities(hibSession);

    iProgress.setPhase("Loading offerings ...", iAllClasses.size());
    Set<Long> loadedOfferings = new HashSet<Long>();
    for (Class_ clazz : iAllClasses) {
        Lecture lecture = (Lecture) iLectures.get(clazz.getUniqueId());
        iProgress.incProgress();

        if (lecture == null)
            continue; //skip classes that were not loaded

        InstructionalOffering offering = clazz.getSchedulingSubpart().getInstrOfferingConfig()
                .getInstructionalOffering();
        if (!loadedOfferings.add(offering.getUniqueId()))
            continue; // already loaded

        iOfferings.put(offering, loadOffering(offering, false));
    }

    List<DistributionPref> distPrefs = new ArrayList<DistributionPref>();
    for (int i = 0; i < iSolverGroup.length; i++) {
        distPrefs.addAll(iSolverGroup[i].getDistributionPreferences());
    }
    iProgress.setPhase("Loading distribution preferences ...", distPrefs.size());
    for (Iterator i = distPrefs.iterator(); i.hasNext();) {
        DistributionPref distributionPref = (DistributionPref) i.next();
        if (!PreferenceLevel.sNeutral.equals(distributionPref.getPrefLevel().getPrefProlog()))
            loadGroupConstraint(distributionPref);
        iProgress.incProgress();
    }

    Set<Long> checkedDistPrefIds = new HashSet<Long>();
    for (int i = 0; i < iSolverGroup.length; i++) {
        for (Iterator j = iSolverGroup[i].getDepartments().iterator(); j.hasNext();) {
            loadInstructorGroupConstraints((Department) j.next(), checkedDistPrefIds, hibSession);
        }
    }

    if (iAutoSameStudents) {
        iProgress.setPhase("Posting automatic same_students constraints ...", iAllClasses.size());
        for (Iterator i1 = iAllClasses.iterator(); i1.hasNext();) {
            Class_ clazz = (Class_) i1.next();
            Lecture lecture = (Lecture) iLectures.get(clazz.getUniqueId());
            if (lecture == null)
                continue;

            if (!lecture.hasAnyChildren())
                postSameStudentConstraint(clazz, iAutoSameStudentsConstraint);

            iProgress.incProgress();
        }
    }

    if (iAutoPrecedence != null) {
        PreferenceLevel pref = PreferenceLevel.getPreferenceLevel(iAutoPrecedence);
        if (pref == null) { // Lookup preference if needed
            for (PreferenceLevel p : PreferenceLevel.getPreferenceLevelList())
                if (iAutoPrecedence.equalsIgnoreCase(p.getPrefProlog())
                        || iAutoPrecedence.equalsIgnoreCase(p.getPrefName())
                        || iAutoPrecedence.equals(p.getAbbreviation())) {
                    pref = p;
                    break;
                }
        }
        if (pref == null) {
            iProgress.message(msglevel("autoPrecedence", Progress.MSGLEVEL_WARN),
                    "Preference " + iAutoPrecedence + " not recognized.");
        } else if (!PreferenceLevel.sNeutral.equals(pref.getPrefProlog())) {
            iProgress.setPhase("Posting automatic precedence constraints ...", iAllClasses.size());
            for (Iterator i1 = iAllClasses.iterator(); i1.hasNext();) {
                Class_ clazz = (Class_) i1.next();
                Lecture lecture = (Lecture) iLectures.get(clazz.getUniqueId());
                if (lecture == null)
                    continue;

                if (!lecture.hasAnyChildren())
                    postPrecedenceConstraint(clazz, pref.getPrefProlog());

                iProgress.incProgress();
            }
        }
    }

    postAutomaticHierarchicalConstraints();

    assignCommited();

    iProgress.setPhase("Posting class limit constraints ...", iOfferings.size());
    for (Map.Entry<InstructionalOffering, Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>>> entry : iOfferings
            .entrySet()) {
        Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>> topSubparts = entry.getValue();
        for (Map.Entry<InstrOfferingConfig, Set<SchedulingSubpart>> subpartEntry : topSubparts.entrySet()) {
            InstrOfferingConfig config = subpartEntry.getKey();
            Set<SchedulingSubpart> topSubpartsThisConfig = subpartEntry.getValue();
            for (SchedulingSubpart subpart : topSubpartsThisConfig) {

                boolean isMakingSense = false;
                for (Class_ clazz : subpart.getClasses()) {
                    Lecture lecture = iLectures.get(clazz.getUniqueId());
                    if (lecture == null)
                        continue;
                    createChildrenClassLimitConstraits(lecture);
                    if (!lecture.isCommitted() && lecture.minClassLimit() != lecture.maxClassLimit())
                        isMakingSense = true;
                }

                if (!isMakingSense)
                    continue;

                if (subpart.getParentSubpart() == null) {

                    ClassLimitConstraint clc = new ClassLimitConstraint(config.getLimit(),
                            getClassLimitConstraitName(subpart));

                    for (Class_ clazz : subpart.getClasses()) {
                        Lecture lecture = iLectures.get(clazz.getUniqueId());
                        if (lecture == null || lecture.isCommitted()) {
                            clc.setClassLimitDelta(clc.getClassLimitDelta() - clazz.getClassLimit());
                            continue;
                        }
                        clc.addVariable(lecture);
                    }

                    if (clc.variables().isEmpty())
                        continue;

                    iProgress.trace("Added constraint " + clc.getName() + " between " + clc.variables());
                    getModel().addConstraint(clc);

                } else {

                    Hashtable<Long, ClassLimitConstraint> clcs = new Hashtable<Long, ClassLimitConstraint>();

                    for (Class_ clazz : subpart.getClasses()) {
                        Lecture lecture = iLectures.get(clazz.getUniqueId());

                        Class_ parentClazz = clazz.getParentClass();

                        ClassLimitConstraint clc = clcs.get(parentClazz.getUniqueId());
                        if (clc == null) {
                            clc = new ClassLimitConstraint(parentClazz.getClassLimit(),
                                    parentClazz.getClassLabel());
                            clcs.put(parentClazz.getUniqueId(), clc);
                        }

                        if (lecture == null || lecture.isCommitted()) {
                            clc.setClassLimitDelta(clc.getClassLimitDelta() - clazz.getClassLimit());
                        } else {
                            clc.addVariable(lecture);
                        }
                    }
                    for (ClassLimitConstraint clc : clcs.values()) {
                        if (!clc.variables().isEmpty()) {
                            iProgress
                                    .trace("Added constraint " + clc.getName() + " between " + clc.variables());
                            getModel().addConstraint(clc);
                        }
                    }
                }

            }
        }
        iProgress.incProgress();
    }

    iStudentCourseDemands.init(hibSession, iProgress, iSession, iOfferings.keySet());

    iProgress.setPhase("Loading students ...", iOfferings.size());
    for (InstructionalOffering offering : iOfferings.keySet()) {

        boolean unlimitedOffering = false;
        int offeringLimit = 0;
        for (InstrOfferingConfig config : offering.getInstrOfferingConfigs())
            if (config.isUnlimitedEnrollment())
                unlimitedOffering = true;
            else
                offeringLimit += config.getLimit();

        Double factor = null;
        if (!unlimitedOffering) {
            int totalCourseLimit = 0;

            for (CourseOffering course : offering.getCourseOfferings()) {
                int courseLimit = -1;
                if (course.getReservation() != null)
                    courseLimit = course.getReservation();
                if (courseLimit < 0) {
                    if (offering.getCourseOfferings().size() == 1)
                        courseLimit = offeringLimit;
                    else {
                        iProgress.message(msglevel("crossListWithoutReservation", Progress.MSGLEVEL_INFO),
                                "Cross-listed course " + getOfferingLabel(course)
                                        + " does not have any course reservation.");
                        if (course.getProjectedDemand() != null && offering.getProjectedDemand() > 0)
                            courseLimit = course.getProjectedDemand();
                        else if (course.getDemand() != null && offering.getDemand() > 0)
                            courseLimit = course.getDemand();
                        else
                            courseLimit = offeringLimit / offering.getCourseOfferings().size();
                    }
                }

                totalCourseLimit += courseLimit;
            }

            if (totalCourseLimit < offeringLimit)
                iProgress.message(
                        msglevel("courseReservationsBelowLimit",
                                totalCourseLimit == 0 ? Progress.MSGLEVEL_INFO : Progress.MSGLEVEL_WARN),
                        "Total number of course reservations is below the offering limit for instructional offering "
                                + getOfferingLabel(offering) + " (" + totalCourseLimit + "<" + offeringLimit
                                + ").");

            if (totalCourseLimit > offeringLimit)
                iProgress.message(msglevel("courseReservationsOverLimit", Progress.MSGLEVEL_INFO),
                        "Total number of course reservations exceeds the offering limit for instructional offering "
                                + getOfferingLabel(offering) + " (" + totalCourseLimit + ">" + offeringLimit
                                + ").");

            if (totalCourseLimit == 0)
                continue;

            if (totalCourseLimit != offeringLimit)
                factor = new Double(((double) offeringLimit) / totalCourseLimit);
        }

        for (CourseOffering course : offering.getCourseOfferings()) {
            Set<WeightedStudentId> studentIds = iStudentCourseDemands.getDemands(course);

            float studentWeight = 0.0f;
            if (studentIds != null)
                for (WeightedStudentId studentId : studentIds)
                    studentWeight += studentId.getWeight();

            int courseLimit = -1;
            if (course.getReservation() != null)
                courseLimit = course.getReservation();
            if (courseLimit < 0) {
                if (offering.getCourseOfferings().size() == 1 && !unlimitedOffering)
                    courseLimit = offeringLimit;
                else {
                    courseLimit = Math.round(studentWeight);
                }
            }

            if (factor != null)
                courseLimit = (int) Math.round(courseLimit * factor);

            if (studentIds == null || studentIds.isEmpty()) {
                iProgress.message(msglevel("offeringWithoutDemand", Progress.MSGLEVEL_INFO),
                        "No student enrollments for course " + getOfferingLabel(course) + ".");
                continue;
            }

            if (courseLimit == 0 && offering.getCourseOfferings().size() > 1) {
                iProgress.message(msglevel("noCourseReservation", Progress.MSGLEVEL_WARN),
                        "No reserved space for students of course " + getOfferingLabel(course) + ".");
            }

            double weight = (iStudentCourseDemands.isWeightStudentsToFillUpOffering() && courseLimit != 0
                    ? (double) courseLimit / studentWeight
                    : 1.0);

            Set<Lecture> cannotAttendLectures = null;

            if (offering.getCourseOfferings().size() > 1) {

                Set<Long> reservedClasses = new HashSet<Long>();
                int limit = 0;
                boolean unlimited = false;

                for (Reservation r : offering.getReservations()) {
                    if (r instanceof CourseReservation && course.equals(((CourseReservation) r).getCourse())) {
                        for (Class_ clazz : r.getClasses()) {
                            limit += clazz.getMaxExpectedCapacity();
                            propagateReservedClasses(clazz, reservedClasses);
                            Class_ parent = clazz.getParentClass();
                            while (parent != null) {
                                reservedClasses.add(parent.getUniqueId());
                                parent = parent.getParentClass();
                            }
                        }
                        for (InstrOfferingConfig config : r.getConfigurations()) {
                            if (config.isUnlimitedEnrollment())
                                unlimited = true;
                            else
                                limit += config.getLimit();
                            for (SchedulingSubpart subpart : config.getSchedulingSubparts())
                                for (Class_ clazz : subpart.getClasses())
                                    reservedClasses.add(clazz.getUniqueId());
                        }
                    }
                }

                if (!reservedClasses.isEmpty()) {
                    iProgress.debug("Course requests for course " + getOfferingLabel(course) + " are "
                            + reservedClasses);
                    if (!unlimited && courseLimit > limit)
                        iProgress.message(msglevel("insufficientCourseReservation", Progress.MSGLEVEL_WARN),
                                "Too little space reserved in for course " + getOfferingLabel(course) + " ("
                                        + limit + "<" + courseLimit + ").");
                    cannotAttendLectures = new HashSet<Lecture>();
                    for (InstrOfferingConfig config : course.getInstructionalOffering()
                            .getInstrOfferingConfigs()) {
                        boolean hasConfigReservation = false;
                        subparts: for (SchedulingSubpart subpart : config.getSchedulingSubparts())
                            for (Class_ clazz : subpart.getClasses())
                                if (reservedClasses.contains(clazz.getUniqueId())) {
                                    hasConfigReservation = true;
                                    break subparts;
                                }
                        for (SchedulingSubpart subpart : config.getSchedulingSubparts()) {
                            boolean hasSubpartReservation = false;
                            for (Class_ clazz : subpart.getClasses())
                                if (reservedClasses.contains(clazz.getUniqueId())) {
                                    hasSubpartReservation = true;
                                    break;
                                }
                            // !hasConfigReservation >> all lectures are cannot attend (there is a reservation on a different config)
                            // otherwise if !hasSubpartReservation >> there is reservation on some other subpoart --> can attend any of the classes of this subpart
                            if (!hasConfigReservation || hasSubpartReservation)
                                for (Class_ clazz : subpart.getClasses()) {
                                    if (reservedClasses.contains(clazz.getUniqueId()))
                                        continue;
                                    Lecture lecture = iLectures.get(clazz.getUniqueId());
                                    if (lecture != null && !lecture.isCommitted())
                                        cannotAttendLectures.add(lecture);
                                }
                        }
                    }
                    if (!cannotAttendLectures.isEmpty()) {
                        iProgress.debug("Prohibited lectures for course " + getOfferingLabel(course) + " are "
                                + cannotAttendLectures);
                        checkReservation(course, cannotAttendLectures, iAltConfigurations.get(offering));
                    }
                }
            }

            for (WeightedStudentId studentId : studentIds) {
                Student student = iStudents.get(studentId.getStudentId());
                if (student == null) {
                    student = new Student(studentId.getStudentId());
                    student.setAcademicArea(studentId.getArea());
                    student.setAcademicClassification(studentId.getClasf());
                    student.setMajor(studentId.getMajor());
                    student.setCurriculum(studentId.getCurriculum());
                    getModel().addStudent(student);
                    iStudents.put(studentId.getStudentId(), student);
                }
                student.addOffering(offering.getUniqueId(), weight * studentId.getWeight(),
                        iStudentCourseDemands.getEnrollmentPriority(studentId.getStudentId(),
                                course.getUniqueId()));

                Set<Student> students = iCourse2students.get(course);
                if (students == null) {
                    students = new HashSet<Student>();
                    iCourse2students.put(course, students);
                }
                students.add(student);

                student.addCanNotEnroll(offering.getUniqueId(), cannotAttendLectures);

                Set<Long> reservedClasses = new HashSet<Long>();
                for (Reservation reservation : offering.getReservations()) {
                    if (reservation.getClasses().isEmpty() && reservation.getConfigurations().isEmpty())
                        continue;
                    if (reservation instanceof CourseReservation)
                        continue;
                    if (reservation instanceof CurriculumReservation) {
                        CurriculumReservation cr = (CurriculumReservation) reservation;
                        if (studentId.getArea() == null)
                            continue;
                        if (!studentId.hasArea(cr.getArea().getAcademicAreaAbbreviation()))
                            continue;
                        if (!cr.getClassifications().isEmpty()) {
                            boolean match = false;
                            for (AcademicClassification clasf : cr.getClassifications()) {
                                if (studentId.hasClassification(cr.getArea().getAcademicAreaAbbreviation(),
                                        clasf.getCode())) {
                                    match = true;
                                    break;
                                }
                            }
                            if (!match)
                                continue;
                        }
                        if (!cr.getMajors().isEmpty()) {
                            if (studentId.getMajor() == null)
                                continue;
                            boolean match = false;
                            for (PosMajor major : cr.getMajors()) {
                                if (studentId.hasMajor(cr.getArea().getAcademicAreaAbbreviation(),
                                        major.getCode())) {
                                    match = true;
                                    break;
                                }
                            }
                            if (!match)
                                continue;
                        }
                    } else
                        continue;
                    for (Class_ clazz : reservation.getClasses()) {
                        propagateReservedClasses(clazz, reservedClasses);
                        Class_ parent = clazz.getParentClass();
                        while (parent != null) {
                            reservedClasses.add(parent.getUniqueId());
                            parent = parent.getParentClass();
                        }
                    }
                    for (InstrOfferingConfig config : reservation.getConfigurations()) {
                        for (SchedulingSubpart subpart : config.getSchedulingSubparts())
                            for (Class_ clazz : subpart.getClasses())
                                reservedClasses.add(clazz.getUniqueId());
                    }
                }

                if (!reservedClasses.isEmpty()) {
                    iProgress.debug(course.getCourseName() + ": Student " + student.getId()
                            + " has reserved classes " + reservedClasses);
                    Set<Lecture> prohibited = new HashSet<Lecture>();
                    for (InstrOfferingConfig config : course.getInstructionalOffering()
                            .getInstrOfferingConfigs()) {
                        boolean hasConfigReservation = false;
                        subparts: for (SchedulingSubpart subpart : config.getSchedulingSubparts())
                            for (Class_ clazz : subpart.getClasses())
                                if (reservedClasses.contains(clazz.getUniqueId())) {
                                    hasConfigReservation = true;
                                    break subparts;
                                }
                        for (SchedulingSubpart subpart : config.getSchedulingSubparts()) {
                            boolean hasSubpartReservation = false;
                            for (Class_ clazz : subpart.getClasses())
                                if (reservedClasses.contains(clazz.getUniqueId())) {
                                    hasSubpartReservation = true;
                                    break;
                                }
                            // !hasConfigReservation >> all lectures are cannot attend (there is a reservation on a different config)
                            // otherwise if !hasSubpartReservation >> there is reservation on some other subpoart --> can attend any of the classes of this subpart
                            if (!hasConfigReservation || hasSubpartReservation)
                                for (Class_ clazz : subpart.getClasses()) {
                                    if (reservedClasses.contains(clazz.getUniqueId()))
                                        continue;
                                    Lecture lecture = iLectures.get(clazz.getUniqueId());
                                    if (lecture != null && !lecture.isCommitted())
                                        prohibited.add(lecture);
                                }
                        }
                    }
                    iProgress.debug(course.getCourseName() + ": Student " + student.getId()
                            + " cannot attend classes " + prohibited);
                    student.addCanNotEnroll(offering.getUniqueId(), prohibited);
                }
            }
        }

        iProgress.incProgress();
    }
    iProgress.debug(iStudents.size() + " students loaded.");

    if (!hibSession.isOpen())
        iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open.");

    if (iCommittedStudentConflictsMode == CommittedStudentConflictsMode.Load
            && !iStudentCourseDemands.isMakingUpStudents())
        loadCommittedStudentConflicts(hibSession, loadedOfferings);
    else if (iCommittedStudentConflictsMode != CommittedStudentConflictsMode.Ignore)
        makeupCommittedStudentConflicts(loadedOfferings);

    if (!hibSession.isOpen())
        iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open.");

    Hashtable<Student, Set<Lecture>> iPreEnrollments = new Hashtable<Student, Set<Lecture>>();
    if (iLoadStudentEnrlsFromSolution) {
        if (iStudentCourseDemands.canUseStudentClassEnrollmentsAsSolution()) {
            // Load real student enrollments (not saved last-like)
            List<Object[]> enrollments = (List<Object[]>) hibSession
                    .createQuery("select distinct e.student.uniqueId, e.clazz.uniqueId from "
                            + "StudentClassEnrollment e, Class_ c where "
                            + "e.courseOffering.instructionalOffering = c.schedulingSubpart.instrOfferingConfig.instructionalOffering and "
                            + "c.managingDept.solverGroup.uniqueId in (" + iSolverGroupIds + ")")
                    .list();
            iProgress.setPhase("Loading current student enrolments  ...", enrollments.size());
            int totalEnrollments = 0;
            for (Object[] o : enrollments) {
                Long studentId = (Long) o[0];
                Long clazzId = (Long) o[1];

                Student student = (Student) iStudents.get(studentId);
                if (student == null)
                    continue;

                Lecture lecture = (Lecture) iLectures.get(clazzId);
                if (lecture != null) {

                    Set<Lecture> preEnrollments = iPreEnrollments.get(student);
                    if (preEnrollments == null) {
                        preEnrollments = new HashSet<Lecture>();
                        iPreEnrollments.put(student, preEnrollments);
                    }
                    preEnrollments.add(lecture);

                    if (student.hasOffering(lecture.getConfiguration().getOfferingId())
                            && student.canEnroll(lecture)) {
                        student.addLecture(lecture);
                        lecture.addStudent(getAssignment(), student);
                        totalEnrollments++;
                    }
                }

                iProgress.incProgress();
            }
            iProgress.message(msglevel("enrollmentsLoaded", Progress.MSGLEVEL_INFO),
                    "Loaded " + totalEnrollments + " enrollments of " + iPreEnrollments.size() + " students.");
        } else {
            // Load enrollments from selected / committed solutions
            for (int idx = 0; idx < iSolverGroupId.length; idx++) {
                Solution solution = (solutions == null ? null : solutions.get(iSolverGroupId[idx]));
                List studentEnrls = null;
                if (solution != null) {
                    studentEnrls = hibSession.createQuery(
                            "select distinct e.studentId, e.clazz.uniqueId from StudentEnrollment e where e.solution.uniqueId=:solutionId")
                            .setLong("solutionId", solution.getUniqueId()).list();
                } else {
                    studentEnrls = hibSession.createQuery(
                            "select distinct e.studentId, e.clazz.uniqueId from StudentEnrollment e where e.solution.owner.uniqueId=:sovlerGroupId and e.solution.commited = true")
                            .setLong("sovlerGroupId", iSolverGroupId[idx]).list();
                }
                iProgress.setPhase("Loading student enrolments [" + (idx + 1) + "] ...", studentEnrls.size());
                for (Iterator i1 = studentEnrls.iterator(); i1.hasNext();) {
                    Object o[] = (Object[]) i1.next();
                    Long studentId = (Long) o[0];
                    Long clazzId = (Long) o[1];

                    Student student = (Student) iStudents.get(studentId);
                    if (student == null)
                        continue;

                    Lecture lecture = (Lecture) iLectures.get(clazzId);
                    if (lecture != null && lecture.getConfiguration() != null) {
                        Set<Lecture> preEnrollments = iPreEnrollments.get(student);
                        if (preEnrollments == null) {
                            preEnrollments = new HashSet<Lecture>();
                            iPreEnrollments.put(student, preEnrollments);
                        }
                        preEnrollments.add(lecture);

                        if (student.hasOffering(lecture.getConfiguration().getOfferingId())
                                && student.canEnroll(lecture)) {
                            student.addLecture(lecture);
                            lecture.addStudent(getAssignment(), student);
                        }
                    }

                    iProgress.incProgress();
                }
            }

            if (getModel().getProperties().getPropertyBoolean("Global.LoadOtherCommittedStudentEnrls", true)) {
                // Other committed enrollments
                List<Object[]> enrollments = (List<Object[]>) hibSession
                        .createQuery("select distinct e.studentId, e.clazz.uniqueId from "
                                + "StudentEnrollment e, Class_ c where "
                                + "e.solution.commited = true and e.solution.owner.uniqueId not in ("
                                + iSolverGroupIds + ") and "
                                + "e.clazz.schedulingSubpart.instrOfferingConfig.instructionalOffering = c.schedulingSubpart.instrOfferingConfig.instructionalOffering and "
                                + "c.managingDept.solverGroup.uniqueId in (" + iSolverGroupIds + ")")
                        .list();
                iProgress.setPhase("Loading other committed student enrolments  ...", enrollments.size());

                for (Object[] o : enrollments) {
                    Long studentId = (Long) o[0];
                    Long clazzId = (Long) o[1];

                    Student student = (Student) iStudents.get(studentId);
                    if (student == null)
                        continue;

                    Lecture lecture = (Lecture) iLectures.get(clazzId);
                    if (lecture != null && lecture.getConfiguration() != null) {

                        Set<Lecture> preEnrollments = iPreEnrollments.get(student);
                        if (preEnrollments == null) {
                            preEnrollments = new HashSet<Lecture>();
                            iPreEnrollments.put(student, preEnrollments);
                        }
                        preEnrollments.add(lecture);

                        if (student.hasOffering(lecture.getConfiguration().getOfferingId())
                                && student.canEnroll(lecture)) {
                            student.addLecture(lecture);
                            lecture.addStudent(getAssignment(), student);
                        }
                    }

                    iProgress.incProgress();
                }
            }
        }
    }

    if (!hibSession.isOpen())
        iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open.");

    RoomAvailabilityInterface availability = null;
    if (SolverServerImplementation.getInstance() != null)
        availability = SolverServerImplementation.getInstance().getRoomAvailability();
    else
        availability = RoomAvailability.getInstance();
    if (availability != null) {
        Date[] startEnd = initializeRoomAvailability(availability);
        if (startEnd != null) {
            loadRoomAvailability(availability, startEnd);
            loadInstructorAvailability(availability, startEnd);
        }
    }

    if (!hibSession.isOpen())
        iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open.");

    iProgress.setPhase("Initial sectioning ...", iOfferings.size());
    for (InstructionalOffering offering : iOfferings.keySet()) {
        Set<Student> students = new HashSet<Student>();
        for (CourseOffering course : offering.getCourseOfferings()) {
            Set<Student> courseStudents = iCourse2students.get(course);
            if (courseStudents != null)
                students.addAll(courseStudents);
        }
        if (students.isEmpty())
            continue;

        getModel().getStudentSectioning().initialSectioning(getAssignment(), offering.getUniqueId(),
                offering.getCourseName(), students, iAltConfigurations.get(offering));

        iProgress.incProgress();
    }

    for (Enumeration e = iStudents.elements(); e.hasMoreElements();) {
        ((Student) e.nextElement()).clearDistanceCache();
    }

    if (!iPreEnrollments.isEmpty()) {
        iProgress.setPhase("Checking loaded enrollments ....", iPreEnrollments.size());
        for (Map.Entry<Student, Set<Lecture>> entry : iPreEnrollments.entrySet()) {
            iProgress.incProgress();
            Student student = entry.getKey();
            Set<Lecture> lectures = entry.getValue();
            for (Lecture lecture : lectures) {
                if (!lecture.students().contains(student)) {
                    iProgress.message(msglevel("studentNotEnrolled", Progress.MSGLEVEL_WARN), "Student "
                            + student.getId() + " is supposed to be enrolled to " + getClassLabel(lecture));
                }
            }
            for (Lecture lecture : student.getLectures()) {
                if (!lectures.contains(lecture)) {
                    Lecture instead = null;
                    if (lecture.sameStudentsLectures() != null) {
                        for (Lecture other : lecture.sameStudentsLectures()) {
                            if (lectures.contains(other))
                                instead = other;
                        }
                    }
                    if (instead != null)
                        iProgress.message(msglevel("studentEnrolled", Progress.MSGLEVEL_WARN),
                                "Student " + student.getId() + " is NOT supposed to be enrolled to "
                                        + getClassLabel(lecture) + ", he/she should have "
                                        + getClassLabel(instead) + " instead.");
                    else
                        iProgress.message(msglevel("studentEnrolled", Progress.MSGLEVEL_INFO),
                                "Student " + student.getId() + " is NOT supposed to be enrolled to "
                                        + getClassLabel(lecture) + ".");
                }
            }
        }
    }

    if (!hibSession.isOpen())
        iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open.");

    if (iLoadStudentInstructorConflicts)
        loadInstructorStudentConflicts(hibSession);

    iProgress.setPhase("Computing jenrl ...", iStudents.size());
    Hashtable jenrls = new Hashtable();
    for (Iterator i1 = iStudents.values().iterator(); i1.hasNext();) {
        Student st = (Student) i1.next();
        for (Iterator i2 = st.getLectures().iterator(); i2.hasNext();) {
            Lecture l1 = (Lecture) i2.next();
            for (Iterator i3 = st.getLectures().iterator(); i3.hasNext();) {
                Lecture l2 = (Lecture) i3.next();
                if (l1.getId() >= l2.getId())
                    continue;
                Hashtable x = (Hashtable) jenrls.get(l1);
                if (x == null) {
                    x = new Hashtable();
                    jenrls.put(l1, x);
                }
                JenrlConstraint jenrl = (JenrlConstraint) x.get(l2);
                if (jenrl == null) {
                    jenrl = new JenrlConstraint();
                    getModel().addConstraint(jenrl);
                    jenrl.addVariable(l1);
                    jenrl.addVariable(l2);
                    x.put(l2, jenrl);
                }
                jenrl.incJenrl(getAssignment(), st);
            }
        }
        iProgress.incProgress();
    }

    if (!hibSession.isOpen())
        iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open.");

    if (solutions != null) {
        for (int idx = 0; idx < iSolverGroupId.length; idx++) {
            Solution solution = (Solution) solutions.get(iSolverGroupId[idx]);
            if (solution == null)
                continue;
            iProgress.setPhase("Creating initial assignment [" + (idx + 1) + "] ...",
                    solution.getAssignments().size());
            for (Iterator i1 = solution.getAssignments().iterator(); i1.hasNext();) {
                Assignment assignment = (Assignment) i1.next();
                loadAssignment(assignment);
                iProgress.incProgress();
            }
        }
    } else if (iLoadCommittedAssignments) {
        iProgress.setPhase("Creating initial assignment ...", getModel().variables().size());
        for (Lecture lecture : getModel().variables()) {
            if (lecture.isCommitted())
                continue;
            Class_ clazz = iClasses.get(lecture.getClassId());
            if (clazz != null && clazz.getCommittedAssignment() != null)
                loadAssignment(clazz.getCommittedAssignment());
            iProgress.incProgress();
        }
    }

    if (!hibSession.isOpen())
        iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open.");

    if (iSpread) {
        iProgress.setPhase("Posting automatic spread constraints ...", subparts.size());
        for (SchedulingSubpart subpart : subparts) {
            if (subpart.getClasses().size() <= 1) {
                iProgress.incProgress();
                continue;
            }
            if (!subpart.isAutoSpreadInTime().booleanValue()) {
                iProgress.debug("Automatic spread constraint disabled for " + getSubpartLabel(subpart));
                iProgress.incProgress();
                continue;
            }
            SpreadConstraint spread = new SpreadConstraint(getModel().getProperties(),
                    subpart.getCourseName() + " " + subpart.getItypeDesc().trim());
            for (Iterator i2 = subpart.getClasses().iterator(); i2.hasNext();) {
                Class_ clazz = (Class_) i2.next();
                Lecture lecture = (Lecture) getLecture(clazz);
                if (lecture == null)
                    continue;
                spread.addVariable(lecture);
            }
            if (spread.variables().isEmpty())
                iProgress.message(msglevel("courseWithNoClasses", Progress.MSGLEVEL_WARN),
                        "No class for course " + getSubpartLabel(subpart));
            else
                getModel().addConstraint(spread);
            iProgress.incProgress();
        }
    }

    if (iDeptBalancing) {
        iProgress.setPhase("Creating dept. spread constraints ...", getModel().variables().size());
        Hashtable<Long, DepartmentSpreadConstraint> depSpreadConstraints = new Hashtable<Long, DepartmentSpreadConstraint>();
        for (Lecture lecture : getModel().variables()) {
            if (lecture.getDepartment() == null)
                continue;
            DepartmentSpreadConstraint deptConstr = (DepartmentSpreadConstraint) depSpreadConstraints
                    .get(lecture.getDepartment());
            if (deptConstr == null) {
                deptConstr = new DepartmentSpreadConstraint(getModel().getProperties(), lecture.getDepartment(),
                        (String) iDeptNames.get(lecture.getDepartment()));
                depSpreadConstraints.put(lecture.getDepartment(), deptConstr);
                getModel().addConstraint(deptConstr);
            }
            deptConstr.addVariable(lecture);
            iProgress.incProgress();
        }
    }

    if (iSubjectBalancing) {
        iProgress.setPhase("Creating subject spread constraints ...", getModel().variables().size());
        Hashtable<Long, SpreadConstraint> subjectSpreadConstraints = new Hashtable<Long, SpreadConstraint>();
        for (Lecture lecture : getModel().variables()) {
            Class_ clazz = iClasses.get(lecture.getClassId());
            if (clazz == null)
                continue;
            for (CourseOffering co : clazz.getSchedulingSubpart().getInstrOfferingConfig()
                    .getInstructionalOffering().getCourseOfferings()) {
                Long subject = co.getSubjectArea().getUniqueId();
                SpreadConstraint subjectSpreadConstr = subjectSpreadConstraints.get(subject);
                if (subjectSpreadConstr == null) {
                    subjectSpreadConstr = new SpreadConstraint(getModel().getProperties(),
                            co.getSubjectArea().getSubjectAreaAbbreviation());
                    subjectSpreadConstraints.put(subject, subjectSpreadConstr);
                    getModel().addConstraint(subjectSpreadConstr);
                }
                subjectSpreadConstr.addVariable(lecture);
            }
            iProgress.incProgress();
        }
    }

    if (getModel().getProperties().getPropertyBoolean("General.PurgeInvalidPlacements", true))
        purgeInvalidValues();

    /*
    for (Constraint c: getModel().constraints()) {
       if (c instanceof SpreadConstraint)
    ((SpreadConstraint)c).init();
       if (c instanceof DiscouragedRoomConstraint)
    ((DiscouragedRoomConstraint)c).setEnabled(true);
       if (c instanceof MinimizeNumberOfUsedRoomsConstraint)
    ((MinimizeNumberOfUsedRoomsConstraint)c).setEnabled(true);
       if (c instanceof MinimizeNumberOfUsedGroupsOfTime)
    ((MinimizeNumberOfUsedGroupsOfTime)c).setEnabled(true);
    }
    */

    iProgress.setPhase("Checking for inconsistencies...", getModel().variables().size());
    for (Lecture lecture : getModel().variables()) {

        iProgress.incProgress();
        for (Iterator i = lecture.students().iterator(); i.hasNext();) {
            Student s = (Student) i.next();
            if (!s.canEnroll(lecture))
                iProgress.message(msglevel("badStudentEnrollment", Progress.MSGLEVEL_INFO),
                        "Invalid student enrollment of student " + s.getId() + " in class "
                                + getClassLabel(lecture) + " found.");
        }

        //check same instructor constraint
        if (!lecture.values(getAssignment()).isEmpty() && lecture.timeLocations().size() == 1
                && !lecture.getInstructorConstraints().isEmpty()) {
            for (Lecture other : getModel().variables()) {
                if (other.values(getAssignment()).isEmpty() || other.timeLocations().size() != 1
                        || lecture.getClassId().compareTo(other.getClassId()) <= 0)
                    continue;
                Placement p1 = lecture.values(getAssignment()).get(0);
                Placement p2 = other.values(getAssignment()).get(0);
                if (!other.getInstructorConstraints().isEmpty()) {
                    for (InstructorConstraint ic : lecture.getInstructorConstraints()) {
                        if (!other.getInstructorConstraints().contains(ic))
                            continue;
                        if (p1.canShareRooms(p2) && p1.sameRooms(p2))
                            continue;
                        if (p1.getTimeLocation().hasIntersection(p2.getTimeLocation())) {
                            iProgress.message(msglevel("reqInstructorOverlap", Progress.MSGLEVEL_WARN),
                                    "Same instructor and overlapping time required:"
                                            + "<br>&nbsp;&nbsp;&nbsp;&nbsp;" + getClassLabel(lecture)
                                            + " &larr; " + p1.getLongName(iUseAmPm)
                                            + "<br>&nbsp;&nbsp;&nbsp;&nbsp;" + getClassLabel(other) + " &larr; "
                                            + p2.getLongName(iUseAmPm));
                        } else if (ic.getDistancePreference(p1, p2) == PreferenceLevel.sIntLevelProhibited
                                && lecture.roomLocations().size() == 1 && other.roomLocations().size() == 1) {
                            iProgress.message(msglevel("reqInstructorBackToBack", Progress.MSGLEVEL_WARN),
                                    "Same instructor, back-to-back time and rooms too far (distance="
                                            + Math.round(10.0 * Placement.getDistanceInMeters(
                                                    getModel().getDistanceMetric(), p1, p2))
                                            + "m) required:" + "<br>&nbsp;&nbsp;&nbsp;&nbsp;"
                                            + getClassLabel(lecture) + " &larr; " + p1.getLongName(iUseAmPm)
                                            + "<br>&nbsp;&nbsp;&nbsp;&nbsp;" + getClassLabel(other) + " &larr; "
                                            + p2.getLongName(iUseAmPm));
                        }
                    }
                }
            }
        }

        if (!lecture.isSingleton())
            continue;
        for (Lecture other : getModel().variables()) {
            if (!other.isSingleton() || lecture.getClassId().compareTo(other.getClassId()) <= 0)
                continue;
            Placement p1 = new Placement(lecture, lecture.timeLocations().get(0), lecture.roomLocations());
            Placement p2 = new Placement(other, other.timeLocations().get(0), other.roomLocations());
            if (p1.shareRooms(p2) && p1.getTimeLocation().hasIntersection(p2.getTimeLocation())
                    && !p1.canShareRooms(p2)) {
                iProgress.message(msglevel("reqRoomOverlap", Progress.MSGLEVEL_WARN),
                        "Same room and overlapping time required:" + "<br>&nbsp;&nbsp;&nbsp;&nbsp;"
                                + getClassLabel(lecture) + " &larr; " + p1.getLongName(iUseAmPm)
                                + "<br>&nbsp;&nbsp;&nbsp;&nbsp;" + getClassLabel(other) + " &larr; "
                                + p2.getLongName(iUseAmPm));
            }
        }
        if (getAssignment().getValue(lecture) == null) {
            Placement placement = new Placement(lecture, lecture.timeLocations().get(0),
                    lecture.roomLocations());
            if (!placement.isValid()) {
                String reason = "";
                for (InstructorConstraint ic : lecture.getInstructorConstraints()) {
                    if (!ic.isAvailable(lecture, placement))
                        reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;instructor " + ic.getName() + " not available";
                }
                if (lecture.getNrRooms() > 0) {
                    if (placement.isMultiRoom()) {
                        for (RoomLocation roomLocation : placement.getRoomLocations()) {
                            if (!roomLocation.getRoomConstraint().isAvailable(lecture,
                                    placement.getTimeLocation(), lecture.getScheduler()))
                                reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;room " + roomLocation.getName()
                                        + " not available";
                        }
                    } else {
                        if (!placement.getRoomLocation().getRoomConstraint().isAvailable(lecture,
                                placement.getTimeLocation(), lecture.getScheduler()))
                            reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;room "
                                    + placement.getRoomLocation().getName() + " not available";
                    }
                }
                Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel()
                        .conflictConstraints(getAssignment(), placement);
                if (!conflictConstraints.isEmpty()) {
                    for (Constraint<Lecture, Placement> c : conflictConstraints.keySet()) {
                        Set<Placement> vals = conflictConstraints.get(c);
                        for (Placement p : vals) {
                            Lecture l = p.variable();
                            if (l.isCommitted())
                                reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;conflict with committed assignment "
                                        + getClassLabel(l) + " = " + p.getLongName(iUseAmPm)
                                        + " (in constraint " + c + ")";
                            if (p.equals(placement))
                                reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;constraint " + c;
                        }
                    }
                }
                iProgress.message(msglevel("reqInvalidPlacement", Progress.MSGLEVEL_WARN),
                        "Class " + getClassLabel(lecture) + " requires an invalid placement "
                                + placement.getLongName(iUseAmPm)
                                + (reason.length() == 0 ? "." : ":" + reason));
            } else if (iAssignSingleton && getModel().conflictValues(getAssignment(), placement).isEmpty())
                getAssignment().assign(0, placement);
        }
    }

    getModel().createAssignmentContexts(getAssignment(), true);

    if (getModel().getProperties().getPropertyBoolean("General.EnrollmentCheck", true))
        new EnrollmentCheck(getModel(), getAssignment(), msglevel("enrollmentCheck", Progress.MSGLEVEL_WARN))
                .checkStudentEnrollments(iProgress);

    if (getModel().getProperties().getPropertyBoolean("General.SwitchStudents", true)
            && getAssignment().nrAssignedVariables() != 0 && !iLoadStudentEnrlsFromSolution)
        getModel().switchStudents(getAssignment());

    iProgress.setPhase("Done", 1);
    iProgress.incProgress();
    iProgress.message(msglevel("allDone", Progress.MSGLEVEL_INFO), "Model successfully loaded.");
}

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

/**
 * The method is the exit point of the overall sequencing loop. When it is
 * invoked, it is assumed that the activity identified for delivery has been
 * validated by the Delivery Request Process. This method performs necessery
 * activity tree management and returns sufficient information to the RTE
 * launching the resource(s) associated with the identified activity.
 * // w w w  . j  a  v  a2s .  co m
 * @param iTarget
 *            The activity identified for delivery.
 * 
 * @param oLaunch
 *            An 'out' parameter that provides information to the RTE for
 *            launching the resources associated with the activity.
 */
private void contentDelivery(String iTarget, ADLLaunch oLaunch) {

    // This method implements the Content Delivery Environment Process
    // (DB.2)
    if (_Debug) {
        System.out.println("  :: ADLSequencer --> BEGIN - " + "contentDelivery");
        System.out.println("  ::-->  " + iTarget);
    }

    SeqActivity target = getActivity(iTarget);
    boolean done = false;

    if (target == null) {
        if (_Debug) {
            System.out.println("  ::--> ERROR : Invalid target");
        }

        oLaunch.mSeqNonContent = ADLLaunch.LAUNCH_ERROR;
        oLaunch.mEndSession = mEndSession;

        done = true;
    }

    SeqActivity cur = mSeqTree.getFirstCandidate();

    if (cur != null && !done) {
        if (cur.getIsActive()) {
            if (_Debug) {
                System.out.println("  ::--> ERROR : " + "Current activity still active.");
            }

            oLaunch.mSeqNonContent = ADLLaunch.LAUNCH_ERROR;
            oLaunch.mEndSession = mEndSession;

            done = true;
        }
    }

    if (!done) {

        // Clear any 'suspended' activity
        clearSuspendedActivity(target);

        // End any active attempts
        terminateDescendentAttempts(target);

        // Begin all required new attempts
        List<SeqActivity> begin = new ArrayList<SeqActivity>();
        SeqActivity walk = target;

        while (walk != null) {
            begin.add(walk);

            walk = walk.getParent();
        }

        if (begin.size() > 0) {

            for (int i = begin.size() - 1; i >= 0; i--) {

                walk = begin.get(i);

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

                if (!walk.getIsActive()) {
                    if (walk.getIsTracked()) {
                        if (walk.getIsSuspended()) {
                            walk.setIsSuspended(false);
                        } else {
                            // Initialize tracking information for the new
                            // attempt
                            walk.incrementAttempt();
                        }
                    }

                    walk.setIsActive(true);

                }
            }
        } else {
            if (_Debug) {
                System.out.println("  ::--> ERROR : Empty begin List");
            }
        }

        // Set the tree in the appropriate state
        mSeqTree.setCurrentActivity(target);
        mSeqTree.setFirstCandidate(target);

        // Fill in required launch information
        oLaunch.mEndSession = mEndSession;
        oLaunch.mActivityID = iTarget;
        oLaunch.mResourceID = target.getResourceID();

        oLaunch.mStateID = target.getStateID();
        if (oLaunch.mStateID == null) {
            oLaunch.mStateID = iTarget;
        }

        oLaunch.mNumAttempt = target.getNumAttempt() + target.getNumSCOAttempt();
        oLaunch.mMaxTime = target.getAttemptAbDur();

        // Create auxilary services List
        Hashtable<String, ADLAuxiliaryResource> services = new Hashtable<String, ADLAuxiliaryResource>();
        ADLAuxiliaryResource test = null;
        walk = target;

        // Starting at the target activity, walk up the tree adding services
        while (walk != null) {
            List<ADLAuxiliaryResource> curSet = walk.getAuxResources();

            if (curSet != null) {

                for (int i = 0; i < curSet.size(); i++) {
                    ADLAuxiliaryResource res = null;
                    res = curSet.get(i);

                    // If the resource isn't already included in the set,
                    // add it
                    test = services.get(res.mType);

                    if (test == null) {
                        services.put(res.mType, res);
                    }
                }
            }

            // Walk up the tree
            walk = walk.getParent();
        }

        if (services.size() > 0) {
            oLaunch.mServices = services;
        }
    }

    if (_Debug) {
        System.out.println("  ::--> Content Delivery Valididation");
    }

    validateRequests();
    oLaunch.mNavState = mSeqTree.getValidRequests();

    // Make sure Continue Exit is not enabled for non-content
    if (oLaunch.mSeqNonContent != null) {
        oLaunch.mNavState.mContinueExit = false;
    }

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