Example usage for java.util ArrayList indexOf

List of usage examples for java.util ArrayList indexOf

Introduction

In this page you can find the example usage for java.util ArrayList indexOf.

Prototype

public int indexOf(Object o) 

Source Link

Document

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Usage

From source file:pcgui.ModelParser.java

public ArrayList<Symbol> modelImport(File file) throws XPRMLicenseError, IOException {

    XPRM mosel;/* www. j  a  v a 2  s  .c  o m*/
    ArrayList<Symbol> symbolList = new ArrayList<Symbol>();
    mosel = new XPRM();

    String path = file.getAbsolutePath();
    this.filePath = path;
    this.fileMosel = file;

    XPRM.unbindAll();

    MyOut cbmsg = new MyOut();

    XPRM.bind("mycb", cbmsg); // Associate Java object with a name in Mosel
    // Set default output stream to cbmsg
    //mosel.setDefaultStream(XPRM.F_ERROR|XPRM.F_LINBUF, "java:mycb");

    mosel.setDefaultStream(XPRM.F_ERROR, "java:mycb");

    try {
        mosel.compile(path);

    } catch (XPRMCompileException e1) {
        System.out.println("cbmsg.errorStr=" + cbmsg.errorStr);

        String error = "<html>" + cbmsg.errorStr + "</html";

        CustomErrorDialog.showDialog("<html>XPRMCompileException occured</html>", error);

        XPRM.unbindAll();
        resetMosel();
        mosel.finalize();
        mosel = null;

        return null;

    }

    //First parsing    
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        br = new BufferedReader(new FileReader(fileMosel));
        String line;
        ArrayList<Symbol> totalSymbFound = new ArrayList<>();

        while ((line = br.readLine()) != null) {

            if (line.contains("parameters")) {
                System.out.println("START OF PARAMETERS BLOCk!!+" + line);

                while (!(line = br.readLine()).contains("end-parameters")) {

                    line = line.trim();

                    if (line.isEmpty() || line.equals("") || line.equals("\n"))
                        continue;

                    //skipping comment line
                    if (line.charAt(0) == '!') {
                        System.out.println("Skipping comment line=" + line);
                        continue;

                    }
                    System.out.println("current line:" + line);

                    //removing comments part from the line beforehand
                    line = line.split("!")[0].trim();

                    // for symbols defined as: symName = myvalue i.e. with "="
                    Symbol symConstant = tokenizeSymbols(line);
                    symbolList.add(symConstant);

                }

                System.out.println("END OF PARAMETERS BLOCk!!");

            } else if (line.contains("declarations")) {
                System.out.println("START OF DECLARATIONS BLOCk!!+" + line);

                while (!(line = br.readLine()).contains("end-declarations")) {

                    line = line.trim();

                    if (line.isEmpty() || line.equals("") || line.equals("\n"))
                        continue;

                    //skipping comment line
                    if (line.charAt(0) == '!') {
                        System.out.println("Skipping comment line=" + line);
                        continue;

                    }

                    System.out.println("current line:" + line);

                    //remove comments before hand only
                    line = line.split("!")[0].trim();

                    if (line.contains("=")) {
                        System.out.println("Symbol Constant case:");
                        // for symbols defined as: symName = myvalue i.e. with "="
                        Symbol symConstant = tokenizeSymbols(line);
                        symbolList.add(symConstant);

                    } else if (line.contains(":")) {
                        System.out.println("Symbol Variable case:");
                        //now logic for variables with ':'
                        String linetokensForVars[] = line.split(":");

                        String name = linetokensForVars[0].trim();

                        Symbol symVariable = new Symbol<>();

                        symVariable.name = name;

                        String symValString = linetokensForVars[1].trim();

                        //remove comments if any after the symbolval
                        symValString = symValString.split("!")[0].trim();

                        symVariable.typeString = symValString;
                        symVariable.set(""); //set value to empty string

                        symbolList.add(symVariable);
                        System.out.println("Symbol added(variable), Name:" + symVariable.name + ", type="
                                + symVariable.typeString + ", val=" + symVariable.get());

                    }

                }

                System.out.println("END OF DECLARATIONS BLOCk!!");

            } else if (line.contains("initializations from")) {

                String externalSourceFileName = line.split("from")[1].trim();

                if (externalSourceFileName.charAt(0) != 34 || externalSourceFileName.charAt(0) != 39) {
                    //eg: init from input_link, here input_link="blahblah.txt"
                    Symbol extSymbol = new Symbol<>();
                    extSymbol.name = externalSourceFileName;

                    int index = symbolList.indexOf(extSymbol);
                    if (index != -1) {

                        externalSourceFileName = symbolList.get(index).get().toString();

                    }

                }

                externalSourceFileName = externalSourceFileName.replace("'", "");
                externalSourceFileName = externalSourceFileName.replace("\"", "");

                System.out.println("init block: externalsource=" + externalSourceFileName);

                while (!(line = br.readLine()).contains("end-initializations")) {

                    line = line.trim();

                    if (line.isEmpty() || line.equals("") || line.equals("\n"))
                        continue;

                    //skipping comment line
                    if (line.trim().charAt(0) == '!') {
                        System.out.println("Skipping comment line=" + line.trim());
                        continue;

                    }
                    if (externalSourceFileName.contains(".xls") || externalSourceFileName.contains(".xlsx")) {
                        String varLine[] = line.split("as");
                        String name = varLine[0].trim();
                        Symbol s = new Symbol<>();
                        s.name = name;

                        int index = symbolList.indexOf(s);
                        if (index != -1) {

                            Symbol sym = symbolList.get(index);
                            sym.externalFile = externalSourceFileName;

                            String excelFR = varLine[1].trim();
                            excelFR = excelFR.replace("'", "");
                            excelFR = excelFR.replace("\"", "");

                            sym.excelFileRange = excelFR;

                        }

                    } else if (line.contains("as")) {
                        String name = line.split("as")[0].trim();
                        Symbol s = new Symbol<>();
                        s.name = name;

                        int index = symbolList.indexOf(s);
                        if (index != -1) {

                            Symbol sym = symbolList.get(index);
                            sym.externalFile = externalSourceFileName;

                        }

                    } else {

                        //tokenizing from space is for case, where all vars are written in same line eg: var1 var2
                        StringTokenizer linetokens = new StringTokenizer(line, " ");

                        while (linetokens.hasMoreTokens()) {
                            String token = linetokens.nextToken().trim();

                            Symbol s = new Symbol<>();
                            s.name = token;

                            int index = symbolList.indexOf(s);
                            if (index != -1) {

                                Symbol sym = symbolList.get(index);
                                sym.externalFile = externalSourceFileName;

                            }

                            System.out.println("Symbol added from 'init block':" + token);

                        }

                    }

                }

            }

        }
    } catch (Exception e) {
        // return;
        System.err.println("Exception in parsing File with e=" + e);
        CustomErrorDialog.showDialog("<html>Exception in parsing File</html>", e.toString());
        e.printStackTrace();

        XPRM.unbindAll();
        resetMosel();
        mosel.finalize();
        mosel = null;

        return null;

    } finally {
        try {
            if (br != null)
                br.close();
        } catch (IOException e) {
            //
            e.printStackTrace();
        }
        try {
            if (bw != null)
                bw.close();
        } catch (IOException e) {
            //
            e.printStackTrace();
        }
    }

    System.out.println("InitialSymbolList::");
    for (int i = 0; i < symbolList.size(); i++) {
        Symbol s = (Symbol) symbolList.get(i);
        System.out.println(s.name + ": " + s.typeString + ": " + s.get());
    }

    this.initialSymbolList = symbolList;

    XPRM.unbindAll();
    mosel.finalize();
    mosel = null;

    return symbolList;

}

From source file:com.stratelia.webactiv.beans.admin.Admin.java

private ArrayList<String> removeTuples(ArrayList<String> al) {
    if (al == null) {
        return new ArrayList<String>();
    }/*from   w w w  .j  av a  2 s  .  c  o m*/

    for (int nI = 0; nI < al.size(); nI++) {
        while (al.lastIndexOf(al.get(nI)) != al.indexOf(al.get(nI))) {
            al.remove(al.lastIndexOf(al.get(nI)));
        }
    }

    return al;
}

From source file:com.bluexml.side.integration.buildHudson.utils.Utils.java

/**
 * Cette mthode analyse le fichier de log (il changera en fonction de
 * l'utilisation de Hudson ou non) et regarde si des updates ont t fait
 * et ainsi, changer le numro de version du projet concern
 *///from   w  ww .j a  v a2s. co m
public static void traitementUpdate() {

    copyFromRepository();

    ArrayList<String> listeProjetReels = new ArrayList<String>();
    ArrayList<String> listeProjetPoms = new ArrayList<String>();

    List<String> projects = new ArrayList<String>();
    projects.addAll(getProjects("project"));
    projects.addAll(getProjects("project.enterprise"));
    projects.addAll(getProjects("projectToVersioned"));

    for (int i = 0; i < projects.size(); i++) {
        if (!Application.projectsExcluded.contains(projects.get(i))) {
            if (projects.get(i).length() > 0)
                listeProjetReels.add(projects.get(i));
        }
    }

    List<String> projectsToVersioned = getVersionedProjects();

    for (int i = 0; i < projectsToVersioned.size(); i++) {
        if (projectsToVersioned.get(i).length() > 0)
            listeProjetReels.add(projectsToVersioned.get(i));
    }

    boolean end = false;

    ArrayList<String> listePlugin = new ArrayList<String>();

    String pathproject = getRepositoryCopyPath();

    listefichierpom = new ArrayList<String>();

    findFile(new File(pathproject + "/" + SourceSVNName + "/"), "pom.xml");

    // si on ne force pas la mise a jour du numro de version
    if ("".equals(getForceNumberVersion())) {
        String ligne = "";
        String modif = "";
        ArrayList<String> listeProjet = new ArrayList<String>();
        boolean update = false;

        // ouverture d'un flux du fichier
        try {
            File log = new File(getPathToLog());
            BufferedReader ficTexte = new BufferedReader(new FileReader(log));
            System.out.println("###### search for updated project from svn log " + log);
            if (ficTexte == null) {
                throw new FileNotFoundException("Fichier non trouv");
            }

            // Analyse et copie de chaque ligne
            while ((ligne = ficTexte.readLine()) != null && !end) {

                // condition d'arret de la lecture du log
                // on arrete la lecture lorsque se lance le build
                if (ligne.startsWith(Application.buildStartLine)) {
                    end = true;
                }

                if (Application.parametre) {
                    // condition pour ne pas traiter les logs du checkout
                    if (ligne.startsWith("+ svn update")) {
                        update = true;
                    }
                    if (ligne.indexOf("Checking out " + Utils.getRepository()) == -1) {
                        update = true;
                    }
                } else {
                    if (ligne.indexOf("svnUD:") != -1) {
                        update = true;
                    }
                }

                if (!"".equals(ligne) && !end) {

                    if (ligne.indexOf("At revision") != -1) {
                        revisionNumber = ligne.substring("At revision".length(), ligne.length()).trim();
                    }

                    if (update) {

                        if ((ligne.charAt(0) == 'A' || ligne.charAt(0) == 'U' || ligne.charAt(0) == 'D'
                                || ligne.charAt(0) == ' ')
                                && (ligne.charAt(1) == ' ' || ligne.charAt(1) == 'U' || ligne.charAt(1) == 'A'
                                        || ligne.charAt(1) == 'D')
                                && update) {

                            if (ligne.indexOf("Integration") > -1 || ligne.indexOf("FrameworksModules") > -1) {
                                for (String valeur : listefichierpom) {
                                    String valeurf = valeur;
                                    String[] tab = valeurf.split("/" + SourceSVNName + "/");
                                    String[] tab2 = tab[1].split("/pom.xml");
                                    if (ligne.indexOf(tab2[0]) > -1) {
                                        if (!listeProjetPoms.contains(valeur))
                                            listeProjetPoms.add(valeur);
                                    }
                                }
                            }

                            modif = ligne.substring(2, ligne.length());
                            modif.trim();
                            String[] proj = modif.split(File.separator);

                            for (int i = 0; i < proj.length; i++) {
                                if (!listeProjet.contains(proj[i])) {
                                    listeProjet.add(proj[i]);
                                }
                            }
                        }
                    }

                }
            }

        } catch (FileNotFoundException e) {
            e.getMessage();
        } catch (IOException e1) {
            e1.getMessage();
        }

        System.out.println("Update project versions");

        // Add all projects to version
        for (String p : projectsToVersioned) {
            if (!listeProjet.contains(p))
                listeProjet.add(p);
        }

        // on parcours la liste des projets qui ont t modifi
        for (String element : listeProjet) {
            if (listeProjetReels.contains(element)) {
                // on met tous les plugins modifis dans un tableau
                if (element.indexOf("feature") == -1) {
                    listePlugin.add(element);
                }
                // et tous les features dans un autre
                else {
                    listeFeatureModif.add(element);
                }
            }
        }

        // si on force la mise a jour du numro de version
    } else {
        System.out.println(
                "Les numros de version de tous les projets sont forcs : " + getForceNumberVersion());
        for (int i = 0; i < projects.size(); i++) {
            if (projects.get(i).indexOf("feature") == -1)
                listePlugin.add(projects.get(i));
        }

    }

    // On parcours la liste des pom et on les met a jour
    for (String pom : listeProjetPoms) {
        updateVersionNumberPom(pom);

    }

    if (listeProjetPoms.size() != 0) {
        System.out.println("\nListe des poms modifies: ");
        for (String pom : listeProjetPoms) {
            String valeurf = pom;
            String[] tab = valeurf.split("/" + SourceSVNName + "/");
            String moduleId = tab[1];
            String versionNumberPom = getVersionNumberPom(pom);
            System.out.println("\t- " + moduleId + ": " + versionNumberPom);
            updatedPoms.put(moduleId, versionNumberPom);
        }

        if (listePlugin.indexOf("com.bluexml.side.Util.dependencies") == -1) {
            listePlugin.add("com.bluexml.side.Util.dependencies");
        }

    }

    // mettre a jour les plugins avec les versions des pom.xml
    // ajouter les plugins modifier dans la listePlugin
    ArrayList<String> listePomsModuleDepencies = new ArrayList<String>();
    if (listeProjetPoms.size() != 0) {
        for (String pom : listeProjetPoms) {
            String versionPom = getVersionNumberPom(pom);
            String valeurf = pom;
            String[] tab = valeurf.split("/pom.xm");
            String valeur2 = tab[0];
            String nomPom = valeur2.substring(valeur2.lastIndexOf("/") + 1);

            // fixer les versions des fichiers plugin.xml
            System.out.println("\nFixer les versions des fichiers plugins : ");
            for (String element : projects) {

                if (element.indexOf("feature") == -1) {

                    // si contient reference pom alors modifie max version
                    // et ajouter a la liste listePlugin
                    boolean ajouter = updatePluginModuleDependencies(element, nomPom, versionPom);
                    if (ajouter) {
                        if (listePlugin.indexOf(element) == -1) {
                            listePlugin.add(element);
                            System.out.println("update plugin : " + element + " pom : " + nomPom + " version : "
                                    + versionPom);
                        }

                    }

                }
            }

            // fixer les versions des fichier pom.xml
            System.out.println("\nFixer les versions des fichiers pom : ");
            for (String element : listefichierpom) {

                // si contient reference pom alors modifie max version
                // et ajouter a la liste listePlugin
                boolean ajouter = updatePomModuleDependencies(element, nomPom, versionPom);
                if (ajouter) {
                    if (listeProjetPoms.indexOf(element) == -1) {
                        listePomsModuleDepencies.add(element);
                        System.out.println(
                                "update pom : " + element + " pom : " + nomPom + " version : " + versionPom);
                    }
                }
            }

        }
    }

    // mettre a jour les pom.xml modifiers
    // On parcours la liste des pom et on les met a jour
    for (String pomModuleDepencies : listePomsModuleDepencies) {
        updateVersionNumberPom(pomModuleDepencies);

    }

    if (listePomsModuleDepencies.size() != 0) {
        System.out.println("\nListe des poms modifies suite mis a jour module: ");
        for (String pom : listePomsModuleDepencies) {
            String valeurf = pom;
            String[] tab = valeurf.split("/" + SourceSVNName + "/");
            String moduleId = tab[1];
            String versionNumberPom = getVersionNumberPom(pom);
            System.out.println("\t- " + moduleId + ": " + versionNumberPom);
            updatedPoms.put(moduleId, versionNumberPom);
        }
    }

    System.out.println("\nFixer les versions des fichiers plugin : ");
    if (listePomsModuleDepencies.size() != 0) {
        for (String pom : listePomsModuleDepencies) {
            String versionPom = getVersionNumberPom(pom);
            String valeurf = pom;
            String[] tab = valeurf.split("/pom.xm");
            String valeur2 = tab[0];
            String nomPom = valeur2.substring(valeur2.lastIndexOf("/") + 1);

            // fixer les versions des fichiers plugin.xml
            for (String element : projects) {

                if (element.indexOf("feature") == -1) {

                    // si contient reference pom alors modifie max version
                    // et ajouter a la liste listePlugin
                    boolean ajouter = updatePluginModuleDependencies(element, nomPom, versionPom);
                    if (ajouter) {
                        if (listePlugin.indexOf(element) == -1) {
                            listePlugin.add(element);
                            System.out.println("update plugin : " + element + " pom : " + nomPom + " version : "
                                    + versionPom);
                        }

                    }

                }
            }
        }
    }

    while (listePomsModuleDepencies.size() != 0) {

        System.out.println("\nFixer les versions des fichiers plugins suite mise a jour module : ");
        // mettre a jour les plugins avec les versions des pom.xml
        // ajouter les plugins modifier dans la listePlugin
        ArrayList<String> listePomsModuleDepencies1 = new ArrayList<String>();
        if (listePomsModuleDepencies.size() != 0) {
            for (String pom : listePomsModuleDepencies) {
                String versionPom = getVersionNumberPom(pom);
                String valeurf = pom;
                String[] tab = valeurf.split("/pom.xm");
                String valeur2 = tab[0];
                String nomPom = valeur2.substring(valeur2.lastIndexOf("/") + 1);

                // fixer les versions des fichiers plugin.xml
                System.out.println("\nFixer les versions des fichiers plugins : ");
                for (String element : projects) {

                    if (element.indexOf("feature") == -1) {

                        // si contient reference pom alors modifie max
                        // version
                        // et ajouter a la liste listePlugin
                        boolean ajouter = updatePluginModuleDependencies(element, nomPom, versionPom);
                        if (ajouter) {
                            if (listePlugin.indexOf(element) == -1) {
                                listePlugin.add(element);
                                System.out.println("update plugin : " + element + " pom : " + nomPom
                                        + " version : " + versionPom);
                            }

                        }

                    }
                }

                // fixer les versions des fichier pom.xml
                System.out.println("\nFixer les versions des fichiers pom suite mise a jour module : ");
                for (String element : listefichierpom) {

                    // si contient reference pom alors modifie max version
                    // et ajouter a la liste listePlugin
                    boolean ajouter = updatePomModuleDependencies(element, nomPom, versionPom);
                    if (ajouter) {
                        if ((listePomsModuleDepencies.indexOf(element) == -1)
                                && (listeProjetPoms.indexOf(element) == -1)) {
                            listePomsModuleDepencies1.add(element);
                            System.out.println("update pom : " + element + " pom : " + nomPom + " version : "
                                    + versionPom);
                        }
                    }
                }

            }
        }

        // mettre a jour les pom.xml modifiers
        // On parcours la liste des pom et on les met a jour
        for (String pomModuleDepencies : listePomsModuleDepencies1) {
            updateVersionNumberPom(pomModuleDepencies);

        }

        if (listePomsModuleDepencies1.size() != 0) {
            System.out.println("\nListe des poms modifies suite mis a jour module: ");
            for (String pom : listePomsModuleDepencies1) {
                String valeurf = pom;
                String[] tab = valeurf.split("/" + SourceSVNName + "/");
                String moduleId = tab[1];
                String versionNumberPom = getVersionNumberPom(pom);
                System.out.println("\t- " + moduleId + ": " + versionNumberPom);
                updatedPoms.put(moduleId, versionNumberPom);
            }
        }

        System.out.println("\nFixer les versions des fichiers plugin : ");
        if (listePomsModuleDepencies1.size() != 0) {
            for (String pom : listePomsModuleDepencies1) {
                String versionPom = getVersionNumberPom(pom);
                String valeurf = pom;
                String[] tab = valeurf.split("/pom.xm");
                String valeur2 = tab[0];
                String nomPom = valeur2.substring(valeur2.lastIndexOf("/") + 1);

                // fixer les versions des fichiers plugin.xml
                for (String element : projects) {

                    if (element.indexOf("feature") == -1) {

                        // si contient reference pom alors modifie max
                        // version
                        // et ajouter a la liste listePlugin
                        boolean ajouter = updatePluginModuleDependencies(element, nomPom, versionPom);
                        if (ajouter) {
                            if (listePlugin.indexOf(element) == -1) {
                                listePlugin.add(element);
                                System.out.println("update plugin : " + element + " pom : " + nomPom
                                        + " version : " + versionPom);
                            }

                        }

                    }
                }
            }
        }

        listePomsModuleDepencies = new ArrayList<String>();
        if (listePomsModuleDepencies1.size() != 0) {
            for (String pom : listePomsModuleDepencies1) {
                listePomsModuleDepencies.add(pom);
            }
        }

    }

    // On parcours la liste des plugins et on les met a jour
    for (String plugin : listePlugin) {
        updateVersionNumber(plugin);

    }

    // On fait la meme chose mais pour toutes les features
    for (int i = 0; i < projects.size(); i++) {
        if (projects.get(i).indexOf("feature") != -1) {
            updateVersionNumber(projects.get(i));
        }
    }

    // affichage des donnes
    if (listePlugin.size() != 0) {
        System.out.println("\nListe des plugins modifis: ");
        // On parcours la liste des plugins et on les met a jour
        for (String plugin : listePlugin) {
            String versionNumber = getVersionNumber(plugin);
            System.out.println("\t- " + plugin + ": " + versionNumber);
            updatedPlugins.put(plugin, versionNumber);
        }
    }

    if (listeFeatureModif.size() != 0) {
        System.out.println("\nListe des features modifies: ");
        for (String feature : listeFeatureModif) {
            String versionNumber = getVersionNumber(feature);
            System.out.println("\t- " + feature + ": " + versionNumber);
            updatedFeatures.put(feature, versionNumber);
        }
    }

    // fin affichage

    // copyToRepository();

    // log updated projects
    // try {
    // serializeUpdatedProjects();
    // } catch (Exception e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }

}

From source file:org.sakaiproject.lessonbuildertool.tool.producers.ShowPageProducer.java

public void fillComponents(UIContainer tofill, ViewParameters viewParams, ComponentChecker checker) {
    GeneralViewParameters params = (GeneralViewParameters) viewParams;

    UIOutput.make(tofill, "html")
            .decorate(new UIFreeAttributeDecorator("lang", localegetter.get().getLanguage()))
            .decorate(new UIFreeAttributeDecorator("xml:lang", localegetter.get().getLanguage()));

    UIOutput.make(tofill, "datepicker").decorate(
            new UIFreeAttributeDecorator("src", (majorVersion >= 10 ? "/library" : "/lessonbuilder-tool")
                    + "/js/lang-datepicker/lang-datepicker.js"));

    boolean iframeJavascriptDone = false;

    // security model:
    // canEditPage and canReadPage are normal Sakai privileges. They apply

    // to all//w w w .  ja  v  a  2s .  co m
    // pages in the site.
    // However when presented with a page, we need to make sure it's
    // actually in
    // this site, or users could get to pages in other sites. That's done
    // by updatePageObject. The model is that producers always work on the
    // current page, and updatePageObject makes sure that is in the current
    // site.
    // At that point we can safely use canEditPage.

    // somewhat misleading. sendingPage specifies the page we're supposed to
    // go to.  If path is "none", we don't want this page to be what we see
    // when we come back to the tool
    if (params.getSendingPage() != -1) {
        // will fail if page not in this site
        // security then depends upon making sure that we only deal with
        // this page
        try {
            simplePageBean.updatePageObject(params.getSendingPage(), !params.getPath().equals("none"));
        } catch (Exception e) {
            log.warn("ShowPage permission exception " + e);
            UIOutput.make(tofill, "error-div");
            UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
            return;
        }
    }

    boolean canEditPage = simplePageBean.canEditPage();
    boolean canReadPage = simplePageBean.canReadPage();
    boolean canSeeAll = simplePageBean.canSeeAll(); // always on if caneditpage

    boolean cameFromGradingPane = params.getPath().equals("none");

    TimeZone localtz = timeService.getLocalTimeZone();
    isoDateFormat.setTimeZone(localtz);

    if (!canReadPage) {
        // this code is intended for the situation where site permissions
        // haven't been set up.
        // So if the user can't read the page (which is pretty abnormal),
        // see if they have site.upd.
        // if so, give them some explanation and offer to call the
        // permissions helper
        String ref = "/site/" + simplePageBean.getCurrentSiteId();
        if (simplePageBean.canEditSite()) {
            SimplePage currentPage = simplePageBean.getCurrentPage();
            UIOutput.make(tofill, "needPermissions");

            GeneralViewParameters permParams = new GeneralViewParameters();
            permParams.setSendingPage(-1L);
            createStandardToolBarLink(PermissionsHelperProducer.VIEW_ID, tofill, "callpermissions",
                    "simplepage.permissions", permParams, "simplepage.permissions.tooltip");

        }

        // in any case, tell them they can't read the page
        UIOutput.make(tofill, "error-div");
        UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.nopermissions"));
        return;
    }

    String addBefore = params.getAddBefore();
    if (params.addTool == GeneralViewParameters.COMMENTS) {
        simplePageBean.addCommentsSection(addBefore);
    } else if (params.addTool == GeneralViewParameters.STUDENT_CONTENT) {
        simplePageBean.addStudentContentSection(addBefore);
    } else if (params.addTool == GeneralViewParameters.STUDENT_PAGE) {
        simplePageBean.createStudentPage(params.studentItemId);
        canEditPage = simplePageBean.canEditPage();
    }

    // Find the MSIE version, if we're running it.
    int ieVersion = checkIEVersion();
    // as far as I can tell, none of these supports fck or ck
    // we can make it configurable if necessary, or use WURFL
    // however this test is consistent with CKeditor's check.
    // that desireable, since if CKeditor is going to use a bare
    // text block, we want to handle it as noEditor
    String userAgent = httpServletRequest.getHeader("User-Agent");
    if (userAgent == null)
        userAgent = "";
    boolean noEditor = userAgent.toLowerCase().indexOf("mobile") >= 0;

    // set up locale
    Locale M_locale = null;
    String langLoc[] = localegetter.get().toString().split("_");
    if (langLoc.length >= 2) {
        if ("en".equals(langLoc[0]) && "ZA".equals(langLoc[1])) {
            M_locale = new Locale("en", "GB");
        } else {
            M_locale = new Locale(langLoc[0], langLoc[1]);
        }
    } else {
        M_locale = new Locale(langLoc[0]);
    }

    // clear session attribute if necessary, after calling Samigo
    String clearAttr = params.getClearAttr();

    if (clearAttr != null && !clearAttr.equals("")) {
        Session session = SessionManager.getCurrentSession();
        // don't let users clear random attributes
        if (clearAttr.startsWith("LESSONBUILDER_RETURNURL")) {
            session.setAttribute(clearAttr, null);
        }
    }

    if (htmlTypes == null) {
        String mmTypes = ServerConfigurationService.getString("lessonbuilder.html.types", DEFAULT_HTML_TYPES);
        htmlTypes = mmTypes.split(",");
        for (int i = 0; i < htmlTypes.length; i++) {
            htmlTypes[i] = htmlTypes[i].trim().toLowerCase();
        }
        Arrays.sort(htmlTypes);
    }

    if (mp4Types == null) {
        String m4Types = ServerConfigurationService.getString("lessonbuilder.mp4.types", DEFAULT_MP4_TYPES);
        mp4Types = m4Types.split(",");
        for (int i = 0; i < mp4Types.length; i++) {
            mp4Types[i] = mp4Types[i].trim().toLowerCase();
        }
        Arrays.sort(mp4Types);
    }

    if (html5Types == null) {
        String jTypes = ServerConfigurationService.getString("lessonbuilder.html5.types", DEFAULT_HTML5_TYPES);
        html5Types = jTypes.split(",");
        for (int i = 0; i < html5Types.length; i++) {
            html5Types[i] = html5Types[i].trim().toLowerCase();
        }
        Arrays.sort(html5Types);
    }

    // remember that page tool was reset, so we need to give user the option
    // of going to the last page from the previous session
    SimplePageToolDao.PageData lastPage = simplePageBean.toolWasReset();

    // if this page was copied from another site we may have to update links
    // can only do the fixups if you can write. We could hack permissions, but
    // I assume a site owner will access the site first
    if (canEditPage)
        simplePageBean.maybeUpdateLinks();

    // if starting the tool, sendingpage isn't set. the following call
    // will give us the top page.
    SimplePage currentPage = simplePageBean.getCurrentPage();

    // now we need to find our own item, for access checks, etc.
    SimplePageItem pageItem = null;
    if (currentPage != null) {
        pageItem = simplePageBean.getCurrentPageItem(params.getItemId());
    }
    // one more security check: make sure the item actually involves this
    // page.
    // otherwise someone could pass us an item from a different page in
    // another site
    // actually this normally happens if the page doesn't exist and we don't
    // have permission to create it
    if (currentPage == null || pageItem == null || (pageItem.getType() != SimplePageItem.STUDENT_CONTENT
            && Long.valueOf(pageItem.getSakaiId()) != currentPage.getPageId())) {
        log.warn("ShowPage item not in page");
        UIOutput.make(tofill, "error-div");
        if (currentPage == null)
            // most likely tool was created by site info but no page
            // has created. It will created the first time an item is created,
            // so from a user point of view it looks like no item has been added
            UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.noitems_error_user"));
        else
            UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
        return;
    }

    // the reason for a seaprate release date test is so we can show the date.
    // there are currently some issues. If the page is not released and the user doesn't have
    // access because of groups, this will show the not released data. That's misleading because
    // when the release date comes the user still won't be able to see it. Not sure if it's worth
    // creating a separate function that just checks the groups. It's easy to test hidden, so I do that. The idea is that
    // if it's both hidden and not released it makes sense to show hidden.

    // check two parts of isitemvisible where we want to give specific errors
    // potentially need time zone for setting release date
    if (!canSeeAll && currentPage.getReleaseDate() != null && currentPage.getReleaseDate().after(new Date())
            && !currentPage.isHidden()) {
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, M_locale);
        TimeZone tz = timeService.getLocalTimeZone();
        df.setTimeZone(tz);
        String releaseDate = df.format(currentPage.getReleaseDate());
        String releaseMessage = messageLocator.getMessage("simplepage.not_yet_available_releasedate")
                .replace("{}", releaseDate);

        UIOutput.make(tofill, "error-div");
        UIOutput.make(tofill, "error", releaseMessage);

        return;
    }

    // the only thing not already tested (or tested in release check below) in isItemVisible is groups. In theory
    // no one should have a URL to a page for which they aren't in the group,
    // so I'm not trying to give a better message than just hidden
    if (!canSeeAll && currentPage.isHidden() || !simplePageBean.isItemVisible(pageItem)) {
        UIOutput.make(tofill, "error-div");
        UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available_hidden"));
        return;
    }

    // I believe we've now checked all the args for permissions issues. All
    // other item and
    // page references are generated here based on the contents of the page
    // and items.

    // needed to process path arguments first, so refresh page goes the right page
    if (simplePageBean.getTopRefresh()) {
        UIOutput.make(tofill, "refresh");
        return; // but there's no point doing anything more
    }

    // error from previous operation
    // consumes the message, so don't do it if refreshing
    List<String> errMessages = simplePageBean.errMessages();
    if (errMessages != null) {
        UIOutput.make(tofill, "error-div");
        for (String e : errMessages) {
            UIBranchContainer er = UIBranchContainer.make(tofill, "errors:");
            UIOutput.make(er, "error-message", e);
        }
    }

    if (canEditPage) {
        // special instructor-only javascript setup.
        // but not if we're refreshing
        UIOutput.make(tofill, "instructoronly");
        // Chome and IE will abort a page if some on it was input from
        // a previous submit. I.e. if an HTML editor was used. In theory they
        // only do this if part of it is Javascript, but in practice they do
        // it for images as well. The protection isn't worthwhile, since it only
        // protects the first time. Since it will reesult in a garbled page, 
        // people will just refresh the page, and then they'll get the new
        // contents. The Chrome guys refuse to fix this so it just applies to Javascript
        httpServletResponse.setHeader("X-XSS-Protection", "0");
    }

    if (currentPage == null || pageItem == null) {
        UIOutput.make(tofill, "error-div");
        if (canEditPage) {
            UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.impossible1"));
        } else {
            UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
        }
        return;
    }

    // Set up customizable CSS
    ContentResource cssLink = simplePageBean.getCssForCurrentPage();
    if (cssLink != null) {
        UIOutput.make(tofill, "customCSS").decorate(new UIFreeAttributeDecorator("href", cssLink.getUrl()));
    }

    // offer to go to saved page if this is the start of a session, in case
    // user has logged off and logged on again.
    // need to offer to go to previous page? even if a new session, no need
    // if we're already on that page
    if (lastPage != null && lastPage.pageId != currentPage.getPageId()) {
        UIOutput.make(tofill, "refreshAlert");
        UIOutput.make(tofill, "refresh-message", messageLocator.getMessage("simplepage.last-visited"));
        // Should simply refresh
        GeneralViewParameters p = new GeneralViewParameters(VIEW_ID);
        p.setSendingPage(lastPage.pageId);
        p.setItemId(lastPage.itemId);
        // reset the path to the saved one
        p.setPath("log");

        String name = lastPage.name;

        // Titles are set oddly by Student Content Pages
        SimplePage lastPageObj = simplePageToolDao.getPage(lastPage.pageId);
        if (lastPageObj.getOwner() != null) {
            name = lastPageObj.getTitle();
        }

        UIInternalLink.make(tofill, "refresh-link", name, p);
    }

    // path is the breadcrumbs. Push, pop or reset depending upon path=
    // programmer documentation.
    String title;
    String ownerName = null;
    if (pageItem.getType() != SimplePageItem.STUDENT_CONTENT) {
        title = pageItem.getName();
    } else {
        title = currentPage.getTitle();
        if (!pageItem.isAnonymous() || canEditPage) {
            try {
                String owner = currentPage.getOwner();
                String group = currentPage.getGroup();
                if (group != null)
                    ownerName = simplePageBean.getCurrentSite().getGroup(group).getTitle();
                else
                    ownerName = UserDirectoryService.getUser(owner).getDisplayName();

            } catch (Exception ignore) {
            }
            ;
            if (ownerName != null && !ownerName.equals(title))
                title += " (" + ownerName + ")";
        }
    }

    String newPath = null;

    // If the path is "none", then we don't want to record this page as being viewed, or set a path
    if (!params.getPath().equals("none")) {
        newPath = simplePageBean.adjustPath(params.getPath(), currentPage.getPageId(), pageItem.getId(), title);
        simplePageBean.adjustBackPath(params.getBackPath(), currentPage.getPageId(), pageItem.getId(),
                pageItem.getName());
    }

    // put out link to index of pages
    GeneralViewParameters showAll = new GeneralViewParameters(PagePickerProducer.VIEW_ID);
    showAll.setSource("summary");
    UIInternalLink.make(tofill, "print-view", messageLocator.getMessage("simplepage.print_view"), showAll);
    UIInternalLink.make(tofill, "show-pages", messageLocator.getMessage("simplepage.showallpages"), showAll);

    if (canEditPage) {
        // show tool bar, but not if coming from grading pane
        if (!cameFromGradingPane) {
            createToolBar(tofill, currentPage, (pageItem.getType() == SimplePageItem.STUDENT_CONTENT));
        }

        UIOutput.make(tofill, "title-descrip");
        String label = null;
        if (pageItem.getType() == SimplePageItem.STUDENT_CONTENT)
            label = messageLocator.getMessage("simplepage.editTitle");
        else
            label = messageLocator.getMessage("simplepage.title");
        String descrip = null;
        if (pageItem.getType() == SimplePageItem.STUDENT_CONTENT)
            descrip = messageLocator.getMessage("simplepage.title-student-descrip");
        else if (pageItem.getPageId() == 0)
            descrip = messageLocator.getMessage("simplepage.title-top-descrip");
        else
            descrip = messageLocator.getMessage("simplepage.title-descrip");

        UIOutput.make(tofill, "edit-title").decorate(new UIFreeAttributeDecorator("title", descrip));
        UIOutput.make(tofill, "edit-title-text", label);
        UIOutput.make(tofill, "title-descrip-text", descrip);

        if (pageItem.getPageId() == 0 && currentPage.getOwner() == null) { // top level page
            // need dropdown 
            UIOutput.make(tofill, "dropdown");
            UIOutput.make(tofill, "moreDiv");
            UIOutput.make(tofill, "new-page").decorate(new UIFreeAttributeDecorator("title",
                    messageLocator.getMessage("simplepage.new-page-tooltip")));
            createToolBarLink(PermissionsHelperProducer.VIEW_ID, tofill, "permissions",
                    "simplepage.permissions", currentPage, "simplepage.permissions.tooltip");
            UIOutput.make(tofill, "import-cc").decorate(new UIFreeAttributeDecorator("title",
                    messageLocator.getMessage("simplepage.import_cc.tooltip")));
            UIOutput.make(tofill, "export-cc").decorate(new UIFreeAttributeDecorator("title",
                    messageLocator.getMessage("simplepage.export_cc.tooltip")));

            // Check to see if we have tools registered for external import
            List<Map<String, Object>> toolsFileItem = simplePageBean.getToolsFileItem();
            if (toolsFileItem.size() > 0) {
                UIOutput.make(tofill, "show-lti-import");
                UIForm ltiImport = UIForm.make(tofill, "lti-import-form");
                makeCsrf(ltiImport, "csrf1");
                GeneralViewParameters ltiParams = new GeneralViewParameters();
                ltiParams.setSendingPage(currentPage.getPageId());
                ltiParams.viewID = LtiFileItemProducer.VIEW_ID;
                UILink link = UIInternalLink.make(tofill, "lti-import-link",
                        messageLocator.getMessage("simplepage.import_lti_button"), ltiParams);
                link.decorate(new UITooltipDecorator(messageLocator.getMessage("simplepage.fileitem.tooltip")));
            }
        }

        // Checks to see that user can edit and that this is either a top level page,
        // or a top level student page (not a subpage to a student page)
        if (simplePageBean.getEditPrivs() == 0 && (pageItem.getPageId() == 0)) {
            UIOutput.make(tofill, "remove-li");
            UIOutput.make(tofill, "remove-page").decorate(new UIFreeAttributeDecorator("title",
                    messageLocator.getMessage("simplepage.remove-page-tooltip")));

            if (allowDeleteOrphans) {
                UIOutput.make(tofill, "delete-orphan-li");
                UIForm orphan = UIForm.make(tofill, "delete-orphan-form");
                makeCsrf(orphan, "csrf1");
                UICommand.make(orphan, "delete-orphan", "#{simplePageBean.deleteOrphanPages}");
                UIOutput.make(orphan, "delete-orphan-link").decorate(new UIFreeAttributeDecorator("title",
                        messageLocator.getMessage("simplepage.delete-orphan-pages-desc")));
            }

        } else if (simplePageBean.getEditPrivs() == 0 && currentPage.getOwner() != null) {
            // getEditPrivs < 2 if we want to let the student delete. Currently we don't. There can be comments
            // from other students and the page can be shared
            SimpleStudentPage studentPage = simplePageToolDao.findStudentPage(currentPage.getTopParent());
            if (studentPage != null && studentPage.getPageId() == currentPage.getPageId()) {
                UIOutput.make(tofill, "remove-student");
                UIOutput.make(tofill, "remove-page-student").decorate(new UIFreeAttributeDecorator("title",
                        messageLocator.getMessage("simplepage.remove-student-page-explanation")));
            }
        }

        UIOutput.make(tofill, "dialogDiv");
        UIOutput.make(tofill, "siteid", simplePageBean.getCurrentSiteId());
        UIOutput.make(tofill, "locale", M_locale.toString());

    } else if (!canReadPage) {
        return;
    } else if (!canSeeAll) {
        // see if there are any unsatisfied prerequisites
        // if this isn't a top level page, this will check that the page above is
        // accessible. That matters because we check visible, available and release
        // only for this page but not for the containing page
        List<String> needed = simplePageBean.pagesNeeded(pageItem);
        if (needed.size() > 0) {
            // yes. error and abort
            if (pageItem.getPageId() != 0) {
                // not top level. This should only happen from a "next"
                // link.
                // at any rate, the best approach is to send the user back
                // to the calling page
                List<SimplePageBean.PathEntry> path = simplePageBean.getHierarchy();
                SimplePageBean.PathEntry containingPage = null;
                if (path.size() > 1) {
                    // page above this. this page is on the top
                    containingPage = path.get(path.size() - 2);
                }

                if (containingPage != null) { // not a top level page, point
                    // to containing page
                    GeneralViewParameters view = new GeneralViewParameters(VIEW_ID);
                    view.setSendingPage(containingPage.pageId);
                    view.setItemId(containingPage.pageItemId);
                    view.setPath(Integer.toString(path.size() - 2));
                    UIInternalLink.make(tofill, "redirect-link", containingPage.title, view);
                    UIOutput.make(tofill, "redirect");
                } else {
                    UIOutput.make(tofill, "error-div");
                    UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
                }

                return;
            }

            // top level page where prereqs not satisified. Output list of
            // pages he needs to do first
            UIOutput.make(tofill, "pagetitle", currentPage.getTitle());
            UIOutput.make(tofill, "error-div");
            UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.has_prerequistes"));
            UIBranchContainer errorList = UIBranchContainer.make(tofill, "error-list:");
            for (String errorItem : needed) {
                UIBranchContainer errorListItem = UIBranchContainer.make(errorList, "error-item:");
                UIOutput.make(errorListItem, "error-item-text", errorItem);
            }
            return;
        }
    }

    ToolSession toolSession = SessionManager.getCurrentToolSession();
    // this code is now for 11 only. helpurl is used in 9 and 10 to indicate neo portal
    // at this point only two code paths are intended to work. inline and iframe.
    // inline pushes stuff into the morpheus-generated header. iframe uses an extra line
    // the previous mode required us to try to duplicate the header generated by morpheus
    // this was too error-prone.
    String helpurl = null; /* (String)toolSession.getAttribute("sakai-portal:help-action"); */
    String reseturl = null; /* (String)toolSession.getAttribute("sakai-portal:reset-action"); */

    Placement placement = toolManager.getCurrentPlacement();
    String toolId = placement.getToolId();
    boolean inline = false;

    // inline includes iframes when morpheus is in effect
    if ("morpheus".equals(portalTemplates) && httpServletRequest.getRequestURI().startsWith("/portal/site/")) {
        inline = true;
    }

    String skinName = null;
    String skinRepo = null;
    String iconBase = null;

    UIComponent titlediv = UIOutput.make(tofill, "titlediv");
    if (inline)
        titlediv.decorate(new UIFreeAttributeDecorator("style", "display:none"));
    // we need to do special CSS for old portal
    else if (helpurl == null)
        titlediv.decorate(new UIStyleDecorator("oldPortal"));

    if (helpurl != null || reseturl != null) {
        // these URLs are defined if we're in the neo portal
        // in that case we need our own help and reset icons. We want
        // to take them from the current skin, so find its prefix.
        // unfortunately the neoportal tacks neo- on front of the skin
        // name, so this is more complex than you might think.

        skinRepo = ServerConfigurationService.getString("skin.repo", "/library/skin");
        iconBase = skinRepo + "/" + CSSUtils.adjustCssSkinFolder(null) + "/images";

        UIVerbatim.make(tofill, "iconstyle", ICONSTYLE.replace("{}", iconBase));

    }

    if (helpurl != null) {
        UILink.make(tofill, (pageItem.getPageId() == 0 ? "helpbutton" : "helpbutton2"), helpurl)
                .decorate(new UIFreeAttributeDecorator("onclick", "openWindow('" + helpurl
                        + "', 'Help', 'resizeable=yes,toolbar=no,scrollbars=yes,menubar=yes,width=800,height=600'); return false"))
                .decorate(new UIFreeAttributeDecorator("title",
                        messageLocator.getMessage("simplepage.help-button")));
        if (!inline)
            UIOutput.make(tofill, (pageItem.getPageId() == 0 ? "helpimage" : "helpimage2")).decorate(
                    new UIFreeAttributeDecorator("alt", messageLocator.getMessage("simplepage.help-button")));
        UIOutput.make(tofill, (pageItem.getPageId() == 0 ? "helpnewwindow" : "helpnewwindow2"),
                messageLocator.getMessage("simplepage.opens-in-new"));
        UILink.make(tofill, "directurl")
                .decorate(new UIFreeAttributeDecorator("rel",
                        "#Main" + Web.escapeJavascript(placement.getId()) + "_directurl"))
                .decorate(new UIFreeAttributeDecorator("title",
                        messageLocator.getMessage("simplepage.direct-link")));
        // if (inline) {
        UIOutput.make(tofill, "directurl-div").decorate(new UIFreeAttributeDecorator("id",
                "Main" + Web.escapeJavascript(placement.getId()) + "_directurl"));
        // in general 2.9 doesn't have the url shortener
        if (majorVersion >= 10) {
            UIOutput.make(tofill, "directurl-input")
                    .decorate(new UIFreeAttributeDecorator("onclick",
                            "toggleShortUrlOutput('" + myUrl() + "/portal/directtool/" + placement.getId()
                                    + "/', this, 'Main" + Web.escapeJavascript(placement.getId())
                                    + "_urlholder');"));
            UIOutput.make(tofill, "directurl-shorten", messageLocator.getMessage("simplepage.short-url"));
        }
        UIOutput.make(tofill, "directurl-textarea", myUrl() + "/portal/directtool/" + placement.getId() + "/")
                .decorate(new UIFreeAttributeDecorator("class",
                        "portlet title-tools Main" + Web.escapeJavascript(placement.getId()) + "_urlholder"));
        // } else
        UIOutput.make(tofill, "directimage").decorate(
                new UIFreeAttributeDecorator("alt", messageLocator.getMessage("simplepage.direct-link")));
    }

    // morpheus does reset as part of title
    if (reseturl != null && !inline) {
        UILink.make(tofill, (pageItem.getPageId() == 0 ? "resetbutton" : "resetbutton2"), reseturl)
                .decorate(new UIFreeAttributeDecorator("onclick",
                        "location.href='" + reseturl + "'; return false"))
                .decorate(new UIFreeAttributeDecorator("title",
                        messageLocator.getMessage("simplepage.reset-button")));
        UIOutput.make(tofill, (pageItem.getPageId() == 0 ? "resetimage" : "resetimage2")).decorate(
                new UIFreeAttributeDecorator("alt", messageLocator.getMessage("simplepage.reset-button")));
    }

    // note page accessed. the code checks to see whether all the required
    // items on it have been finished, and if so marks it complete, else just updates
    // access date save the path because if user goes to it later we want to restore the
    // breadcrumbs
    if (newPath != null) {
        if (pageItem.getType() != SimplePageItem.STUDENT_CONTENT) {
            simplePageBean.track(pageItem.getId(), newPath);
        } else {
            simplePageBean.track(pageItem.getId(), newPath, currentPage.getPageId());
        }
    }

    if (currentPage.getOwner() != null && simplePageBean.getEditPrivs() == 0) {
        SimpleStudentPage student = simplePageToolDao.findStudentPageByPageId(currentPage.getPageId());

        // Make sure this is a top level student page
        if (student != null && pageItem.getGradebookId() != null) {
            UIOutput.make(tofill, "gradingSpan");
            UIOutput.make(tofill, "commentsUUID", String.valueOf(student.getId()));
            UIOutput.make(tofill, "commentPoints",
                    String.valueOf((student.getPoints() != null ? student.getPoints() : "")));
            UIOutput pointsBox = UIOutput.make(tofill, "studentPointsBox");
            UIOutput.make(tofill, "topmaxpoints", String
                    .valueOf((pageItem.getGradebookPoints() != null ? pageItem.getGradebookPoints() : "")));
            if (ownerName != null)
                pointsBox.decorate(new UIFreeAttributeDecorator("title",
                        messageLocator.getMessage("simplepage.grade-for-student").replace("{}", ownerName)));

            List<SimpleStudentPage> studentPages = simplePageToolDao.findStudentPages(student.getItemId());

            Collections.sort(studentPages, new Comparator<SimpleStudentPage>() {
                public int compare(SimpleStudentPage o1, SimpleStudentPage o2) {
                    String title1 = o1.getTitle();
                    if (title1 == null)
                        title1 = "";
                    String title2 = o2.getTitle();
                    if (title2 == null)
                        title2 = "";
                    return title1.compareTo(title2);
                }
            });

            for (int in = 0; in < studentPages.size(); in++) {
                if (studentPages.get(in).isDeleted()) {
                    studentPages.remove(in);
                }
            }

            int i = -1;

            for (int in = 0; in < studentPages.size(); in++) {
                if (student.getId() == studentPages.get(in).getId()) {
                    i = in;
                    break;
                }
            }

            if (i > 0) {
                GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID,
                        studentPages.get(i - 1).getPageId());
                eParams.setItemId(studentPages.get(i - 1).getItemId());
                eParams.setPath("next");

                UIInternalLink.make(tofill, "gradingBack", eParams);
            }

            if (i < studentPages.size() - 1) {
                GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID,
                        studentPages.get(i + 1).getPageId());
                eParams.setItemId(studentPages.get(i + 1).getItemId());
                eParams.setPath("next");

                UIInternalLink.make(tofill, "gradingForward", eParams);
            }

            printGradingForm(tofill);
        }
    }

    // breadcrumbs
    if (pageItem.getPageId() != 0) {
        // Not top-level, so we have to show breadcrumbs

        List<SimplePageBean.PathEntry> breadcrumbs = simplePageBean.getHierarchy();

        int index = 0;
        if (breadcrumbs.size() > 1 || reseturl != null || helpurl != null) {
            UIOutput.make(tofill, "crumbdiv");
            if (breadcrumbs.size() > 1)
                for (SimplePageBean.PathEntry e : breadcrumbs) {
                    // don't show current page. We already have a title. This
                    // was too much
                    UIBranchContainer crumb = UIBranchContainer.make(tofill, "crumb:");
                    GeneralViewParameters view = new GeneralViewParameters(VIEW_ID);
                    view.setSendingPage(e.pageId);
                    view.setItemId(e.pageItemId);
                    view.setPath(Integer.toString(index));
                    UIComponent link = null;
                    if (index < breadcrumbs.size() - 1) {
                        // Not the last item
                        link = UIInternalLink.make(crumb, "crumb-link", e.title, view);
                        UIOutput.make(crumb, "crumb-follow", " > ");
                    } else {
                        UIOutput.make(crumb, "crumb-follow", e.title).decorate(new UIStyleDecorator("bold"));
                    }
                    index++;
                }
            else {
                UIBranchContainer crumb = UIBranchContainer.make(tofill, "crumb:");
                UILink.make(crumb, "crum-link", currentPage.getTitle(), reseturl);
            }
        } else {
            if (reseturl != null) {
                UIOutput.make(tofill, "pagetitletext", currentPage.getTitle());
            } else if (!inline) {
                UIOutput.make(tofill, "pagetitle", currentPage.getTitle());
            }
        }
    } else {
        if (reseturl != null) {
            UILink.make(tofill, "pagetitlelink", reseturl);
            UIOutput.make(tofill, "pagetitletext", currentPage.getTitle());
        } else if (!inline) {
            UIOutput.make(tofill, "pagetitle", currentPage.getTitle());
        }
    }

    // see if there's a next item in sequence.
    simplePageBean.addPrevLink(tofill, pageItem);
    simplePageBean.addNextLink(tofill, pageItem);

    // swfObject is not currently used
    boolean shownSwfObject = false;

    long newItemId = -1L;
    String newItemStr = (String) toolSession.getAttribute("lessonbuilder.newitem");
    if (newItemStr != null) {
        toolSession.removeAttribute("lessonbuilder.newitem");
        try {
            newItemId = Long.parseLong(newItemStr);
        } catch (Exception e) {
        }
    }

    // items to show
    List<SimplePageItem> itemList = (List<SimplePageItem>) simplePageBean
            .getItemsOnPage(currentPage.getPageId());

    // Move all items with sequence <= 0 to the end of the list.
    // Count is necessary to guarantee we don't infinite loop over a
    // list that only has items with sequence <= 0.
    // Becauses sequence number is < 0, these start out at the beginning
    int count = 1;
    while (itemList.size() > count && itemList.get(0).getSequence() <= 0) {
        itemList.add(itemList.remove(0));
        count++;
    }

    // Make sure we only add the comments javascript file once,
    // even if there are multiple comments tools on the page.
    boolean addedCommentsScript = false;
    int commentsCount = 0;

    // Find the most recent comment on the page by current user
    long postedCommentId = -1;
    if (params.postedComment) {
        postedCommentId = findMostRecentComment();
    }

    boolean showDownloads = (simplePageBean.getCurrentSite().getProperties()
            .getProperty("lessonbuilder-nodownloadlinks") == null);

    //
    //
    // MAIN list of items
    //
    // produce the main table

    // Is anything visible?
    // Note that we don't need to check whether any item is available, since the first visible
    // item is always available.
    boolean anyItemVisible = false;

    if (itemList.size() > 0) {
        UIBranchContainer container = UIBranchContainer.make(tofill, "itemContainer:");

        boolean showRefresh = false;
        boolean fisrt = false;
        int textboxcount = 1;

        int cols = 0;
        int colnum = 0;

        UIBranchContainer sectionContainer = null;
        UIBranchContainer columnContainer = null;
        UIBranchContainer tableContainer = null;

        boolean first = true;

        for (SimplePageItem i : itemList) {

            // break is not a normal item. handle it first
            // this will work whether first item is break or not. Might be a section
            // break or a normal item
            if (first || i.getType() == SimplePageItem.BREAK) {
                boolean sectionbreak = false;
                if (first || "section".equals(i.getFormat())) {
                    sectionContainer = UIBranchContainer.make(container, "section:");
                    cols = colCount(itemList, i.getId());
                    sectionbreak = true;
                    colnum = 0;
                } else if ("colunn".equals(i.getFormat()))
                    colnum++;
                columnContainer = UIBranchContainer.make(sectionContainer, "column:");

                tableContainer = UIBranchContainer.make(columnContainer, "itemTable:");
                Integer width = new Integer(
                        i.getAttribute("colwidth") == null ? "1" : i.getAttribute("colwidth"));
                Integer split = new Integer(
                        i.getAttribute("colsplit") == null ? "1" : i.getAttribute("colsplit"));
                colnum += width; // number after this column

                String color = i.getAttribute("colcolor");

                columnContainer.decorate(new UIStyleDecorator(
                        "cols" + cols + (colnum == cols ? " lastcol" : "") + (width > 1 ? " double" : "")
                                + (split > 1 ? " split" : "") + (color == null ? "" : " col" + color)));
                UIComponent delIcon = UIOutput.make(columnContainer, "section-td");
                if (first)
                    delIcon.decorate(new UIFreeAttributeDecorator("style", "display:none"));

                UIOutput.make(columnContainer, "break-msg", messageLocator
                        .getMessage(sectionbreak ? "simplepage.break-here" : "simplepage.break-column-here"));
                UIOutput.make(columnContainer, "section2");
                UIOutput.make(columnContainer, "section3").decorate(new UIFreeAttributeDecorator("title",
                        messageLocator.getMessage("simplepage.columnopen")));
                UIOutput.make(columnContainer, "addbottom");
                UIOutput.make(columnContainer, "addbottom2").decorate(new UIFreeAttributeDecorator("title",
                        messageLocator.getMessage("simplepage.add-item-column")));
                UILink link = UILink.make(columnContainer, "section-del-link", (String) null, "/" + i.getId());
                link.decorate(new UIFreeAttributeDecorator("title",
                        messageLocator.getMessage("simplepage.join-items")));
                link.decorate(new UIStyleDecorator(sectionbreak ? "section-merge-link" : "column-merge-link"));

                UIBranchContainer tableRow = UIBranchContainer.make(tableContainer, "item:");
                tableRow.decorate(new UIFreeAttributeDecorator("class", "break" + i.getFormat()));

                first = false;
                if (i.getType() == SimplePageItem.BREAK)
                    continue;
                // for first item, if wasn't break, process it
            }

            // listitem is mostly historical. it uses some shared HTML, but
            // if I were
            // doing it from scratch I wouldn't make this distinction. At
            // the moment it's
            // everything that isn't inline.

            boolean listItem = !(i.getType() == SimplePageItem.TEXT || i.getType() == SimplePageItem.MULTIMEDIA
                    || i.getType() == SimplePageItem.COMMENTS || i.getType() == SimplePageItem.STUDENT_CONTENT
                    || i.getType() == SimplePageItem.QUESTION || i.getType() == SimplePageItem.PEEREVAL
                    || i.getType() == SimplePageItem.BREAK);
            // (i.getType() == SimplePageItem.PAGE &&
            // "button".equals(i.getFormat())))

            if (!simplePageBean.isItemVisible(i, currentPage)) {
                continue;
            }
            // break isn't a real item. probably don't want to count it
            if (i.getType() != SimplePageItem.BREAK)
                anyItemVisible = true;

            UIBranchContainer tableRow = UIBranchContainer.make(tableContainer, "item:");

            // set class name showing what the type is, so people can do funky CSS

            String itemClassName = null;

            switch (i.getType()) {
            case SimplePageItem.RESOURCE:
                itemClassName = "resourceType";
                break;
            case SimplePageItem.PAGE:
                itemClassName = "pageType";
                break;
            case SimplePageItem.ASSIGNMENT:
                itemClassName = "assignmentType";
                break;
            case SimplePageItem.ASSESSMENT:
                itemClassName = "assessmentType";
                break;
            case SimplePageItem.TEXT:
                itemClassName = "textType";
                break;
            case SimplePageItem.URL:
                itemClassName = "urlType";
                break;
            case SimplePageItem.MULTIMEDIA:
                itemClassName = "multimediaType";
                break;
            case SimplePageItem.FORUM:
                itemClassName = "forumType";
                break;
            case SimplePageItem.COMMENTS:
                itemClassName = "commentsType";
                break;
            case SimplePageItem.STUDENT_CONTENT:
                itemClassName = "studentContentType";
                break;
            case SimplePageItem.QUESTION:
                itemClassName = "question";
                break;
            case SimplePageItem.BLTI:
                itemClassName = "bltiType";
                break;
            case SimplePageItem.PEEREVAL:
                itemClassName = "peereval";
                break;
            }

            if (listItem) {
                itemClassName = itemClassName + " listType";
            }
            if (canEditPage) {
                itemClassName = itemClassName + "  canEdit";
            }

            if (i.getId() == newItemId)
                itemClassName = itemClassName + " newItem";

            tableRow.decorate(new UIFreeAttributeDecorator("class", itemClassName));

            if (canEditPage)
                UIOutput.make(tableRow, "itemid", String.valueOf(i.getId()));

            // you really need the HTML file open at the same time to make
            // sense of the following code
            if (listItem) { // Not an HTML Text, Element or Multimedia
                // Element

                if (canEditPage) {
                    UIOutput.make(tableRow, "current-item-id2", String.valueOf(i.getId()));
                }

                // users can declare a page item to be navigational. If so
                // we display
                // it to the left of the normal list items, and use a
                // button. This is
                // used for pages that are "next" pages, i.e. they replace
                // this page
                // rather than creating a new level in the breadcrumbs.
                // Since they can't
                // be required, they don't need the status image, which is
                // good because
                // they're displayed with colspan=2, so there's no space for
                // the image.

                boolean navButton = "button".equals(i.getFormat()) && !i.isRequired();
                boolean notDone = false;
                Status status = Status.NOT_REQUIRED;
                if (!navButton) {
                    status = handleStatusImage(tableRow, i);
                    if (status == Status.REQUIRED) {
                        notDone = true;
                    }
                }

                boolean isInline = (i.getType() == SimplePageItem.BLTI && "inline".equals(i.getFormat()));

                UIOutput linktd = UIOutput.make(tableRow, "item-td");

                UIOutput contentCol = UIOutput.make(tableRow, "contentCol");
                // BLTI seems to require explicit specificaiton for column width. Otherwise
                // we get 300 px wide. Don't know why. Doesn't happen to other iframes
                if (isInline)
                    contentCol.decorate(new UIFreeAttributeDecorator("style", "width:100%"));

                UIBranchContainer linkdiv = null;
                if (!isInline) {
                    linkdiv = UIBranchContainer.make(tableRow, "link-div:");
                    UIOutput itemicon = UIOutput.make(linkdiv, "item-icon");
                    switch (i.getType()) {
                    case SimplePageItem.FORUM:
                        itemicon.decorate(new UIStyleDecorator("fa-comments"));
                        break;
                    case SimplePageItem.ASSIGNMENT:
                        itemicon.decorate(new UIStyleDecorator("fa-tasks"));
                        break;
                    case SimplePageItem.ASSESSMENT:
                        itemicon.decorate(new UIStyleDecorator("fa-puzzle-piece"));
                        break;
                    case SimplePageItem.BLTI:
                        itemicon.decorate(new UIStyleDecorator("fa-globe"));
                        break;
                    case SimplePageItem.PAGE:
                        itemicon.decorate(new UIStyleDecorator("fa-folder-open-o"));
                        break;
                    case SimplePageItem.RESOURCE:
                        String mimeType = i.getHtml();

                        if ("application/octet-stream".equals(mimeType)) {
                            // OS X reports octet stream for things like MS Excel documents.
                            // Force a mimeType lookup so we get a decent icon.
                            mimeType = null;
                        }

                        if (mimeType == null || mimeType.equals("")) {
                            String s = i.getSakaiId();
                            int j = s.lastIndexOf(".");
                            if (j >= 0)
                                s = s.substring(j + 1);
                            mimeType = ContentTypeImageService.getContentType(s);
                            // System.out.println("type " + s + ">" + mimeType);
                        }

                        String src = null;
                        //if (!useSakaiIcons)
                        src = imageToMimeMap.get(mimeType);
                        if (src == null) {
                            src = "fa-file-o";
                            //String image = ContentTypeImageService.getContentTypeImage(mimeType);
                            // if (image != null)
                            //   src = "/library/image/" + image;
                        }

                        if (src != null) {
                            itemicon.decorate(new UIStyleDecorator(src));
                        }
                        break;
                    }
                }

                UIOutput descriptiondiv = null;

                // refresh isn't actually used anymore. We've changed the
                // way things are
                // done so the user never has to request a refresh.
                //   FYI: this actually puts in an IFRAME for inline BLTI items
                showRefresh = !makeLink(tableRow, "link", i, canSeeAll, currentPage, notDone, status)
                        || showRefresh;
                UILink.make(tableRow, "copylink", i.getName(),
                        "http://lessonbuilder.sakaiproject.org/" + i.getId() + "/")
                        .decorate(new UIFreeAttributeDecorator("title",
                                messageLocator.getMessage("simplepage.copylink2").replace("{}", i.getName())));

                // dummy is used when an assignment, quiz, or forum item is
                // copied
                // from another site. The way the copy code works, our
                // import code
                // doesn't have access to the necessary info to use the item
                // from the
                // new site. So we add a dummy, which generates an
                // explanation that the
                // author is going to have to choose the item from the
                // current site
                if (i.getSakaiId().equals(SimplePageItem.DUMMY)) {
                    String code = null;
                    switch (i.getType()) {
                    case SimplePageItem.ASSIGNMENT:
                        code = "simplepage.copied.assignment";
                        break;
                    case SimplePageItem.ASSESSMENT:
                        code = "simplepage.copied.assessment";
                        break;
                    case SimplePageItem.FORUM:
                        code = "simplepage.copied.forum";
                        break;
                    }
                    descriptiondiv = UIOutput.make(tableRow, "description", messageLocator.getMessage(code));
                } else {
                    descriptiondiv = UIOutput.make(tableRow, "description", i.getDescription());
                }
                if (isInline)
                    descriptiondiv.decorate(new UIFreeAttributeDecorator("style", "margin-top: 4px"));

                if (!isInline) {
                    // nav button gets float left so any description goes to its
                    // right. Otherwise the
                    // description block will display underneath
                    if ("button".equals(i.getFormat())) {
                        linkdiv.decorate(new UIFreeAttributeDecorator("style", "float:none"));
                    }
                    // for accessibility
                    if (navButton) {
                        linkdiv.decorate(new UIFreeAttributeDecorator("role", "navigation"));
                    }
                }

                // note that a lot of the info here is used by the
                // javascript that prepares
                // the jQuery dialogs
                String itemGroupString = null;
                boolean entityDeleted = false;
                boolean notPublished = false;
                if (canEditPage) {
                    UIOutput.make(tableRow, "edit-td");
                    UILink.make(tableRow, "edit-link", (String) null, "")
                            .decorate(new UIFreeAttributeDecorator("title", messageLocator
                                    .getMessage("simplepage.edit-title.generic").replace("{}", i.getName())));

                    // the following information is displayed using <INPUT
                    // type=hidden ...
                    // it contains information needed to populate the "edit"
                    // popup dialog
                    UIOutput.make(tableRow, "prerequisite-info", String.valueOf(i.isPrerequisite()));

                    if (i.getType() == SimplePageItem.ASSIGNMENT) {
                        // the type indicates whether scoring is letter
                        // grade, number, etc.
                        // the javascript needs this to present the right
                        // choices to the user
                        // types 6 and 8 aren't legal scoring types, so they
                        // are used as
                        // markers for quiz or forum. I ran out of numbers
                        // and started using
                        // text for things that aren't scoring types. That's
                        // better anyway
                        int type = 4;
                        LessonEntity assignment = null;
                        if (!i.getSakaiId().equals(SimplePageItem.DUMMY)) {
                            assignment = assignmentEntity.getEntity(i.getSakaiId(), simplePageBean);
                            if (assignment != null) {
                                type = assignment.getTypeOfGrade();
                                String editUrl = assignment.editItemUrl(simplePageBean);
                                if (editUrl != null) {
                                    UIOutput.make(tableRow, "edit-url", editUrl);
                                }
                                itemGroupString = simplePageBean.getItemGroupString(i, assignment, true);
                                UIOutput.make(tableRow, "item-groups", itemGroupString);
                                if (!assignment.objectExists())
                                    entityDeleted = true;
                                else if (assignment.notPublished())
                                    notPublished = true;
                            }
                        }

                        UIOutput.make(tableRow, "type", String.valueOf(type));
                        String requirement = String.valueOf(i.getSubrequirement());
                        if ((type == SimplePageItem.PAGE || type == SimplePageItem.ASSIGNMENT)
                                && i.getSubrequirement()) {
                            requirement = i.getRequirementText();
                        }
                        UIOutput.make(tableRow, "requirement-text", requirement);
                    } else if (i.getType() == SimplePageItem.ASSESSMENT) {
                        UIOutput.make(tableRow, "type", "6"); // Not used by
                        // assignments,
                        // so it is
                        // safe to dedicate to assessments
                        UIOutput.make(tableRow, "requirement-text",
                                (i.getSubrequirement() ? i.getRequirementText() : "false"));
                        LessonEntity quiz = quizEntity.getEntity(i.getSakaiId(), simplePageBean);
                        if (quiz != null) {
                            String editUrl = quiz.editItemUrl(simplePageBean);
                            if (editUrl != null) {
                                UIOutput.make(tableRow, "edit-url", editUrl);
                            }
                            editUrl = quiz.editItemSettingsUrl(simplePageBean);
                            if (editUrl != null) {
                                UIOutput.make(tableRow, "edit-settings-url", editUrl);
                            }
                            itemGroupString = simplePageBean.getItemGroupString(i, quiz, true);
                            UIOutput.make(tableRow, "item-groups", itemGroupString);
                            if (!quiz.objectExists())
                                entityDeleted = true;

                        } else
                            notPublished = quizEntity.notPublished(i.getSakaiId());
                    } else if (i.getType() == SimplePageItem.BLTI) {
                        UIOutput.make(tableRow, "type", "b");
                        LessonEntity blti = (bltiEntity == null ? null : bltiEntity.getEntity(i.getSakaiId()));
                        if (blti != null) {
                            String editUrl = blti.editItemUrl(simplePageBean);
                            if (editUrl != null)
                                UIOutput.make(tableRow, "edit-url", editUrl);
                            UIOutput.make(tableRow, "item-format", i.getFormat());

                            if (i.getHeight() != null)
                                UIOutput.make(tableRow, "item-height", i.getHeight());
                            itemGroupString = simplePageBean.getItemGroupString(i, null, true);
                            UIOutput.make(tableRow, "item-groups", itemGroupString);
                            if (!blti.objectExists())
                                entityDeleted = true;
                            else if (blti.notPublished())
                                notPublished = true;
                        }
                    } else if (i.getType() == SimplePageItem.FORUM) {
                        UIOutput.make(tableRow, "extra-info");
                        UIOutput.make(tableRow, "type", "8");
                        LessonEntity forum = forumEntity.getEntity(i.getSakaiId());
                        if (forum != null) {
                            String editUrl = forum.editItemUrl(simplePageBean);
                            if (editUrl != null) {
                                UIOutput.make(tableRow, "edit-url", editUrl);
                            }
                            itemGroupString = simplePageBean.getItemGroupString(i, forum, true);
                            UIOutput.make(tableRow, "item-groups", itemGroupString);
                            if (!forum.objectExists())
                                entityDeleted = true;
                            else if (forum.notPublished())
                                notPublished = true;

                        }
                    } else if (i.getType() == SimplePageItem.PAGE) {
                        UIOutput.make(tableRow, "type", "page");
                        UIOutput.make(tableRow, "page-next", Boolean.toString(i.getNextPage()));
                        UIOutput.make(tableRow, "page-button",
                                Boolean.toString("button".equals(i.getFormat())));
                        itemGroupString = simplePageBean.getItemGroupString(i, null, true);
                        UIOutput.make(tableRow, "item-groups", itemGroupString);
                    } else if (i.getType() == SimplePageItem.RESOURCE) {
                        try {
                            itemGroupString = simplePageBean.getItemGroupStringOrErr(i, null, true);
                        } catch (IdUnusedException e) {
                            itemGroupString = "";
                            entityDeleted = true;
                        }
                        if (simplePageBean.getInherited())
                            UIOutput.make(tableRow, "item-groups", "--inherited--");
                        else
                            UIOutput.make(tableRow, "item-groups", itemGroupString);
                        UIOutput.make(tableRow, "item-samewindow", Boolean.toString(i.isSameWindow()));

                        UIVerbatim.make(tableRow, "item-path", getItemPath(i));
                    }

                } // end of canEditPage

                if (canSeeAll) {
                    // haven't set up itemgroupstring yet
                    if (!canEditPage) {
                        if (!i.getSakaiId().equals(SimplePageItem.DUMMY)) {
                            LessonEntity lessonEntity = null;
                            switch (i.getType()) {
                            case SimplePageItem.ASSIGNMENT:
                                lessonEntity = assignmentEntity.getEntity(i.getSakaiId(), simplePageBean);
                                if (lessonEntity != null)
                                    itemGroupString = simplePageBean.getItemGroupString(i, lessonEntity, true);
                                if (!lessonEntity.objectExists())
                                    entityDeleted = true;
                                else if (lessonEntity.notPublished())
                                    notPublished = true;
                                break;
                            case SimplePageItem.ASSESSMENT:
                                lessonEntity = quizEntity.getEntity(i.getSakaiId(), simplePageBean);
                                if (lessonEntity != null)
                                    itemGroupString = simplePageBean.getItemGroupString(i, lessonEntity, true);
                                else
                                    notPublished = quizEntity.notPublished(i.getSakaiId());
                                if (!lessonEntity.objectExists())
                                    entityDeleted = true;
                                break;
                            case SimplePageItem.FORUM:
                                lessonEntity = forumEntity.getEntity(i.getSakaiId());
                                if (lessonEntity != null)
                                    itemGroupString = simplePageBean.getItemGroupString(i, lessonEntity, true);
                                if (!lessonEntity.objectExists())
                                    entityDeleted = true;
                                else if (lessonEntity.notPublished())
                                    notPublished = true;
                                break;
                            case SimplePageItem.BLTI:
                                if (bltiEntity != null)
                                    lessonEntity = bltiEntity.getEntity(i.getSakaiId());
                                if (lessonEntity != null)
                                    itemGroupString = simplePageBean.getItemGroupString(i, null, true);
                                if (!lessonEntity.objectExists())
                                    entityDeleted = true;
                                else if (lessonEntity.notPublished())
                                    notPublished = true;
                                break;
                            case SimplePageItem.PAGE:
                                itemGroupString = simplePageBean.getItemGroupString(i, null, true);
                                break;
                            case SimplePageItem.RESOURCE:
                                try {
                                    itemGroupString = simplePageBean.getItemGroupStringOrErr(i, null, true);
                                } catch (IdUnusedException e) {
                                    itemGroupString = "";
                                    entityDeleted = true;
                                }
                                break;
                            }
                        }
                    }

                    String releaseString = simplePageBean.getReleaseString(i);
                    if (itemGroupString != null || releaseString != null || entityDeleted || notPublished) {
                        if (itemGroupString != null)
                            itemGroupString = simplePageBean.getItemGroupTitles(itemGroupString, i);
                        if (itemGroupString != null) {
                            itemGroupString = " [" + itemGroupString + "]";
                            if (releaseString != null)
                                itemGroupString = " " + releaseString + itemGroupString;
                        } else if (releaseString != null)
                            itemGroupString = " " + releaseString;
                        if (notPublished) {
                            if (itemGroupString != null)
                                itemGroupString = itemGroupString + " "
                                        + messageLocator.getMessage("simplepage.not-published");
                            else
                                itemGroupString = messageLocator.getMessage("simplepage.not-published");
                        }
                        if (entityDeleted) {
                            if (itemGroupString != null)
                                itemGroupString = itemGroupString + " "
                                        + messageLocator.getMessage("simplepage.deleted-entity");
                            else
                                itemGroupString = messageLocator.getMessage("simplepage.deleted-entity");
                        }

                        if (itemGroupString != null)
                            UIOutput.make(tableRow, (isInline ? "item-group-titles-div" : "item-group-titles"),
                                    itemGroupString);
                    }

                } // end of canSeeAll

                // the following are for the inline item types. Multimedia
                // is the most complex because
                // it can be IMG, IFRAME, or OBJECT, and Youtube is treated
                // separately

            } else if (i.getType() == SimplePageItem.MULTIMEDIA) {
                // This code should be read together with the code in SimplePageBean
                // that sets up this data, method addMultimedia.  Most display is set
                // up here, but note that show-page.js invokes the jquery oembed on all
                // <A> items with class="oembed".

                // historically this code was to display files ,and urls leading to things
                // like MP4. as backup if we couldn't figure out what to do we'd put something
                // in an iframe. The one exception is youtube, which we supposed explicitly.
                //   However we now support several ways to embed content. We use the
                // multimediaDisplayType code to indicate which. The codes are
                //     1 -- embed code, 2 -- av type, 3 -- oembed, 4 -- iframe
                // 2 is the original code: MP4, image, and as a special case youtube urls
                // since we have old entries with no type code, and that behave the same as
                // 2, we start by converting 2 to null.
                //  then the logic is
                //  if type == null & youtube, do youtube
                //  if type == null & image, do iamge
                //  if type == null & not HTML do MP4 or other player for file 
                //  final fallthrough to handel the new types, with IFRAME if all else fails
                // the old code creates ojbects in ContentHosting for both files and URLs.
                // The new code saves the embed code or URL itself as an atteibute of the item
                // If I were doing it again, I wouldn't create the ContebtHosting item
                //   Note that IFRAME is only used for something where the far end claims the MIME
                // type is HTML. For weird stuff like MS Word files I use the file display code, which
                // will end up producing <OBJECT>.

                // the reason this code is complex is that we try to choose
                // the best
                // HTML for displaying the particular type of object. We've
                // added complexities
                // over time as we get more experience with different
                // object types and browsers.

                String itemGroupString = null;
                String itemGroupTitles = null;
                boolean entityDeleted = false;
                // new format explicit display indication
                String mmDisplayType = i.getAttribute("multimediaDisplayType");
                // 2 is the generic "use old display" so treat it as null
                if ("".equals(mmDisplayType) || "2".equals(mmDisplayType))
                    mmDisplayType = null;
                if (canSeeAll) {
                    try {
                        itemGroupString = simplePageBean.getItemGroupStringOrErr(i, null, true);
                    } catch (IdUnusedException e) {
                        itemGroupString = "";
                        entityDeleted = true;
                    }
                    itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
                    if (entityDeleted) {
                        if (itemGroupTitles != null)
                            itemGroupTitles = itemGroupTitles + " "
                                    + messageLocator.getMessage("simplepage.deleted-entity");
                        else
                            itemGroupTitles = messageLocator.getMessage("simplepage.deleted-entity");
                    }
                    if (itemGroupTitles != null) {
                        itemGroupTitles = "[" + itemGroupTitles + "]";
                    }
                    UIOutput.make(tableRow, "item-groups", itemGroupString);
                } else if (entityDeleted)
                    continue;

                if (!"1".equals(mmDisplayType) && !"3".equals(mmDisplayType))
                    UIVerbatim.make(tableRow, "item-path", getItemPath(i));

                // the reason this code is complex is that we try to choose
                // the best
                // HTML for displaying the particular type of object. We've
                // added complexities
                // over time as we get more experience with different
                // object types and browsers.

                StringTokenizer token = new StringTokenizer(i.getSakaiId(), ".");

                String extension = "";

                while (token.hasMoreTokens()) {
                    extension = token.nextToken().toLowerCase();
                }

                // the extension is almost never used. Normally we have
                // the MIME type and use it. Extension is used only if
                // for some reason we don't have the MIME type
                UIComponent item;
                String youtubeKey;

                Length width = null;
                if (i.getWidth() != null) {
                    width = new Length(i.getWidth());
                }
                Length height = null;
                if (i.getHeight() != null) {
                    height = new Length(i.getHeight());
                }

                // Get the MIME type. For multimedia types is should be in
                // the html field.
                // The old code saved the URL there. So if it looks like a
                // URL ignore it.
                String mimeType = i.getHtml();
                if (mimeType != null && (mimeType.startsWith("http") || mimeType.equals(""))) {
                    mimeType = null;
                }

                // here goes. dispatch on the type and produce the right tag
                // type,
                // followed by the hidden INPUT tags with information for the
                // edit dialog
                if (mmDisplayType == null && simplePageBean.isImageType(i)) {

                    if (canSeeAll || simplePageBean.isItemAvailable(i)) {
                        UIOutput.make(tableRow, "imageSpan");

                        if (itemGroupString != null) {
                            UIOutput.make(tableRow, "item-group-titles3", itemGroupTitles);
                            UIOutput.make(tableRow, "item-groups3", itemGroupString);
                        }

                        String imageName = i.getAlt();
                        if (imageName == null || imageName.equals("")) {
                            imageName = abbrevUrl(i.getURL());
                        }

                        item = UIOutput.make(tableRow, "image")
                                .decorate(new UIFreeAttributeDecorator("src",
                                        i.getItemURL(simplePageBean.getCurrentSiteId(),
                                                currentPage.getOwner())))
                                .decorate(new UIFreeAttributeDecorator("alt", imageName));
                        if (lengthOk(width)) {
                            item.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
                        }

                        if (lengthOk(height)) {
                            item.decorate(new UIFreeAttributeDecorator("height", height.getOld()));
                        }
                    } else {
                        UIComponent notAvailableText = UIOutput.make(tableRow, "notAvailableText",
                                messageLocator.getMessage("simplepage.multimediaItemUnavailable"));
                        // Grey it out
                        notAvailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-text-item"));
                    }

                    // stuff for the jquery dialog
                    if (canEditPage) {
                        UIOutput.make(tableRow, "imageHeight", getOrig(height));
                        UIOutput.make(tableRow, "imageWidth", getOrig(width));
                        UIOutput.make(tableRow, "mimetype2", mimeType);
                        UIOutput.make(tableRow, "current-item-id4", Long.toString(i.getId()));
                        UIOutput.make(tableRow, "item-prereq3", String.valueOf(i.isPrerequisite()));
                        UIVerbatim.make(tableRow, "item-path3", getItemPath(i));
                        UIOutput.make(tableRow, "editimage-td");
                        UILink.make(tableRow, "image-edit", (String) null, "")
                                .decorate(new UIFreeAttributeDecorator("title",
                                        messageLocator.getMessage("simplepage.edit-title.url").replace("{}",
                                                abbrevUrl(i.getURL()))));
                    }

                    UIOutput.make(tableRow, "description2", i.getDescription());

                } else if (mmDisplayType == null && (youtubeKey = simplePageBean.getYoutubeKey(i)) != null) {
                    String youtubeUrl = SimplePageBean.getYoutubeUrlFromKey(youtubeKey);

                    if (canSeeAll || simplePageBean.isItemAvailable(i)) {
                        UIOutput.make(tableRow, "youtubeSpan");

                        if (itemGroupString != null) {
                            UIOutput.make(tableRow, "item-group-titles4", itemGroupTitles);
                            UIOutput.make(tableRow, "item-groups4", itemGroupString);
                        }

                        // if width is blank or 100% scale the height
                        if (width != null && height != null && !height.number.equals("")) {
                            if (width.number.equals("") && width.unit.equals("")
                                    || width.number.equals("100") && width.unit.equals("%")) {

                                int h = Integer.parseInt(height.number);
                                if (h > 0) {
                                    width.number = Integer.toString((int) Math.round(h * 1.641025641));
                                    width.unit = height.unit;
                                }
                            }
                        }

                        // <object style="height: 390px; width: 640px"><param
                        // name="movie"
                        // value="http://www.youtube.com/v/AKIC7OQqBrA?version=3"><param
                        // name="allowFullScreen" value="true"><param
                        // name="allowScriptAccess" value="always"><embed
                        // src="http://www.youtube.com/v/AKIC7OQqBrA?version=3"
                        // type="application/x-shockwave-flash"
                        // allowfullscreen="true" allowScriptAccess="always"
                        // width="640" height="390"></object>

                        item = UIOutput.make(tableRow, "youtubeIFrame");
                        // youtube seems ok with length and width
                        if (lengthOk(height)) {
                            item.decorate(new UIFreeAttributeDecorator("height", height.getOld()));
                        }

                        if (lengthOk(width)) {
                            item.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
                        }

                        item.decorate(new UIFreeAttributeDecorator("title",
                                messageLocator.getMessage("simplepage.youtube_player")));
                        item.decorate(new UIFreeAttributeDecorator("src", youtubeUrl));
                    } else {
                        UIComponent notAvailableText = UIOutput.make(tableRow, "notAvailableText",
                                messageLocator.getMessage("simplepage.multimediaItemUnavailable"));
                        // Grey it out
                        notAvailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-text-item"));
                    }

                    if (canEditPage) {
                        UIOutput.make(tableRow, "youtubeId", String.valueOf(i.getId()));
                        UIOutput.make(tableRow, "currentYoutubeURL", youtubeUrl);
                        UIOutput.make(tableRow, "currentYoutubeHeight", getOrig(height));
                        UIOutput.make(tableRow, "currentYoutubeWidth", getOrig(width));
                        UIOutput.make(tableRow, "current-item-id5", Long.toString(i.getId()));
                        UIOutput.make(tableRow, "item-prereq4", String.valueOf(i.isPrerequisite()));
                        UIVerbatim.make(tableRow, "item-path4", getItemPath(i));
                        UIOutput.make(tableRow, "youtube-td");
                        UILink.make(tableRow, "youtube-edit", (String) null, "")
                                .decorate(new UIFreeAttributeDecorator("title",
                                        messageLocator.getMessage("simplepage.edit-title.youtube")));
                    }

                    UIOutput.make(tableRow, "description4", i.getDescription());

                    // as of Oct 28, 2010, we store the mime type. mimeType
                    // null is an old entry.
                    // For that use the old approach of checking the
                    // extension.
                    // Otherwise we want to use iframes for HTML and OBJECT
                    // for everything else
                    // We need the iframes because IE up through 8 doesn't
                    // reliably display
                    // HTML with OBJECT. Experiments show that everything
                    // else works with OBJECT
                    // for most browsers. Unfortunately IE, even IE 9,
                    // doesn't reliably call the
                    // right player with OBJECT. EMBED works. But it's not
                    // as nice because you can't
                    // nest error recovery code. So we use OBJECT for
                    // everything except IE, where we
                    // use EMBED. OBJECT does work with Flash.
                    // application/xhtml+xml is XHTML.

                } else if (mmDisplayType == null && ((mimeType != null && !mimeType.equals("text/html")
                        && !mimeType.equals("application/xhtml+xml")) ||
                // ((mimeType != null && (mimeType.startsWith("audio/") || mimeType.startsWith("video/"))) || 
                        (mimeType == null && !(Arrays.binarySearch(htmlTypes, extension) >= 0)))) {

                    // except where explicit display is set,
                    // this code is used for everything that isn't an image,
                    // Youtube, or HTML
                    // This could be audio, video, flash, or something random like MS word.
                    // Random stuff will turn into an object.
                    // HTML is done with an IFRAME in the next "if" case
                    // The explicit display types are handled there as well

                    // in theory the things that fall through to iframe are
                    // html and random stuff without a defined mime type
                    // random stuff with mime type is displayed with object

                    if (mimeType == null) {
                        mimeType = "";
                    }

                    String oMimeType = mimeType; // in case we change it for
                    // FLV or others

                    if (itemGroupString != null) {
                        UIOutput.make(tableRow, "item-group-titles5", itemGroupTitles);
                        UIOutput.make(tableRow, "item-groups5", itemGroupString);
                    }

                    UIOutput.make(tableRow, "movieSpan");

                    if (canSeeAll || simplePageBean.isItemAvailable(i)) {

                        UIComponent item2;

                        String movieUrl = i.getItemURL(simplePageBean.getCurrentSiteId(),
                                currentPage.getOwner());
                        // movieUrl = "https://heidelberg.rutgers.edu" + movieUrl;
                        // Safari doens't always pass cookies to plugins, so we have to pass the arg
                        // this requires session.parameter.allow=true in sakai.properties
                        // don't pass the arg unless that is set, since the whole point of defaulting
                        // off is to not expose the session id
                        String sessionParameter = getSessionParameter(movieUrl);
                        if (sessionParameter != null)
                            movieUrl = movieUrl + "?lb.session=" + sessionParameter;

                        UIComponent movieLink = UIOutput.make(tableRow, "movie-link-div");
                        if (showDownloads)
                            UILink.make(tableRow, "movie-link-link",
                                    messageLocator.getMessage("simplepage.download_file"), movieUrl);

                        //   if (allowSessionId)
                        //  movieUrl = movieUrl + "?sakai.session=" + SessionManager.getCurrentSession().getId();
                        boolean useFlvPlayer = false;

                        // isMp4 means we try the flash player (if not HTML5)
                        // we also try the flash player for FLV but for mp4 we do an
                        // additional backup if flash fails, but that doesn't make sense for FLV
                        boolean isMp4 = Arrays.binarySearch(mp4Types, mimeType) >= 0;
                        boolean isHtml5 = Arrays.binarySearch(html5Types, mimeType) >= 0;

                        // wrap whatever stuff we decide to put out in HTML5 if appropriate
                        // javascript is used to do the wrapping, because RSF can't really handle this
                        if (isHtml5) {
                            // flag for javascript
                            boolean isAudio = mimeType.startsWith("audio/");
                            UIComponent h5video = UIOutput.make(tableRow, (isAudio ? "h5audio" : "h5video"));
                            UIComponent h5source = UIOutput.make(tableRow,
                                    (isAudio ? "h5asource" : "h5source"));
                            if (lengthOk(height) && height.getOld().indexOf("%") < 0)
                                h5video.decorate(new UIFreeAttributeDecorator("height", height.getOld()));
                            if (lengthOk(width) && width.getOld().indexOf("%") < 0)
                                h5video.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
                            h5source.decorate(new UIFreeAttributeDecorator("src", movieUrl))
                                    .decorate(new UIFreeAttributeDecorator("type", mimeType));
                            String caption = i.getAttribute("captionfile");
                            if (!isAudio && caption != null && caption.length() > 0) {
                                movieLink.decorate(
                                        new UIFreeAttributeDecorator("class", "has-caption allow-caption"));
                                String captionUrl = "/access/lessonbuilder/item/" + i.getId() + caption;
                                sessionParameter = getSessionParameter(captionUrl);
                                // sessionParameter should always be non-null
                                // because this overrides all other checks in /access/lessonbuilder,
                                // we haven't adjusted it to handle these files otherwise
                                if (sessionParameter != null)
                                    captionUrl = captionUrl + "?lb.session=" + sessionParameter;
                                UIOutput.make(tableRow, "h5track")
                                        .decorate(new UIFreeAttributeDecorator("src", captionUrl));
                            } else if (!isAudio) {
                                movieLink.decorate(new UIFreeAttributeDecorator("class", "allow-caption"));
                            }
                        }

                        // FLV is special. There's no player for flash video in
                        // the browser
                        // it shows with a special flash program, which I
                        // supply. For the moment MP4 is
                        // shown with the same player so it uses much of the
                        // same code
                        if (mimeType != null
                                && (mimeType.equals("video/x-flv") || mimeType.equals("video/flv") || isMp4)) {
                            mimeType = "application/x-shockwave-flash";
                            movieUrl = "/lessonbuilder-tool/templates/StrobeMediaPlayback.swf";
                            useFlvPlayer = true;
                        }
                        // for IE, if we're not supplying a player it's safest
                        // to use embed
                        // otherwise Quicktime won't work. Oddly, with IE 9 only
                        // it works if you set CLASSID to the MIME type,
                        // but that's so unexpected that I hate to rely on it.
                        // EMBED is in HTML 5, so I think we're OK
                        // using it permanently for IE.
                        // I prefer OBJECT where possible because of the nesting
                        // ability.
                        boolean useEmbed = ieVersion > 0 && !mimeType.equals("application/x-shockwave-flash");

                        if (useEmbed) {
                            item2 = UIOutput.make(tableRow, "movieEmbed")
                                    .decorate(new UIFreeAttributeDecorator("src", movieUrl))
                                    .decorate(new UIFreeAttributeDecorator("alt",
                                            messageLocator.getMessage("simplepage.mm_player").replace("{}",
                                                    abbrevUrl(i.getURL()))));
                        } else {
                            item2 = UIOutput.make(tableRow, "movieObject")
                                    .decorate(new UIFreeAttributeDecorator("data", movieUrl))
                                    .decorate(new UIFreeAttributeDecorator("title",
                                            messageLocator.getMessage("simplepage.mm_player").replace("{}",
                                                    abbrevUrl(i.getURL()))));
                        }
                        if (mimeType != null) {
                            item2.decorate(new UIFreeAttributeDecorator("type", mimeType));
                        }
                        if (canEditPage) {
                            //item2.decorate(new UIFreeAttributeDecorator("style", "border: 1px solid black"));
                        }

                        // some object types seem to need a specification, so supply our default if necessary
                        if (lengthOk(height) && lengthOk(width)) {
                            item2.decorate(new UIFreeAttributeDecorator("height", height.getOld()))
                                    .decorate(new UIFreeAttributeDecorator("width", width.getOld()));
                        } else {
                            if (oMimeType.startsWith("audio/"))
                                item2.decorate(new UIFreeAttributeDecorator("height", "100"))
                                        .decorate(new UIFreeAttributeDecorator("width", "400"));
                            else
                                item2.decorate(new UIFreeAttributeDecorator("height", "300"))
                                        .decorate(new UIFreeAttributeDecorator("width", "400"));
                        }
                        if (!useEmbed) {
                            if (useFlvPlayer) {
                                UIOutput.make(tableRow, "flashvars")
                                        .decorate(
                                                new UIFreeAttributeDecorator("value",
                                                        "src=" + URLEncoder.encode(myUrl() + i.getItemURL(
                                                                simplePageBean.getCurrentSiteId(),
                                                                currentPage.getOwner()))));
                                // need wmode=opaque for player to stack properly with dialogs, etc.
                                // there is a performance impact, but I'm guessing in our application we don't 
                                // need ultimate performance for embedded video. I'm setting it only for
                                // the player, so flash games and other applications will still get wmode=window
                                UIOutput.make(tableRow, "wmode");
                            } else if (mimeType.equals("application/x-shockwave-flash"))
                                UIOutput.make(tableRow, "wmode");

                            UIOutput.make(tableRow, "movieURLInject")
                                    .decorate(new UIFreeAttributeDecorator("value", movieUrl));
                            if (!isMp4 && showDownloads) {
                                UIOutput.make(tableRow, "noplugin-p",
                                        messageLocator.getMessage("simplepage.noplugin"));
                                UIOutput.make(tableRow, "noplugin-br");
                                UILink.make(tableRow, "noplugin", i.getName(), movieUrl);
                            }
                        }

                        if (isMp4) {
                            // do fallback. for ie use EMBED
                            if (ieVersion > 0) {
                                item2 = UIOutput.make(tableRow, "mp4-embed")
                                        .decorate(new UIFreeAttributeDecorator("src",
                                                i.getItemURL(simplePageBean.getCurrentSiteId(),
                                                        currentPage.getOwner())))
                                        .decorate(new UIFreeAttributeDecorator("alt",
                                                messageLocator.getMessage("simplepage.mm_player").replace("{}",
                                                        abbrevUrl(i.getURL()))));
                            } else {
                                item2 = UIOutput.make(tableRow, "mp4-object")
                                        .decorate(new UIFreeAttributeDecorator("data",
                                                i.getItemURL(simplePageBean.getCurrentSiteId(),
                                                        currentPage.getOwner())))
                                        .decorate(new UIFreeAttributeDecorator("title",
                                                messageLocator.getMessage("simplepage.mm_player").replace("{}",
                                                        abbrevUrl(i.getURL()))));
                            }
                            if (oMimeType != null) {
                                item2.decorate(new UIFreeAttributeDecorator("type", oMimeType));
                            }

                            // some object types seem to need a specification, so give a default if needed
                            if (lengthOk(height) && lengthOk(width)) {
                                item2.decorate(new UIFreeAttributeDecorator("height", height.getOld()))
                                        .decorate(new UIFreeAttributeDecorator("width", width.getOld()));
                            } else {
                                if (oMimeType.startsWith("audio/"))
                                    item2.decorate(new UIFreeAttributeDecorator("height", "100"))
                                            .decorate(new UIFreeAttributeDecorator("width", "100%"));
                                else
                                    item2.decorate(new UIFreeAttributeDecorator("height", "300"))
                                            .decorate(new UIFreeAttributeDecorator("width", "100%"));
                            }

                            if (!useEmbed) {
                                UIOutput.make(tableRow, "mp4-inject")
                                        .decorate(new UIFreeAttributeDecorator("value", i.getItemURL(
                                                simplePageBean.getCurrentSiteId(), currentPage.getOwner())));

                                if (showDownloads) {
                                    UIOutput.make(tableRow, "mp4-noplugin-p",
                                            messageLocator.getMessage("simplepage.noplugin"));
                                    UILink.make(tableRow, "mp4-noplugin", i.getName(), i.getItemURL(
                                            simplePageBean.getCurrentSiteId(), currentPage.getOwner()));
                                }
                            }
                        }
                        UIOutput.make(tableRow, "description3", i.getDescription());
                    } else {
                        UIVerbatim notAvailableText = UIVerbatim.make(tableRow, "notAvailableText",
                                messageLocator.getMessage("simplepage.multimediaItemUnavailable"));
                        // Grey it out
                        notAvailableText
                                .decorate(new UIFreeAttributeDecorator("class", "disabled-multimedia-item"));
                    }

                    if (canEditPage) {
                        UIOutput.make(tableRow, "movieId", String.valueOf(i.getId()));
                        UIOutput.make(tableRow, "movieHeight", getOrig(height));
                        UIOutput.make(tableRow, "movieWidth", getOrig(width));
                        UIOutput.make(tableRow, "mimetype5", oMimeType);
                        UIOutput.make(tableRow, "prerequisite", (i.isPrerequisite()) ? "true" : "false");
                        UIOutput.make(tableRow, "current-item-id6", Long.toString(i.getId()));
                        UIVerbatim.make(tableRow, "item-path5", getItemPath(i));
                        UIOutput.make(tableRow, "movie-td");
                        UILink.make(tableRow, "edit-movie", (String) null, "")
                                .decorate(new UIFreeAttributeDecorator("title",
                                        messageLocator.getMessage("simplepage.edit-title.url").replace("{}",
                                                abbrevUrl(i.getURL()))));
                    }

                } else {
                    // this is fallthrough for html or an explicit mm display type (i.e. embed code)
                    // odd types such as MS word will be handled by the AV code, and presented as <OBJECT>

                    if (canSeeAll || simplePageBean.isItemAvailable(i)) {

                        // definition of resizeiframe, at top of page
                        if (!iframeJavascriptDone && getOrig(height).equals("auto")) {
                            UIOutput.make(tofill, "iframeJavascript");
                            iframeJavascriptDone = true;
                        }

                        UIOutput.make(tableRow, "iframeSpan");

                        if (itemGroupString != null) {
                            UIOutput.make(tableRow, "item-group-titles2", itemGroupTitles);
                            UIOutput.make(tableRow, "item-groups2", itemGroupString);
                        }
                        String itemUrl = i.getItemURL(simplePageBean.getCurrentSiteId(),
                                currentPage.getOwner());
                        if ("1".equals(mmDisplayType)) {
                            // embed
                            item = UIVerbatim.make(tableRow, "mm-embed", i.getAttribute("multimediaEmbedCode"));
                            //String style = getStyle(width, height);
                            //if (style != null)
                            //item.decorate(new UIFreeAttributeDecorator("style", style));
                        } else if ("3".equals(mmDisplayType)) {
                            item = UILink.make(tableRow, "mm-oembed", i.getAttribute("multimediaUrl"),
                                    i.getAttribute("multimediaUrl"));
                            if (lengthOk(width))
                                item.decorate(new UIFreeAttributeDecorator("maxWidth", width.getOld()));
                            if (lengthOk(height))
                                item.decorate(new UIFreeAttributeDecorator("maxHeight", height.getOld()));
                            // oembed
                        } else {
                            UIOutput.make(tableRow, "iframe-link-div");
                            UILink.make(tableRow, "iframe-link-link",
                                    messageLocator.getMessage("simplepage.open_new_window"), itemUrl);
                            item = UIOutput.make(tableRow, "iframe")
                                    .decorate(new UIFreeAttributeDecorator("src", itemUrl));
                            // if user specifies auto, use Javascript to resize the
                            // iframe when the
                            // content changes. This only works for URLs with the
                            // same origin, i.e.
                            // URLs in this sakai system
                            if (getOrig(height).equals("auto")) {
                                item.decorate(new UIFreeAttributeDecorator("onload",
                                        "resizeiframe('" + item.getFullID() + "')"));
                                if (lengthOk(width)) {
                                    item.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
                                }
                                item.decorate(new UIFreeAttributeDecorator("height", "300"));
                            } else {
                                // we seem OK without a spec
                                if (lengthOk(height) && lengthOk(width)) {
                                    item.decorate(new UIFreeAttributeDecorator("height", height.getOld()))
                                            .decorate(new UIFreeAttributeDecorator("width", width.getOld()));
                                }
                            }
                        }
                        item.decorate(new UIFreeAttributeDecorator("title", messageLocator
                                .getMessage("simplepage.web_content").replace("{}", abbrevUrl(i.getURL()))));

                        if (canEditPage) {
                            UIOutput.make(tableRow, "iframeHeight", getOrig(height));
                            UIOutput.make(tableRow, "iframeWidth", getOrig(width));
                            UIOutput.make(tableRow, "mimetype3", mimeType);
                            UIOutput.make(tableRow, "item-prereq2", String.valueOf(i.isPrerequisite()));
                            UIOutput.make(tableRow, "embedtype", mmDisplayType);
                            UIOutput.make(tableRow, "current-item-id3", Long.toString(i.getId()));
                            UIVerbatim.make(tableRow, "item-path2", getItemPath(i));
                            UIOutput.make(tableRow, "editmm-td");
                            UILink.make(tableRow, "iframe-edit", (String) null, "")
                                    .decorate(new UIFreeAttributeDecorator("title",
                                            messageLocator.getMessage("simplepage.edit-title.url").replace("{}",
                                                    abbrevUrl(i.getURL()))));
                        }

                        UIOutput.make(tableRow, "description5", i.getDescription());
                    } else {

                        UIVerbatim notAvailableText = UIVerbatim.make(tableRow, "notAvailableText",
                                messageLocator.getMessage("simplepage.multimediaItemUnavailable"));
                        // Grey it out
                        notAvailableText
                                .decorate(new UIFreeAttributeDecorator("class", "disabled-multimedia-item"));
                    }

                }

                // end of multimedia object

            } else if (i.getType() == SimplePageItem.COMMENTS) {
                // Load later using AJAX and CommentsProducer

                UIOutput.make(tableRow, "commentsSpan");

                boolean isAvailable = simplePageBean.isItemAvailable(i);
                // faculty missing preqs get warning but still see the comments
                if (!isAvailable && canSeeAll)
                    UIOutput.make(tableRow, "missing-prereqs",
                            messageLocator.getMessage("simplepage.fake-missing-prereqs"));

                // students get warning and not the content
                if (!isAvailable && !canSeeAll) {
                    UIOutput.make(tableRow, "missing-prereqs",
                            messageLocator.getMessage("simplepage.missing-prereqs"));
                } else {
                    UIOutput.make(tableRow, "commentsDiv");
                    UIOutput.make(tableRow, "placementId", placement.getId());

                    // note: the URL will be rewritten in comments.js to look like
                    //  /lessonbuilder-tool/faces/Comments...
                    CommentsViewParameters eParams = new CommentsViewParameters(CommentsProducer.VIEW_ID);
                    eParams.itemId = i.getId();
                    eParams.placementId = placement.getId();
                    if (params.postedComment) {
                        eParams.postedComment = postedCommentId;
                    }
                    eParams.siteId = simplePageBean.getCurrentSiteId();
                    eParams.pageId = currentPage.getPageId();

                    if (params.author != null && !params.author.equals("")) {
                        eParams.author = params.author;
                        eParams.showAllComments = true;
                    }

                    UIInternalLink.make(tableRow, "commentsLink", eParams);

                    if (!addedCommentsScript) {
                        UIOutput.make(tofill, "comments-script");
                        UIOutput.make(tofill, "fckScript");
                        addedCommentsScript = true;
                        UIOutput.make(tofill, "delete-dialog");
                    }

                    // forced comments have to be edited on the main page
                    if (canEditPage) {
                        // Checks to make sure that the comments item isn't on a student page.
                        // That it is graded.  And that we didn't just come from the grading pane.
                        if (i.getPageId() > 0 && i.getGradebookId() != null && !cameFromGradingPane) {
                            CommentsGradingPaneViewParameters gp = new CommentsGradingPaneViewParameters(
                                    CommentGradingPaneProducer.VIEW_ID);
                            gp.placementId = toolManager.getCurrentPlacement().getId();
                            gp.commentsItemId = i.getId();
                            gp.pageId = currentPage.getPageId();
                            gp.pageItemId = pageItem.getId();
                            gp.siteId = simplePageBean.getCurrentSiteId();

                            UIInternalLink.make(tableRow, "gradingPaneLink",
                                    messageLocator.getMessage("simplepage.show-grading-pane-comments"), gp)
                                    .decorate(new UIFreeAttributeDecorator("title", messageLocator
                                            .getMessage("simplepage.show-grading-pane-comments")));
                        }

                        UIOutput.make(tableRow, "comments-td");

                        if (i.getSequence() > 0) {
                            UILink.make(tableRow, "edit-comments", (String) null, "")
                                    .decorate(new UIFreeAttributeDecorator("title",
                                            messageLocator.getMessage("simplepage.edit-title.comments")));

                            UIOutput.make(tableRow, "commentsId", String.valueOf(i.getId()));
                            UIOutput.make(tableRow, "commentsAnon", String.valueOf(i.isAnonymous()));
                            UIOutput.make(tableRow, "commentsitem-required", String.valueOf(i.isRequired()));
                            UIOutput.make(tableRow, "commentsitem-prerequisite",
                                    String.valueOf(i.isPrerequisite()));
                            UIOutput.make(tableRow, "commentsGrade",
                                    String.valueOf(i.getGradebookId() != null));
                            UIOutput.make(tableRow, "commentsMaxPoints",
                                    String.valueOf(i.getGradebookPoints()));

                            String itemGroupString = simplePageBean.getItemGroupString(i, null, true);
                            if (itemGroupString != null) {
                                String itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
                                if (itemGroupTitles != null) {
                                    itemGroupTitles = "[" + itemGroupTitles + "]";
                                }
                                UIOutput.make(tableRow, "comments-groups", itemGroupString);
                                UIOutput.make(tableRow, "item-group-titles6", itemGroupTitles);
                            }
                        }

                        // Allows AJAX posting of comment grades
                        printGradingForm(tofill);
                    }

                    UIForm form = UIForm.make(tableRow, "comment-form");
                    makeCsrf(form, "csrf2");

                    UIInput.make(form, "comment-item-id", "#{simplePageBean.itemId}",
                            String.valueOf(i.getId()));
                    UIInput.make(form, "comment-edit-id", "#{simplePageBean.editId}");

                    // usage * image is required and not done
                    if (i.isRequired() && !simplePageBean.isItemComplete(i))
                        UIOutput.make(tableRow, "comment-required-image");

                    UIOutput.make(tableRow, "add-comment-link");
                    UIOutput.make(tableRow, "add-comment-text",
                            messageLocator.getMessage("simplepage.add-comment"));
                    UIInput fckInput = UIInput.make(form, "comment-text-area-evolved:",
                            "#{simplePageBean.formattedComment}");
                    fckInput.decorate(new UIFreeAttributeDecorator("height", "175"));
                    fckInput.decorate(new UIFreeAttributeDecorator("width", "800"));
                    fckInput.decorate(new UIStyleDecorator("evolved-box"));
                    fckInput.decorate(new UIFreeAttributeDecorator("aria-label",
                            messageLocator.getMessage("simplepage.editor")));
                    fckInput.decorate(new UIFreeAttributeDecorator("role", "dialog"));

                    if (!noEditor) {
                        fckInput.decorate(new UIStyleDecorator("using-editor")); // javascript needs to know
                        ((SakaiFCKTextEvolver) richTextEvolver).evolveTextInput(fckInput, "" + commentsCount);
                    }
                    UICommand.make(form, "add-comment", "#{simplePageBean.addComment}");
                }

            } else if (i.getType() == SimplePageItem.PEEREVAL) {

                String owner = currentPage.getOwner();
                String currentUser = UserDirectoryService.getCurrentUser().getId();
                Long pageId = currentPage.getPageId();

                UIOutput.make(tableRow, "peerReviewRubricStudent");
                UIOutput.make(tableRow, "peer-review-form");

                makePeerRubric(tableRow, i, makeStudentRubric);

                boolean isOpen = false;
                boolean isPastDue = false;

                String peerEvalDateOpenStr = i.getAttribute("rubricOpenDate");
                String peerEvalDateDueStr = i.getAttribute("rubricDueDate");
                boolean peerEvalAllowSelfGrade = Boolean.parseBoolean(i.getAttribute("rubricAllowSelfGrade"));
                boolean gradingSelf = owner.equals(currentUser) && peerEvalAllowSelfGrade;

                if (peerEvalDateOpenStr != null && peerEvalDateDueStr != null) {
                    Date peerEvalNow = new Date();
                    Date peerEvalOpen = new Date(Long.valueOf(peerEvalDateOpenStr));
                    Date peerEvalDue = new Date(Long.valueOf(peerEvalDateDueStr));

                    isOpen = peerEvalNow.after(peerEvalOpen);
                    isPastDue = peerEvalNow.after(peerEvalDue);
                }

                if (isOpen) {

                    if (owner.equals(currentUser)) { //owner gets their own data
                        class PeerEvaluation {
                            String category;
                            public int grade, count;

                            public PeerEvaluation(String category, int grade) {
                                this.category = category;
                                this.grade = grade;
                                count = 1;
                            }

                            public void increment() {
                                count++;
                            }

                            public boolean equals(Object o) {
                                if (!(o instanceof PeerEvaluation))
                                    return false;
                                PeerEvaluation pe = (PeerEvaluation) o;
                                return category.equals(pe.category) && grade == pe.grade;
                            }

                            public String toString() {
                                return category + " " + grade + " [" + count + "]";
                            }
                        }

                        ArrayList<PeerEvaluation> myEvaluations = new ArrayList<PeerEvaluation>();

                        List<SimplePagePeerEvalResult> evaluations = simplePageToolDao
                                .findPeerEvalResultByOwner(pageId.longValue(), owner);
                        if (evaluations != null)
                            for (SimplePagePeerEvalResult eval : evaluations) {
                                PeerEvaluation target = new PeerEvaluation(eval.getRowText(),
                                        eval.getColumnValue());
                                int targetIndex = myEvaluations.indexOf(target);
                                if (targetIndex != -1) {
                                    myEvaluations.get(targetIndex).increment();
                                } else
                                    myEvaluations.add(target);
                            }

                        UIOutput.make(tableRow, "my-existing-peer-eval-data");
                        for (PeerEvaluation eval : myEvaluations) {
                            UIBranchContainer evalData = UIBranchContainer.make(tableRow, "my-peer-eval-data:");
                            UIOutput.make(evalData, "peer-eval-row-text", eval.category);
                            UIOutput.make(evalData, "peer-eval-grade", String.valueOf(eval.grade));
                            UIOutput.make(evalData, "peer-eval-count", String.valueOf(eval.count));
                        }
                    }

                    if (!owner.equals(currentUser) || gradingSelf) {
                        List<SimplePagePeerEvalResult> evaluations = simplePageToolDao
                                .findPeerEvalResult(pageId, currentUser, owner);
                        //existing evaluation data
                        if (evaluations != null && evaluations.size() != 0) {
                            UIOutput.make(tableRow, "existing-peer-eval-data");
                            for (SimplePagePeerEvalResult eval : evaluations) {
                                UIBranchContainer evalData = UIBranchContainer.make(tableRow,
                                        "peer-eval-data:");
                                UIOutput.make(evalData, "peer-eval-row-text", eval.getRowText());
                                UIOutput.make(evalData, "peer-eval-grade",
                                        String.valueOf(eval.getColumnValue()));
                            }
                        }

                        //form for peer evaluation results
                        UIForm form = UIForm.make(tofill, "rubricSelection");
                        makeCsrf(form, "csrf6");

                        UIInput.make(form, "rubricPeerGrade", "#{simplePageBean.rubricPeerGrade}");
                        UICommand.make(form, "update-peer-eval-grade",
                                messageLocator.getMessage("simplepage.edit"),
                                "#{simplePageBean.savePeerEvalResult}");
                    }

                    //buttons
                    UIOutput.make(tableRow, "add-peereval-link");
                    UIOutput.make(tableRow, "add-peereval-text",
                            messageLocator.getMessage("simplepage.view-peereval"));

                    if (isPastDue) {
                        UIOutput.make(tableRow, "peer-eval-grade-directions",
                                messageLocator.getMessage("simplepage.peer-eval.past-due-date"));
                    } else if (!owner.equals(currentUser) || gradingSelf) {
                        UIOutput.make(tableRow, "save-peereval-link");
                        UIOutput.make(tableRow, "save-peereval-text",
                                messageLocator.getMessage("simplepage.save"));
                        UIOutput.make(tableRow, "cancel-peereval-link");
                        UIOutput.make(tableRow, "cancel-peereval-text",
                                messageLocator.getMessage("simplepage.cancel"));

                        UIOutput.make(tableRow, "peer-eval-grade-directions",
                                messageLocator.getMessage("simplepage.peer-eval.click-on-cell"));
                    } else { //owner who cannot grade himself
                        UIOutput.make(tableRow, "peer-eval-grade-directions",
                                messageLocator.getMessage("simplepage.peer-eval.cant-eval-yourself"));
                    }

                    if (canEditPage)
                        UIOutput.make(tableRow, "peerReviewRubricStudent-edit");//lines up rubric with edit btn column for users with editing privs
                }
            } else if (i.getType() == SimplePageItem.STUDENT_CONTENT) {

                UIOutput.make(tableRow, "studentSpan");

                boolean isAvailable = simplePageBean.isItemAvailable(i);
                // faculty missing preqs get warning but still see the comments
                if (!isAvailable && canSeeAll)
                    UIOutput.make(tableRow, "student-missing-prereqs",
                            messageLocator.getMessage("simplepage.student-fake-missing-prereqs"));
                if (!isAvailable && !canSeeAll)
                    UIOutput.make(tableRow, "student-missing-prereqs",
                            messageLocator.getMessage("simplepage.student-missing-prereqs"));
                else {
                    UIOutput.make(tableRow, "studentDiv");

                    HashMap<Long, SimplePageLogEntry> cache = simplePageBean
                            .cacheStudentPageLogEntries(i.getId());
                    List<SimpleStudentPage> studentPages = simplePageToolDao.findStudentPages(i.getId());

                    boolean hasOwnPage = false;
                    String userId = UserDirectoryService.getCurrentUser().getId();

                    Collections.sort(studentPages, new Comparator<SimpleStudentPage>() {
                        public int compare(SimpleStudentPage o1, SimpleStudentPage o2) {
                            String title1 = o1.getTitle();
                            if (title1 == null)
                                title1 = "";
                            String title2 = o2.getTitle();
                            if (title2 == null)
                                title2 = "";
                            return title1.compareTo(title2);
                        }
                    });

                    UIOutput contentList = UIOutput.make(tableRow, "studentContentTable");
                    UIOutput contentTitle = UIOutput.make(tableRow, "studentContentTitle",
                            messageLocator.getMessage("simplepage.student"));
                    contentList.decorate(
                            new UIFreeAttributeDecorator("aria-labelledby", contentTitle.getFullID()));

                    // Print each row in the table
                    for (SimpleStudentPage page : studentPages) {
                        if (page.isDeleted())
                            continue;

                        SimplePageLogEntry entry = cache.get(page.getPageId());
                        UIBranchContainer row = UIBranchContainer.make(tableRow, "studentRow:");

                        // There's content they haven't seen
                        if (entry == null || entry.getLastViewed().compareTo(page.getLastUpdated()) < 0) {
                            UIOutput.make(row, "newContentImg").decorate(new UIFreeAttributeDecorator("title",
                                    messageLocator.getMessage("simplepage.new-student-content")));
                        } else
                            UIOutput.make(row, "newContentImgT");

                        // The comments tool exists, so we might have to show the icon
                        if (i.getShowComments() != null && i.getShowComments()) {

                            // New comments have been added since they last viewed the page
                            if (page.getLastCommentChange() != null && (entry == null
                                    || entry.getLastViewed().compareTo(page.getLastCommentChange()) < 0)) {
                                UIOutput.make(row, "newCommentsImg").decorate(new UIFreeAttributeDecorator(
                                        "title", messageLocator.getMessage("simplepage.new-student-comments")));
                            } else
                                UIOutput.make(row, "newCommentsImgT");
                        }

                        // Never visited page
                        if (entry == null) {
                            UIOutput.make(row, "newPageImg").decorate(new UIFreeAttributeDecorator("title",
                                    messageLocator.getMessage("simplepage.new-student-page")));
                        } else
                            UIOutput.make(row, "newPageImgT");

                        GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID,
                                page.getPageId());
                        eParams.setItemId(i.getId());
                        eParams.setPath("push");

                        String studentTitle = page.getTitle();

                        String sownerName = null;
                        try {
                            if (!i.isAnonymous() || canEditPage) {
                                if (page.getGroup() != null)
                                    sownerName = simplePageBean.getCurrentSite().getGroup(page.getGroup())
                                            .getTitle();
                                else
                                    sownerName = UserDirectoryService.getUser(page.getOwner()).getDisplayName();
                                if (sownerName != null && sownerName.equals(studentTitle))
                                    studentTitle = "(" + sownerName + ")";
                                else
                                    studentTitle += " (" + sownerName + ")";
                            } else if (simplePageBean.isPageOwner(page)) {
                                studentTitle += " (" + messageLocator.getMessage("simplepage.comment-you")
                                        + ")";
                            }
                        } catch (UserNotDefinedException e) {
                        }

                        UIInternalLink.make(row, "studentLink", studentTitle, eParams);

                        if (simplePageBean.isPageOwner(page)) {
                            hasOwnPage = true;
                        }

                        if (i.getGradebookId() != null && simplePageBean.getEditPrivs() == 0) {
                            UIOutput.make(row, "studentGradingCell",
                                    String.valueOf((page.getPoints() != null ? page.getPoints() : "")));
                        }
                    }

                    if (!hasOwnPage && simplePageBean.myStudentPageGroupsOk(i)) {
                        UIBranchContainer row = UIBranchContainer.make(tableRow, "studentRow:");
                        UIOutput.make(row, "linkRow");
                        UIOutput.make(row, "linkCell");

                        if (i.isRequired() && !simplePageBean.isItemComplete(i))
                            UIOutput.make(row, "student-required-image");
                        GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID);
                        eParams.addTool = GeneralViewParameters.STUDENT_PAGE;
                        eParams.studentItemId = i.getId();
                        UIInternalLink.make(row, "linkLink", messageLocator.getMessage("simplepage.add-page"),
                                eParams);
                    }

                    String itemGroupString = null;
                    // do before canEditAll because we need itemGroupString in it
                    if (canSeeAll) {
                        itemGroupString = simplePageBean.getItemGroupString(i, null, true);
                        if (itemGroupString != null) {
                            String itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
                            if (itemGroupTitles != null) {
                                itemGroupTitles = "[" + itemGroupTitles + "]";
                            }
                            UIOutput.make(tableRow, "item-group-titles7", itemGroupTitles);
                        }
                    }

                    if (canEditPage) {
                        // Checks to make sure that the comments are graded and that we didn't
                        // just come from a grading pane (would be confusing)
                        if (i.getAltGradebook() != null && !cameFromGradingPane) {
                            CommentsGradingPaneViewParameters gp = new CommentsGradingPaneViewParameters(
                                    CommentGradingPaneProducer.VIEW_ID);
                            gp.placementId = toolManager.getCurrentPlacement().getId();
                            gp.commentsItemId = i.getId();
                            gp.pageId = currentPage.getPageId();
                            gp.pageItemId = pageItem.getId();
                            gp.studentContentItem = true;

                            UIInternalLink.make(tableRow, "studentGradingPaneLink",
                                    messageLocator.getMessage("simplepage.show-grading-pane-content"), gp)
                                    .decorate(new UIFreeAttributeDecorator("title",
                                            messageLocator.getMessage("simplepage.show-grading-pane-content")));
                        }

                        UIOutput.make(tableRow, "student-td");
                        UILink.make(tableRow, "edit-student", (String) null, "")
                                .decorate(new UIFreeAttributeDecorator("title",
                                        messageLocator.getMessage("simplepage.edit-title.student")));

                        UIOutput.make(tableRow, "studentId", String.valueOf(i.getId()));
                        UIOutput.make(tableRow, "studentAnon", String.valueOf(i.isAnonymous()));
                        UIOutput.make(tableRow, "studentComments", String.valueOf(i.getShowComments()));
                        UIOutput.make(tableRow, "forcedAnon", String.valueOf(i.getForcedCommentsAnonymous()));
                        UIOutput.make(tableRow, "studentGrade", String.valueOf(i.getGradebookId() != null));
                        UIOutput.make(tableRow, "studentMaxPoints", String.valueOf(i.getGradebookPoints()));
                        UIOutput.make(tableRow, "studentGrade2", String.valueOf(i.getAltGradebook() != null));
                        UIOutput.make(tableRow, "studentMaxPoints2", String.valueOf(i.getAltPoints()));
                        UIOutput.make(tableRow, "studentitem-required", String.valueOf(i.isRequired()));
                        UIOutput.make(tableRow, "studentitem-prerequisite", String.valueOf(i.isPrerequisite()));
                        UIOutput.make(tableRow, "peer-eval", String.valueOf(i.getShowPeerEval()));
                        makePeerRubric(tableRow, i, makeMaintainRubric);
                        makeSamplePeerEval(tableRow);

                        String peerEvalDate = i.getAttribute("rubricOpenDate");
                        String peerDueDate = i.getAttribute("rubricDueDate");

                        Calendar peerevalcal = Calendar.getInstance();

                        if (peerEvalDate != null && peerDueDate != null) {
                            DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT,
                                    M_locale);
                            //Open date from attribute string
                            peerevalcal.setTimeInMillis(Long.valueOf(peerEvalDate));

                            String dateStr = isoDateFormat.format(peerevalcal.getTime());

                            UIOutput.make(tableRow, "peer-eval-open-date", dateStr);

                            //Due date from attribute string
                            peerevalcal.setTimeInMillis(Long.valueOf(peerDueDate));

                            dateStr = isoDateFormat.format(peerevalcal.getTime());

                            UIOutput.make(tableRow, "peer-eval-due-date", dateStr);
                            UIOutput.make(tableRow, "peer-eval-allow-self",
                                    i.getAttribute("rubricAllowSelfGrade"));

                        } else {
                            //Default open and due date
                            Date now = new Date();
                            peerevalcal.setTime(now);

                            //Default open date: now
                            String dateStr = isoDateFormat.format(peerevalcal.getTime());

                            UIOutput.make(tableRow, "peer-eval-open-date", dateStr);

                            //Default due date: 7 days from now
                            Date later = new Date(peerevalcal.getTimeInMillis() + 604800000);
                            peerevalcal.setTime(later);

                            dateStr = isoDateFormat.format(peerevalcal.getTime());

                            //System.out.println("Setting date to " + dateStr + " and time to " + timeStr);

                            UIOutput.make(tableRow, "peer-eval-due-date", dateStr);
                            UIOutput.make(tableRow, "peer-eval-allow-self",
                                    i.getAttribute("rubricAllowSelfGrade"));
                        }

                        //Peer Eval Stats link
                        GeneralViewParameters view = new GeneralViewParameters(PeerEvalStatsProducer.VIEW_ID);
                        view.setSendingPage(currentPage.getPageId());
                        view.setItemId(i.getId());
                        if (i.getShowPeerEval()) {
                            UILink link = UIInternalLink.make(tableRow, "peer-eval-stats-link", view);
                        }

                        if (itemGroupString != null) {
                            UIOutput.make(tableRow, "student-groups", itemGroupString);
                        }
                        UIOutput.make(tableRow, "student-owner-groups",
                                simplePageBean.getItemOwnerGroupString(i));
                        UIOutput.make(tableRow, "student-group-owned", (i.isGroupOwned() ? "true" : "false"));
                    }
                }
            } else if (i.getType() == SimplePageItem.QUESTION) {
                String itemGroupString = null;
                String itemGroupTitles = null;
                if (canSeeAll) {
                    itemGroupString = simplePageBean.getItemGroupString(i, null, true);
                    if (itemGroupString != null)
                        itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
                    if (itemGroupTitles != null) {
                        itemGroupTitles = "[" + itemGroupTitles + "]";
                    }
                    if (canEditPage)
                        UIOutput.make(tableRow, "item-groups", itemGroupString);
                    if (itemGroupTitles != null)
                        UIOutput.make(tableRow, "questionitem-group-titles", itemGroupTitles);
                }
                SimplePageQuestionResponse response = simplePageToolDao.findQuestionResponse(i.getId(),
                        simplePageBean.getCurrentUserId());

                UIOutput.make(tableRow, "questionSpan");

                boolean isAvailable = simplePageBean.isItemAvailable(i) || canSeeAll;

                UIOutput.make(tableRow, "questionDiv");

                UIOutput.make(tableRow, "questionText", i.getAttribute("questionText"));

                List<SimplePageQuestionAnswer> answers = new ArrayList<SimplePageQuestionAnswer>();
                if ("multipleChoice".equals(i.getAttribute("questionType"))) {
                    answers = simplePageToolDao.findAnswerChoices(i);
                    UIOutput.make(tableRow, "multipleChoiceDiv");
                    UIForm questionForm = UIForm.make(tableRow, "multipleChoiceForm");
                    makeCsrf(questionForm, "csrf4");

                    UIInput.make(questionForm, "multipleChoiceId", "#{simplePageBean.questionId}",
                            String.valueOf(i.getId()));

                    String[] options = new String[answers.size()];
                    String initValue = null;
                    for (int j = 0; j < answers.size(); j++) {
                        options[j] = String.valueOf(answers.get(j).getId());
                        if (response != null && answers.get(j).getId() == response.getMultipleChoiceId()) {
                            initValue = String.valueOf(answers.get(j).getId());
                        }
                    }

                    UISelect multipleChoiceSelect = UISelect.make(questionForm, "multipleChoiceSelect:",
                            options, "#{simplePageBean.questionResponse}", initValue);
                    if (!isAvailable || response != null) {
                        multipleChoiceSelect.decorate(new UIDisabledDecorator());
                    }

                    for (int j = 0; j < answers.size(); j++) {
                        UIBranchContainer answerContainer = UIBranchContainer.make(questionForm,
                                "multipleChoiceAnswer:", String.valueOf(j));
                        UISelectChoice multipleChoiceInput = UISelectChoice.make(answerContainer,
                                "multipleChoiceAnswerRadio", multipleChoiceSelect.getFullID(), j);

                        multipleChoiceInput
                                .decorate(new UIFreeAttributeDecorator("id", multipleChoiceInput.getFullID()));
                        UIOutput.make(answerContainer, "multipleChoiceAnswerText", answers.get(j).getText())
                                .decorate(new UIFreeAttributeDecorator("for", multipleChoiceInput.getFullID()));

                        if (!isAvailable || response != null) {
                            multipleChoiceInput.decorate(new UIDisabledDecorator());
                        }
                    }

                    UICommand answerButton = UICommand.make(questionForm, "answerMultipleChoice",
                            messageLocator.getMessage("simplepage.answer_question"),
                            "#{simplePageBean.answerMultipleChoiceQuestion}");
                    if (!isAvailable || response != null) {
                        answerButton.decorate(new UIDisabledDecorator());
                    }
                } else if ("shortanswer".equals(i.getAttribute("questionType"))) {
                    UIOutput.make(tableRow, "shortanswerDiv");

                    UIForm questionForm = UIForm.make(tableRow, "shortanswerForm");
                    makeCsrf(questionForm, "csrf5");

                    UIInput.make(questionForm, "shortanswerId", "#{simplePageBean.questionId}",
                            String.valueOf(i.getId()));

                    UIInput shortanswerInput = UIInput.make(questionForm, "shortanswerInput",
                            "#{simplePageBean.questionResponse}");
                    if (!isAvailable || response != null) {
                        shortanswerInput.decorate(new UIDisabledDecorator());
                        if (response != null && response.getShortanswer() != null) {
                            shortanswerInput.setValue(response.getShortanswer());
                        }
                    }

                    UICommand answerButton = UICommand.make(questionForm, "answerShortanswer",
                            messageLocator.getMessage("simplepage.answer_question"),
                            "#{simplePageBean.answerShortanswerQuestion}");
                    if (!isAvailable || response != null) {
                        answerButton.decorate(new UIDisabledDecorator());
                    }
                }

                Status questionStatus = getQuestionStatus(i, response);
                addStatusImage(questionStatus, tableRow, "questionStatus", null);
                String statusNote = getStatusNote(questionStatus);
                if (statusNote != null) // accessibility version of icon
                    UIOutput.make(tableRow, "questionNote", statusNote);
                String statusText = null;
                if (questionStatus == Status.COMPLETED)
                    statusText = i.getAttribute("questionCorrectText");
                else if (questionStatus == Status.FAILED)
                    statusText = i.getAttribute("questionIncorrectText");
                if (statusText != null && !"".equals(statusText.trim()))
                    UIOutput.make(tableRow, "questionStatusText", statusText);

                // Output the poll data
                if ("multipleChoice".equals(i.getAttribute("questionType"))
                        && (canEditPage || ("true".equals(i.getAttribute("questionShowPoll"))
                                && (questionStatus == Status.COMPLETED || questionStatus == Status.FAILED)))) {
                    UIOutput.make(tableRow, "showPollGraph", messageLocator.getMessage("simplepage.show-poll"));
                    UIOutput questionGraph = UIOutput.make(tableRow, "questionPollGraph");
                    questionGraph.decorate(new UIFreeAttributeDecorator("id", "poll" + i.getId()));

                    List<SimplePageQuestionResponseTotals> totals = simplePageToolDao.findQRTotals(i.getId());
                    HashMap<Long, Long> responseCounts = new HashMap<Long, Long>();
                    // in theory we don't need the first loop, as there should be a total
                    // entry for all possible answers. But in case things are out of sync ...
                    for (SimplePageQuestionAnswer answer : answers)
                        responseCounts.put(answer.getId(), 0L);
                    for (SimplePageQuestionResponseTotals total : totals)
                        responseCounts.put(total.getResponseId(), total.getCount());

                    for (int j = 0; j < answers.size(); j++) {
                        UIBranchContainer pollContainer = UIBranchContainer.make(tableRow, "questionPollData:",
                                String.valueOf(j));
                        UIOutput.make(pollContainer, "questionPollText", answers.get(j).getText());
                        UIOutput.make(pollContainer, "questionPollNumber",
                                String.valueOf(responseCounts.get(answers.get(j).getId())));
                    }
                }

                if (canEditPage) {
                    UIOutput.make(tableRow, "question-td");

                    // always show grading panel. Currently this is the only way to get feedback
                    if (!cameFromGradingPane) {
                        QuestionGradingPaneViewParameters gp = new QuestionGradingPaneViewParameters(
                                QuestionGradingPaneProducer.VIEW_ID);
                        gp.placementId = toolManager.getCurrentPlacement().getId();
                        gp.questionItemId = i.getId();
                        gp.pageId = currentPage.getPageId();
                        gp.pageItemId = pageItem.getId();

                        UIInternalLink
                                .make(tableRow, "questionGradingPaneLink",
                                        messageLocator.getMessage("simplepage.show-grading-pane"), gp)
                                .decorate(new UIFreeAttributeDecorator("title",
                                        messageLocator.getMessage("simplepage.show-grading-pane")));
                    }

                    UILink.make(tableRow, "edit-question", (String) null, "")
                            .decorate(new UIFreeAttributeDecorator("title",
                                    messageLocator.getMessage("simplepage.edit-title.question")));

                    UIOutput.make(tableRow, "questionId", String.valueOf(i.getId()));
                    boolean graded = "true".equals(i.getAttribute("questionGraded"))
                            || i.getGradebookId() != null;
                    UIOutput.make(tableRow, "questionGrade", String.valueOf(graded));
                    UIOutput.make(tableRow, "questionMaxPoints", String.valueOf(i.getGradebookPoints()));
                    UIOutput.make(tableRow, "questionGradebookTitle", String.valueOf(i.getGradebookTitle()));
                    UIOutput.make(tableRow, "questionitem-required", String.valueOf(i.isRequired()));
                    UIOutput.make(tableRow, "questionitem-prerequisite", String.valueOf(i.isPrerequisite()));
                    UIOutput.make(tableRow, "questionitem-groups", itemGroupString);
                    UIOutput.make(tableRow, "questionCorrectText",
                            String.valueOf(i.getAttribute("questionCorrectText")));
                    UIOutput.make(tableRow, "questionIncorrectText",
                            String.valueOf(i.getAttribute("questionIncorrectText")));

                    if ("shortanswer".equals(i.getAttribute("questionType"))) {
                        UIOutput.make(tableRow, "questionType", "shortanswer");
                        UIOutput.make(tableRow, "questionAnswer", i.getAttribute("questionAnswer"));
                    } else {
                        UIOutput.make(tableRow, "questionType", "multipleChoice");

                        for (int j = 0; j < answers.size(); j++) {
                            UIBranchContainer answerContainer = UIBranchContainer.make(tableRow,
                                    "questionMultipleChoiceAnswer:", String.valueOf(j));
                            UIOutput.make(answerContainer, "questionMultipleChoiceAnswerId",
                                    String.valueOf(answers.get(j).getId()));
                            UIOutput.make(answerContainer, "questionMultipleChoiceAnswerText",
                                    answers.get(j).getText());
                            UIOutput.make(answerContainer, "questionMultipleChoiceAnswerCorrect",
                                    String.valueOf(answers.get(j).isCorrect()));
                        }

                        UIOutput.make(tableRow, "questionShowPoll",
                                String.valueOf(i.getAttribute("questionShowPoll")));
                    }
                }
            } else {
                // remaining type must be a block of HTML
                UIOutput.make(tableRow, "itemSpan");

                if (canSeeAll) {
                    String itemGroupString = simplePageBean.getItemGroupString(i, null, true);
                    String itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
                    if (itemGroupTitles != null) {
                        itemGroupTitles = "[" + itemGroupTitles + "]";
                    }

                    UIOutput.make(tableRow, "item-groups-titles-text", itemGroupTitles);
                }

                if (canSeeAll || simplePageBean.isItemAvailable(i)) {
                    UIVerbatim.make(tableRow, "content", (i.getHtml() == null ? "" : i.getHtml()));
                } else {
                    UIComponent unavailableText = UIOutput.make(tableRow, "content",
                            messageLocator.getMessage("simplepage.textItemUnavailable"));
                    unavailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-text-item"));
                }

                // editing is done using a special producer that calls FCK.
                if (canEditPage) {
                    GeneralViewParameters eParams = new GeneralViewParameters();
                    eParams.setSendingPage(currentPage.getPageId());
                    eParams.setItemId(i.getId());
                    eParams.viewID = EditPageProducer.VIEW_ID;
                    UIOutput.make(tableRow, "edittext-td");
                    UIInternalLink.make(tableRow, "edit-link", (String) null, eParams)
                            .decorate(new UIFreeAttributeDecorator("title",
                                    messageLocator.getMessage("simplepage.edit-title.textbox").replace("{}",
                                            Integer.toString(textboxcount))));
                    textboxcount++;
                }
            }
        }

        // end of items. This is the end for normal users. Following is
        // special
        // checks and putting out the dialogs for the popups, for
        // instructors.

        boolean showBreak = false;

        // I believe refresh is now done automatically in all cases
        // if (showRefresh) {
        // UIOutput.make(tofill, "refreshAlert");
        //
        // // Should simply refresh
        // GeneralViewParameters p = new GeneralViewParameters(VIEW_ID);
        // p.setSendingPage(currentPage.getPageId());
        // UIInternalLink.make(tofill, "refreshLink", p);
        // showBreak = true;
        // }

        // stuff goes on the page in the order in the HTML file. So the fact
        // that it's here doesn't mean it shows
        // up at the end. This code produces errors and other odd stuff.

        if (canSeeAll) {
            // if the page is hidden, warn the faculty [students get stopped
            // at
            // the top]
            if (currentPage.isHidden()) {
                UIOutput.make(tofill, "hiddenAlert").decorate(new UIFreeAttributeDecorator("title",
                        messageLocator.getMessage("simplepage.pagehidden")));
                UIVerbatim.make(tofill, "hidden-text", messageLocator.getMessage("simplepage.pagehidden.text"));

                showBreak = true;
                // similarly warn them if it isn't released yet
            } else if (currentPage.getReleaseDate() != null && currentPage.getReleaseDate().after(new Date())) {
                DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, M_locale);
                TimeZone tz = timeService.getLocalTimeZone();
                df.setTimeZone(tz);
                String releaseDate = df.format(currentPage.getReleaseDate());
                UIOutput.make(tofill, "hiddenAlert").decorate(new UIFreeAttributeDecorator("title",
                        messageLocator.getMessage("simplepage.notreleased")));
                UIVerbatim.make(tofill, "hidden-text",
                        messageLocator.getMessage("simplepage.notreleased.text").replace("{}", releaseDate));
                showBreak = true;
            }
        }

        if (showBreak) {
            UIOutput.make(tofill, "breakAfterWarnings");
        }
    }

    // more warnings: if no item on the page, give faculty instructions,
    // students an error
    if (!anyItemVisible) {
        if (canEditPage) {
            String helpUrl = null;
            // order:
            // localized placedholder
            // localized general
            // default placeholder
            // we know the defaults exist because we include them, so
            // we never need to consider default general
            if (currentPage.getOwner() != null)
                helpUrl = getLocalizedURL("student.html", true);
            else {
                helpUrl = getLocalizedURL("placeholder.html", false);
                if (helpUrl == null)
                    helpUrl = getLocalizedURL("general.html", false);
                if (helpUrl == null)
                    helpUrl = getLocalizedURL("placeholder.html", true);
            }

            UIOutput.make(tofill, "startupHelp").decorate(new UIFreeAttributeDecorator("src", helpUrl))
                    .decorate(new UIFreeAttributeDecorator("id", "iframe"));
            if (!iframeJavascriptDone) {
                UIOutput.make(tofill, "iframeJavascript");
                iframeJavascriptDone = true;
            }
        } else {
            UIOutput.make(tofill, "error-div");
            UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.noitems_error_user"));
        }
    }

    // now output the dialogs. but only for faculty (to avoid making the
    // file bigger)
    if (canEditPage) {
        createSubpageDialog(tofill, currentPage);
    }

    createDialogs(tofill, currentPage, pageItem);
}

From source file:com.nest5.businessClient.Initialactivity.java

@Override
public void OnPrintSelect(int Type) {
    LinkedHashMap<Registrable, Integer> imprimiendo = cookingOrders.get(currentSelectedPosition);
    Date date = new Date();
    String fecha = new SimpleDateFormat("dd/MM/yyyy - HH:mm:ss").format(date);
    String mesa = "DOMICILIO / PARA LLEVAR";
    CurrentTable<Table, Integer> mesaActual = cookingOrdersTable.get(imprimiendo);
    if (mesaActual != null) {
        mesa = mesaActual.getTable().getName().toUpperCase(Locale.getDefault());
    }//from  w  w  w.j a  v  a  2  s  .  c o m

    StringBuilder factura = new StringBuilder();
    SharedPreferences prefs = Util.getSharedPreferences(mContext);
    String empresa = prefs.getString(Setup.COMPANY_NAME, "Nombre de Empresa");
    String nit = prefs.getString(Setup.COMPANY_NIT, "000000000-0");
    String email = prefs.getString(Setup.COMPANY_EMAIL, "email@empresa.com");
    String pagina = prefs.getString(Setup.COMPANY_URL, "http://www.empresa.com");
    String direccion = prefs.getString(Setup.COMPANY_ADDRESS, "Direccin Fsica Empresa");
    String telefono = prefs.getString(Setup.COMPANY_TEL, "555-55-55");
    String mensaje = prefs.getString(Setup.COMPANY_MESSAGE,
            "No hay ningn mensaje configurado an. En el mensaje es recomendable mencionar tus redes sociales, benficios y promociones que tengas, adems de informacin de inters paratus clientes. ");
    String propina = prefs.getString(Setup.TIP_MESSAGE,
            "No hay ningn mensaje de propina configurado an. ");
    String resolution = prefs.getString(Setup.RESOLUTION_MESSAGE,
            "Resolucin de facturacin No. 00000-0000 de 1970 DIAN");
    //int currentSale = prefs.getInt(Setup.CURRENT_SALE, 0);
    factura.append("COPIA DE ORDEN\r\n");
    factura.append("NO VLIDO COMO FACTURA\r\n");
    factura.append("--------------------\r\n");
    factura.append(empresa + "\r\n");
    factura.append(empresa + "\r\n");
    factura.append(nit + "\r\n");
    factura.append(direccion + "\r\n");
    factura.append(telefono + "\r\n");
    factura.append(email + "\r\n");
    factura.append(pagina + "\r\n");
    factura.append(resolution + "\r\n");
    factura.append("\r\n");
    factura.append(fecha);
    factura.append("\r\n");
    factura.append(mesa);
    factura.append("\r\n");
    factura.append("    Item       Cantidad   Precio\r\n");
    Iterator<Entry<Registrable, Integer>> it = imprimiendo.entrySet().iterator();
    //////Log.i("MISPRUEBAS","Valor de currentOrder"+String.valueOf(currentOrder.size()));
    // Log.d(TAG,String.valueOf(currentOrder.size()));
    LinkedHashMap<Registrable, Integer> currentObjects = new LinkedHashMap<Registrable, Integer>();
    float base = 0;
    float iva = 0;
    float total = 0;
    ArrayList<String> productos = new ArrayList<String>();
    ArrayList<String> quantities = new ArrayList<String>();
    ArrayList<String> precios = new ArrayList<String>();
    while (it.hasNext()) {

        LinkedHashMap.Entry<Registrable, Integer> pairs = (LinkedHashMap.Entry<Registrable, Integer>) it.next();

        currentObjects.put(pairs.getKey(), pairs.getValue());

        String name = pairs.getKey().name;

        int longName = name.length();
        int subLength = 14 - longName;
        if (subLength < 0)
            name = name.substring(0, 14);
        int espacios1 = 4;
        int espacios2 = 12;
        if (name.length() < 14) {
            espacios1 += 14 - name.length();
        }
        factura.append(name);
        productos.add(name);
        int qtyL = String.valueOf(pairs.getValue()).length();
        float precioiva = (float) Math.round(pairs.getKey().price + pairs.getKey().price * pairs.getKey().tax);
        base += (float) Math.round(pairs.getKey().price * pairs.getValue());
        iva += (float) Math.round((pairs.getKey().price * pairs.getKey().tax) * pairs.getValue());
        total += precioiva * pairs.getValue();

        int priceL = String.valueOf(precioiva).length();
        espacios1 = espacios1 - qtyL < 1 ? espacios1 = 1 : espacios1 - qtyL;
        espacios2 = espacios2 - priceL < 1 ? espacios2 = 1 : espacios2 - priceL;
        espacios2 = espacios2 - qtyL < 1 ? espacios2 = 1 : espacios2 - qtyL;
        for (int k = 0; k < espacios1; k++) {
            factura.append(" ");
        }
        factura.append(pairs.getValue());
        quantities.add(String.valueOf(pairs.getValue()));
        for (int k = 0; k < espacios2; k++) {
            factura.append(" ");
        }
        factura.append("$");
        factura.append(precioiva);
        factura.append("\r\n");
        precios.add("$" + precioiva);
    }
    factura.append("\r\n");
    factura.append("<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>\r\n");
    factura.append("BASE:      $" + base + "\r\n");
    factura.append("Imp.:      $" + iva + "\r\n");
    factura.append("SUBTOTAL:     $" + total + "\r\n");
    factura.append("\r\n");
    factura.append("<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>\r\n");
    factura.append("\r\n");
    factura.append(propina + "\r\n");
    factura.append(mensaje);

    Boolean printed = true;
    try {
        if (mChatService.getState() == mChatService.STATE_CONNECTED) {
            try {
                mChatService.write(factura.toString().getBytes("x-UnicodeBig"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            printed = false;
            Toast.makeText(mContext, "No hay impresora bluetooth conectada.", Toast.LENGTH_LONG).show();
        }
    } catch (NullPointerException e) {
        printed = false;
        e.printStackTrace();
    }
    if (!printed) {//buscar impresora TCP/IP
        StringBuilder formateado = new StringBuilder();
        formateado.append(CLEAR_PRINTER);
        formateado.append(INITIALIZE_PRINTER);
        formateado.append(JUSTIFICATION_CENTER);
        formateado.append(DOUBLE_WIDE_CHARACTERS);
        formateado.append("CUENTA PEDIDO No." + String.valueOf(currentSelectedPosition + 1));
        formateado.append(PRINT_FEED_ONE_LINE);
        formateado.append(fecha);
        formateado.append(PRINT_FEED_N_LINES);
        formateado.append((char) 0x02);
        formateado.append(mesa);
        formateado.append(PRINT_FEED_N_LINES);
        formateado.append((char) 0x02);
        formateado.append(SINGLE_WIDE_CHARACTERS);
        formateado.append("NO VLIDO COMO FACTURA DE VENTA");
        formateado.append(PRINT_FEED_ONE_LINE);
        formateado.append(PRINT_FEED_N_LINES);
        formateado.append((char) 0x03);
        formateado.append(DOUBLE_WIDE_CHARACTERS);
        formateado.append(JUSTIFICATION_LEFT);
        formateado.append("ITEM");
        formateado.append(HORIZONTAL_TAB);
        formateado.append("CANT.");
        formateado.append(HORIZONTAL_TAB);
        formateado.append("PRECIO");
        formateado.append(SINGLE_WIDE_CHARACTERS);
        formateado.append(PRINT_FEED_ONE_LINE);
        for (String actual : productos) {
            int pos = productos.indexOf(actual);
            String cantidad = quantities.get(pos);
            String precio = precios.get(pos);
            formateado.append(actual);
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append("x" + cantidad);
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append(precio);
            formateado.append(PRINT_FEED_ONE_LINE);
        }
        formateado.append(DOUBLE_WIDE_CHARACTERS);
        formateado.append("______________________");
        formateado.append(SINGLE_WIDE_CHARACTERS);
        formateado.append(PRINT_FEED_N_LINES);
        formateado.append((char) 0x02);
        formateado.append("BASE:");
        formateado.append(HORIZONTAL_TAB);
        formateado.append(HORIZONTAL_TAB);
        formateado.append(HORIZONTAL_TAB);
        formateado.append(HORIZONTAL_TAB);
        formateado.append("$" + base);
        formateado.append(PRINT_FEED_ONE_LINE);
        formateado.append("Impuesto:");
        formateado.append(HORIZONTAL_TAB);
        formateado.append(HORIZONTAL_TAB);
        formateado.append(HORIZONTAL_TAB);
        formateado.append("$" + iva);
        formateado.append(PRINT_FEED_ONE_LINE);
        formateado.append("TOTAL:");
        formateado.append(HORIZONTAL_TAB);
        formateado.append(HORIZONTAL_TAB);
        formateado.append(HORIZONTAL_TAB);
        formateado.append("$" + total);
        formateado.append(PRINT_FEED_ONE_LINE);
        formateado.append(DOUBLE_WIDE_CHARACTERS);
        formateado.append("______________________");
        formateado.append(SINGLE_WIDE_CHARACTERS);
        formateado.append(PRINT_FEED_N_LINES);
        formateado.append((char) 0x02);
        formateado.append(ITALIC_STYLE);
        formateado.append(propina);
        formateado.append(PRINT_FEED_ONE_LINE);
        formateado.append("DESEA INCLUIRLA?");
        formateado.append(PRINT_FEED_ONE_LINE);
        formateado.append("SI: |____|");
        formateado.append(HORIZONTAL_TAB);
        formateado.append("NO:|____|");
        formateado.append(PRINT_FEED_N_LINES);
        formateado.append((char) 0x02);
        formateado.append(mensaje);
        formateado.append(ITALIC_CANCEL);
        formateado.append(FINALIZE_TICKET);
        formateado.append(FULL_CUT);
        if (mTCPPrint != null) {
            if (mTCPPrint.getStatus() == TCPPrint.CONNECTED) {
                mTCPPrint.sendMessage(formateado.toString());
                mTCPPrint.sendMessage(formateado.toString());
            } else {
                mTCPPrint.stopClient();
                new connectTask().execute(formateado.toString());
                alertbox("Oops!",
                        "Al Parecer no hay impresora disponible. Estamos tratando de reconectarnos e imprimir. Si no funciona, reinicia la Red o la impresora y ve a rdenes para imprimir el pedido.");
            }
        } else {
            alertbox("Oops!",
                    "Al Parecer no hay impresora disponible. Trataremos en este momento de nuevo de imprimir el pedido. Si no funciona, reinicia la red o la impreso y ve a rdenes para imprimir de nuevo la orden.");
            new connectTask().execute(formateado.toString());
        }
    }
    //currentOrder.clear(); //NUEVOO
    //makeTable("NA");
    List<Long> items = new ArrayList<Long>();
    List<String> nameTables = new ArrayList<String>();
    for (LinkedHashMap<Registrable, Integer> current : cookingOrders) {
        items.add(cookingOrdersTimes.get(current));
        nameTables.add(cookingOrdersTable.get(current).getTable().getName());
    }
    cookingAdapter = new SaleAdapter(mContext, items, nameTables, inflater);
    ordersList.setAdapter(cookingAdapter);
    ordersList.setOnItemClickListener(orderListListener);
    currentSelectedPosition = -1;

}

From source file:org.fhaes.analysis.FHInterval.java

/**
 * Actually perform the analysis./*from ww  w  .  j  a va2  s  .  c o m*/
 */
@SuppressWarnings("deprecation")
private void doAnalysis() {

    log.debug("INPUT PARAMETERS");
    log.debug("inputFileArray = " + inputFileArray);
    log.debug("analyissType = " + analysisType);
    log.debug("startYear = " + startYear);
    log.debug("endYear = " + endYear);
    log.debug("fireFilterType = " + fireFilterType);
    log.debug("filterValue = " + filterValue);
    log.debug("includeIncomplete = " + includeIncomplete);
    log.debug("alphaLevel = " + alphaLevel);

    boolean highway = true;

    ArrayList<FHX2FileReader> myReader = new ArrayList<FHX2FileReader>();
    Integer minFirstYear = new Integer(9999);
    Integer maxLastYear = new Integer(0);

    String savePath = new String();
    savePath = inputFileArray[0].getAbsolutePath();

    for (int i = 0; i < inputFileArray.length; i++) {
        myReader.add(new FHX2FileReader(inputFileArray[i]));

        /*
         * set the beginning year accounting for the filter
         */
        if (eventTypeToProcess.equals(EventTypeToProcess.FIRE_EVENT)) {
            // myReader.get(i).makeClimate2d();
            if (startYear == 0 && highway) {
                if (myReader.get(i).getFirstFireYear() < minFirstYear) {
                    minFirstYear = myReader.get(i).getFirstFireYear();
                }
            } else if (startYear != 0 && highway) {
                if (myReader.get(i).getFirstYear() < minFirstYear) {
                    minFirstYear = myReader.get(i).getFirstYear();
                }
            }
            if (startYear != 0) {
                minFirstYear = startYear;
                // minFirstYear = minFirstYear+1;
            }
        } else if (eventTypeToProcess.equals(EventTypeToProcess.INJURY_EVENT)) {
            // myReader.get(i).makeClimate2dII();
            if (startYear == 0 && highway) {
                if (myReader.get(i).getFirstInjuryYear() < minFirstYear) {
                    minFirstYear = myReader.get(i).getFirstInjuryYear();
                }
            } else if (startYear != 0 && highway) {
                if (myReader.get(i).getFirstYear() < minFirstYear) {
                    minFirstYear = myReader.get(i).getFirstYear();
                }
            }
            if (startYear != 0) {
                minFirstYear = startYear;
                // minFirstYear = minFirstYear+1;
            }
        } else if (eventTypeToProcess.equals(EventTypeToProcess.FIRE_AND_INJURY_EVENT)) {
            // myReader.get(i).makeClimate2dII();
            if (startYear == 0 && highway) {
                if (myReader.get(i).getFirstIndicatorYear() < minFirstYear) {
                    minFirstYear = myReader.get(i).getFirstIndicatorYear();
                }
            } else if (startYear != 0 && highway) {
                if (myReader.get(i).getFirstYear() < minFirstYear) {
                    minFirstYear = myReader.get(i).getFirstYear();
                }
            }
            if (startYear != 0) {
                minFirstYear = startYear;
                // minFirstYear = minFirstYear+1;
            }
        } else {
            log.error("Unsupported event type caught");
        }
        /*
         * Set the last year accounting for the filter
         */
        if (myReader.get(i).getLastYear() > maxLastYear) {
            maxLastYear = myReader.get(i).getLastYear();
        }
        if (endYear != 0) {
            maxLastYear = endYear;
        }
    } // end of i loop

    log.debug("the input filelength is " + inputFileArray.length);
    log.debug("The FIRST FIRE YEAR is " + minFirstYear);
    log.debug("The LAST YEAR is " + maxLastYear);
    log.debug("Minimum and Maximum years are " + minFirstYear + " " + maxLastYear);
    /*
     * set the format for the output of the numbers to 2 decimal formats
     */
    DecimalFormat twoPlace = new DecimalFormat("0.00");
    DecimalFormat threePlace = new DecimalFormat("0.000");

    /*
     * Calculate the listYears the common years where the files will be analyzed
     */
    ArrayList<Integer> listYears = new ArrayList<Integer>();
    for (int i = 0; i < maxLastYear - minFirstYear + 1; i++) {
        listYears.add(minFirstYear + i);
    }
    /*
     * create arraylist need for the Interval Analysis
     */

    ArrayList<ArrayList<Integer>> climateMatrixSite = new ArrayList<ArrayList<Integer>>();
    ArrayList<ArrayList<Double>> filterMatrix = new ArrayList<ArrayList<Double>>();
    ArrayList<Integer> climateVector = new ArrayList<Integer>();
    ArrayList<ArrayList<Double>> climateVectorFilter2 = new ArrayList<ArrayList<Double>>();
    // ArrayList<Double> fireintervalspersite = new ArrayList<Double>();
    ArrayList<Integer> climateVectorActualSite = null;
    ArrayList<Double> filterVectorActual = null;
    ArrayList<Integer> climateYear = new ArrayList<Integer>();
    ArrayList<Integer> minSampleFilter = null;
    ArrayList<Double> percentOfRecordingfilter = null;
    Double[] Dfireintervalspersite;
    double[] dfireintervalspersite;
    String[] statsparam = new String[22];
    if (eventTypeToProcess.equals(EventTypeToProcess.FIRE_EVENT)) {
        statsparam[0] = "Total intervals";
        statsparam[1] = "Mean fire interval";
        statsparam[2] = "Median fire interval";
        statsparam[3] = "Standard deviation";
        statsparam[4] = "Fire frequency";
        statsparam[5] = "Coefficient of variation";
        statsparam[6] = "Skewness";
        statsparam[7] = "Kurtosis";
        statsparam[8] = "Minimum fire interval";
        statsparam[9] = "Maximum fire interval";
        statsparam[10] = "Weibull scale parameter";
        statsparam[11] = "Weibull shape parameter";
        statsparam[12] = "Weibull mean";
        statsparam[13] = "Weibull median";
        statsparam[14] = "Weibull mode";
        statsparam[15] = "Weibull standard deviation";
        statsparam[16] = "Weibull fire frequency";
        statsparam[17] = "Weibull skewness";
        statsparam[18] = "Lower exceedance interval";
        statsparam[19] = "Upper exceedance interval";
        statsparam[20] = "Significantly short interval upper bound";
        statsparam[21] = "Significantly long interval lower bound";
    } else if (eventTypeToProcess.equals(EventTypeToProcess.INJURY_EVENT)) {
        statsparam[0] = "Total intervals";
        statsparam[1] = "Mean indicator interval";
        statsparam[2] = "Median indicator interval";
        statsparam[3] = "Standard deviation";
        statsparam[4] = "Indicator frequency";
        statsparam[5] = "Coefficient of variation";
        statsparam[6] = "Skewness";
        statsparam[7] = "Kurtosis";
        statsparam[8] = "Minimum fire interval";
        statsparam[9] = "Maximum indicator interval";
        statsparam[10] = "Weibull scale parameter";
        statsparam[11] = "Weibull shape parameter";
        statsparam[12] = "Weibull mean";
        statsparam[13] = "Weibull median";
        statsparam[14] = "Weibull mode";
        statsparam[15] = "Weibull standard deviation";
        statsparam[16] = "Weibull indicator frequency";
        statsparam[17] = "Weibull skewness";
        statsparam[18] = "Lower exceedance interval";
        statsparam[19] = "Upper exceedance interval";
        statsparam[20] = "Significantly short interval upper bound";
        statsparam[21] = "Significantly long interval lower bound";
    } else if (eventTypeToProcess.equals(EventTypeToProcess.FIRE_AND_INJURY_EVENT)) {
        statsparam[0] = "Total intervals";
        statsparam[1] = "Mean fire and other indicator interval";
        statsparam[2] = "Median fire and other indicator interval";
        statsparam[3] = "Standard deviation";
        statsparam[4] = "Fire and other indicator frequency";
        statsparam[5] = "Coefficient of variation";
        statsparam[6] = "Skewness";
        statsparam[7] = "Kurtosis";
        statsparam[8] = "Minimum fire and other indicator interval";
        statsparam[9] = "Maximum fire interval";
        statsparam[10] = "Weibull scale parameter";
        statsparam[11] = "Weibull shape parameter";
        statsparam[12] = "Weibull mean";
        statsparam[13] = "Weibull median";
        statsparam[14] = "Weibull mode";
        statsparam[15] = "Weibull standard deviation";
        statsparam[16] = "Weibull indicator frequency";
        statsparam[17] = "Weibull skewness";
        statsparam[18] = "Lower exceedance interval";
        statsparam[19] = "Upper exceedance interval";
        statsparam[20] = "Significantly short interval upper bound";
        statsparam[21] = "Significantly long interval lower bound";
    } else {

        log.error("Unsupported event type caught");
    }

    double[] fixvalt = { 0.999, 0.99, 0.975, 0.95, 0.9, 0.875, 0.8, 0.75, 0.7, 0.667, 0.5, 0.333, 0.3, 0.25,
            0.2, 0.125, 0.1, 0.05, 0.025, 0.01, 0.001 };

    double[][] ExceeProbcomp = new double[fixvalt.length][myReader.size()];
    double[][] ExceeProbsample = new double[fixvalt.length][myReader.size()];
    // log.debug("the size of statsparam is " +
    // statsparam.length);
    double[][] summaryComp = new double[statsparam.length][myReader.size()];
    double[] numberOfintervalscomp = new double[myReader.size()];
    // ArrayList<ArrayList<Integer>>();
    // ArrayList<ArrayList<Integer>> FIyearperSample = new
    // ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> FyearperSampletemp;
    ArrayList<Integer> FIyearperSampletemp;
    // ArrayList<Double> fireintervalspersample = new
    double[] numberOfintervalssamp = new double[myReader.size()];
    double[][] summarySample = new double[statsparam.length][myReader.size()];
    Double[] Dfireintervalspersample;
    double[] dfireintervalspersample;
    /*
     * Set up either of the two filters two create the binary matrix on the case of composite analysis there are two possible filters:
     * Number of fires and percentage of scarred trees.
     */
    Integer firesFilter1 = new Integer(0);
    Double firesFilter2 = new Double(0);
    if (fireFilterType.equals(FireFilterType.NUMBER_OF_EVENTS)) {
        if (filterValue != 1)
            firesFilter1 = filterValue.intValue();
        // log.debug("number of fires is selected is: "+
        // firesFilter1);
    } else if (fireFilterType.equals(FireFilterType.PERCENTAGE_OF_ALL_TREES)) {
        if (filterValue != 1)
            firesFilter2 = filterValue / 100.0;
        // log.debug("percentage of fires is selected is: "+
        // firesFilter2);
    } else if (fireFilterType.equals(FireFilterType.PERCENTAGE_OF_RECORDING)) {
        if (filterValue != 1)
            firesFilter2 = filterValue / 100.0;
        // TODO ELENA TO CHECK
    } else {
        log.error("Unknown FireFilterType");
        return;
    }

    boolean[] enoughIntComp = new boolean[myReader.size()];
    boolean[] enoughIntSamp = new boolean[myReader.size()];
    // NEW FOR ELENA
    log.debug("Sample depth filter type = " + sampleDepthFilterType);
    log.debug("Sample depth value = " + sampleDepthFilterValue);

    // if (sampleDepthFilterType.equals(SampleDepthFilterType.MIN_NUM_SAMPLES))
    // {
    // // TODO ELENA
    // }
    // else if (sampleDepthFilterType.equals(SampleDepthFilterType.MIN_NUM_RECORDER_SAMPLES))
    // {
    // // TODO ELENA
    // }
    /*
     * start processing each file individually: The analysis can be done by either tree (by sample/non-binary) or by site
     * (composite/binary). by tree the box selected is: jCheckTree. by site the box selected is:
     */
    for (int i = 0; i < myReader.size(); i++) {
        log.debug("  Starting to Process file : " + myReader.get(i).getName());

        /*
         * get the vector Year containing the vector of year of a given fhx file load it into the array list climateYear.
         */

        climateYear = myReader.get(i).getYearArray();

        // new stuff
        // Create filter based on min number of samples/recorder samples
        int[] depths = null;
        if (sampleDepthFilterType.equals(SampleDepthFilterType.MIN_NUM_SAMPLES)) {
            depths = myReader.get(i).getSampleDepths();
            log.debug("MIN_NUM_SAMPLES ");
        } else if (sampleDepthFilterType.equals(SampleDepthFilterType.MIN_NUM_RECORDER_SAMPLES)) {
            depths = myReader.get(i).getRecordingDepths(eventTypeToProcess);
            log.debug(" MIN_NUM_RECORDER_SAMPLES");
        } else {
            log.error("Unknown sample depth filter type.");
            return;
        }
        minSampleFilter = new ArrayList<Integer>();
        for (int ij = 0; ij < listYears.size(); ij++) {
            if (climateYear.indexOf(listYears.get(ij)) == -1) {
                minSampleFilter.add(-1);
            } else {
                // log.debug("the sample depth is "
                // + myReader.get(i).getSampleDepths()[climateYear.indexOf(listYearsComp.get(ij))]);
                minSampleFilter.add(new Integer(depths[climateYear.indexOf(listYears.get(ij))]));
            }
            // log.debug(" " + minSampleFilter.get(ij));
        }

        // end new stuff

        /*
         * get filter matrix for each file.
         * 
         * filters2d matrix composed of the 3 filters number of fires (total capital letter per row) total number of tree (total lower
         * case letter plus bars counting only after a fire) percent of scared trees total fires/total trees
         */

        // climateVectorFilter2 = myReader.get(i).getFilterArrays(eventTypeToProcess);
        /*
         * More new stuff
         */
        if (filterValue != 1) {
            /*
             * get both matrices:
             * 
             * 2. filters2d matrix composed of the 3 filters number of fires (total capital letter per row) total number of tree (total
             * lower case letter plus bars counting only after a fire) percent of scared trees total fires/total trees
             */

            climateVectorFilter2 = myReader.get(i).getFilterArrays(eventTypeToProcess);

            /*
             * if by tree analysis is selected create two matrices (array list) 1. filterMatrix containing the three filter vectors only
             * in between common years (so using the listYearComp array list subset of the years vector) 2. climateMatrix 2 dimensional
             * array list containing binary matrices restricted to the listYear list.
             */
            if (fireFilterType.equals(FireFilterType.PERCENTAGE_OF_RECORDING)) {
                percentOfRecordingfilter = new ArrayList<Double>();

                for (int ij = 0; ij < listYears.size(); ij++) {

                    if (climateYear.indexOf(listYears.get(ij)) == -1) {
                        percentOfRecordingfilter.add(-1.0);
                    } else {
                        if (myReader.get(i).getRecordingDepths(eventTypeToProcess)[climateYear
                                .indexOf(listYears.get(ij))] != 0) {
                            percentOfRecordingfilter.add(new Double(
                                    climateVectorFilter2.get(0).get(climateYear.indexOf(listYears.get(ij)))
                                            / myReader.get(i).getRecordingDepths(eventTypeToProcess)[climateYear
                                                    .indexOf(listYears.get(ij))]));
                        } else {
                            percentOfRecordingfilter.add(-99.0);
                        }
                    }
                    log.debug("PERCENTAGE_OF_RECORDING is: " + percentOfRecordingfilter.get(ij));
                }
            } else {
                for (int ik = 0; ik < 3; ik++) {
                    log.debug("filter number is: " + ik);
                    filterVectorActual = new ArrayList<Double>();
                    for (int ij = 0; ij < listYears.size(); ij++) { // log.debug(" climateYear.indexOf(listYearsComp.get(j))" +
                                                                    // climateYear.indexOf(listYearsComp.get(ij)));
                                                                    // if(ik==0){log.debug("number of fires
                                                                    // "+climateVectorFilter2.get(0).get(climateYear.indexOf(listYears.get(ij)))+" year
                                                                    // "+listYearsComp.get(ij));}
                        if (climateYear.indexOf(listYears.get(ij)) == -1) {
                            filterVectorActual.add(-1.0);
                        } else {
                            filterVectorActual.add(new Double(
                                    climateVectorFilter2.get(ik).get(climateYear.indexOf(listYears.get(ij)))));
                        }
                        if (ik == 2) {
                            log.debug("filteperc  " + filterVectorActual.get(ij));
                        }
                    }
                    // log.debug("size of filterVectorActual is : "+filterVectorActual.size());
                    filterMatrix.add(filterVectorActual);
                    // if(ik==0){log.debug("filters is: "+filter);
                }
            } // end of if-else percentageofrecording
              // log.debug("size of the FilterMatrix is" + filterMatrix.size());

        } // end of if filters not equal to 1
        /*
         * end of more new stuff
         */
        /*
         * 
         * 1. Create the filterMatrix containing the tree filter vectors only in between common years (so using the listYearComp array
         * list subset of the years vector)
         */
        // for (int ik = 0; ik < 3; ik++)
        // {
        // filterVectorActual = new ArrayList<Double>();
        // for (int ij = 0; ij < listYears.size(); ij++)
        // {
        // if (climateYear.indexOf(listYears.get(ij)) == -1)
        // {
        // filterVectorActual.add(-1.0);
        // }
        // else
        // {
        // filterVectorActual.add(new Double(climateVectorFilter2.get(ik).get(climateYear.indexOf(listYears.get(ij)))));
        // }

        // }
        /*
         * ArrayList filterMatrix containes the filter matrix for each of the files
         */
        // filterMatrix.add(filterVectorActual);
        // }//end of creating the filter matrix.

        /*
         * get matrix climate binary matrix by site (binary analysis) if Composite is selected.
         */
        // if ((doComposite)&&(!jTextOfFires.getText().equals("1"))){
        if (analysisType.equals(AnalysisType.COMPOSITE)) {
            log.debug("inside the comp");
            // System.out.println("inside the comp " + " working on file "+ myReader.get(i).getName() );

            if (eventTypeToProcess.equals(EventTypeToProcess.FIRE_EVENT)) {
                climateVector = myReader.get(i).getFireEventsArray();
            } else if (eventTypeToProcess.equals(EventTypeToProcess.INJURY_EVENT)) {
                climateVector = myReader.get(i).getOtherInjuriesArray();
            } else if (eventTypeToProcess.equals(EventTypeToProcess.FIRE_AND_INJURY_EVENT)) {
                climateVector = myReader.get(i).getFiresAndInjuriesArray();
            } else {

                log.error("Unsupported event type caught");
            }

            climateVectorActualSite = new ArrayList<Integer>();

            for (int j = 0; j < listYears.size(); j++) {

                if (climateYear.indexOf(listYears.get(j)) == -1) {
                    climateVectorActualSite.add(-1);
                } else {
                    if (minSampleFilter.get(j).intValue() >= sampleDepthFilterValue.intValue()) {
                        if (filterValue != 1) {
                            if (fireFilterType.equals(FireFilterType.NUMBER_OF_EVENTS)) {
                                // log.debug("fire filter: "+firesFilter1+" year is: "+listYears.get(j)
                                // +" fires: "+filterMatrix.get(3*i).get(j)+" climatevector:
                                // "+climateVector.get(climateYear.indexOf(listYears.get(j))));
                                if ((filterMatrix.get(3 * i).get(j) < firesFilter1)
                                        && (climateVector.get(climateYear.indexOf(listYears.get(j)))) != -1.0) {
                                    climateVectorActualSite.add(0);
                                } else {
                                    climateVectorActualSite
                                            .add(climateVector.get(climateYear.indexOf(listYears.get(j))));
                                }
                            } else if (fireFilterType.equals(FireFilterType.PERCENTAGE_OF_ALL_TREES)) {
                                // log.debug("percent of fires is selected is: "+
                                // firesFilter2+" "+climateVector.get(climateYear.indexOf(listYearsComp.get(j))));
                                // log.debug("the filter percent of fires is"+filterMatrix.get((3*i+2)).get(j));
                                if ((filterMatrix.get(3 * i + 2).get(j) == -99)) {
                                    climateVectorActualSite.add(-1);
                                } else {
                                    if ((filterMatrix.get(3 * i + 2).get(j) < firesFilter2) && ((climateVector
                                            .get(climateYear.indexOf(listYears.get(j)))) != -1.0)) {
                                        climateVectorActualSite.add(0);
                                    } else {
                                        climateVectorActualSite
                                                .add(climateVector.get(climateYear.indexOf(listYears.get(j))));
                                    }
                                }
                            } else if (fireFilterType.equals(FireFilterType.PERCENTAGE_OF_RECORDING)) {

                                // TODO
                                // ELENA TO IMPLEMENT
                                if (percentOfRecordingfilter.get(j) == -99) {
                                    climateVectorActualSite.add(-1);
                                } else {
                                    if ((percentOfRecordingfilter.get(j) < firesFilter2) && ((climateVector
                                            .get(climateYear.indexOf(listYears.get(j)))) != -1.0)) {
                                        climateVectorActualSite.add(0);
                                    } else {
                                        climateVectorActualSite
                                                .add(climateVector.get(climateYear.indexOf(listYears.get(j))));
                                    }
                                }

                            } else {
                                log.error("Unknown FireFilterType");
                                return;
                            }

                        } // end of if filter not equal to 1
                        else {
                            climateVectorActualSite
                                    .add(climateVector.get(climateYear.indexOf(listYears.get(j))));
                        } // end of else of if filter not equal to 1
                    } // end of if the filter minsampedepth
                    else {
                        // log.debug("j is " + j + "minSampleFilter is " + minSampleFilter.get(j));
                        climateVectorActualSite.add(-1);

                    }
                } // end else 645 to 721
            } // end of j loop listyears (420-459)
            /*
             * climateMatrixSite has the composite information taking in consideration both the filters and common years
             */
            climateMatrixSite.add(climateVectorActualSite);

            /*
             * Must get the years with Fires from the climateMatrixSite which has been filter already
             */
            ArrayList<Double> fireintervalspersite = new ArrayList<Double>();
            ArrayList<Integer> yearsWithFires = new ArrayList<Integer>();
            for (int ij = 0; ij < listYears.size(); ij++) {
                if (climateMatrixSite.get(i).get(ij) == 1) {
                    yearsWithFires.add(listYears.get(ij));
                    log.debug("year with fires " + listYears.get(ij));
                }
            }

            /*
             * check that the number of years with fires is bigger of equal than 3 if so make the fire intervals else the test can not
             * be run and report NA
             */
            // new swich
            if (yearsWithFires.size() != 0) {
                if (includeIncomplete) {
                    if (maxLastYear.compareTo(yearsWithFires.get(yearsWithFires.size() - 1)) != 0) {
                        log.debug("here");
                        numberOfintervalscomp[i] = yearsWithFires.size();
                    } else {
                        numberOfintervalscomp[i] = yearsWithFires.size() - 1;
                    }
                } else {
                    numberOfintervalscomp[i] = yearsWithFires.size() - 1;
                }
            }
            log.debug("number of invervlas in comp is: " + numberOfintervalscomp[i]);
            // end of new switch
            if (numberOfintervalscomp[i] >= 3) {
                enoughIntComp[i] = true;
                ArrayList<Integer> fireIntervals = generateFireIntervals(yearsWithFires);
                for (int ij = 0; ij < fireIntervals.size(); ij++) {
                    // log.debug("fire intervals are: "+
                    // test1.getFireIntervals().get(ij));
                    fireintervalspersite.add(fireIntervals.get(ij) * 1.0);
                }

                /*
                 * Add extra interval if include incomplete is selected. the interval goes from the last fire scar year to the last year
                 * of the fire history.
                 */
                if (includeIncomplete) {
                    double includeinterval = maxLastYear - yearsWithFires.get(yearsWithFires.size() - 1);
                    if (includeinterval > 0) {
                        fireintervalspersite.add(includeinterval);
                        System.out.println("the last year is " + maxLastYear + "the last year with fire is "
                                + yearsWithFires.get(yearsWithFires.size() - 1));
                        log.debug("the included interval is " + includeinterval);
                    }
                }
                log.debug("FireintervalsPerSite =" + fireintervalspersite);
                /*
                 * Get the normal statistics for the fire intervals add the values to the stats and then call them for the stats
                 */
                DescriptiveStatistics stats = new DescriptiveStatistics();
                Dfireintervalspersite = new Double[fireintervalspersite.size()];
                Dfireintervalspersite = fireintervalspersite.toArray(Dfireintervalspersite);
                dfireintervalspersite = new double[fireintervalspersite.size()];
                // summaryComp = new
                // double[statsparam.length][myReader.size()];
                for (int ik = 0; ik < fireintervalspersite.size(); ik++) {
                    stats.addValue(Dfireintervalspersite[ik].doubleValue());
                    dfireintervalspersite[ik] = Dfireintervalspersite[ik].doubleValue();
                }
                /*
                 * load the Summary Analysis for the Composite fire intervals
                 */
                summaryComp[0][i] = fireintervalspersite.size();
                // double mean = stats.getMean();
                summaryComp[1][i] = stats.getMean();
                // double median =
                // StatUtils.percentile(dfireintervalspersite, 50);
                summaryComp[2][i] = StatUtils.percentile(dfireintervalspersite, 50);
                // double std = stats.getStandardDeviation();
                summaryComp[3][i] = stats.getStandardDeviation();
                // double skew = stats.getSkewness();
                summaryComp[4][i] = 1.0 / summaryComp[1][i];
                summaryComp[5][i] = summaryComp[3][i] / summaryComp[1][i];
                summaryComp[6][i] = stats.getSkewness();
                // double kurt = stats.getKurtosis();
                if (numberOfintervalscomp[i] == 3) {
                    summaryComp[7][i] = -99;
                } else {
                    summaryComp[7][i] = stats.getKurtosis();
                }
                // log.debug("nomean \t\t nostd \t\t nokurt \t noskew \t\t nomedian");
                // log.debug(twoPlace.format(mean)+"\t\t"+twoPlace.format(std)+"\t\t"+twoPlace.format(kurt)+"\t\t"+twoPlace.format(skew)+"\t\t"+twoPlace.format(median));

                Weibull weibull = new Weibull(fireintervalspersite);

                ArrayList<Double> weibullProb = weibull.getWeibullProbability(fireintervalspersite);
                ArrayList<Double> siglonglowbound = new ArrayList<Double>();
                ArrayList<Double> sigshortupbound = new ArrayList<Double>();
                log.debug("the weibull probability of first element is " + weibullProb.get(0));
                log.debug("the index  the size of the interval is " + weibullProb.indexOf(weibullProb.get(0)));
                for (int ij = 0; ij < weibullProb.size() - 1; ij++) {
                    if (weibullProb.get(ij) <= alphaLevel) {
                        siglonglowbound.add(fireintervalspersite.get(ij));

                    }
                    if (weibullProb.get(ij) >= (1 - alphaLevel)) {
                        sigshortupbound.add(fireintervalspersite.get(ij));

                    }

                }

                summaryComp[10][i] = weibull.getScale();
                summaryComp[11][i] = weibull.getShape();
                summaryComp[12][i] = weibull.getMean();
                summaryComp[13][i] = weibull.getMedian();
                summaryComp[14][i] = weibull.getMode();
                summaryComp[15][i] = weibull.getSigma();
                summaryComp[16][i] = 1.0 / summaryComp[13][i];
                summaryComp[17][i] = weibull.getSkew();
                summaryComp[18][i] = weibull.getExceedenceProbability2()[0];
                summaryComp[19][i] = weibull.getExceedenceProbability2()[1];
                Collections.sort(sigshortupbound);
                log.debug("siglonglowbound is " + siglonglowbound);
                try {
                    summaryComp[20][i] = sigshortupbound.get(sigshortupbound.size() - 1);
                } catch (Exception e) {
                    summaryComp[20][i] = Double.NaN;
                }
                Collections.sort(siglonglowbound);

                try {
                    summaryComp[21][i] = siglonglowbound.get(0);
                } catch (Exception e) {
                    summaryComp[21][i] = Double.NaN;
                }
                log.debug("sigshortupbound is " + sigshortupbound);
                Collections.sort(fireintervalspersite);
                summaryComp[8][i] = fireintervalspersite.get(0);
                summaryComp[9][i] = fireintervalspersite.get(fireintervalspersite.size() - 1);
                // log.debug("shape \t\t scale \t\t median ");
                // log.debug(twoPlace.format(test1.Weibull_Parameters(fireintervalspersite)[0])+"\t\t"+twoPlace.format(test1.Weibull_Parameters(fireintervalspersite)[1])+"\t\t"+twoPlace.format(test1.weibull_median(test1.Weibull_Parameters(fireintervalspersite))));
                // log.debug("mean \t\t sigma \t\t mode \t\t skewness");
                // log.debug(twoPlace.format(test1.weibull_mean(test1.Weibull_Parameters(fireintervalspersite)))+"\t\t"+twoPlace.format(test1.weibull_sigma(test1.Weibull_Parameters(fireintervalspersite)))+"\t\t"+twoPlace.format(test1.weibull_mode(test1.Weibull_Parameters(fireintervalspersite)))+"\t\t"+twoPlace.format(test1.weibull_skew(test1.Weibull_Parameters(fireintervalspersite))));
                // log.debug("maxhazard \t\t lei \t\t uei ");
                // log.debug(twoPlace.format(test1.maxhazard_int(test1.Weibull_Parameters(fireintervalspersite)))+"\t\t"+twoPlace.format(test1.weibull_lowuppexcint(test1.Weibull_Parameters(fireintervalspersite))[0])+"\t\t"+twoPlace.format(test1.weibull_lowuppexcint(test1.Weibull_Parameters(fireintervalspersite))[1]));
                // log.debug("the size of YearWith Fires is "+YearsWithFires.size());
                System.out.println("the size of the prb exdc is " + weibull.getExceedenceProbability().length);
                for (int kk = 0; kk < weibull.getExceedenceProbability().length; kk++) {
                    ExceeProbcomp[kk][i] = weibull.getExceedenceProbability()[kk];
                    // log.debug("file "+i+"Exce probability "+
                    // ExceeProbcomp[kk][i]);
                }
            } // end of if enoughIntComp
            else {
                enoughIntComp[i] = false;
            }
        } // end the if composite is selected
        /*
         * starting the process for the sample mode.
         */
        if (analysisType.equals(AnalysisType.SAMPLE)) {
            log.debug("I am in sample ");

            ArrayList<Double> fireintervalspersample = new ArrayList<Double>();
            FIyearperSampletemp = new ArrayList<Integer>();
            // FyearperSampletemp = new ArrayList<Integer>();
            for (int k = 0; k < myReader.get(i).getNumberOfSeries(); k++) {

                log.debug("Parsing file index " + i + ", series number " + (k + 1));
                FyearperSampletemp = new ArrayList<Integer>();
                // log.debug("the size of the years of the file is:"+
                // myReader.get(i).getYear().size());
                // log.debug("years with fires in sample "+k +
                // "years are ");
                // for (int j = 0; j < myReader.get(i).getYearArray().size(); j++)
                for (int j = 0; j < listYears.size(); j++) {
                    // log.debug("the size climate2d is "+myReader.get(i).getClimate2d().get(k).get(j));
                    if (eventTypeToProcess.equals(EventTypeToProcess.FIRE_EVENT)) {
                        if (climateYear.indexOf(listYears.get(j)) != -1) {
                            if (myReader.get(i).getClimate2d().get(k)
                                    .get(climateYear.indexOf(listYears.get(j))) == 1) {
                                // FyearperSampletemp.add((j + myReader.get(i).getFirstYear()));
                                FyearperSampletemp.add(listYears.get(j));
                            }
                        }

                    }
                    // {
                    // if ((myReader.get(i).getClimate2d().get(k).get(j) == 1))
                    // {
                    // / log.debug("I here inside ==1 "+
                    // / j+" "+myReader.get(i).getFirstYear());
                    // / int temp=j+myReader.get(i).getFirstYear();
                    // / log.debug((j+myReader.get(i).getFirstYear()));
                    // /// FyearperSampletemp.add((j + myReader.get(i).getFirstYear()));
                    // }
                    // }
                    else if (eventTypeToProcess.equals(EventTypeToProcess.INJURY_EVENT)) {
                        if (climateYear.indexOf(listYears.get(j)) != -1) {
                            if (myReader.get(i).getClimate2dII().get(k)
                                    .get(climateYear.indexOf(listYears.get(j))) == 1) {
                                FyearperSampletemp.add(listYears.get(j));
                            }
                        }
                        // if ((myReader.get(i).getClimate2dII().get(k).get(j) == 1))
                        // {
                        // FyearperSampletemp.add((j + myReader.get(i).getFirstYear()));
                        // }
                    } else if (eventTypeToProcess.equals(EventTypeToProcess.FIRE_AND_INJURY_EVENT)) {
                        if (climateYear.indexOf(listYears.get(j)) != -1) {
                            if (myReader.get(i).getClimate2dIII().get(k)
                                    .get(climateYear.indexOf(listYears.get(j))) == 1) {
                                FyearperSampletemp.add(listYears.get(j));
                            }
                        }
                        // if ((myReader.get(i).getClimate2dIII().get(k).get(j) == 1))
                        // {
                        // FyearperSampletemp.add((j + myReader.get(i).getFirstYear()));
                        // }
                    } else {

                        log.error("Unsupported event type caught");
                    }

                } // / end of the loop for listYears in common (finish loading the fire year per sample
                log.debug(
                        "series number " + (k + 1) + " FyearperSampletemp.size() " + FyearperSampletemp.size());
                if (FyearperSampletemp.size() != 0) {
                    if (includeIncomplete) {
                        if (maxLastYear.compareTo(FyearperSampletemp.get(FyearperSampletemp.size() - 1)) != 0) {
                            numberOfintervalssamp[i] = numberOfintervalssamp[i] + FyearperSampletemp.size();
                        }
                    } else {
                        numberOfintervalssamp[i] = numberOfintervalssamp[i] + (FyearperSampletemp.size() - 1);
                    }
                }
                log.debug("series number: " + (k + 1) + " number of intervals " + numberOfintervalssamp[i]);
                // new
                if ((FyearperSampletemp.size() == 1) && (includeIncomplete)) {
                    log.debug("last index per sample is " + myReader.get(i).getLastYearIndexPerSample()[k]);
                    log.debug("first year per sample is " + myReader.get(i).getFirstYear());
                    log.debug("maxLastyear is " + maxLastYear);
                    // if (maxLastYear != FyearperSampletemp.get(FyearperSampletemp.size() - 1))
                    if (maxLastYear.compareTo(FyearperSampletemp.get(FyearperSampletemp.size() - 1)) != 0) {
                        log.debug("I am in not equal ");
                        log.debug(
                                "last year in the sample  is " + (myReader.get(i).getLastYearIndexPerSample()[k]
                                        + myReader.get(i).getFirstYear()));
                        log.debug("maxLastyear is " + maxLastYear);
                        log.debug("the last fire year in the sample "
                                + FyearperSampletemp.get(FyearperSampletemp.size() - 1));
                        if (maxLastYear <= (myReader.get(i).getLastYearIndexPerSample()[k]
                                + myReader.get(i).getFirstYear())) {
                            Integer temp = ((maxLastYear)
                                    - FyearperSampletemp.get(FyearperSampletemp.size() - 1));
                            // int temp1 = maxLastYear.intValue() - FyearperSampletemp.get(FyearperSampletemp.size() - 1).intValue();
                            log.debug("in less than or equal to ");
                            // temp = (maxLastYear) - FyearperSampletemp.get(FyearperSampletemp.size() - 1);
                            log.debug("the resta temp is " + temp);
                            // FIyearperSampletemp.add(((maxLastYear) - FyearperSampletemp.get(FyearperSampletemp.size() - 1)));
                            if ((maxLastYear) - FyearperSampletemp.get(FyearperSampletemp.size() - 1) > 0) {
                                FIyearperSampletemp.add(
                                        (maxLastYear) - FyearperSampletemp.get(FyearperSampletemp.size() - 1));
                                log.debug("the fire intervals for sample " + k + " is "
                                        + FIyearperSampletemp.get(0));
                            }
                            // FIyearperSampletemp.add(temp);
                            // log.debug("the fire intervals for sample " + k + " is " + FIyearperSampletemp.get(0));
                        } else {
                            log.debug("in else ");
                            FIyearperSampletemp.add((myReader.get(i).getLastYearIndexPerSample()[k]
                                    + myReader.get(i).getFirstYear())
                                    - FyearperSampletemp.get(FyearperSampletemp.size() - 1));
                            log.debug("fire intervals for sample " + k + " is " + FIyearperSampletemp.get(0));
                        }
                        // FIyearperSampletemp.add((myReader.get(i).getFirstYear() + myReader.get(i).getLastYearIndexPerSample()[k])
                        // - FyearperSampletemp.get(FyearperSampletemp.size() - 1));
                    }
                    // log.debug("fire intervals for sample " + k + " is " + FIyearperSampletemp.get(0));
                } // end of if one fire year and includelastyear so we have at least one interval in a given series.
                  // endofnew
                if ((FyearperSampletemp.size() >= 2)) {
                    log.debug("Series number is " + (k + 1));
                    for (int jk = 0; jk < FyearperSampletemp.size() - 1; jk++) {
                        // FIyearperSampletemp.add(FyearperSample.get(k).get(jk+1)
                        // - FyearperSample.get(k).get(jk));
                        log.debug("FyearperSampletemp is " + FyearperSampletemp.get(jk));
                        if ((FyearperSampletemp.get(jk + 1) - FyearperSampletemp.get(jk)) > 0) {
                            FIyearperSampletemp
                                    .add(FyearperSampletemp.get(jk + 1) - FyearperSampletemp.get(jk));
                        }
                        // FIyearperSampletemp.add(FyearperSampletemp.get(jk+1)
                        // - FyearperSampletemp.get(jk));
                        log.debug("fire intervals for sample " + k + " is " + FIyearperSampletemp.get(jk));
                        // fisumtemp= fisumtemp +
                        // FIyearperSampletemp.get(jk).intValue();
                    }
                    if (includeIncomplete) {
                        // if (maxLastYear != FyearperSampletemp.get(FyearperSampletemp.size() - 1))
                        if (maxLastYear.compareTo(FyearperSampletemp.get(FyearperSampletemp.size() - 1)) != 0)
                        // if ((myReader.get(i).getLastYearIndexPerSample()[k] + myReader.get(i).getFirstYear()) != FyearperSampletemp
                        // .get(FyearperSampletemp.size() - 1))
                        {
                            if (maxLastYear <= (myReader.get(i).getLastYearIndexPerSample()[k]
                                    + myReader.get(i).getFirstYear())) {
                                if (((maxLastYear)
                                        - FyearperSampletemp.get(FyearperSampletemp.size() - 1)) > 0) {
                                    FIyearperSampletemp.add(((maxLastYear)
                                            - FyearperSampletemp.get(FyearperSampletemp.size() - 1)));
                                }
                            } else {
                                FIyearperSampletemp.add((myReader.get(i).getLastYearIndexPerSample()[k]
                                        + myReader.get(i).getFirstYear())
                                        - FyearperSampletemp.get(FyearperSampletemp.size() - 1));
                            }
                            // log.debug("the sample number is "+k+
                            // " the size of the fyearpersampletemp is "+
                            // FyearperSampletemp.size() );
                            // log.debug("the last year per sample is "
                            // + (myReader.get(i).getLastYearIndexPerSample()[k] + myReader.get(i).getFirstYear()));
                            // log.debug(" the last fire year per sample " + FyearperSampletemp.get(FyearperSampletemp.size() - 1));
                            // FIyearperSampletemp.add((maxLastYear) - FyearperSampletemp.get(FyearperSampletemp.size() - 1));
                            // log.debug("the last intrval in included is on is   "
                            // + FIyearperSampletemp.get(FIyearperSampletemp.size() - 1));
                        }
                    }
                } // end of if at least 2 fier years so we have at least one interval in a given series.
                log.debug("size of FIyearperSampletemp " + FIyearperSampletemp.size() + "  at series is :"
                        + (k + 1));
                // FIyearperSampletemp.size()+
                // " X "+FIyearperSampletemp.get(0).size());

            } // end of the loop for number of series.
              // log.debug("size of FIyearperSample "+
              // FIyearperSampletemp.size());
            for (int j = 0; j < FIyearperSampletemp.size(); j++) {
                fireintervalspersample.add(FIyearperSampletemp.get(j) * 1.0);
            }
            /*
             * Get the normal statistics for the fire intervals add the values to the stats and then call them for the stats
             */
            if (fireintervalspersample.size() >= 3) {
                enoughIntSamp[i] = true;
                DescriptiveStatistics stasample = new DescriptiveStatistics();
                Dfireintervalspersample = new Double[fireintervalspersample.size()];
                Dfireintervalspersample = fireintervalspersample.toArray(Dfireintervalspersample);
                dfireintervalspersample = new double[fireintervalspersample.size()];
                // summarySample = new
                // double[statsparam.length][myReader.size()];
                for (int ik = 0; ik < fireintervalspersample.size(); ik++) {
                    stasample.addValue(Dfireintervalspersample[ik].doubleValue());
                    dfireintervalspersample[ik] = Dfireintervalspersample[ik].doubleValue();
                    log.debug("the " + ik + " fire interval is " + dfireintervalspersample[ik]);
                }
                log.debug("the size for dfireintervalspersample is " + dfireintervalspersample.length);

                // ADDED BY PETE
                if (dfireintervalspersample.length == 0)
                    continue;

                /*
                 * load the Summary Analysis for the Sample fire intervals
                 */
                summarySample[0][i] = fireintervalspersample.size();
                // double mean = stats.getMean();
                summarySample[1][i] = stasample.getMean();
                log.debug("mean sample is " + stasample.getMean());
                // double median =
                // StatUtils.percentile(dfireintervalspersite, 50);
                summarySample[2][i] = StatUtils.percentile(dfireintervalspersample, 50);
                log.debug("summarySample[2][] " + i + " " + summarySample[2][i]);
                // double std = stats.getStandardDeviation();
                summarySample[3][i] = stasample.getStandardDeviation();
                log.debug("summarySample[3][] " + i + " " + summarySample[3][i]);
                // double skew = stats.getSkewness();
                summarySample[4][i] = 1.0 / summarySample[1][i];
                log.debug("summarySample[4][] " + i + " " + summarySample[4][i]);
                summarySample[5][i] = summarySample[3][i] / summarySample[1][i];
                log.debug("summarySample[5][] " + i + " " + summarySample[5][i]);
                summarySample[6][i] = stasample.getSkewness();
                log.debug("summarySample[6][] " + i + " " + summarySample[6][i]);
                // double kurt = stats.getKurtosis();
                if (numberOfintervalssamp[i] == 3) {
                    summarySample[7][i] = -99;
                } else {
                    summarySample[7][i] = stasample.getKurtosis();
                }
                // summarySample[7][i] = stasample.getKurtosis();
                log.debug("summarySample[7][] " + i + " " + summarySample[7][i]);
                // log.debug("nomean \t\t nostd \t\t nokurt \t noskew \t\t nomedian");
                // log.debug(twoPlace.format(mean)+"\t\t"+twoPlace.format(std)+"\t\t"+twoPlace.format(kurt)+"\t\t"+twoPlace.format(skew)+"\t\t"+twoPlace.format(median));

                Weibull weibull = new Weibull(fireintervalspersample);

                //
                ArrayList<Double> weibullProb = weibull.getWeibullProbability(fireintervalspersample);
                ArrayList<Double> siglonglowbound = new ArrayList<Double>();
                ArrayList<Double> sigshortupbound = new ArrayList<Double>();
                log.debug("the weibull probability of first element is " + weibullProb.get(0));
                log.debug("the index  the size of the interval is " + weibullProb.indexOf(weibullProb.get(0)));
                for (int ij = 0; ij < weibullProb.size() - 1; ij++) {
                    if (weibullProb.get(ij) <= alphaLevel) {
                        siglonglowbound.add(fireintervalspersample.get(ij));

                    }
                    if (weibullProb.get(ij) >= (1 - alphaLevel)) {
                        sigshortupbound.add(fireintervalspersample.get(ij));

                    }

                }

                //

                summarySample[10][i] = weibull.getScale();
                log.debug("summarySample[10][] " + i + " " + summarySample[10][i]);
                summarySample[11][i] = weibull.getShape();
                log.debug("summarySample[11][] " + i + " " + summarySample[11][i]);
                summarySample[12][i] = weibull.getMean();
                summarySample[13][i] = weibull.getMedian();
                summarySample[14][i] = weibull.getMode();
                summarySample[15][i] = weibull.getSigma();
                summarySample[16][i] = 1.0 / summarySample[13][i];
                summarySample[17][i] = weibull.getSkew();
                summarySample[18][i] = weibull.getExceedenceProbability2()[0];
                summarySample[19][i] = weibull.getExceedenceProbability2()[1];
                Collections.sort(sigshortupbound);
                log.debug("siglonglowbound is " + siglonglowbound);
                try {
                    summarySample[20][i] = sigshortupbound.get(sigshortupbound.size() - 1);
                } catch (Exception e) {
                    summarySample[20][i] = Double.NaN;
                }
                Collections.sort(siglonglowbound);

                try {
                    summarySample[21][i] = siglonglowbound.get(0);
                } catch (Exception e) {
                    summarySample[21][i] = Double.NaN;
                }
                log.debug("sigshortupbound is " + sigshortupbound);

                Collections.sort(fireintervalspersample);

                try {
                    summarySample[8][i] = fireintervalspersample.get(0);
                } catch (Exception ex) {
                    log.error("Index out of bounds exception caught: ");
                    log.error("    summarySample[8][i] = fireintervalspersample.get(0)");
                    ex.printStackTrace();
                }
                summarySample[9][i] = fireintervalspersample.get(fireintervalspersample.size() - 1);
                // log.debug("shape \t\t scale \t\t median ");
                // log.debug(twoPlace.format(test2.Weibull_Parameters(fireintervalspersample)[0])+"\t\t"+twoPlace.format(test2.Weibull_Parameters(fireintervalspersample)[1])+"\t\t"+twoPlace.format(test2.weibull_median(test1.Weibull_Parameters(fireintervalspersample))));
                // log.debug("mean \t\t sigma \t\t mode \t\t skewness");
                // log.debug(twoPlace.format(test1.weibull_mean(test2.Weibull_Parameters(fireintervalspersample)))+"\t\t"+twoPlace.format(test1.weibull_sigma(test2.Weibull_Parameters(fireintervalspersample)))+"\t\t"+twoPlace.format(test2.weibull_mode(test1.Weibull_Parameters(fireintervalspersample)))+"\t\t"+twoPlace.format(test1.weibull_skew(test2.Weibull_Parameters(fireintervalspersample))));
                // log.debug("maxhazard \t\t lei \t\t uei ");
                // log.debug(twoPlace.format(test2.maxhazard_int(test2.Weibull_Parameters(fireintervalspersample)))+"\t\t"+twoPlace.format(test2.weibull_lowuppexcint(test2.Weibull_Parameters(fireintervalspersample))[0])+"\t\t"+twoPlace.format(test2.weibull_lowuppexcint(test2.Weibull_Parameters(fireintervalspersample))[1]));
                // log.debug("the size of YearWith Fires is "+YearsWithFires.size());
                // log.debug("the size of the prb exdc is
                // "+test2.weibull_Exprob(test2.Weibull_Parameters(fireintervalspersample)).length);
                System.out.println(
                        "the size of the prb exdc sample  is " + weibull.getExceedenceProbability().length);
                for (int kk = 0; kk < weibull.getExceedenceProbability().length; kk++) {
                    ExceeProbsample[kk][i] = weibull.getExceedenceProbability()[kk];
                    log.debug("file " + i + " Exce probability " + ExceeProbsample[kk][i]);
                    // log.debug("the size is "+ExceeProbsample.length);
                }
            } // end of if at least 4 fireintervals
            else {
                enoughIntSamp[i] = false;
            }
        } // end of if jRadioSample selected.
          // log.debug("the size of exceeprobsample is "ExceeProbsample.length+" X "+ExceeProbsample[0].length);
    } // end of i readering each file loop do loop (354-1185)
    /*
     * 
     */
    // log.debug("size of the climateMatrixSite is "+climateMatrixSite.size()+" X "+climateMatrixSite.get(0).size());
    // for (int j = 0; j < listYears.size(); j++){
    // log.debug(climateMatrixSite.get(0).get(j) + " " +
    // listYears.get(j));
    // }
    // setCursor(Cursor.getDefaultCursor());
    /*
     * create JFileChooser object to generate a browsing capabilities
     */
    JFileChooser fileBrowse = new JFileChooser();

    fileBrowse = new JFileChooser(savePath.substring(0, savePath.lastIndexOf(File.separator)));
    /*
     * set multiselect on (even though we don't need it)
     */
    fileBrowse.setMultiSelectionEnabled(true);
    /*
     * set file and folder directive
     */
    fileBrowse.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    /*
     * set file type: coma delimited file csv
     */
    //
    FileFilter filter1 = new CSVFileFilter();
    fileBrowse.setFileFilter(filter1);
    /*
     * set dialog text: select the name and location of the matrix files
     */
    fileBrowse.setDialogTitle("Select the name and location of the Stats Summary file:");

    /*
     * create the writer object for each of the files to be created
     */
    Writer wr;
    Writer wrWDE;
    Writer wrSample;
    Writer wrWDESample;
    /*
     * set delimiter in this case we are using comas ","
     */
    String delim = ",";

    /*
     * Start writing information into the files
     */
    try {
        if (analysisType.equals(AnalysisType.COMPOSITE)) {
            wr = new BufferedWriter(new FileWriter(summaryFile));
            wrWDE = new BufferedWriter(new FileWriter(exceedenceFile));
            /*
             * write the heading to the files
             */
            String buffer = "";

            buffer = buffer + "Composite Parameters" + delim;
            for (int i = 0; i < inputFileArray.length; i++) {
                buffer = buffer + inputFileArray[i].getLabel() + delim;
            }
            ;
            wr.write(buffer.substring(0, buffer.length() - 1) + System.getProperty("line.separator"));

            buffer = "";
            for (int j = 0; j < statsparam.length; j++) {
                buffer = buffer + statsparam[j] + delim;

                for (int k = 0; k < inputFileArray.length; k++) {
                    if (j == 0) {
                        if (numberOfintervalscomp[k] < 3) {
                            buffer = buffer + twoPlace.format(numberOfintervalscomp[k]) + delim;
                        } else {
                            buffer = buffer + twoPlace.format(summaryComp[0][k]) + delim;
                        }

                    } else {
                        if (enoughIntComp[k]) {
                            if (summaryComp[j][k] == -99) {
                                buffer = buffer + "" + delim;
                            } else {
                                buffer = buffer + twoPlace.format(summaryComp[j][k]) + delim;
                            }
                        } else {
                            buffer = buffer + "" + delim;
                        }
                    }
                } // end of k loop filearray

                wr.write(buffer.substring(0, buffer.length() - 1) + System.getProperty("line.separator"));
                buffer = "";
            } // end of j loop Stats
              // wr.close();
              //
              //
              // wrWDE = new BufferedWriter(new
              // FileWriter(outputWDExceeTable));
              /*
               * write the heading to the files
               */

            buffer = "";
            wrWDE.write("Exceedence Prob" + delim);
            for (int i = 0; i < inputFileArray.length; i++) {
                buffer = buffer + inputFileArray[i].getLabel() + delim;
            }
            wrWDE.write(buffer.substring(0, buffer.length() - 1) + System.getProperty("line.separator"));
            buffer = "";

            for (int j = 0; j < fixvalt.length; j++) {
                buffer = buffer + threePlace.format(fixvalt[j]) + delim;

                for (int k = 0; k < inputFileArray.length; k++) {
                    if (enoughIntComp[k]) {
                        buffer = buffer + twoPlace.format(ExceeProbcomp[j][k]) + delim;
                    } else {
                        buffer = buffer + "" + delim;
                    }
                }
                wrWDE.write(buffer.substring(0, buffer.length() - 1) + System.getProperty("line.separator"));
                buffer = "";
            }

            wr.close();
            wrWDE.close();

        } // end of if jRadioComp is selecte
        if (analysisType.equals(AnalysisType.SAMPLE)) {
            wrSample = new BufferedWriter(new FileWriter(summaryFile));
            wrWDESample = new BufferedWriter(new FileWriter(exceedenceFile));
            /*
             * write the heading to the files
             */
            wrSample.write("Sample Parameters" + delim);
            for (int i = 0; i < inputFileArray.length; i++) {
                wrSample.write(inputFileArray[i].getLabel() + delim);
            }
            wrSample.write(System.getProperty("line.separator"));
            for (int j = 0; j < statsparam.length; j++) {
                wrSample.write(statsparam[j] + delim);
                for (int k = 0; k < inputFileArray.length; k++) {
                    if (j == 0) {
                        if (numberOfintervalssamp[k] < 3) {
                            wrSample.write(twoPlace.format(numberOfintervalssamp[k]) + delim);
                        } else {
                            wrSample.write(twoPlace.format(summarySample[0][k]) + delim);
                        }

                    } else {
                        if (enoughIntSamp[k]) {
                            if (summarySample[j][k] == -99) {
                                wrSample.write("" + delim);
                            } else {
                                wrSample.write(twoPlace.format(summarySample[j][k]) + delim);
                            }
                        } else {
                            wrSample.write("" + delim);
                        }
                    }
                } // end of k loop file array
                wrSample.write(System.getProperty("line.separator"));
            } // end of loop j loop stats
              // wrSample.close();
              //
              //
              // log.debug("the size is "+fixvalt.length+" X "+inputFile.length);
              // wrWDESample = new BufferedWriter(new
              // FileWriter(outputWDExceeTablesample));
              /*
               * write the heading to the files
               */
            wrWDESample.write("Exceedence Prob" + delim);
            for (int i = 0; i < inputFileArray.length; i++) {
                wrWDESample.write(inputFileArray[i].getLabel() + delim);
            }
            wrWDESample.write(System.getProperty("line.separator"));
            for (int j = 0; j < fixvalt.length; j++) {
                wrWDESample.write(threePlace.format(fixvalt[j]) + delim);
                for (int k = 0; k < inputFileArray.length; k++) {
                    // System.out.print(ExceeProbcomp[j][k]+delim);
                    if (enoughIntSamp[k]) {
                        wrWDESample.write(twoPlace.format(ExceeProbsample[j][k]) + delim);
                    } else {
                        wrWDESample.write("" + delim);
                    }

                }
                // System.out.print(System.getProperty("line.separator"));
                wrWDESample.write(System.getProperty("line.separator"));
            }
            wrSample.close();
            wrWDESample.close();
        } // end of jradiosample

    } // end of Try
    catch (IOException ex) {
        ex.printStackTrace();
    } finally {

    }

}

From source file:revaligner.service.FileAligner.java

public ArrayList<String[]> populateSourceTxlf() throws Exception {
    System.out.println("populating source txlf with aligned segments....");

    ArrayList<String[]> reportStates = new ArrayList();

    ExtractionSupportImpl extractionSupportImpl = new ExtractionSupportImpl(
            Locale.makeLocale(this.sourcelanguage), Locale.makeLocale(this.targetlanguage));
    Configuration config = new BaseConfiguration();
    config.setProperty("extraction.tokens.extract", "all");
    extractionSupportImpl.setConfiguration(config);

    Locale locale = Locale.makeLocale(this.sourcelanguage);
    TradosWordCounter wcounter = new TradosWordCounter(locale, config);

    org.dom4j.Document document_src = XmlParser.parseXmlFile(this.sourcetxlf_nonSeg);
    org.dom4j.Element root_src = document_src.getRootElement();

    org.dom4j.Document document_src_ingt = XmlParser.parseXmlFile(this.sourcetxlf_nonSeg);
    org.dom4j.Element root_src_ingt = document_src_ingt.getRootElement();

    org.dom4j.Document document_src_seg = XmlParser.parseXmlFile(this.sourcetxlf_seg);
    org.dom4j.Element root_src_seg = document_src_seg.getRootElement();

    List<com.aspose.words.Node> list_source = root_src
            .selectNodes("//*[name() = 'group'][@restype = 'x-paragraph']");
    List<com.aspose.words.Node> list_source_ingt = root_src_ingt
            .selectNodes("//*[name() = 'group'][@restype = 'x-paragraph']");
    List<com.aspose.words.Node> list_source_seg = root_src_seg
            .selectNodes("//*[name() = 'group'][@restype = 'x-paragraph']");
    int count = 0;
    int totalWC = 0;

    org.dom4j.Document document = XmlParser.parseXmlFile(this.alignedfile);
    List<org.dom4j.Element> groups = document.getRootElement().element("aligned").elements("group");
    for (int i = 0; i < groups.size(); i++) {
        org.dom4j.Element group = (org.dom4j.Element) groups.get(i);
        List<org.dom4j.Element> units = group.elements("unit");
        if (((org.dom4j.Element) units.get(0)).element("src_para") != null) {
            boolean isParaAllSegmented = true;
            for (int j = 0; j < units.size(); j++) {
                if (((org.dom4j.Element) units.get(j)).attributeValue("alignsegs").equals("false")) {
                    isParaAllSegmented = false;
                    break;
                }//from   w w w .j  a va2  s .c o m
            }
            String srcTextAccepted = group.elementText("text").replaceAll("(?s)<del>.*?</del>", "")
                    .replaceAll("<(/)*ins>", "");
            if (!extractionSupportImpl.isExtractable(srcTextAccepted)) {
                if (isParaAllSegmented) {
                    for (int j = 0; j < units.size(); j++) {
                        org.dom4j.Element unit = (org.dom4j.Element) units.get(j);
                        List<org.dom4j.Element> srcsegs = unit.element("src_para").element("segments")
                                .elements("src_seg");
                        List<org.dom4j.Element> trgsegs = unit.element("trg_para").element("segments")
                                .elements("trg_seg");
                        for (int x = 0; x < srcsegs.size(); x++) {
                            String[] s = new String[7];
                            s[0] = ((org.dom4j.Element) srcsegs.get(x)).getText();
                            if (x >= trgsegs.size()) {
                                s[1] = "";
                            } else {
                                org.dom4j.Element trgseg = (org.dom4j.Element) trgsegs.get(x);
                                String id = trgseg.attributeValue("id");
                                if (id.startsWith("n - ")) {
                                    s[1] = trgseg.getText();
                                } else {
                                    List tmp_contents = new ArrayList();
                                    if (id.contains(" - ")) {
                                        int start = Integer.parseInt(id.split(" - ")[0]);
                                        int end = Integer.parseInt(id.split(" - ")[1]);
                                        tmp_contents.addAll(
                                                (Collection) this.txlftrgsegmap.get(Integer.valueOf(start)));
                                        for (int su = start + 1; su <= end; su++) {
                                            boolean isprevendofpara = ((boolean[]) this.txlftrgsewsmap
                                                    .get(Integer.valueOf(su - 1)))[1];
                                            boolean iscurrentstartofpara = ((boolean[]) this.txlftrgsewsmap
                                                    .get(Integer.valueOf(su)))[0];
                                            if ((isprevendofpara) && (iscurrentstartofpara)) {
                                                List prevseg = (List) this.txlftrgsegmap
                                                        .get(Integer.valueOf(su - 1));
                                                int previdx = -1;
                                                for (int prev = 0; prev < prevseg.size(); prev++) {
                                                    org.dom4j.Node prevnode = (org.dom4j.Node) prevseg
                                                            .get(prev);
                                                    if (prevnode.getNodeType() == 1) {
                                                        org.dom4j.Element prevnode_e = (org.dom4j.Element) prevnode;
                                                        if ((prevnode_e.getName().equals("ws")) && (prevnode_e
                                                                .attributeValue("pos").equals("after"))) {
                                                            previdx = prevseg.size() - prev;
                                                        }
                                                    }
                                                }
                                                if (previdx != -1) {
                                                    tmp_contents.remove(tmp_contents.size() - previdx);
                                                }
                                                List currseg = (List) this.txlftrgsegmap
                                                        .get(Integer.valueOf(su));
                                                int curridx = -1;
                                                for (int curr = 0; curr < currseg.size(); curr++) {
                                                    org.dom4j.Node currnode = (org.dom4j.Node) currseg
                                                            .get(curr);
                                                    if (currnode.getNodeType() == 1) {
                                                        org.dom4j.Element currnode_e = (org.dom4j.Element) currnode;
                                                        if ((currnode_e.getName().equals("ws")) && (currnode_e
                                                                .attributeValue("pos").equals("before"))) {
                                                            curridx = curr;
                                                        }
                                                    }
                                                }
                                                if (curridx != -1) {
                                                    currseg.remove(curridx);
                                                }
                                                if (Locale.makeLocale(this.targetlanguage).isFarEast()) {
                                                    tmp_contents.addAll(currseg);
                                                } else {
                                                    tmp_contents.add(DocumentHelper.createText(" "));
                                                    tmp_contents.addAll(currseg);
                                                }
                                            } else {
                                                tmp_contents.addAll((Collection) this.txlftrgsegmap
                                                        .get(Integer.valueOf(su)));
                                            }
                                        }
                                    } else {
                                        tmp_contents.addAll((Collection) this.txlftrgsegmap
                                                .get(Integer.valueOf(Integer.parseInt(id))));
                                    }
                                    s[1] = trimText(assembleText(tmp_contents).replace("<br> ", "&#8629;<br>"),
                                            false)[0];
                                }
                            }
                            s[2] = "N/A";
                            s[3] = "N/A";
                            s[4] = ((org.dom4j.Element) srcsegs.get(x)).attributeValue("tctype");
                            s[5] = "0";
                            s[6] = "";
                            reportStates.add(s);
                        }
                    }
                } else {
                    String[] s = new String[7];
                    for (int j = 0; j < units.size(); j++) {
                        s[0] = ((org.dom4j.Element) units.get(j)).element("src_para").elementText("text");
                        if (((org.dom4j.Element) units.get(j)).element("trg_para") != null) {
                            s[1] = ((org.dom4j.Element) units.get(j)).element("trg_para").elementText("text");
                        } else {
                            s[1] = "";
                        }
                        s[2] = "N/A";
                        s[3] = "N/A";
                        s[4] = ((org.dom4j.Element) units.get(j)).element("src_para").attributeValue("tctype");
                        s[5] = "0";
                        s[6] = "";
                        reportStates.add(s);
                    }
                }
            } else {
                if (isParaAllSegmented) {
                    org.dom4j.Element txlf_group = (org.dom4j.Element) list_source.get(count);
                    org.dom4j.Element txlf_group_ingt = (org.dom4j.Element) list_source_ingt.get(count);
                    org.dom4j.Element txlf_group_seg = (org.dom4j.Element) list_source_seg.get(count);
                    txlf_group.setContent(txlf_group_seg.content());
                    List transunits = txlf_group.elements("trans-unit");

                    txlf_group_ingt.setContent(txlf_group_seg.content());
                    List transunits_ingt = txlf_group_ingt.elements("trans-unit");

                    ArrayList<String> mergedsegtext = new ArrayList();
                    ArrayList<List> merged_trg_contents = new ArrayList();
                    ArrayList<String> mergedsegtctypes = new ArrayList();

                    ArrayList<String> keys = new ArrayList();
                    ArrayList<String> key_left = new ArrayList();
                    ArrayList<String> key_right = new ArrayList();
                    ArrayList<String> org_keys = new ArrayList();
                    ArrayList<String> trg_keys = new ArrayList();
                    ArrayList<List> trg_contents = new ArrayList();
                    ArrayList<String> src_tctypes = new ArrayList();
                    ArrayList<String> src_review_stats = new ArrayList();
                    ArrayList<String> src_ignore_stats = new ArrayList();
                    ArrayList<Integer> edited_idx = new ArrayList();
                    for (int j = 0; j < units.size(); j++) {
                        org.dom4j.Element unit = (org.dom4j.Element) units.get(j);
                        org.dom4j.Element src_para = unit.element("src_para");
                        org.dom4j.Element trg_para = unit.element("trg_para");
                        List src_segs = src_para.element("segments").elements("src_seg");
                        for (int z = 0; z < src_segs.size(); z++) {
                            org.dom4j.Element src_seg = (org.dom4j.Element) src_segs.get(z);
                            src_tctypes.add(src_seg.attributeValue("tctype"));
                            src_review_stats.add(src_seg.attributeValue("needreview"));
                            src_ignore_stats.add(src_seg.attributeValue("ignored"));
                            keys.add(src_seg.getText().replaceAll("(?s)<del>.*?</del>", "")
                                    .replaceAll("<(/)*ins>", "").replace("<br>", "").trim());
                            org_keys.add(src_seg.getText());
                            if (trg_para != null) {
                                List trg_segs = trg_para.element("segments").elements("trg_seg");
                                if (((org.dom4j.Element) trg_segs.get(z)).attributeValue("edited")
                                        .equals("true")) {
                                    edited_idx.add(Integer.valueOf(trg_contents.size()));
                                }
                                if (trg_segs.size() > z) {
                                    trg_keys.add(((org.dom4j.Element) trg_segs.get(z)).getText());
                                    String id = ((org.dom4j.Element) trg_segs.get(z)).attributeValue("id");
                                    if (id.startsWith("n - ")) {
                                        trg_contents.add(new ArrayList());
                                    } else {
                                        List tmp_contents = new ArrayList();
                                        if (id.contains(" - ")) {
                                            int start = Integer.parseInt(id.split(" - ")[0]);
                                            int end = Integer.parseInt(id.split(" - ")[1]);
                                            tmp_contents.addAll((Collection) this.txlftrgsegmap
                                                    .get(Integer.valueOf(start)));
                                            for (int su = start + 1; su <= end; su++) {
                                                boolean isprevendofpara = ((boolean[]) this.txlftrgsewsmap
                                                        .get(Integer.valueOf(su - 1)))[1];
                                                boolean iscurrentstartofpara = ((boolean[]) this.txlftrgsewsmap
                                                        .get(Integer.valueOf(su)))[0];
                                                if ((isprevendofpara) && (iscurrentstartofpara)) {
                                                    List prevseg = (List) this.txlftrgsegmap
                                                            .get(Integer.valueOf(su - 1));
                                                    int previdx = -1;
                                                    for (int prev = 0; prev < prevseg.size(); prev++) {
                                                        org.dom4j.Node prevnode = (org.dom4j.Node) prevseg
                                                                .get(prev);
                                                        if (prevnode.getNodeType() == 1) {
                                                            org.dom4j.Element prevnode_e = (org.dom4j.Element) prevnode;
                                                            if ((prevnode_e.getName().equals("ws"))
                                                                    && (prevnode_e.attributeValue("pos")
                                                                            .equals("after"))) {
                                                                previdx = prevseg.size() - prev;
                                                            }
                                                        }
                                                    }
                                                    if (previdx != -1) {
                                                        tmp_contents.remove(tmp_contents.size() - previdx);
                                                    }
                                                    List currseg = (List) this.txlftrgsegmap
                                                            .get(Integer.valueOf(su));
                                                    int curridx = -1;
                                                    for (int curr = 0; curr < currseg.size(); curr++) {
                                                        org.dom4j.Node currnode = (org.dom4j.Node) currseg
                                                                .get(curr);
                                                        if (currnode.getNodeType() == 1) {
                                                            org.dom4j.Element currnode_e = (org.dom4j.Element) currnode;
                                                            if ((currnode_e.getName().equals("ws"))
                                                                    && (currnode_e.attributeValue("pos")
                                                                            .equals("before"))) {
                                                                curridx = curr;
                                                            }
                                                        }
                                                    }
                                                    if (curridx != -1) {
                                                        currseg.remove(curridx);
                                                    }
                                                    if (Locale.makeLocale(this.targetlanguage).isFarEast()) {
                                                        tmp_contents.addAll(currseg);
                                                    } else {
                                                        tmp_contents.add(DocumentHelper.createText(" "));
                                                        tmp_contents.addAll(currseg);
                                                    }
                                                } else {
                                                    tmp_contents.addAll((Collection) this.txlftrgsegmap
                                                            .get(Integer.valueOf(su)));
                                                }
                                            }
                                        } else {
                                            tmp_contents.addAll((Collection) this.txlftrgsegmap
                                                    .get(Integer.valueOf(Integer.parseInt(id))));
                                        }
                                        trg_contents.add(tmp_contents);
                                    }
                                } else {
                                    trg_keys.add("");
                                    trg_contents.add(new ArrayList());
                                }
                            } else {
                                trg_keys.add("");
                                trg_contents.add(new ArrayList());
                            }
                            if ((z == 0) && (z == src_segs.size() - 1)) {
                                key_left.add(src_para.attributeValue("lefttrim"));
                                key_right.add(src_para.attributeValue("righttrim"));
                            } else if (z == 0) {
                                key_left.add(src_para.attributeValue("lefttrim"));
                                key_right.add("true");
                            } else if (z == src_segs.size() - 1) {
                                key_left.add("true");
                                key_right.add(src_para.attributeValue("righttrim"));
                            } else {
                                key_left.add("true");
                                key_right.add("true");
                            }
                        }
                    }
                    SegmenterFactory factory = new SegmenterFactory();
                    Configuration segconfig = createConfigForSegmenter(false, this.sourcelanguage);
                    Segmenter segmenter = factory.getSegmenter("trados", Locale.makeLocale(this.sourcelanguage),
                            segconfig);
                    List<String> finsegs = segmenter
                            .segment(group.elementText("text").replaceAll("(?s)<del>.*?</del>", "")
                                    .replaceAll("<(/)*ins>", "").replace("<br>", "").replace("&lt;", "<")
                                    .replace("&gt;", ">").replace("&amp;", "&"));
                    ArrayList<ArrayList<Integer>> indices = new ArrayList();
                    int key_start_index = 0;
                    for (int k = 0; k < finsegs.size(); k++) {
                        String finsegtext = ((String) finsegs.get(k)).replace("&", "&amp;").replace("<", "&lt;")
                                .replace(">", "&gt;");

                        String combined_key = "";
                        ArrayList<Integer> indice = new ArrayList();
                        for (int x = key_start_index; x < keys.size(); x++) {
                            combined_key = combined_key + (String) keys.get(x);

                            indice.add(Integer.valueOf(x));
                            if (combined_key.replace("", " ").trim().replaceAll("(\\s)+", "")
                                    .equals(finsegtext.replace("", " ").trim().replaceAll("(\\s)+", ""))) {
                                indices.add(indice);
                                key_start_index = x + 1;
                                break;
                            }
                        }
                    }
                    ArrayList<Integer> merged_edited_idx = new ArrayList();
                    ArrayList<String[]> statss = new ArrayList();
                    for (int m = 0; m < indices.size(); m++) {
                        boolean iscontentsuseable = true;
                        ArrayList<Integer> temp_indice = (ArrayList) indices.get(m);
                        String temp_src = "";
                        String temp_org_src = "";
                        String temp_trg = "";
                        List temp_trg_content = new ArrayList();
                        int id = 1;
                        int rid = 1;
                        int bxrid = 1;
                        int bptrid = 1;
                        int bxid = 1;
                        int bptid = 1;
                        HashMap<String, String> map_rid = new HashMap();
                        String temp_tctype = (String) src_tctypes
                                .get(((Integer) temp_indice.get(0)).intValue());
                        String temp_review_stats = (String) src_review_stats
                                .get(((Integer) temp_indice.get(0)).intValue());
                        for (Iterator localIterator = temp_indice.iterator(); localIterator.hasNext();) {
                            int it = ((Integer) localIterator.next()).intValue();
                            temp_tctype = temp_tctype.equals(src_tctypes.get(it)) ? temp_tctype : "MIX";
                            temp_review_stats = ((String) src_review_stats.get(it)).equals("true") ? "true"
                                    : temp_review_stats.equals("true") ? "true" : "false";
                            String temp_ignore_stats = (String) src_ignore_stats.get(it);
                            if (edited_idx.contains(Integer.valueOf(it))) {
                                iscontentsuseable = false;
                            }
                            temp_src = temp_src + (String) keys.get(it);
                            temp_org_src = temp_org_src + (String) org_keys.get(it);
                            if (temp_ignore_stats.equals("true")) {
                                temp_trg = temp_trg + "[skipseg]";
                                temp_trg_content.add(DocumentHelper.createText("[skipseg]"));
                            } else {
                                temp_trg = temp_trg + (String) trg_keys.get(it);

                                List trg_content = (List) trg_contents.get(it);
                                for (int nc = 0; nc < trg_content.size(); nc++) {
                                    org.dom4j.Node raw = (org.dom4j.Node) trg_content.get(nc);
                                    if (raw.getNodeType() == 3) {
                                        temp_trg_content.add(raw);
                                    } else if (raw.getNodeType() == 1) {
                                        org.dom4j.Element rawe = (org.dom4j.Element) raw;
                                        if (rawe.getName().equals("source")) {
                                            for (int ncc = 0; ncc < rawe.content().size(); ncc++) {
                                                org.dom4j.Node node = (org.dom4j.Node) rawe.content().get(ncc);
                                                if (node.getNodeType() == 3) {
                                                    temp_trg_content.add(node);
                                                } else if (node.getNodeType() == 1) {
                                                    org.dom4j.Element e = (org.dom4j.Element) node;
                                                    if (!e.getName().equals("x")) {
                                                        if (!e.getName().equals("ph")) {
                                                            if (e.getName().equals("bx")) {
                                                                if ((e.attribute("fake") != null)
                                                                        && (e.attributeValue("fake")
                                                                                .equals("true"))
                                                                        && (temp_indice.indexOf(
                                                                                Integer.valueOf(it)) != 0)) {
                                                                    continue;
                                                                }
                                                                if ((e.attribute("fake") == null)
                                                                        || (!e.attributeValue("fake")
                                                                                .equals("true"))) {
                                                                }
                                                            } else if (e.getName().equals("ex")) {
                                                                if ((e.attribute("fake") != null)
                                                                        && (e.attributeValue("fake")
                                                                                .equals("true"))
                                                                        && (temp_indice.indexOf(Integer.valueOf(
                                                                                it)) != temp_indice.size()
                                                                                        - 1)) {
                                                                    continue;
                                                                }
                                                                if ((e.attribute("fake") == null)
                                                                        || (!e.attributeValue("fake")
                                                                                .equals("true"))) {
                                                                }
                                                            } else if (e.getName().equals("bpt")) {
                                                                if ((e.attribute("fake") != null)
                                                                        && (e.attributeValue("fake")
                                                                                .equals("true"))
                                                                        && (temp_indice.indexOf(
                                                                                Integer.valueOf(it)) != 0)) {
                                                                    continue;
                                                                }
                                                                if ((e.attribute("fake") == null)
                                                                        || (!e.attributeValue("fake")
                                                                                .equals("true"))) {
                                                                }
                                                            } else if (e.getName().equals("ept")) {
                                                                if ((e.attribute("fake") != null)
                                                                        && (e.attributeValue("fake")
                                                                                .equals("true"))
                                                                        && (temp_indice.indexOf(Integer.valueOf(
                                                                                it)) != temp_indice.size()
                                                                                        - 1)) {
                                                                    continue;
                                                                }
                                                                if ((e.attribute("fake") == null)
                                                                        || (!e.attributeValue("fake")
                                                                                .equals("true"))) {
                                                                }
                                                            }
                                                        }
                                                    }
                                                    if (e.attribute("fake") != null) {
                                                        e.remove(e.attribute("fake"));
                                                    }
                                                    temp_trg_content.add(e);
                                                }
                                            }
                                        } else if (rawe.getName().equals("ws")) {
                                            String pos = rawe.attributeValue("pos");
                                            if (pos.equals("before")) {
                                                for (int ncc = 0; ncc < rawe.content().size(); ncc++) {
                                                    org.dom4j.Node node = (org.dom4j.Node) rawe.content()
                                                            .get(ncc);
                                                    if (node.getNodeType() == 3) {
                                                        temp_trg_content.add(0, node);
                                                    } else if (node.getNodeType() == 1) {
                                                        org.dom4j.Element e = (org.dom4j.Element) node;
                                                        if ((!e.getName().equals("x"))
                                                                && (e.getName().equals("it"))) {
                                                            if (e.attributeValue("pos").equals("open")) {
                                                                if ((e.attribute("fake") != null)
                                                                        && (e.attributeValue("fake")
                                                                                .equals("true"))
                                                                        && (temp_indice.indexOf(
                                                                                Integer.valueOf(it)) != 0)) {
                                                                    continue;
                                                                }
                                                                if (e.getText().equals("")) {
                                                                    e.setName("bx");
                                                                } else {
                                                                    e.setName("bpt");
                                                                }
                                                                if ((e.attribute("fake") == null)
                                                                        || (!e.attributeValue("fake")
                                                                                .equals("true"))) {
                                                                }
                                                            } else if (e.attributeValue("pos")
                                                                    .equals("close")) {
                                                                if ((e.attribute("fake") != null)
                                                                        && (e.attributeValue("fake")
                                                                                .equals("true"))
                                                                        && (temp_indice.indexOf(Integer.valueOf(
                                                                                it)) != temp_indice.size()
                                                                                        - 1)) {
                                                                    continue;
                                                                }
                                                                if (e.getText().equals("")) {
                                                                    e.setName("ex");
                                                                } else {
                                                                    e.setName("ept");
                                                                }
                                                                e.remove(e.attribute("ctype"));
                                                                if ((e.attribute("fake") == null)
                                                                        || (!e.attributeValue("fake")
                                                                                .equals("true"))) {
                                                                }
                                                            }
                                                            e.remove(e.attribute("pos"));
                                                        } else {
                                                            if (e.attribute("fake") != null) {
                                                                e.remove(e.attribute("fake"));
                                                            }
                                                            temp_trg_content.add(0, e);
                                                        }
                                                    }
                                                }
                                            } else if (pos.equals("after")) {
                                                for (int ncc = 0; ncc < rawe.content().size(); ncc++) {
                                                    org.dom4j.Node node = (org.dom4j.Node) rawe.content()
                                                            .get(ncc);
                                                    if (node.getNodeType() == 3) {
                                                        temp_trg_content.add(node);
                                                    } else if (node.getNodeType() == 1) {
                                                        org.dom4j.Element e = (org.dom4j.Element) node;
                                                        if ((!e.getName().equals("x"))
                                                                && (e.getName().equals("it"))) {
                                                            if (e.attributeValue("pos").equals("open")) {
                                                                if ((e.attribute("fake") != null)
                                                                        && (e.attributeValue("fake")
                                                                                .equals("true"))
                                                                        && (temp_indice.indexOf(
                                                                                Integer.valueOf(it)) != 0)) {
                                                                    continue;
                                                                }
                                                                if (e.getText().equals("")) {
                                                                    e.setName("bx");
                                                                } else {
                                                                    e.setName("bpt");
                                                                }
                                                                if ((e.attribute("fake") == null)
                                                                        || (!e.attributeValue("fake")
                                                                                .equals("true"))) {
                                                                }
                                                            } else if (e.attributeValue("pos")
                                                                    .equals("close")) {
                                                                if ((e.attribute("fake") != null)
                                                                        && (e.attributeValue("fake")
                                                                                .equals("true"))
                                                                        && (temp_indice.indexOf(Integer.valueOf(
                                                                                it)) != temp_indice.size()
                                                                                        - 1)) {
                                                                    continue;
                                                                }
                                                                if (e.getText().equals("")) {
                                                                    e.setName("ex");
                                                                } else {
                                                                    e.setName("ept");
                                                                }
                                                                e.remove(e.attribute("ctype"));
                                                                if ((e.attribute("fake") == null)
                                                                        || (!e.attributeValue("fake")
                                                                                .equals("true"))) {
                                                                }
                                                            }
                                                            e.remove(e.attribute("pos"));
                                                        } else {
                                                            if (e.attribute("fake") != null) {
                                                                e.remove(e.attribute("fake"));
                                                            }
                                                            temp_trg_content.add(e);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        String[] stats = TrackChangeHelper.getTxlfTrgStatsFromTCType(temp_tctype, temp_trg);
                        if ((stats[0].equals("1")) && (temp_review_stats.equals("true"))) {
                            stats[2] = "fuzzy-match";
                        }
                        String[] s = new String[7];
                        s[0] = temp_org_src.replace("<br> ", "&#8629;<br>");
                        if (iscontentsuseable) {
                            s[1] = trimText(assembleText(temp_trg_content).replace("<br> ", "&#8629;<br>"),
                                    false)[0];
                        } else {
                            s[1] = temp_trg.replace("<br> ", "&#8629;<br>");
                        }
                        if (s[1].contains("[skipseg]")) {
                            if (s[1].replace("[skipseg]", "").trim().equals("")) {
                                s[1] = "";
                                temp_trg_content = new ArrayList();
                                temp_trg_content.add(DocumentHelper.createText(""));
                                temp_trg = "";
                                stats[0] = "1";
                                stats[1] = "translated";
                                stats[2] = "exact-match";
                            } else {
                                s[1] = s[1].replace("[skipseg]", "");
                                temp_trg_content = replacetextinDomObj(temp_trg_content);
                                temp_trg = temp_trg.replace("[skipseg]", "");
                            }
                        }
                        s[2] = stats[0];
                        s[3] = stats[2];
                        s[4] = temp_tctype;
                        wcounter = new TradosWordCounter(locale, config);
                        wcounter.countText(((org.dom4j.Element) transunits.get(m)).element("source").getText());
                        s[5] = Integer.toString(wcounter.getWordCount());
                        s[6] = "";
                        totalWC += wcounter.getWordCount();
                        reportStates.add(s);
                        if (extractionSupportImpl.isExtractable(temp_src)) {
                            mergedsegtext.add(temp_trg);
                            if (!iscontentsuseable) {
                                merged_edited_idx.add(Integer.valueOf(merged_trg_contents.size()));
                            }
                            merged_trg_contents.add(temp_trg_content);
                            mergedsegtctypes.add(temp_tctype);
                            statss.add(stats);
                        }
                    }
                    for (int t = 0; t < transunits.size(); t++) {
                        org.dom4j.Element trans_unit = (org.dom4j.Element) transunits.get(t);
                        org.dom4j.Element trans_unit_ignt = (org.dom4j.Element) transunits_ingt.get(t);
                        trans_unit.addAttribute("gs4tr:editStatus", "leveraged");
                        org.dom4j.Element source = trans_unit.element("source");

                        org.dom4j.Element target = trans_unit.addElement("target");
                        trans_unit.elements().add(source.indexOf(source.getParent()) + 2, target.clone());
                        trans_unit.remove(target);
                        target = trans_unit.element("target");

                        org.dom4j.Element target_ignt = trans_unit_ignt.addElement("target");
                        trans_unit_ignt.elements().add(source.indexOf(source.getParent()) + 2,
                                target_ignt.clone());
                        trans_unit_ignt.remove(target_ignt);
                        target_ignt = trans_unit_ignt.element("target");
                        if (merged_edited_idx.contains(Integer.valueOf(t))) {
                            target.setText(((String) mergedsegtext.get(t)).replace("&lt;", "<")
                                    .replace("&gt;", ">").replace("&amp;", "&").trim());
                            target_ignt.setText(((String) mergedsegtext.get(t)).replace("&lt;", "<")
                                    .replace("&gt;", ">").replace("&amp;", "&").trim());
                        } else {
                            target.setContent(trimContents((List) merged_trg_contents.get(t)));
                            target_ignt.setContent(trimContents((List) merged_trg_contents.get(t)));
                            if (!((String[]) statss.get(t))[0].equals("75")) {
                                org.dom4j.Element source_ingt = trans_unit_ignt.element("source");
                                source_ingt.setContent(trimContents((List) merged_trg_contents.get(t)));
                            }
                        }
                        String[] stats = (String[]) statss.get(t);
                        if (stats[0].equals("1")) {
                            trans_unit.addAttribute("gs4tr:locked", "true");
                        }
                        target.addAttribute("gs4tr:score", stats[0]);
                        target.addAttribute("state", stats[1]);
                        target.addAttribute("state-qualifier", stats[2]);
                        if (stats[0].equals("0")) {
                            trans_unit.remove(target);
                        }
                    }
                } else {
                    String trgtext = "";
                    if (((org.dom4j.Element) units.get(0)).element("trg_para") != null) {
                        trgtext = ((org.dom4j.Element) units.get(0)).element("trg_para").elementText("text");
                    }
                    String temp_tctype = ((org.dom4j.Element) units.get(0)).element("src_para")
                            .attributeValue("tctype");
                    for (int j = 1; j < units.size(); j++) {
                        org.dom4j.Element prev_unit = (org.dom4j.Element) units.get(j - 1);
                        org.dom4j.Element unit = (org.dom4j.Element) units.get(j);
                        String src_tctype = unit.element("src_para").attributeValue("tctype");
                        temp_tctype = temp_tctype.equals(src_tctype) ? temp_tctype : "MIX";
                        if (unit.element("trg_para") != null) {
                            String Rtrim = prev_unit.element("src_para").attributeValue("righttrim");
                            String Ltrim = unit.element("src_para").attributeValue("lefttrim");
                            if ((Rtrim.equals("true")) || (Ltrim.equals("true"))) {
                                trgtext = trgtext + " " + unit.element("trg_para").elementText("text");
                            } else {
                                trgtext = trgtext + unit.element("trg_para").elementText("text");
                            }
                        }
                    }
                    org.dom4j.Element txlf_group = (org.dom4j.Element) list_source.get(count);
                    org.dom4j.Element trans_unit = txlf_group.element("trans-unit");
                    trans_unit.addAttribute("gs4tr:editStatus", "leveraged");
                    org.dom4j.Element source = trans_unit.element("source");

                    org.dom4j.Element target = trans_unit.addElement("target");
                    trans_unit.elements().add(source.indexOf(source.getParent()) + 2, target.clone());
                    trans_unit.remove(target);
                    target = trans_unit.element("target");

                    int lb_cnt = 0;
                    String surfix = trgtext;
                    while (surfix.indexOf("<br> ") != -1) {
                        lb_cnt++;
                        int pos = surfix.indexOf("<br> ");
                        String prefix = surfix.substring(0, pos);
                        target.addText(prefix.replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&"));
                        org.dom4j.Element x = target.addElement("x");
                        x.addAttribute("ctype", "lb");
                        x.addAttribute("id", Integer.toString(lb_cnt));
                        x.addAttribute("equiv-text", " ");
                        surfix = surfix.substring(pos + 5, surfix.length());
                    }
                    target.addText(surfix.replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&"));
                    String[] stats = TrackChangeHelper.getTxlfTrgStatsFromTCType(temp_tctype, trgtext);
                    target.addAttribute("gs4tr:score", stats[0]);
                    target.addAttribute("state", stats[1]);
                    target.addAttribute("state-qualifier", stats[2]);

                    String[] s = new String[7];
                    s[0] = group.elementText("text").replace("<br> ", "&#8629;<br>");
                    s[1] = trgtext.replace("<br> ", "&#8629;<br>");
                    s[2] = stats[0];
                    s[3] = stats[2];
                    s[4] = temp_tctype;
                    wcounter = new TradosWordCounter(locale, config);
                    wcounter.countText(source.getText());
                    s[5] = Integer.toString(wcounter.getWordCount());
                    s[6] = "";
                    totalWC += wcounter.getWordCount();
                    reportStates.add(s);
                }
                count++;
            }
        }
    }
    root_src.element("file").addAttribute("gs4tr:wordcount", Integer.toString(totalWC));
    fixTxlfTrgTags(document_src);

    this.populatedsourcetxlf = (this.sourcefile + ".txlf");
    if (new File(this.populatedsourcetxlf).exists()) {
        new File(this.populatedsourcetxlf).delete();
    }
    OutputStreamWriter writer = new OutputStreamWriter(
            new BufferedOutputStream(new FileOutputStream(this.populatedsourcetxlf)), "UTF8");
    document_src.write(writer);
    writer.close();

    removeBlankLinesAndNameSpace(this.populatedsourcetxlf);

    root_src_ingt.element("file").addAttribute("gs4tr:wordcount", Integer.toString(totalWC));
    fixTxlfTrgTags(document_src_ingt);

    String ingtfile = this.sourcefile + ".ingt.txlf";
    if (new File(ingtfile).exists()) {
        new File(ingtfile).delete();
    }
    OutputStreamWriter writer_ingt = new OutputStreamWriter(
            new BufferedOutputStream(new FileOutputStream(ingtfile)), "UTF8");
    document_src_ingt.write(writer_ingt);
    writer_ingt.close();

    removeBlankLinesAndNameSpace(ingtfile);

    return reportStates;
}

From source file:com.nest5.businessClient.Initialactivity.java

@Override
public void OnPayClicked(String method, double value, double discount, int tipp) {
    currentOrder = cookingOrders.get(currentSelectedPosition);
    int togo = 0;
    int delivery = 0;
    try {/* ww w.  j  av  a  2s .  co m*/
        togo = cookingOrdersTogo.get(currentOrder) != null ? cookingOrdersTogo.get(currentOrder) : 0;
        delivery = cookingOrdersDelivery.get(currentOrder) != null ? cookingOrdersDelivery.get(currentOrder)
                : 0;
    } catch (Exception e) {
        e.printStackTrace();
    }

    int number = checkSaleNumber(); //si falla se resta un numero de las ventas actuales mas adelante,.
    if (number > 0) {
        saveSale(method, value, discount, delivery, togo, tipp);
        Date date = new Date();
        String fecha = new SimpleDateFormat("dd/MM/yyyy - HH:mm:ss").format(date);
        //String fecha = DateFormat.getDateFormat(Initialactivity.this).format(
        //   date);

        // imprimir, conectar por wifi y enviar el texto arregladito a la app de
        // puente
        String mesa = "DOMICILIO / PARA LLEVAR";
        if (currentTable != null) {
            mesa = currentTable.getTable().getName().toUpperCase(Locale.getDefault());
        }
        int lines = 0;
        StringBuilder factura = new StringBuilder();
        //factura.append("MR. PASTOR COMIDA\r\nRaPIDA MEXICANA" + "\r\n");
        SharedPreferences prefs = Util.getSharedPreferences(mContext);
        String empresa = prefs.getString(Setup.COMPANY_NAME, "Nombre de Empresa");
        String nit = prefs.getString(Setup.COMPANY_NIT, "000000000-0");
        String email = prefs.getString(Setup.COMPANY_EMAIL, "email@empresa.com");
        String pagina = prefs.getString(Setup.COMPANY_URL, "http://www.empresa.com");
        String direccion = prefs.getString(Setup.COMPANY_ADDRESS, "Direccin Fsica Empresa");
        String telefono = prefs.getString(Setup.COMPANY_TEL, "555-55-55");
        String mensaje = prefs.getString(Setup.COMPANY_MESSAGE,
                "No hay ningn mensaje configurado an. En el mensaje es recomendable mencionar tus redes sociales, benficios y promociones que tengas, adems de informacin de inters paratus clientes. ");
        String propina = prefs.getString(Setup.TIP_MESSAGE,
                "No hay ningn mensaje de propina configurado an. ");
        String resolution = prefs.getString(Setup.RESOLUTION_MESSAGE,
                "Resolucin de facturacin No. 00000-0000 de 1970 DIAN");
        int currentSale = prefs.getInt(Setup.CURRENT_SALE, 0);
        factura.append(empresa + "\r\n");
        factura.append(nit + "\r\n");
        factura.append(direccion + "\r\n");
        factura.append(telefono + "\r\n");
        factura.append(email + "\r\n");
        factura.append(pagina + "\r\n");
        factura.append(resolution + "\r\n");
        factura.append("Factura de Venta No. " + String.valueOf(currentSale) + "\r\n");
        lines++;
        factura.append("\r\n");
        factura.append(fecha);
        factura.append("\r\n");
        factura.append(mesa);
        lines++;
        lines++;
        lines++;
        factura.append("\r\n");
        factura.append("    Item       Cantidad   Precio\r\n");
        lines++;
        Iterator<Entry<Registrable, Integer>> it = currentOrder.entrySet().iterator();
        //////Log.i("MISPRUEBAS","Valor de currentOrder"+String.valueOf(currentOrder.size()));
        // Log.d(TAG,String.valueOf(currentOrder.size()));
        LinkedHashMap<Registrable, Integer> currentObjects = new LinkedHashMap<Registrable, Integer>();
        float base = 0;
        float iva = 0;
        float total = 0;
        ArrayList<String> productos = new ArrayList<String>();
        ArrayList<String> quantities = new ArrayList<String>();
        ArrayList<String> precios = new ArrayList<String>();
        while (it.hasNext()) {

            LinkedHashMap.Entry<Registrable, Integer> pairs = (LinkedHashMap.Entry<Registrable, Integer>) it
                    .next();

            currentObjects.put(pairs.getKey(), pairs.getValue());

            String name = pairs.getKey().name;

            int longName = name.length();
            int subLength = 14 - longName;
            if (subLength < 0)
                name = name.substring(0, 14);
            int espacios1 = 4;
            int espacios2 = 12;
            if (name.length() < 14) {
                espacios1 += 14 - name.length();
            }
            factura.append(name);
            productos.add(name);
            int qtyL = String.valueOf(pairs.getValue()).length();
            float precioiva = (float) Math
                    .round(pairs.getKey().price + pairs.getKey().price * pairs.getKey().tax);
            base += (float) Math.round(pairs.getKey().price * pairs.getValue());
            iva += (float) Math.round((pairs.getKey().price * pairs.getKey().tax) * pairs.getValue());
            total += precioiva * pairs.getValue();

            int priceL = String.valueOf(precioiva).length();
            espacios1 = espacios1 - qtyL < 1 ? espacios1 = 1 : espacios1 - qtyL;
            espacios2 = espacios2 - priceL < 1 ? espacios2 = 1 : espacios2 - priceL;
            espacios2 = espacios2 - qtyL < 1 ? espacios2 = 1 : espacios2 - qtyL;
            for (int k = 0; k < espacios1; k++) {
                factura.append(" ");
            }
            factura.append(pairs.getValue());
            for (int k = 0; k < espacios2; k++) {
                factura.append(" ");
            }
            quantities.add(String.valueOf(pairs.getValue()));
            factura.append("$");
            factura.append(precioiva);
            factura.append("\r\n");
            precios.add("$" + precioiva);
            lines++;
        }
        float propvalue = 0;
        if (tipp == 1)
            propvalue = (float) Math.round(total * 0.1);

        float descuento = 0;
        if (discount > 0) {
            descuento = (float) Math.round(base - (base * (discount / 0)));
        }
        lines++;
        lines++;
        factura.append("\r\n");
        factura.append("<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>\r\n");
        factura.append("BASE:      $" + base + "\r\n");
        factura.append("Descuento (" + discount + "):      $" + descuento + "\r\n");
        factura.append("Imp.:      $" + iva + "\r\n");
        factura.append("SUBTOTAL:     $" + Math.round(total - descuento) + "\r\n");
        factura.append("PROPINA:     $" + propvalue + "\r\n");
        float precfinal = propvalue + total - descuento;
        factura.append("TOTAL:     $" + precfinal + "\r\n");
        factura.append("\r\n");
        factura.append("<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>\r\n");
        factura.append("\r\n");
        lines++;
        factura.append(propina + "\r\n");
        factura.append(mensaje);
        String send = factura.toString();
        //////Log.i("MISPRUEBAS",factura.toString());

        // Enviar un string diferente que lleva la orden actual.
        //   new WiFiSend().execute(comanda.toString());// enviar el mensaje de
        // verdad

        int[] arrayOfInt = new int[2];
        arrayOfInt[0] = 27;
        arrayOfInt[1] = 64;
        int[] array2 = new int[3];
        array2[0] = 27;
        array2[1] = 74;
        array2[2] = 2;
        StringBuilder builder1 = new StringBuilder();
        for (int h = 0; h < 2; h++) {
            builder1.append(Character.toChars(arrayOfInt[h]));
        }
        StringBuilder builder2 = new StringBuilder();

        builder2.append(Character.toChars(10));

        StringBuilder complete = new StringBuilder(String.valueOf(builder1.toString()))
                .append(String.valueOf(builder2.toString()));
        String enviar = complete.toString();
        Boolean printed = true;
        try {
            if (mChatService.getState() == mChatService.STATE_CONNECTED) {
                try {
                    mChatService.write(factura.toString().getBytes("x-UnicodeBig"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else {
                printed = false;
                Toast.makeText(mContext, "No hay impresora bluetooth conectada.", Toast.LENGTH_LONG).show();
            }
        } catch (NullPointerException e) {
            printed = false;
            e.printStackTrace();
        }
        if (!printed) {//buscar impresora TCP/IP
            StringBuilder formateado = new StringBuilder();
            formateado.append(CLEAR_PRINTER);
            formateado.append(INITIALIZE_PRINTER);
            formateado.append(JUSTIFICATION_CENTER);
            formateado.append(DOUBLE_WIDE_CHARACTERS);
            formateado.append(empresa);
            formateado.append(SINGLE_WIDE_CHARACTERS);
            formateado.append(PRINT_FEED_ONE_LINE);
            formateado.append(nit);
            formateado.append(PRINT_FEED_ONE_LINE);
            formateado.append(direccion);
            formateado.append(PRINT_FEED_ONE_LINE);
            formateado.append(telefono);
            formateado.append(PRINT_FEED_ONE_LINE);
            formateado.append(email);
            formateado.append(PRINT_FEED_ONE_LINE);
            formateado.append(pagina);
            formateado.append(PRINT_FEED_ONE_LINE);
            formateado.append("Factura de Venta No." + String.valueOf(currentSale));
            formateado.append(PRINT_FEED_ONE_LINE);
            formateado.append(resolution);
            formateado.append(PRINT_FEED_ONE_LINE);
            formateado.append(fecha);
            formateado.append(PRINT_FEED_N_LINES);
            formateado.append((char) 0x02);
            formateado.append(mesa);
            formateado.append(PRINT_FEED_N_LINES);
            formateado.append((char) 0x02);
            formateado.append(DOUBLE_WIDE_CHARACTERS);
            formateado.append(JUSTIFICATION_LEFT);
            formateado.append("ITEM");
            formateado.append(HORIZONTAL_TAB);
            formateado.append("CANT.");
            formateado.append(HORIZONTAL_TAB);
            formateado.append("PRECIO");
            formateado.append(SINGLE_WIDE_CHARACTERS);
            formateado.append(PRINT_FEED_ONE_LINE);
            for (String actual : productos) {
                int pos = productos.indexOf(actual);
                String cantidad = quantities.get(pos);
                String precio = precios.get(pos);
                formateado.append(actual);
                formateado.append(HORIZONTAL_TAB);
                formateado.append(HORIZONTAL_TAB);
                formateado.append("x" + cantidad);
                formateado.append(HORIZONTAL_TAB);
                formateado.append(HORIZONTAL_TAB);
                formateado.append(precio);
                formateado.append(PRINT_FEED_ONE_LINE);
            }
            formateado.append(DOUBLE_WIDE_CHARACTERS);
            formateado.append("______________________");
            formateado.append(SINGLE_WIDE_CHARACTERS);
            formateado.append(PRINT_FEED_N_LINES);
            formateado.append((char) 0x02);
            formateado.append("BASE:");
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append("$" + base);
            formateado.append(PRINT_FEED_ONE_LINE);
            formateado.append("DESCUENTO (:" + discount + "%)");
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append("$" + descuento);
            formateado.append(PRINT_FEED_ONE_LINE);
            formateado.append("Impuesto:");
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append("$" + iva);
            formateado.append(PRINT_FEED_ONE_LINE);
            formateado.append("SUBTOTAL:");
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append("$" + Math.round(total - descuento));
            formateado.append(PRINT_FEED_ONE_LINE);
            formateado.append("PROPINA:");
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append("$" + propvalue);
            formateado.append(PRINT_FEED_ONE_LINE);
            formateado.append("TOTAL:");
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append(HORIZONTAL_TAB);
            formateado.append("$" + precfinal);
            formateado.append(PRINT_FEED_ONE_LINE);
            formateado.append(DOUBLE_WIDE_CHARACTERS);
            formateado.append("______________________");
            formateado.append(SINGLE_WIDE_CHARACTERS);
            formateado.append(PRINT_FEED_N_LINES);
            formateado.append((char) 0x02);
            formateado.append(ITALIC_STYLE);
            formateado.append(propina);
            formateado.append(PRINT_FEED_N_LINES);
            formateado.append((char) 0x02);
            formateado.append(mensaje);
            formateado.append(ITALIC_CANCEL);
            formateado.append(FINALIZE_TICKET);
            formateado.append(FULL_CUT);
            if (mTCPPrint != null) {
                if (mTCPPrint.getStatus() == TCPPrint.CONNECTED) {
                    mTCPPrint.sendMessage(formateado.toString());
                    mTCPPrint.sendMessage(formateado.toString());
                } else {
                    mTCPPrint.stopClient();
                    new connectTask().execute(formateado.toString());
                    alertbox("Oops!",
                            "Al Parecer no hay impresora disponible. Estamos tratando de reconectarnos e imprimir. Si no funciona, reinicia la Red o la impresora y ve a rdenes para imprimir el pedido.");
                }
            } else {
                alertbox("Oops!",
                        "Al Parecer no hay impresora disponible. Trataremos en este momento de nuevo de imprimir el pedido. Si no funciona, reinicia la red o la impreso y ve a rdenes para imprimir de nuevo la orden.");
                new connectTask().execute(formateado.toString());
            }
        }
        currentOrder.clear(); //NUEVOO

        makeTable("NA");

    } else {
        alertbox("!ATENCIN!",
                "Esta venta no se puede facturar. Este dispositivo no tiene ms facturas autorizadas. Consulta el administrador, o si tu lo eres, ve a tu panel de control Nest5 y autoriza ms facturas. Para ms informacin: http://soporte.nest5.com");
    }
}

From source file:org.pentaho.di.ui.spoon.Spoon.java

public void pasteXML(TransMeta transMeta, String clipcontent, Point loc) {
    if (RepositorySecurityUI.verifyOperations(shell, rep, RepositoryOperation.MODIFY_TRANSFORMATION,
            RepositoryOperation.EXECUTE_TRANSFORMATION)) {
        return;/*from   w w  w .  ja  v  a2s  . com*/
    }
    try {
        Document doc = XMLHandler.loadXMLString(clipcontent);
        Node transNode = XMLHandler.getSubNode(doc, Spoon.XML_TAG_TRANSFORMATION_STEPS);
        // De-select all, re-select pasted steps...
        transMeta.unselectAll();

        Node stepsNode = XMLHandler.getSubNode(transNode, "steps");
        int nr = XMLHandler.countNodes(stepsNode, "step");
        if (getLog().isDebug()) {
            // "I found "+nr+" steps to paste on location: "
            getLog().logDebug(BaseMessages.getString(PKG, "Spoon.Log.FoundSteps", "" + nr) + loc);
        }
        StepMeta[] steps = new StepMeta[nr];
        ArrayList<String> stepOldNames = new ArrayList<String>(nr);

        // Point min = new Point(loc.x, loc.y);
        Point min = new Point(99999999, 99999999);

        // Load the steps...
        for (int i = 0; i < nr; i++) {
            Node stepNode = XMLHandler.getSubNodeByNr(stepsNode, "step", i);
            steps[i] = new StepMeta(stepNode, transMeta.getDatabases(), metaStore);

            if (loc != null) {
                Point p = steps[i].getLocation();

                if (min.x > p.x) {
                    min.x = p.x;
                }
                if (min.y > p.y) {
                    min.y = p.y;
                }
            }
        }

        // Load the hops...
        Node hopsNode = XMLHandler.getSubNode(transNode, "order");
        nr = XMLHandler.countNodes(hopsNode, "hop");
        if (getLog().isDebug()) {
            // "I found "+nr+" hops to paste."
            getLog().logDebug(BaseMessages.getString(PKG, "Spoon.Log.FoundHops", "" + nr));
        }
        TransHopMeta[] hops = new TransHopMeta[nr];

        ArrayList<StepMeta> alSteps = new ArrayList<StepMeta>();
        Collections.addAll(alSteps, steps);

        for (int i = 0; i < nr; i++) {
            Node hopNode = XMLHandler.getSubNodeByNr(hopsNode, "hop", i);
            hops[i] = new TransHopMeta(hopNode, alSteps);
        }

        // This is the offset:
        //
        Point offset = new Point(loc.x - min.x, loc.y - min.y);

        // Undo/redo object positions...
        int[] position = new int[steps.length];

        for (int i = 0; i < steps.length; i++) {
            Point p = steps[i].getLocation();
            String name = steps[i].getName();

            steps[i].setLocation(p.x + offset.x, p.y + offset.y);
            steps[i].setDraw(true);

            // Check the name, find alternative...
            stepOldNames.add(name);
            steps[i].setName(transMeta.getAlternativeStepname(name));
            transMeta.addStep(steps[i]);
            position[i] = transMeta.indexOfStep(steps[i]);
            steps[i].setSelected(true);
        }

        // Add the hops too...
        for (TransHopMeta hop : hops) {
            transMeta.addTransHop(hop);
        }

        // Load the notes...
        Node notesNode = XMLHandler.getSubNode(transNode, "notepads");
        nr = XMLHandler.countNodes(notesNode, "notepad");
        if (getLog().isDebug()) {
            // "I found "+nr+" notepads to paste."
            getLog().logDebug(BaseMessages.getString(PKG, "Spoon.Log.FoundNotepads", "" + nr));
        }
        NotePadMeta[] notes = new NotePadMeta[nr];

        for (int i = 0; i < notes.length; i++) {
            Node noteNode = XMLHandler.getSubNodeByNr(notesNode, "notepad", i);
            notes[i] = new NotePadMeta(noteNode);
            Point p = notes[i].getLocation();
            notes[i].setLocation(p.x + offset.x, p.y + offset.y);
            transMeta.addNote(notes[i]);
            notes[i].setSelected(true);
        }

        // Set the source and target steps ...
        for (StepMeta step : steps) {
            StepMetaInterface smi = step.getStepMetaInterface();
            smi.searchInfoAndTargetSteps(transMeta.getSteps());
        }

        // Set the error handling hops
        Node errorHandlingNode = XMLHandler.getSubNode(transNode, TransMeta.XML_TAG_STEP_ERROR_HANDLING);
        int nrErrorHandlers = XMLHandler.countNodes(errorHandlingNode, StepErrorMeta.XML_TAG);
        for (int i = 0; i < nrErrorHandlers; i++) {
            Node stepErrorMetaNode = XMLHandler.getSubNodeByNr(errorHandlingNode, StepErrorMeta.XML_TAG, i);
            StepErrorMeta stepErrorMeta = new StepErrorMeta(transMeta.getParentVariableSpace(),
                    stepErrorMetaNode, transMeta.getSteps());

            // Handle pasting multiple times, need to update source and target step names
            int srcStepPos = stepOldNames.indexOf(stepErrorMeta.getSourceStep().getName());
            int tgtStepPos = stepOldNames.indexOf(stepErrorMeta.getTargetStep().getName());
            StepMeta sourceStep = transMeta.findStep(steps[srcStepPos].getName());
            if (sourceStep != null) {
                sourceStep.setStepErrorMeta(stepErrorMeta);
            }
            StepMeta targetStep = transMeta.findStep(steps[tgtStepPos].getName());
            stepErrorMeta.setSourceStep(sourceStep);
            stepErrorMeta.setTargetStep(targetStep);
        }

        // Save undo information too...
        addUndoNew(transMeta, steps, position, false);

        int[] hopPos = new int[hops.length];
        for (int i = 0; i < hops.length; i++) {
            hopPos[i] = transMeta.indexOfTransHop(hops[i]);
        }
        addUndoNew(transMeta, hops, hopPos, true);

        int[] notePos = new int[notes.length];
        for (int i = 0; i < notes.length; i++) {
            notePos[i] = transMeta.indexOfNote(notes[i]);
        }
        addUndoNew(transMeta, notes, notePos, true);

        if (transMeta.haveStepsChanged()) {
            refreshTree();
            refreshGraph();
        }
    } catch (KettleException e) {
        // "Error pasting steps...",
        // "I was unable to paste steps to this transformation"
        new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Dialog.UnablePasteSteps.Title"),
                BaseMessages.getString(PKG, "Spoon.Dialog.UnablePasteSteps.Message"), e);
    }
}

From source file:org.telegram.android.MessagesController.java

public boolean processUpdateArray(ArrayList<TLRPC.Update> updates, final ArrayList<TLRPC.User> usersArr,
        final ArrayList<TLRPC.Chat> chatsArr) {
    if (updates.isEmpty()) {
        return true;
    }/*from w ww .ja  v a  2 s  .  co  m*/
    long currentTime = System.currentTimeMillis();

    final HashMap<Long, ArrayList<MessageObject>> messages = new HashMap<>();
    final HashMap<Long, TLRPC.WebPage> webPages = new HashMap<>();
    final ArrayList<MessageObject> pushMessages = new ArrayList<>();
    final ArrayList<TLRPC.Message> messagesArr = new ArrayList<>();
    final HashMap<Integer, Integer> markAsReadMessagesInbox = new HashMap<>();
    final HashMap<Integer, Integer> markAsReadMessagesOutbox = new HashMap<>();
    final ArrayList<Integer> markAsReadMessages = new ArrayList<>();
    final HashMap<Integer, Integer> markAsReadEncrypted = new HashMap<>();
    final ArrayList<Integer> deletedMessages = new ArrayList<>();
    boolean printChanged = false;
    final ArrayList<TLRPC.ChatParticipants> chatInfoToUpdate = new ArrayList<>();
    final ArrayList<TLRPC.Update> updatesOnMainThread = new ArrayList<>();
    final ArrayList<TLRPC.TL_updateEncryptedMessagesRead> tasks = new ArrayList<>();
    final ArrayList<Integer> contactsIds = new ArrayList<>();

    boolean checkForUsers = true;
    ConcurrentHashMap<Integer, TLRPC.User> usersDict;
    ConcurrentHashMap<Integer, TLRPC.Chat> chatsDict;
    if (usersArr != null) {
        usersDict = new ConcurrentHashMap<>();
        for (TLRPC.User user : usersArr) {
            usersDict.put(user.id, user);
        }
    } else {
        checkForUsers = false;
        usersDict = users;
    }
    if (chatsArr != null) {
        chatsDict = new ConcurrentHashMap<>();
        for (TLRPC.Chat chat : chatsArr) {
            chatsDict.put(chat.id, chat);
        }
    } else {
        checkForUsers = false;
        chatsDict = chats;
    }

    if (usersArr != null || chatsArr != null) {
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                putUsers(usersArr, false);
                putChats(chatsArr, false);
            }
        });
    }

    int interfaceUpdateMask = 0;

    for (TLRPC.Update update : updates) {
        if (update instanceof TLRPC.TL_updateNewMessage) {
            TLRPC.TL_updateNewMessage upd = (TLRPC.TL_updateNewMessage) update;
            if (checkForUsers) {
                TLRPC.User user = getUser(upd.message.from_id);
                if (usersDict.get(upd.message.from_id) == null && user == null
                        || upd.message.to_id.chat_id != 0 && chatsDict.get(upd.message.to_id.chat_id) == null
                                && getChat(upd.message.to_id.chat_id) == null) {
                    return false;
                }

                if (user != null && user.status != null && user.status.expires <= 0) {
                    onlinePrivacy.put(upd.message.from_id, ConnectionsManager.getInstance().getCurrentTime());
                    interfaceUpdateMask |= UPDATE_MASK_STATUS;
                }
            }
            messagesArr.add(upd.message);
            ImageLoader.saveMessageThumbs(upd.message);
            MessageObject obj = new MessageObject(upd.message, usersDict, true);
            if (obj.type == 11) {
                interfaceUpdateMask |= UPDATE_MASK_CHAT_AVATAR;
            } else if (obj.type == 10) {
                interfaceUpdateMask |= UPDATE_MASK_CHAT_NAME;
            }
            long uid;
            if (upd.message.to_id.chat_id != 0) {
                uid = -upd.message.to_id.chat_id;
            } else {
                if (upd.message.to_id.user_id == UserConfig.getClientUserId()) {
                    upd.message.to_id.user_id = upd.message.from_id;
                }
                uid = upd.message.to_id.user_id;
            }
            ArrayList<MessageObject> arr = messages.get(uid);
            if (arr == null) {
                arr = new ArrayList<>();
                messages.put(uid, arr);
            }
            arr.add(obj);
            if (!obj.isOut() && obj.isUnread()) {
                pushMessages.add(obj);
            }
        } else if (update instanceof TLRPC.TL_updateReadMessagesContents) {
            markAsReadMessages.addAll(update.messages);
        } else if (update instanceof TLRPC.TL_updateReadHistoryInbox) {
            TLRPC.Peer peer = ((TLRPC.TL_updateReadHistoryInbox) update).peer;
            if (peer.chat_id != 0) {
                markAsReadMessagesInbox.put(-peer.chat_id, update.max_id);
            } else {
                markAsReadMessagesInbox.put(peer.user_id, update.max_id);
            }
        } else if (update instanceof TLRPC.TL_updateReadHistoryOutbox) {
            TLRPC.Peer peer = ((TLRPC.TL_updateReadHistoryOutbox) update).peer;
            if (peer.chat_id != 0) {
                markAsReadMessagesOutbox.put(-peer.chat_id, update.max_id);
            } else {
                markAsReadMessagesOutbox.put(peer.user_id, update.max_id);
            }
        } else if (update instanceof TLRPC.TL_updateDeleteMessages) {
            deletedMessages.addAll(update.messages);
        } else if (update instanceof TLRPC.TL_updateUserTyping
                || update instanceof TLRPC.TL_updateChatUserTyping) {
            if (update.user_id != UserConfig.getClientUserId()) {
                long uid = -update.chat_id;
                if (uid == 0) {
                    uid = update.user_id;
                }
                ArrayList<PrintingUser> arr = printingUsers.get(uid);
                if (update.action instanceof TLRPC.TL_sendMessageCancelAction) {
                    if (arr != null) {
                        for (int a = 0; a < arr.size(); a++) {
                            PrintingUser pu = arr.get(a);
                            if (pu.userId == update.user_id) {
                                arr.remove(a);
                                printChanged = true;
                                break;
                            }
                        }
                        if (arr.isEmpty()) {
                            printingUsers.remove(uid);
                        }
                    }
                } else {
                    if (arr == null) {
                        arr = new ArrayList<>();
                        printingUsers.put(uid, arr);
                    }
                    boolean exist = false;
                    for (PrintingUser u : arr) {
                        if (u.userId == update.user_id) {
                            exist = true;
                            u.lastTime = currentTime;
                            u.action = update.action;
                            break;
                        }
                    }
                    if (!exist) {
                        PrintingUser newUser = new PrintingUser();
                        newUser.userId = update.user_id;
                        newUser.lastTime = currentTime;
                        newUser.action = update.action;
                        arr.add(newUser);
                        printChanged = true;
                    }
                }
                onlinePrivacy.put(update.user_id, ConnectionsManager.getInstance().getCurrentTime());
            }
        } else if (update instanceof TLRPC.TL_updateChatParticipants) {
            interfaceUpdateMask |= UPDATE_MASK_CHAT_MEMBERS;
            chatInfoToUpdate.add(update.participants);
        } else if (update instanceof TLRPC.TL_updateUserStatus) {
            interfaceUpdateMask |= UPDATE_MASK_STATUS;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserName) {
            interfaceUpdateMask |= UPDATE_MASK_NAME;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserPhoto) {
            interfaceUpdateMask |= UPDATE_MASK_AVATAR;
            MessagesStorage.getInstance().clearUserPhotos(update.user_id);
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserPhone) {
            interfaceUpdateMask |= UPDATE_MASK_PHONE;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateContactRegistered) {
            if (enableJoined && usersDict.containsKey(update.user_id)) {
                TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
                newMessage.action = new TLRPC.TL_messageActionUserJoined();
                newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
                UserConfig.saveConfig(false);
                newMessage.flags = TLRPC.MESSAGE_FLAG_UNREAD;
                newMessage.date = update.date;
                newMessage.from_id = update.user_id;
                newMessage.to_id = new TLRPC.TL_peerUser();
                newMessage.to_id.user_id = UserConfig.getClientUserId();
                newMessage.dialog_id = update.user_id;

                messagesArr.add(newMessage);
                MessageObject obj = new MessageObject(newMessage, usersDict, true);
                ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
                if (arr == null) {
                    arr = new ArrayList<>();
                    messages.put(newMessage.dialog_id, arr);
                }
                arr.add(obj);
                pushMessages.add(obj);
            }
        } else if (update instanceof TLRPC.TL_updateContactLink) {
            if (update.my_link instanceof TLRPC.TL_contactLinkContact) {
                int idx = contactsIds.indexOf(-update.user_id);
                if (idx != -1) {
                    contactsIds.remove(idx);
                }
                if (!contactsIds.contains(update.user_id)) {
                    contactsIds.add(update.user_id);
                }
            } else {
                int idx = contactsIds.indexOf(update.user_id);
                if (idx != -1) {
                    contactsIds.remove(idx);
                }
                if (!contactsIds.contains(update.user_id)) {
                    contactsIds.add(-update.user_id);
                }
            }
        } else if (update instanceof TLRPC.TL_updateNewAuthorization) {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    NotificationCenter.getInstance()
                            .postNotificationName(NotificationCenter.newSessionReceived);
                }
            });
            TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
            newMessage.action = new TLRPC.TL_messageActionLoginUnknownLocation();
            newMessage.action.title = update.device;
            newMessage.action.address = update.location;
            newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
            UserConfig.saveConfig(false);
            newMessage.flags = TLRPC.MESSAGE_FLAG_UNREAD;
            newMessage.date = update.date;
            newMessage.from_id = 777000;
            newMessage.to_id = new TLRPC.TL_peerUser();
            newMessage.to_id.user_id = UserConfig.getClientUserId();
            newMessage.dialog_id = 777000;

            messagesArr.add(newMessage);
            MessageObject obj = new MessageObject(newMessage, usersDict, true);
            ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
            if (arr == null) {
                arr = new ArrayList<>();
                messages.put(newMessage.dialog_id, arr);
            }
            arr.add(obj);
            pushMessages.add(obj);
        } else if (update instanceof TLRPC.TL_updateNewGeoChatMessage) {
            //DEPRECATED
        } else if (update instanceof TLRPC.TL_updateNewEncryptedMessage) {
            ArrayList<TLRPC.Message> decryptedMessages = SecretChatHelper.getInstance()
                    .decryptMessage(((TLRPC.TL_updateNewEncryptedMessage) update).message);
            if (decryptedMessages != null && !decryptedMessages.isEmpty()) {
                int cid = ((TLRPC.TL_updateNewEncryptedMessage) update).message.chat_id;
                long uid = ((long) cid) << 32;
                ArrayList<MessageObject> arr = messages.get(uid);
                if (arr == null) {
                    arr = new ArrayList<>();
                    messages.put(uid, arr);
                }
                for (TLRPC.Message message : decryptedMessages) {
                    ImageLoader.saveMessageThumbs(message);
                    messagesArr.add(message);
                    MessageObject obj = new MessageObject(message, usersDict, true);
                    arr.add(obj);
                    pushMessages.add(obj);
                }
            }
        } else if (update instanceof TLRPC.TL_updateEncryptedChatTyping) {
            TLRPC.EncryptedChat encryptedChat = getEncryptedChatDB(update.chat_id);
            if (encryptedChat != null) {
                update.user_id = encryptedChat.user_id;
                long uid = ((long) update.chat_id) << 32;
                ArrayList<PrintingUser> arr = printingUsers.get(uid);
                if (arr == null) {
                    arr = new ArrayList<>();
                    printingUsers.put(uid, arr);
                }
                boolean exist = false;
                for (PrintingUser u : arr) {
                    if (u.userId == update.user_id) {
                        exist = true;
                        u.lastTime = currentTime;
                        u.action = new TLRPC.TL_sendMessageTypingAction();
                        break;
                    }
                }
                if (!exist) {
                    PrintingUser newUser = new PrintingUser();
                    newUser.userId = update.user_id;
                    newUser.lastTime = currentTime;
                    newUser.action = new TLRPC.TL_sendMessageTypingAction();
                    arr.add(newUser);
                    printChanged = true;
                }
                onlinePrivacy.put(update.user_id, ConnectionsManager.getInstance().getCurrentTime());
            }
        } else if (update instanceof TLRPC.TL_updateEncryptedMessagesRead) {
            markAsReadEncrypted.put(update.chat_id, Math.max(update.max_date, update.date));
            tasks.add((TLRPC.TL_updateEncryptedMessagesRead) update);
        } else if (update instanceof TLRPC.TL_updateChatParticipantAdd) {
            MessagesStorage.getInstance().updateChatInfo(update.chat_id, update.user_id, false,
                    update.inviter_id, update.version);
        } else if (update instanceof TLRPC.TL_updateChatParticipantDelete) {
            MessagesStorage.getInstance().updateChatInfo(update.chat_id, update.user_id, true, 0,
                    update.version);
        } else if (update instanceof TLRPC.TL_updateDcOptions) {
            ConnectionsManager.getInstance().updateDcSettings(0);
        } else if (update instanceof TLRPC.TL_updateEncryption) {
            SecretChatHelper.getInstance().processUpdateEncryption((TLRPC.TL_updateEncryption) update,
                    usersDict);
        } else if (update instanceof TLRPC.TL_updateUserBlocked) {
            final TLRPC.TL_updateUserBlocked finalUpdate = (TLRPC.TL_updateUserBlocked) update;
            if (finalUpdate.blocked) {
                ArrayList<Integer> ids = new ArrayList<>();
                ids.add(finalUpdate.user_id);
                MessagesStorage.getInstance().putBlockedUsers(ids, false);
            } else {
                MessagesStorage.getInstance().deleteBlockedUser(finalUpdate.user_id);
            }
            MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
                @Override
                public void run() {
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            if (finalUpdate.blocked) {
                                if (!blockedUsers.contains(finalUpdate.user_id)) {
                                    blockedUsers.add(finalUpdate.user_id);
                                }
                            } else {
                                blockedUsers.remove((Integer) finalUpdate.user_id);
                            }
                            NotificationCenter.getInstance()
                                    .postNotificationName(NotificationCenter.blockedUsersDidLoaded);
                        }
                    });
                }
            });
        } else if (update instanceof TLRPC.TL_updateNotifySettings) {
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateServiceNotification) {
            TLRPC.TL_message newMessage = new TLRPC.TL_message();
            newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
            UserConfig.saveConfig(false);
            newMessage.flags = TLRPC.MESSAGE_FLAG_UNREAD;
            newMessage.date = ConnectionsManager.getInstance().getCurrentTime();
            newMessage.from_id = 777000;
            newMessage.to_id = new TLRPC.TL_peerUser();
            newMessage.to_id.user_id = UserConfig.getClientUserId();
            newMessage.dialog_id = 777000;
            newMessage.media = update.media;
            newMessage.message = ((TLRPC.TL_updateServiceNotification) update).message;

            messagesArr.add(newMessage);
            MessageObject obj = new MessageObject(newMessage, usersDict, true);
            ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
            if (arr == null) {
                arr = new ArrayList<>();
                messages.put(newMessage.dialog_id, arr);
            }
            arr.add(obj);
            pushMessages.add(obj);
        } else if (update instanceof TLRPC.TL_updatePrivacy) {
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateWebPage) {
            webPages.put(update.webpage.id, update.webpage);
        }
    }
    if (!messages.isEmpty()) {
        for (HashMap.Entry<Long, ArrayList<MessageObject>> pair : messages.entrySet()) {
            Long key = pair.getKey();
            ArrayList<MessageObject> value = pair.getValue();
            if (updatePrintingUsersWithNewMessages(key, value)) {
                printChanged = true;
            }
        }
    }

    if (printChanged) {
        updatePrintingStrings();
    }

    final int interfaceUpdateMaskFinal = interfaceUpdateMask;
    final boolean printChangedArg = printChanged;

    if (!contactsIds.isEmpty()) {
        ContactsController.getInstance().processContactsUpdates(contactsIds, usersDict);
    }

    MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
        @Override
        public void run() {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    if (!pushMessages.isEmpty()) {
                        NotificationsController.getInstance().processNewMessages(pushMessages, true);
                    }
                }
            });
        }
    });

    if (!messagesArr.isEmpty()) {
        MessagesStorage.getInstance().putMessages(messagesArr, true, true, false,
                MediaController.getInstance().getAutodownloadMask());
    }

    AndroidUtilities.runOnUIThread(new Runnable() {
        @Override
        public void run() {
            int updateMask = interfaceUpdateMaskFinal;

            boolean avatarsUpdate = false;
            if (!updatesOnMainThread.isEmpty()) {
                ArrayList<TLRPC.User> dbUsers = new ArrayList<>();
                ArrayList<TLRPC.User> dbUsersStatus = new ArrayList<>();
                SharedPreferences.Editor editor = null;
                for (TLRPC.Update update : updatesOnMainThread) {
                    final TLRPC.User toDbUser = new TLRPC.User();
                    toDbUser.id = update.user_id;
                    final TLRPC.User currentUser = getUser(update.user_id);
                    if (update instanceof TLRPC.TL_updatePrivacy) {
                        if (update.key instanceof TLRPC.TL_privacyKeyStatusTimestamp) {
                            ContactsController.getInstance().setPrivacyRules(update.rules);
                        }
                    } else if (update instanceof TLRPC.TL_updateUserStatus) {
                        if (update.status instanceof TLRPC.TL_userStatusRecently) {
                            update.status.expires = -100;
                        } else if (update.status instanceof TLRPC.TL_userStatusLastWeek) {
                            update.status.expires = -101;
                        } else if (update.status instanceof TLRPC.TL_userStatusLastMonth) {
                            update.status.expires = -102;
                        }
                        if (currentUser != null) {
                            currentUser.id = update.user_id;
                            currentUser.status = update.status;
                        }
                        toDbUser.status = update.status;
                        dbUsersStatus.add(toDbUser);
                        if (update.user_id == UserConfig.getClientUserId()) {
                            NotificationsController.getInstance()
                                    .setLastOnlineFromOtherDevice(update.status.expires);
                        }
                    } else if (update instanceof TLRPC.TL_updateUserName) {
                        if (currentUser != null) {
                            if (!(currentUser instanceof TLRPC.TL_userContact)) {
                                currentUser.first_name = update.first_name;
                                currentUser.last_name = update.last_name;
                            }
                            if (currentUser.username != null && currentUser.username.length() > 0) {
                                usersByUsernames.remove(currentUser.username);
                            }
                            if (update.username != null && update.username.length() > 0) {
                                usersByUsernames.put(update.username, currentUser);
                            }
                            currentUser.username = update.username;
                        }
                        toDbUser.first_name = update.first_name;
                        toDbUser.last_name = update.last_name;
                        toDbUser.username = update.username;
                        dbUsers.add(toDbUser);
                    } else if (update instanceof TLRPC.TL_updateUserPhoto) {
                        if (currentUser != null) {
                            currentUser.photo = update.photo;
                        }
                        avatarsUpdate = true;
                        toDbUser.photo = update.photo;
                        dbUsers.add(toDbUser);
                    } else if (update instanceof TLRPC.TL_updateUserPhone) {
                        if (currentUser != null) {
                            currentUser.phone = update.phone;
                            Utilities.phoneBookQueue.postRunnable(new Runnable() {
                                @Override
                                public void run() {
                                    ContactsController.getInstance().addContactToPhoneBook(currentUser, true);
                                }
                            });
                        }
                        toDbUser.phone = update.phone;
                        dbUsers.add(toDbUser);
                    } else if (update instanceof TLRPC.TL_updateNotifySettings) {
                        if (update.notify_settings instanceof TLRPC.TL_peerNotifySettings
                                && update.peer instanceof TLRPC.TL_notifyPeer) {
                            if (editor == null) {
                                SharedPreferences preferences = ApplicationLoader.applicationContext
                                        .getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
                                editor = preferences.edit();
                            }
                            long dialog_id = update.peer.peer.user_id;
                            if (dialog_id == 0) {
                                dialog_id = -update.peer.peer.chat_id;
                            }
                            TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);
                            if (dialog != null) {
                                dialog.notify_settings = update.notify_settings;
                            }
                            if (update.notify_settings.mute_until > ConnectionsManager.getInstance()
                                    .getCurrentTime()) {
                                int until = 0;
                                if (update.notify_settings.mute_until > ConnectionsManager.getInstance()
                                        .getCurrentTime() + 60 * 60 * 24 * 365) {
                                    editor.putInt("notify2_" + dialog_id, 2);
                                    if (dialog != null) {
                                        dialog.notify_settings.mute_until = Integer.MAX_VALUE;
                                    }
                                } else {
                                    until = update.notify_settings.mute_until;
                                    editor.putInt("notify2_" + dialog_id, 3);
                                    editor.putInt("notifyuntil_" + dialog_id,
                                            update.notify_settings.mute_until);
                                    if (dialog != null) {
                                        dialog.notify_settings.mute_until = until;
                                    }
                                }
                                MessagesStorage.getInstance().setDialogFlags(dialog_id,
                                        ((long) until << 32) | 1);
                            } else {
                                if (dialog != null) {
                                    dialog.notify_settings.mute_until = 0;
                                }
                                editor.remove("notify2_" + dialog_id);
                                MessagesStorage.getInstance().setDialogFlags(dialog_id, 0);
                            }

                        } /* else if (update.peer instanceof TLRPC.TL_notifyChats) { disable global settings sync
                          if (editor == null) {
                              SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
                              editor = preferences.edit();
                          }
                          editor.putBoolean("EnableGroup", update.notify_settings.mute_until == 0);
                          editor.putBoolean("EnablePreviewGroup", update.notify_settings.show_previews);
                          } else if (update.peer instanceof TLRPC.TL_notifyUsers) {
                          if (editor == null) {
                              SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
                              editor = preferences.edit();
                          }
                          editor.putBoolean("EnableAll", update.notify_settings.mute_until == 0);
                          editor.putBoolean("EnablePreviewAll", update.notify_settings.show_previews);
                          }*/
                    }
                }
                if (editor != null) {
                    editor.commit();
                    NotificationCenter.getInstance()
                            .postNotificationName(NotificationCenter.notificationsSettingsUpdated);
                }
                MessagesStorage.getInstance().updateUsers(dbUsersStatus, true, true, true);
                MessagesStorage.getInstance().updateUsers(dbUsers, false, true, true);
            }

            if (!webPages.isEmpty()) {
                NotificationCenter.getInstance()
                        .postNotificationName(NotificationCenter.didReceivedWebpagesInUpdates, webPages);
            }

            if (!messages.isEmpty()) {
                for (HashMap.Entry<Long, ArrayList<MessageObject>> entry : messages.entrySet()) {
                    Long key = entry.getKey();
                    ArrayList<MessageObject> value = entry.getValue();
                    updateInterfaceWithMessages(key, value);
                }
                NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
            }
            if (printChangedArg) {
                updateMask |= UPDATE_MASK_USER_PRINT;
            }
            if (!contactsIds.isEmpty()) {
                updateMask |= UPDATE_MASK_NAME;
                updateMask |= UPDATE_MASK_USER_PHONE;
            }
            if (!chatInfoToUpdate.isEmpty()) {
                for (TLRPC.ChatParticipants info : chatInfoToUpdate) {
                    MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true);
                    NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded,
                            info.chat_id, info);
                }
            }
            if (updateMask != 0) {
                NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces,
                        updateMask);
            }
        }
    });

    MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
        @Override
        public void run() {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    int updateMask = 0;
                    if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty()) {
                        NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesRead,
                                markAsReadMessagesInbox, markAsReadMessagesOutbox);
                        NotificationsController.getInstance().processReadMessages(markAsReadMessagesInbox, 0, 0,
                                0, false);
                        for (HashMap.Entry<Integer, Integer> entry : markAsReadMessagesInbox.entrySet()) {
                            TLRPC.TL_dialog dialog = dialogs_dict.get((long) entry.getKey());
                            if (dialog != null && dialog.top_message <= entry.getValue()) {
                                MessageObject obj = dialogMessage.get(dialog.top_message);
                                if (obj != null) {
                                    obj.setIsRead();
                                    updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
                                }
                            }
                        }
                        for (HashMap.Entry<Integer, Integer> entry : markAsReadMessagesOutbox.entrySet()) {
                            TLRPC.TL_dialog dialog = dialogs_dict.get((long) entry.getKey());
                            if (dialog != null && dialog.top_message <= entry.getValue()) {
                                MessageObject obj = dialogMessage.get(dialog.top_message);
                                if (obj != null) {
                                    obj.setIsRead();
                                    updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
                                }
                            }
                        }
                    }
                    if (!markAsReadEncrypted.isEmpty()) {
                        for (HashMap.Entry<Integer, Integer> entry : markAsReadEncrypted.entrySet()) {
                            NotificationCenter.getInstance().postNotificationName(
                                    NotificationCenter.messagesReadEncrypted, entry.getKey(), entry.getValue());
                            long dialog_id = (long) (entry.getKey()) << 32;
                            TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);
                            if (dialog != null) {
                                MessageObject message = dialogMessage.get(dialog.top_message);
                                if (message != null && message.messageOwner.date <= entry.getValue()) {
                                    message.setIsRead();
                                    updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
                                }
                            }
                        }
                    }
                    if (!markAsReadMessages.isEmpty()) {
                        NotificationCenter.getInstance().postNotificationName(
                                NotificationCenter.messagesReadContent, markAsReadMessages);
                    }
                    if (!deletedMessages.isEmpty()) {
                        NotificationCenter.getInstance()
                                .postNotificationName(NotificationCenter.messagesDeleted, deletedMessages);
                        for (Integer id : deletedMessages) {
                            MessageObject obj = dialogMessage.get(id);
                            if (obj != null) {
                                obj.deleted = true;
                            }
                        }
                    }
                    if (updateMask != 0) {
                        NotificationCenter.getInstance()
                                .postNotificationName(NotificationCenter.updateInterfaces, updateMask);
                    }
                }
            });
        }
    });

    if (!webPages.isEmpty()) {
        MessagesStorage.getInstance().putWebPages(webPages);
    }
    if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty()
            || !markAsReadEncrypted.isEmpty()) {
        if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty()) {
            MessagesStorage.getInstance().updateDialogsWithReadedMessages(markAsReadMessagesInbox, true);
        }
        MessagesStorage.getInstance().markMessagesAsRead(markAsReadMessagesInbox, markAsReadMessagesOutbox,
                markAsReadEncrypted, true);
    }
    if (!markAsReadMessages.isEmpty()) {
        MessagesStorage.getInstance().markMessagesContentAsRead(markAsReadMessages);
    }
    if (!deletedMessages.isEmpty()) {
        MessagesStorage.getInstance().markMessagesAsDeleted(deletedMessages, true);
    }
    if (!deletedMessages.isEmpty()) {
        MessagesStorage.getInstance().updateDialogsWithDeletedMessages(deletedMessages, true);
    }
    if (!tasks.isEmpty()) {
        for (TLRPC.TL_updateEncryptedMessagesRead update : tasks) {
            MessagesStorage.getInstance().createTaskForSecretChat(update.chat_id, update.max_date, update.date,
                    1, null);
        }
    }

    return true;
}