Example usage for java.awt Desktop getDesktop

List of usage examples for java.awt Desktop getDesktop

Introduction

In this page you can find the example usage for java.awt Desktop getDesktop.

Prototype

public static synchronized Desktop getDesktop() 

Source Link

Document

Returns the Desktop instance of the current desktop context.

Usage

From source file:com.github.vatbub.awsvpnlauncher.Main.java

private static void setup() {
    FOKLogger.info(Main.class.getName(),
            "Welcome to the awsVPNLauncher v" + Common.getInstance().getAppVersion());
    FOKLogger.info(Main.class.getName(), "You will now be guided through the setup process.");
    FOKLogger.info(Main.class.getName(), "You will have to do this only once.");
    FOKLogger.info(Main.class.getName(),
            "If you already did the setup once, setup will override previous values.");

    FOKLogger.info(Main.class.getName(),
            "--------------------------------------------------------------------------");
    FOKLogger.info(Main.class.getName(), "Amazon AWS Account");
    FOKLogger.info(Main.class.getName(),
            "--------------------------------------------------------------------------");
    FOKLogger.info(Main.class.getName(),
            "Once you hit enter, your browser will be opened and you will be guided to");
    FOKLogger.info(Main.class.getName(), "the Amazon AWS login page.");
    FOKLogger.info(Main.class.getName(),
            "If you already have an Amazon Account, you can use that, if not, please create a new account.");
    FOKLogger.info(Main.class.getName(),
            "Once you logged in, please return to this window to read the new instructions.");

    FOKLogger.info(Main.class.getName(), "Press enter to continue...");
    try {//w ww  .j  a va 2  s.c o  m
        //noinspection unused
        int readResult = System.in.read();
    } catch (IOException e) {
        FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not read from System.in, resuming setup...",
                e);
    }

    boolean cont = false;
    while (!cont) {
        try {
            Desktop.getDesktop().browse(new URI(projectConfig.getValue("awsCreateIAMUserURL")));
        } catch (IOException | URISyntaxException e) {
            FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not open the login page", e);
            cont = true;
        }

        try {
            Parsable result = new Prompt("Reload the login page or continue?",
                    new ParsableEnum<>(ReloadContinue.class, ReloadContinue.Reload)).doPrompt();
            if (result.toValue() == ReloadContinue.Continue) {
                cont = true;
            }
        } catch (ParseException e) {
            cont = false;
            if (e.getMessage() != null) {
                FOKLogger.severe(Main.class.getName(), "Unable to parse the input: " + e.getMessage());
            } else {
                FOKLogger.severe(Main.class.getName(), "Unable to parse the input");
            }
        }
    }
}

From source file:pi.bestdeal.gui.InterfacePrincipale.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    int idd = (int) jTable3.getModel().getValueAt(jTable3.getSelectedRow(), 0);
    ChoixStat1 chStat = new ChoixStat1();
    ChoixStat2 chStat2 = new ChoixStat2();

    Object[] options = { "BACK", "NEXT" };
    int a = JOptionPane.showOptionDialog(null, chStat, "", JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.WARNING_MESSAGE, null, options, options[0]);
    int b = 0;/*from  w w w .ja  v  a  2  s  .  c o  m*/
    if (chStat.jRadiosexe.isSelected() && chStat.jRadioconsult.isSelected()) {
        b = 0;
    }
    if (chStat.jRadiosexe.isSelected() && chStat.jRadiores.isSelected()) {
        b = 1;
    }
    if (chStat.jRadiooperation.isSelected() && chStat.jRadioconsult.isSelected()) {
        b = 2;
    }
    if (chStat.jRadiooperation.isSelected() && chStat.jRadiores.isSelected()) {
        b = 3;
    }
    if (a == 1 && b == 2) {
        chStat.setVisible(false);
        Object[] options2 = { "Annuler", "Afficher la Statistique" };
        int c = JOptionPane.showOptionDialog(null, chStat2, "", JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE, null, options2, options[0]);
        if (c == 1) {
            java.util.Date d1 = chStat2.jDateDebut.getCalendar().getTime();
            java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
            java.util.Date d2 = chStat2.jDatefin.getCalendar().getTime();
            java.sql.Date sqlDate2 = new java.sql.Date(d2.getTime());
            Charts charts = new Charts();

            XYSeriesCollection dataxy = charts.createDataset(sqlDate.toString(), sqlDate2.toString(), idd);
            final JFreeChart chart = ChartFactory.createXYLineChart(
                    "Evolution des Consultation par rapport au temps", "Jours", "Nombre des Consultations", //
                    dataxy, // Dataset
                    PlotOrientation.VERTICAL, // 

                    true, true, false);
            XYItemRenderer rend = chart.getXYPlot().getRenderer();

            ChartPanel crepart = new ChartPanel(chart);
            Plot plot = chart.getPlot();

            JPanel jpan = new JPanel();
            JButton button = new JButton("Sauvegarder");
            button.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        JFileChooser chooser = new JFileChooser();
                        chooser.showSaveDialog(jPanel3);
                        String path = chooser.getSelectedFile().getPath();
                        if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                            path = path + ".png";
                        }
                        File f = new File(path);
                        ChartUtilities.saveChartAsPNG(new File(path), chart, 800, 600);

                        if (f.exists() && !f.isDirectory()) {
                            JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                            Desktop.getDesktop().open(f);
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });

            jpan.add(crepart);
            jpan.add(button);
            JOptionPane.showConfirmDialog(null, jpan, "Chart d'volution des consultations",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        }
    }
    if (a == 1 && (b == 3)) {
        Object[] options2 = { "Annuler", "Afficher la Statistique" };
        int c = JOptionPane.showOptionDialog(null, chStat2, "", JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE, null, options2, options[0]);
        if (c == 1) {
            java.util.Date d1 = chStat2.jDateDebut.getCalendar().getTime();
            java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
            java.util.Date d2 = chStat2.jDatefin.getCalendar().getTime();
            java.sql.Date sqlDate2 = new java.sql.Date(d2.getTime());
            Charts charts = new Charts();
            //     JFreeChart chrt = ChartFactory.createXYStepAreaChart(null, null, null, null, PlotOrientation.HORIZONTAL, rootPaneCheckingEnabled, rootPaneCheckingEnabled, rootPaneCheckingEnabled)
            XYSeriesCollection dataxy = charts.createDatasetRes(sqlDate.toString(), sqlDate2.toString(), idd);
            final JFreeChart chart = ChartFactory.createXYLineChart(
                    "Evolution des Consultation par rapport au temps", "Jours", "Nombre des Reservations",
                    dataxy, PlotOrientation.VERTICAL, true, true, false);
            XYItemRenderer rend = chart.getXYPlot().getRenderer();

            ChartPanel crepart = new ChartPanel(chart);
            Plot plot = chart.getPlot();

            JPanel jpan = new JPanel();
            jpan.setLayout(new FlowLayout(FlowLayout.LEADING));
            JButton button = new JButton();

            button.setText("Sauvegarder");
            button.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        JFileChooser chooser = new JFileChooser();
                        chooser.showSaveDialog(jPanel3);
                        String path = chooser.getSelectedFile().getPath();
                        if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                            path = path + ".png";
                        }
                        File f = new File(path);
                        ChartUtilities.saveChartAsPNG(new File(path), chart, 800, 600);

                        if (f.exists() && !f.isDirectory()) {
                            JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                            Desktop.getDesktop().open(f);
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });

            jpan.add(crepart);
            jpan.add(button);
            JOptionPane.showConfirmDialog(null, jpan, "Test", JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.PLAIN_MESSAGE);
        }

    }
    if (a == 1 && b == 0) {
        ConsultationDAO cdao = ConsultationDAO.getInstance();
        DefaultPieDataset union = new DefaultPieDataset();
        union.setValue("Homme", cdao.consultationCounterByGender(false, idd));
        union.setValue("Femme", cdao.consultationCounterByGender(true, idd));

        final JFreeChart repart = ChartFactory.createPieChart3D("Rpartition par Sexe", union, true, true,
                false);
        ChartPanel crepart = new ChartPanel(repart);
        Plot plot = repart.getPlot();
        JPanel jpan = new JPanel();
        JButton button = new JButton("Sauvegarder");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    JFileChooser chooser = new JFileChooser();
                    chooser.showSaveDialog(jPanel3);
                    String path = chooser.getSelectedFile().getPath();
                    if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                        path = path + ".png";
                    }
                    File f = new File(path);
                    ChartUtilities.saveChartAsPNG(new File(path), repart, 800, 600);

                    if (f.exists() && !f.isDirectory()) {
                        JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                        Desktop.getDesktop().open(f);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        jpan.add(crepart);
        jpan.add(button);
        JOptionPane.showConfirmDialog(null, jpan, "", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

    }
    if (a == 1 && b == 1) {
        DefaultPieDataset union = new DefaultPieDataset();
        ReservationDAO dAO = ReservationDAO.getInstance();
        union.setValue("Homme", dAO.reservationCounterByGender(false, idd));
        union.setValue("Femme", dAO.reservationCounterByGender(true, idd));

        final JFreeChart repart = ChartFactory.createPieChart3D("Rpartition par Sexe", union, true, true,
                false);
        ChartPanel crepart = new ChartPanel(repart);
        Plot plot = repart.getPlot();
        JPanel jpan = new JPanel();
        JButton button = new JButton("Sauvegarder");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    JFileChooser chooser = new JFileChooser();
                    chooser.showSaveDialog(jPanel3);
                    String path = chooser.getSelectedFile().getPath();
                    if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                        path = path + ".png";
                    }
                    File f = new File(path);
                    ChartUtilities.saveChartAsPNG(new File(path), repart, 800, 600);

                    if (f.exists() && !f.isDirectory()) {
                        JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                        Desktop.getDesktop().open(f);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        jpan.add(crepart);
        jpan.add(button);
        JOptionPane.showConfirmDialog(null, jpan, "Chart de la rpartition des achat par sexe",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

    }
}

From source file:gtu._work.etc.EnglishTester.java

void browseOnlineDictionary() {
    try {/*from ww w .  j  a va  2  s  .  com*/
        String text = currentWordIndex.trim().toLowerCase();
        ClipboardUtil.getInstance().setContents(text);
        text = text.replace(" ", "%20");
        URI uri = new URI("http://www.thefreedictionary.com/" + text);
        Desktop.getDesktop().browse(uri);
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}

From source file:sdf_manager.ExporterSiteHTML.java

/**
 *
 * @return//from w w  w .j  av a  2  s .co  m
 */
public Document processDatabase() {
    OutputStream os = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        SDF_Util.getProperties();
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();

        Iterator itrSites = this.sitecodes.iterator();
        int flush = 0;
        ExporterSiteHTML.log.info("Parsing sitecodes...");

        Document doc = docBuilder.newDocument();
        Element sdfs = doc.createElement("sdfs");
        doc.appendChild(sdfs);

        while (itrSites.hasNext()) {
            Element sdf = doc.createElement("sdf");
            Element siteIdentification = doc.createElement("siteIdentification");

            Site site = (Site) session.get(Site.class, (String) itrSites.next()); // results.get(i);

            siteIdentification.appendChild(doc.createElement("siteType"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteType(), "siteType")));
            siteIdentification.appendChild(doc.createElement("siteCode"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteCode().toUpperCase(), "siteCode")));
            ExporterSiteHTML.log.info("Parsing sitecode:::" + site.getSiteCode());
            siteIdentification.appendChild(doc.createElement("siteName"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteName(), "siteName")));

            if (site.getSiteCompDate() != null) {
                siteIdentification.appendChild(doc.createElement("compilationDate"))
                        .appendChild(doc.createTextNode(
                                fmt(SDF_Util.getFormatDateToXML(site.getSiteCompDate()), "compilationDate")));
            }

            if (site.getSiteUpdateDate() != null) {
                siteIdentification.appendChild(doc.createElement("updateDate")).appendChild(doc.createTextNode(
                        fmt(SDF_Util.getFormatDateToXML(site.getSiteUpdateDate()), "updateDate")));
            }

            Resp resp = site.getResp();
            if (resp != null) {

                Element respNode = doc.createElement("respondent");
                respNode.appendChild(doc.createElement("name"))
                        .appendChild(doc.createTextNode(fmt(resp.getRespName(), "respName")));
                if (resp.getRespAddressArea() != null && !resp.getRespAddressArea().equals("")) {

                    Element addresElem = doc.createElement("address");

                    // THE NAME DOES NOT MATCH THEIR RESPECTIVES
                    addresElem.appendChild(doc.createElement("adminUnit"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespAdminUnit(), "adminUnit")));
                    addresElem.appendChild(doc.createElement("thoroughfare"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespLocatorName(), "locatorName")));
                    addresElem.appendChild(doc.createElement("locatorDesignator"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespThoroughFare(), "thoroughfare")));
                    addresElem.appendChild(doc.createElement("postCode"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespAddressArea(), "addressArea")));
                    addresElem.appendChild(doc.createElement("postName"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespPostName(), "postName")));
                    addresElem.appendChild(doc.createElement("addressArea"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespPostCode(), "postCode")));
                    addresElem.appendChild(doc.createElement("locatorName")).appendChild(
                            doc.createTextNode(fmt(resp.getRespLocatorDesig(), "locatorDesignator")));
                    respNode.appendChild(addresElem);

                } else {
                    Element addresElem = doc.createElement("address");
                    addresElem.appendChild(doc.createElement("addressArea"))
                            .appendChild(doc.createTextNode(fmt(resp.getRespAddress(), "addressArea")));
                    respNode.appendChild(addresElem);
                }

                respNode.appendChild(doc.createElement("email"))
                        .appendChild(doc.createTextNode(fmt(resp.getRespEmail(), "respEmail")));
                siteIdentification.appendChild(respNode);
            }

            if (SDF_ManagerApp.isEmeraldMode()) {
                XmlGenerationUtils.appendDateElement(site.getSiteProposedAsciDate(), siteIdentification,
                        "asciProposalDate", doc);
                if (site.getSiteProposedAsciDate() == null) {
                    XmlGenerationUtils.appendDateElement(XmlGenerationUtils.nullDate(), siteIdentification,
                            "asciProposalDate", doc);
                }
                XmlGenerationUtils.appendDateElement(site.getSiteConfirmedCandidateAsciDate(),
                        siteIdentification, "asciConfirmedCandidateDate", doc);
                XmlGenerationUtils.appendDateElement(site.getSiteConfirmedAsciDate(), siteIdentification,
                        "asciConfirmationDate", doc);
                XmlGenerationUtils.appendDateElement(site.getSiteDesignatedAsciDate(), siteIdentification,
                        "asciDesignationDate", doc);

                siteIdentification.appendChild(doc.createElement("asciLegalReference"))
                        .appendChild(doc.createTextNode(fmt(site.getSiteAsciLegalRef(), "asciLegalReference")));

            } else {

                if (site.getSiteSpaDate() != null) {
                    siteIdentification.appendChild(doc.createElement("spaClassificationDate")).appendChild(
                            doc.createTextNode(fmt(SDF_Util.getFormatDateToXML(site.getSiteSpaDate()),
                                    "spaClassificationDate")));
                } else {
                    siteIdentification.appendChild(doc.createElement("spaClassificationDate"))
                            .appendChild(doc.createTextNode(fmt("0000-00", "spaClassificationDate")));
                }

                siteIdentification.appendChild(doc.createElement("spaLegalReference"))
                        .appendChild(doc.createTextNode(fmt(site.getSiteSpaLegalRef(), "spaLegalReference")));

                if (site.getSiteSciPropDate() != null) {
                    siteIdentification.appendChild(doc.createElement("sciProposalDate")).appendChild(
                            doc.createTextNode(fmt(SDF_Util.getFormatDateToXML(site.getSiteSciPropDate()),
                                    "sciProposalDate")));
                }

                if (site.getSiteSciConfDate() != null) {
                    siteIdentification.appendChild(doc.createElement("sciConfirmationDate")).appendChild(
                            doc.createTextNode(fmt(SDF_Util.getFormatDateToXML(site.getSiteSciConfDate()),
                                    "sciConfirmationDate")));
                }

                if (site.getSiteSacDate() != null) {
                    siteIdentification.appendChild(doc.createElement("sacDesignationDate")).appendChild(
                            doc.createTextNode(fmt(SDF_Util.getFormatDateToXML(site.getSiteSacDate()),
                                    "sacDesignationDate")));
                }

                siteIdentification.appendChild(doc.createElement("sacLegalReference"))
                        .appendChild(doc.createTextNode(fmt(site.getSiteSacLegalRef(), "sacLegalReference")));

            }
            siteIdentification.appendChild(doc.createElement("explanations"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteExplanations(), "explanations")));
            sdf.appendChild(siteIdentification);

            /**************LOCATION***************/

            Element location = doc.createElement("siteLocation");
            location.appendChild(doc.createElement("longitude"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteLongitude(), "longitude")));
            location.appendChild(doc.createElement("latitude"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteLatitude(), "latitude")));
            location.appendChild(doc.createElement("area"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteArea(), "area")));
            location.appendChild(doc.createElement("marineAreaPercentage"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteMarineArea(), "marineArea")));
            location.appendChild(doc.createElement("siteLength"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteLength(), "siteLength")));

            /*regions*/
            Element regions = doc.createElement("adminRegions");
            Set siteRegions = site.getRegions();
            Iterator itr = siteRegions.iterator();
            while (itr.hasNext()) {
                Region r = (Region) itr.next();
                Element rElem = doc.createElement("region");
                rElem.appendChild(doc.createElement("code"))
                        .appendChild(doc.createTextNode(fmt(r.getRegionCode(), "regionCode")));
                //descomentado--> adaptar nuevo xml
                rElem.appendChild(doc.createElement("name"))
                        .appendChild(doc.createTextNode(fmt(r.getRegionName(), "regionName")));
                regions.appendChild(rElem);
            }
            //adaptacion al nuevo xml
            location.appendChild(regions);

            /*bioregions*/
            Element biogeoRegions = doc.createElement("biogeoRegions");
            Set siteBioRegions = site.getSiteBiogeos();
            if (!(siteBioRegions.isEmpty())) {
                Iterator itbr = siteBioRegions.iterator();
                while (itbr.hasNext()) {
                    SiteBiogeo s = (SiteBiogeo) itbr.next();
                    Element biogeoElement = doc.createElement("biogeoRegions");
                    Biogeo b = s.getBiogeo();
                    //this XMl doesn't need validate, so it's better to use bioregion name instead bioregion code
                    biogeoElement.appendChild(doc.createElement("code"))
                            .appendChild(doc.createTextNode(fmt(b.getBiogeoName(), "bioRegionCode")));
                    biogeoElement.appendChild(doc.createElement("percentage"))
                            .appendChild(doc.createTextNode(fmt(s.getBiogeoPercent(), "biogeoPercent")));
                    location.appendChild(biogeoElement);
                }

            }

            sdf.appendChild(location);

            /********ECOLOGICAL INFORMATION***********/
            //adptacion nuevo XML
            Element ecologicalInformation = doc.createElement("ecologicalInformation");

            /************HABITATS****************/
            Element habitatsTypes = doc.createElement("habitatTypes");

            Set siteHabs = site.getHabitats();
            itr = siteHabs.iterator();
            while (itr.hasNext()) {
                Habitat h = (Habitat) itr.next();
                Element hElem = doc.createElement("habitatType");
                hElem.appendChild(doc.createElement("code"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatCode(), "habitatCode")));
                hElem.appendChild(doc.createElement("priorityFormOfHabitatType")).appendChild(
                        doc.createTextNode(fmt(toBoolean(h.getHabitatPriority()), "habitatPriority")));
                hElem.appendChild(doc.createElement("nonPresenceInSite"))
                        .appendChild(doc.createTextNode(fmt(toBoolean(h.getHabitatNp()), "habitatNp")));
                hElem.appendChild(doc.createElement("coveredArea"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatCoverHa(), "habitatCover")));
                hElem.appendChild(doc.createElement("caves"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatCaves(), "habitatCaves")));

                hElem.appendChild(doc.createElement("observationDataQuality"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatDataQuality(), "habitatDataQuality")));
                hElem.appendChild(doc.createElement("representativity")).appendChild(
                        doc.createTextNode(fmt(h.getHabitatRepresentativity(), "habitatRepresentativity")));
                hElem.appendChild(doc.createElement("relativeSurface"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatRelativeSurface(), "relativeSurface")));
                hElem.appendChild(doc.createElement("conservation")).appendChild(
                        doc.createTextNode(fmt(h.getHabitatConservation(), "habitatConservation")));
                hElem.appendChild(doc.createElement("global"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatGlobal(), "habitatGlobal")));

                habitatsTypes.appendChild(hElem);

            }
            ecologicalInformation.appendChild(habitatsTypes);

            /************SPECIES****************/
            Element specieses = doc.createElement("species");
            Set siteSpecies = site.getSpecieses();
            itr = siteSpecies.iterator();
            while (itr.hasNext()) {

                Species s = (Species) itr.next();
                Element sElem = doc.createElement("speciesPopulation");
                sElem.appendChild(doc.createElement("speciesGroup"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesGroup(), "speciesGroup")));
                sElem.appendChild(doc.createElement("speciesCode"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesCode(), "speciesCode")));
                sElem.appendChild(doc.createElement("scientificName"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesName(), "speciesName")));

                sElem.appendChild(doc.createElement("sensitiveInfo")).appendChild(
                        doc.createTextNode(fmt(toBoolean(s.getSpeciesSensitive()), "speciesSensitive")));
                sElem.appendChild(doc.createElement("nonPresenceInSite"))
                        .appendChild(doc.createTextNode(fmt(toBoolean(s.getSpeciesNp()), "speciesNP")));
                sElem.appendChild(doc.createElement("populationType"))
                        .appendChild(doc.createTextNode(fmtToLowerCase(s.getSpeciesType(), "speciesType")));

                Element popElem = doc.createElement("populationSize");
                popElem.appendChild(doc.createElement("lowerBound"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesSizeMin(), "speciesSizeMin")));
                popElem.appendChild(doc.createElement("upperBound"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesSizeMax(), "speciesSizeMax")));
                popElem.appendChild(doc.createElement("countingUnit"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesUnit(), "speciesUnit")));
                sElem.appendChild(popElem);

                if (s.getSpeciesCategory() != null) {
                    if (!("").equals(s.getSpeciesCategory().toString())) {
                        sElem.appendChild(doc.createElement("abundanceCategory")).appendChild(
                                doc.createTextNode(fmtToUpperCase(s.getSpeciesCategory(), "speciesCategory")));
                    }
                }

                sElem.appendChild(doc.createElement("dataQuality"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesDataQuality(), "speciesQuality")));
                // sElem.appendChild(doc.createElement("observationDataQuality")).appendChild(doc.createTextNode(fmt(s.getSpeciesDataQuality(), "speciesQuality")));
                sElem.appendChild(doc.createElement("population"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesPopulation(), "speciesPopulation")));
                sElem.appendChild(doc.createElement("conservation")).appendChild(
                        doc.createTextNode(fmt(s.getSpeciesConservation(), "speciesConservation")));

                sElem.appendChild(doc.createElement("isolation"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesIsolation(), "speciesIsolation")));
                sElem.appendChild(doc.createElement("global"))
                        .appendChild(doc.createTextNode(fmt(s.getSpeciesGlobal(), "speciesGlobal")));

                specieses.appendChild(sElem);
            }

            siteSpecies = site.getOtherSpecieses();
            itr = siteSpecies.iterator();
            while (itr.hasNext()) {

                OtherSpecies s = (OtherSpecies) itr.next();
                Element sElem = doc.createElement("speciesPopulation");

                sElem.appendChild(doc.createElement("speciesGroup"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesGroup(), "ospeciesGroup")));
                sElem.appendChild(doc.createElement("speciesCode"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesCode(), "ospeciesCode")));
                sElem.appendChild(doc.createElement("scientificName"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesName(), "ospeciesName")));
                sElem.appendChild(doc.createElement("sensitiveInfo")).appendChild(
                        doc.createTextNode(fmt(toBoolean(s.getOtherSpeciesSensitive()), "ospeciesSensitive")));

                if (s.getOtherSpeciesNp() != null) {
                    if (!(("").equals(s.getOtherSpeciesNp().toString()))) {
                        sElem.appendChild(doc.createElement("nonPresenceInSite")).appendChild(
                                doc.createTextNode(fmt(toBoolean(s.getOtherSpeciesNp()), "ospeciesNP")));
                    }
                }

                Element popElem = doc.createElement("populationSize");
                popElem.appendChild(doc.createElement("lowerBound"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesSizeMin(), "speciesSizeMin")));
                popElem.appendChild(doc.createElement("upperBound"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesSizeMax(), "speciesSizeMax")));
                popElem.appendChild(doc.createElement("countingUnit"))
                        .appendChild(doc.createTextNode(fmt(s.getOtherSpeciesUnit(), "speciesUnit")));
                sElem.appendChild(popElem);
                if (s.getOtherSpeciesCategory() != null) {
                    if (!(("").equals(s.getOtherSpeciesCategory().toString()))) {
                        sElem.appendChild(doc.createElement("abundanceCategory")).appendChild(
                                doc.createTextNode(fmt(s.getOtherSpeciesCategory(), "ospeciesCategory")));
                    }

                }

                //modificar porque es un tree primero es motivations y despues el nodo motivation (solo en el caso que haya motivations es other species en caso contrario
                //es species
                if (s.getOtherSpeciesMotivation() != null && !(("").equals(s.getOtherSpeciesMotivation()))) {
                    Element sElemMot = doc.createElement("motivations");

                    String strMotivation = s.getOtherSpeciesMotivation();
                    StringTokenizer st2 = new StringTokenizer(strMotivation, ",");

                    while (st2.hasMoreElements()) {
                        String mot = (String) st2.nextElement();
                        sElemMot.appendChild(doc.createElement("motivation"))
                                .appendChild(doc.createTextNode(fmt(mot, "ospeciesMotivation")));
                        sElem.appendChild(sElemMot);
                    }
                }

                specieses.appendChild(sElem);
            }
            ecologicalInformation.appendChild(specieses);

            sdf.appendChild(ecologicalInformation);

            /**************DESCRIPTION***********************/
            Element description = doc.createElement("siteDescription");
            Set classes = site.getHabitatClasses();
            itr = classes.iterator();

            while (itr.hasNext()) {
                HabitatClass h = (HabitatClass) itr.next();
                Element cElem = doc.createElement("habitatClass");
                cElem.appendChild(doc.createElement("code"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatClassCode(), "habitatClassCode")));
                cElem.appendChild(doc.createElement("coveragePercentage"))
                        .appendChild(doc.createTextNode(fmt(h.getHabitatClassCover(), "habitatClassCover")));
                description.appendChild(cElem);
            }

            description.appendChild(doc.createElement("otherSiteCharacteristics")).appendChild(
                    doc.createTextNode(fmt(site.getSiteCharacteristics(), "otherSiteCharacteristics")));
            description.appendChild(doc.createElement("qualityAndImportance"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteQuality(), "qualityAndImportance")));
            Element impacts = doc.createElement("impacts");
            Set siteImpacts = site.getImpacts();
            itr = siteImpacts.iterator();

            while (itr.hasNext()) {

                Element iElem = doc.createElement("impact");
                Impact im = (Impact) itr.next();
                iElem.appendChild(doc.createElement("code"))
                        .appendChild(doc.createTextNode(fmt(im.getImpactCode(), "impactCode")));

                iElem.appendChild(doc.createElement("rank"))
                        .appendChild(doc.createTextNode(fmt(im.getImpactRank(), "impactRank")));

                if (im.getImpactPollutionCode() != null) {
                    if (!("").equals(im.getImpactPollutionCode().toString())) {
                        iElem.appendChild(doc.createElement("pollutionCode")).appendChild(
                                doc.createTextNode(fmt(im.getImpactPollutionCode(), "impactPollution")));
                    }

                }

                iElem.appendChild(doc.createElement("occurrence"))
                        .appendChild(doc.createTextNode(fmt(im.getImpactOccurrence(), "impactOccurrece")));

                String impacType = "";
                if (im.getImpactType() != null) {
                    if (("P").equals(im.getImpactType().toString())) {
                        impacType = "Positive";
                    } else {
                        impacType = "Negative";
                    }
                }
                iElem.appendChild(doc.createElement("natureOfImpact"))
                        .appendChild(doc.createTextNode(fmt(impacType, "natureOfImpact")));
                impacts.appendChild(iElem);
            }

            description.appendChild(impacts);

            Element ownership = doc.createElement("ownership");
            Set owners = site.getSiteOwnerships();
            itr = owners.iterator();
            while (itr.hasNext()) {
                SiteOwnership o = (SiteOwnership) itr.next();
                Ownership o2 = o.getOwnership();
                Element oElem = doc.createElement("ownershipPart");
                oElem.appendChild(doc.createElement("ownershiptype"))
                        .appendChild(doc.createTextNode(fmt(o2.getOwnershipCode(), "ownershipType")));
                oElem.appendChild(doc.createElement("percent"))
                        .appendChild(doc.createTextNode(fmt(o.getOwnershipPercent(), "ownershipPercent")));
                ownership.appendChild(oElem);
            }

            description.appendChild(ownership);

            Element documentation = doc.createElement("documentation");
            Doc docObj = site.getDoc();
            if (docObj != null) {

                documentation.appendChild(doc.createElement("description"))
                        .appendChild(doc.createTextNode(fmt(docObj.getDocDescription(), "docDescription")));
                Set docLinks = docObj.getDocLinks();
                itr = docLinks.iterator();
                Element links = doc.createElement("links");
                while (itr.hasNext()) {
                    DocLink docLink = (DocLink) itr.next();
                    links.appendChild(doc.createElement("link"))
                            .appendChild(doc.createTextNode(fmt(docLink.getDocLinkUrl(), "linkURL")));
                }
                documentation.appendChild(links);
                description.appendChild(documentation);
            }
            sdf.appendChild(description);

            /********PROTECTION**********/
            Element protection = doc.createElement("siteProtection");

            Element natDesigs = doc.createElement("nationalDesignations");
            Set dsigs = site.getNationalDtypes();
            itr = dsigs.iterator();
            while (itr.hasNext()) {
                NationalDtype dtype = (NationalDtype) itr.next();
                Element nElem = doc.createElement("nationalDesignation");
                nElem.appendChild(doc.createElement("designationCode"))
                        .appendChild(doc.createTextNode(fmt(dtype.getNationalDtypeCode(), "dtypecode")));
                nElem.appendChild(doc.createElement("cover"))
                        .appendChild(doc.createTextNode(fmt(dtype.getNationalDtypeCover(), "dtypecover")));
                natDesigs.appendChild(nElem);
            }
            protection.appendChild(natDesigs);

            Set rels = site.getSiteRelations();
            if (!rels.isEmpty()) {
                Element relations = doc.createElement("relations");
                Element nationalRelations = doc.createElement("nationalRelationships");
                Element internationalRelations = doc.createElement("internationalRelationships");

                itr = rels.iterator();
                while (itr.hasNext()) {

                    SiteRelation rel = (SiteRelation) itr.next();
                    Element rElem;
                    Character scope = rel.getSiteRelationScope();

                    if (("N").equals(scope.toString())) {
                        rElem = doc.createElement("nationalRelationship");
                        rElem.appendChild(doc.createElement("designationCode")).appendChild(
                                doc.createTextNode(fmt(rel.getSiteRelationCode(), "relationCode")));
                        nationalRelations.appendChild(rElem);
                    } else if (("I").equals(scope.toString())) {
                        rElem = doc.createElement("internationalRelationship");
                        rElem.appendChild(doc.createElement("convention")).appendChild(
                                doc.createTextNode(fmt(rel.getSiteRelationConvention(), "relationConvention")));
                        internationalRelations.appendChild(rElem);
                    } else {
                        //                            log("Relation type undefined, ignoring relation: " + scope.toString());
                        continue;
                    }
                    rElem.appendChild(doc.createElement("siteName")).appendChild(
                            doc.createTextNode(fmt(rel.getSiteRelationSitename(), "relationSite")));
                    rElem.appendChild(doc.createElement("type"))
                            .appendChild(doc.createTextNode(fmt(rel.getSiteRelationType(), "relationType")));
                    rElem.appendChild(doc.createElement("cover"))
                            .appendChild(doc.createTextNode(fmt(rel.getSiteRelationCover(), "relationCover")));
                }
                relations.appendChild(nationalRelations);
                relations.appendChild(internationalRelations);

                protection.appendChild(relations);
            }

            protection.appendChild(doc.createElement("siteDesignationAdditional"))
                    .appendChild(doc.createTextNode(fmt(site.getSiteDesignation(), "siteDesignation")));
            sdf.appendChild(protection);

            /******************MANAGEMENT************************/

            Element mgmtElem = doc.createElement("siteManagement");
            Mgmt mgmt = site.getMgmt();
            if (mgmt != null) {
                // Management Body
                Set bodies = mgmt.getMgmtBodies();
                itr = bodies.iterator();
                Element bodiesElem = doc.createElement("managementBodies");
                while (itr.hasNext()) {

                    MgmtBody bodyObj = (MgmtBody) itr.next();
                    Element bElem = doc.createElement("managementBody");
                    bElem.appendChild(doc.createElement("organisation"))
                            .appendChild(doc.createTextNode(fmt(bodyObj.getMgmtBodyOrg(), "mgmtBodyOrg")));
                    //if el campo addressunestructured esta vacio entonces addres es un tipo complejo (implementar) en caso contrario
                    if (bodyObj.getMgmtBodyAddressArea() != null
                            && !bodyObj.getMgmtBodyAddressArea().equals("")) {
                        Element addresElem = doc.createElement("address");

                        addresElem.appendChild(doc.createElement("adminUnit")).appendChild(
                                doc.createTextNode(fmt(bodyObj.getMgmtBodyAdminUnit(), "adminUnit") + "  "));
                        addresElem.appendChild(doc.createElement("locatorDesignator")).appendChild(doc
                                .createTextNode(fmt(bodyObj.getMgmtBodyThroughFare(), "thoroughfare") + "  "));
                        addresElem.appendChild(doc.createElement("locatorName")).appendChild(doc.createTextNode(
                                fmt(bodyObj.getMgmtBodyLocatorDesignator(), "locatorDesignator") + "  "));
                        addresElem.appendChild(doc.createElement("addressArea")).appendChild(
                                doc.createTextNode(fmt(bodyObj.getMgmtBodyPostCode(), "postCode") + "  "));
                        addresElem.appendChild(doc.createElement("postName")).appendChild(
                                doc.createTextNode(fmt(bodyObj.getMgmtBodyPostName(), "postName") + "  "));
                        addresElem.appendChild(doc.createElement("postCode")).appendChild(doc
                                .createTextNode(fmt(bodyObj.getMgmtBodyAddressArea(), "addressArea") + "  "));
                        addresElem.appendChild(doc.createElement("thoroughfare")).appendChild(doc
                                .createTextNode(fmt(bodyObj.getMgmtBodyLocatorName(), "locatorName") + "  "));

                        bElem.appendChild(addresElem);
                    } else {
                        Element addresElem = doc.createElement("address");
                        addresElem.appendChild(doc.createElement("addressArea")).appendChild(
                                doc.createTextNode(fmt(bodyObj.getMgmtBodyAddress(), "addressArea")));
                        bElem.appendChild(addresElem);
                    }

                    bElem.appendChild(doc.createElement("email"))
                            .appendChild(doc.createTextNode(fmt(bodyObj.getMgmtBodyEmail(), "mgmtBodyMail")));
                    bodiesElem.appendChild(bElem);
                }
                mgmtElem.appendChild(bodiesElem);

                // Management Plan

                Character status = mgmt.getMgmtStatus();
                Element mgmtExists = (Element) mgmtElem.appendChild(doc.createElement("exists"));
                if (status != null) {
                    mgmtExists
                            .appendChild(doc.createTextNode(fmt(Character.toUpperCase(status), "mgmtExists")));
                }
                Set plans = mgmt.getMgmtPlans();
                itr = plans.iterator();
                Element plansElem = doc.createElement("managementPlans");
                plansElem.appendChild(mgmtExists);
                while (itr.hasNext()) {
                    MgmtPlan planObj = (MgmtPlan) itr.next();
                    Element pElem = doc.createElement("managementPlan");
                    pElem.appendChild(doc.createElement("name"))
                            .appendChild(doc.createTextNode(fmt(planObj.getMgmtPlanName(), "mgmtPlanName")));
                    pElem.appendChild(doc.createElement("url"))
                            .appendChild(doc.createTextNode(fmt(planObj.getMgmtPlanUrl(), "mgmtPlanUrl")));
                    plansElem.appendChild(pElem);
                }
                mgmtElem.appendChild(plansElem);

                mgmtElem.appendChild(doc.createElement("conservationMeasures")).appendChild(
                        doc.createTextNode(fmt(mgmt.getMgmtConservMeasures(), "conservationMeasures")));
            }
            sdf.appendChild(mgmtElem);

            Map map = site.getMap();
            Element mapElem = doc.createElement("map");
            if (map != null) {
                mapElem.appendChild(doc.createElement("InspireID"))
                        .appendChild(doc.createTextNode(fmt(map.getMapInspire(), "mapInspireID")));

                Boolean bMap;
                if (map.getMapPdf() != null && map.getMapPdf().equals(Short.valueOf("1"))) {
                    bMap = true;
                } else {
                    bMap = false;
                }
                mapElem.appendChild(doc.createElement("pdfProvided"))
                        .appendChild(doc.createTextNode(fmt(bMap, "mapPDF")));
                mapElem.appendChild(doc.createElement("mapReference"))
                        .appendChild(doc.createTextNode(fmt(map.getMapReference(), "mapRef")));
            }
            sdf.appendChild(mapElem);

            if (flush++ % 100 == 0) {
                session.clear();
            }
            sdfs.appendChild(sdf);
        }

        //All the data is stored in the node instead of the document.
        Source source = new DOMSource(doc);

        // File file = new File(this.fileName);
        File file = new File("xsl" + File.separator + this.siteCode + ".html");

        Result result = new StreamResult(file.toURI().getPath());

        TransformerFactory tFactory = TransformerFactory.newInstance();
        String xslFileName = SDF_ManagerApp.isEmeraldMode() ? "EmeraldSiteXSL.xsl" : "SiteXSL.xsl";

        Source xsl = new StreamSource("." + File.separator + "xsl" + File.separator + xslFileName);
        Templates template = tFactory.newTemplates(xsl);
        Transformer transformer = template.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        //transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS,
                "siteName name otherSiteCharacteristics"
                        + " qualityAndImportance selectiveBasis derogationJustification comments "
                        + "location licensedJustification licensingAuthority licenseValidFrom licenseValidUntil otherType "
                        + "method activity reason");

        transformer.transform(source, result);

        String pdfPath = new File("").getAbsolutePath() + File.separator + "xsl" + File.separator
                + this.siteCode + ".pdf";
        // File inputFile = new File(this.fileName);
        File inputFile = new File("xsl" + File.separator + this.siteCode + ".html");
        os = new FileOutputStream(new File(pdfPath));

        ITextRenderer renderer = new ITextRenderer();
        FontFactory.register("resources/fonts");

        renderer.setDocument(inputFile);
        renderer.layout();
        renderer.createPDF(os);

        Desktop desktop = null;
        // Before more Desktop API is used, first check
        // whether the API is supported by this particular
        // virtual machine (VM) on this particular host.
        if (Desktop.isDesktopSupported()) {
            desktop = Desktop.getDesktop();
            Desktop.getDesktop().open(file);
        }
        return null;
    } catch (TransformerConfigurationException e) {
        ExporterSiteHTML.log
                .error("A TransformerConfigurationException has occurred in processDatabase. Error Message:::"
                        + e.getMessage());
        return null;
    } catch (TransformerException e) {
        ExporterSiteHTML.log.error(
                "A TransformerException has occurred in processDatabase. Error Message:::" + e.getMessage());
        return null;
    } catch (FileNotFoundException e) {
        ExporterSiteHTML.log.error(
                "A FileNotFoundException has occurred in processDatabase. Error Message:::" + e.getMessage());
        return null;
    } catch (IOException e) {
        ExporterSiteHTML.log
                .error("An IOException has occurred in processDatabase. Error Message:::" + e.getMessage());
        return null;
    } catch (Exception e) {
        ExporterSiteHTML.log.error(
                "A general exception has occurred in processDatabase. Error Message:::" + e.getMessage());
        return null;
    } finally {
        IOUtils.closeQuietly(os);
        session.close();
    }

}

From source file:editeurpanovisu.EditeurPanovisu.java

private void genereVisite() throws IOException {
    if (!repertSauveChoisi) {
        repertoireProjet = currentDir;//from   w w  w . ja va2s. c o m
    }
    if (!dejaSauve) {
        projetSauve();
    }
    if (dejaSauve) {
        deleteDirectory(repertTemp + "/panovisu/images");
        File imagesRepert = new File(repertTemp + "/panovisu/images");
        if (!imagesRepert.exists()) {
            imagesRepert.mkdirs();
        }
        File boutonRepert = new File(repertTemp + "/panovisu/images/navigation");
        if (!boutonRepert.exists()) {
            boutonRepert.mkdirs();
        }
        File boussoleRepert = new File(repertTemp + "/panovisu/images/boussoles");
        if (!boussoleRepert.exists()) {
            boussoleRepert.mkdirs();
        }
        copieDirectory(repertAppli + File.separator + "panovisu/images/boussoles",
                boussoleRepert.getAbsolutePath());
        File planRepert = new File(repertTemp + "/panovisu/images/plan");
        if (!planRepert.exists()) {
            planRepert.mkdirs();
        }
        copieDirectory(repertAppli + File.separator + "panovisu/images/plan", planRepert.getAbsolutePath());
        File reseauRepert = new File(repertTemp + "/panovisu/images/reseaux");
        if (!reseauRepert.exists()) {
            reseauRepert.mkdirs();
        }
        copieDirectory(repertAppli + File.separator + "panovisu/images/reseaux",
                reseauRepert.getAbsolutePath());
        File interfaceRepert = new File(repertTemp + "/panovisu/images/interface");
        if (!interfaceRepert.exists()) {
            interfaceRepert.mkdirs();
        }
        copieDirectory(repertAppli + File.separator + "panovisu/images/interface",
                interfaceRepert.getAbsolutePath());
        File MARepert = new File(repertTemp + "/panovisu/images/MA");
        if (!MARepert.exists()) {
            MARepert.mkdirs();
        }
        File hotspotsRepert = new File(repertTemp + "/panovisu/images/hotspots");
        if (!hotspotsRepert.exists()) {
            hotspotsRepert.mkdirs();
        }
        copieFichierRepertoire(repertAppli + File.separator + "panovisu" + File.separator + "images"
                + File.separator + "aide_souris.png", repertTemp + "/panovisu/images");
        copieFichierRepertoire(repertAppli + File.separator + "panovisu" + File.separator + "images"
                + File.separator + "fermer.png", repertTemp + "/panovisu/images");
        copieFichierRepertoire(repertAppli + File.separator + "panovisu" + File.separator + "images"
                + File.separator + "precedent.png", repertTemp + "/panovisu/images");
        copieFichierRepertoire(repertAppli + File.separator + "panovisu" + File.separator + "images"
                + File.separator + "suivant.png", repertTemp + "/panovisu/images");
        for (int i = 0; i < gestionnaireInterface.nombreImagesBouton - 1; i++) {
            ReadWriteImage.writePng(gestionnaireInterface.nouveauxBoutons[i],
                    boutonRepert.getAbsolutePath() + File.separator + gestionnaireInterface.nomImagesBoutons[i],
                    false, 0.f);
        }
        ReadWriteImage.writePng(
                gestionnaireInterface.nouveauxBoutons[gestionnaireInterface.nombreImagesBouton - 1],
                hotspotsRepert.getAbsolutePath() + File.separator + "hotspot.png", false, 0.f);
        ReadWriteImage.writePng(gestionnaireInterface.nouveauxBoutons[gestionnaireInterface.nombreImagesBouton],
                hotspotsRepert.getAbsolutePath() + File.separator + "hotspotImage.png", false, 0.f);
        ReadWriteImage.writePng(gestionnaireInterface.nouveauxMasque,
                MARepert.getAbsolutePath() + File.separator + "MA.png", false, 0.f);

        File xmlRepert = new File(repertTemp + File.separator + "xml");
        if (!xmlRepert.exists()) {
            xmlRepert.mkdirs();
        }
        File cssRepert = new File(repertTemp + File.separator + "css");
        if (!cssRepert.exists()) {
            cssRepert.mkdirs();
        }
        File jsRepert = new File(repertTemp + File.separator + "js");
        if (!jsRepert.exists()) {
            jsRepert.mkdirs();
        }
        String contenuFichier;
        File xmlFile;
        String chargeImages = "";

        for (int i = 0; i < nombrePanoramiques; i++) {
            String fPano = "panos/" + panoramiquesProjet[i].getNomFichier()
                    .substring(panoramiquesProjet[i].getNomFichier().lastIndexOf(File.separator) + 1,
                            panoramiquesProjet[i].getNomFichier().length())
                    .split("\\.")[0];
            if (panoramiquesProjet[i].getTypePanoramique().equals(Panoramique.CUBE)) {
                fPano = fPano.substring(0, fPano.length() - 2);
                chargeImages += "                images[" + i + "]=\"" + fPano + "_f.jpg\"\n";
                chargeImages += "                images[" + i + "]=\"" + fPano + "_b.jpg\"\n";
                chargeImages += "                images[" + i + "]=\"" + fPano + "_u.jpg\"\n";
                chargeImages += "                images[" + i + "]=\"" + fPano + "_d.jpg\"\n";
                chargeImages += "                images[" + i + "]=\"" + fPano + "_r.jpg\"\n";
                chargeImages += "                images[" + i + "]=\"" + fPano + "_l.jpg\"\n";
            } else {
                chargeImages += "                images[" + i + "]=\"" + fPano + ".jpg\"\n";
            }
            String affInfo = (panoramiquesProjet[i].isAfficheInfo()) ? "oui" : "non";
            String affTitre = (gestionnaireInterface.bAfficheTitre) ? "oui" : "non";
            double regX;
            double zN;
            if (panoramiquesProjet[i].getTypePanoramique().equals(Panoramique.SPHERE)) {
                regX = Math.round(((panoramiquesProjet[i].getLookAtX() - 180) % 360) * 10) / 10;
                zN = Math.round(((panoramiquesProjet[i].getZeroNord() - 180) % 360) * 10) / 10;
            } else {
                regX = Math.round(((panoramiquesProjet[i].getLookAtX() + 90) % 360) * 10) / 10;
                zN = Math.round(((panoramiquesProjet[i].getZeroNord() + 90) % 360) * 10) / 10;
            }
            int rouge = (int) (Color.valueOf(gestionnaireInterface.couleurDiaporama).getRed() * 255.d);
            int bleu = (int) (Color.valueOf(gestionnaireInterface.couleurDiaporama).getBlue() * 255.d);
            int vert = (int) (Color.valueOf(gestionnaireInterface.couleurDiaporama).getGreen() * 255.d);
            String coulDiapo = "rgba(" + rouge + "," + vert + "," + bleu + ","
                    + gestionnaireInterface.diaporamaOpacite + ")";

            Color coulTitre = Color.valueOf(gestionnaireInterface.couleurFondTitre);
            rouge = (int) (coulTitre.getRed() * 255.d);
            bleu = (int) (coulTitre.getBlue() * 255.d);
            vert = (int) (coulTitre.getGreen() * 255.d);
            String coulFondTitre = "rgba(" + rouge + "," + vert + "," + bleu + ","
                    + gestionnaireInterface.titreOpacite + ")";

            contenuFichier = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!--\n"
                    + "     Visite gnre par l'diteur panoVisu \n" + "\n"
                    + "             Cration L.LANG      le monde  360  : http://lemondea360.fr\n"
                    + "-->\n" + "\n" + "\n" + "<scene>\n" + "   <pano \n" + "      image=\"" + fPano + "\"\n"
                    + "      titre=\"" + panoramiquesProjet[i].getTitrePanoramique() + "\"\n"
                    + "      titrePolice=\"" + gestionnaireInterface.titrePoliceNom + "\"\n"
                    + "      titreTaillePolice=\""
                    + Math.round(Double.parseDouble(gestionnaireInterface.titrePoliceTaille)) + "px\"\n"
                    + "      titreTaille=\"" + Math.round(gestionnaireInterface.titreTaille) + "%\"\n"
                    + "      titreFond=\"" + coulFondTitre + "\"\n" + "      titreCouleur=\""
                    + gestionnaireInterface.couleurTitre + "\"\n"
                    //                        + "      titreOpacite=\"" + gestionnaireInterface.titreOpacite + "\"\n"
                    + "      diaporamaCouleur=\"" + coulDiapo + "\"\n" + "      type=\""
                    + panoramiquesProjet[i].getTypePanoramique() + "\"\n" + "      multiReso=\"oui\"\n"
                    + "      nombreNiveaux=\"" + panoramiquesProjet[i].getNombreNiveaux() + "\"\n"
                    + "      zeroNord=\"" + zN + "\"\n" + "      regardX=\"" + regX + "\"\n"
                    + "      regardY=\"" + Math.round(panoramiquesProjet[i].getLookAtY() * 10) / 10 + "\"\n"
                    + "      affinfo=\"" + affInfo + "\"\n" + "      afftitre=\"" + affTitre + "\"\n"
                    + "   />\n" + "   <!--Dfinition de la Barre de navigation-->\n" + "   <boutons \n"
                    + "      styleBoutons=\"navigation\"\n" + "      couleur=\"rgba(255,255,255,0)\"\n"
                    + "      bordure=\"rgba(255,255,255,0)\"\n" + "      deplacements=\""
                    + gestionnaireInterface.toggleBarreDeplacements + "\" \n" + "      zoom=\""
                    + gestionnaireInterface.toggleBarreZoom + "\" \n" + "      outils=\""
                    + gestionnaireInterface.toggleBarreOutils + "\"\n" + "      fs=\""
                    + gestionnaireInterface.toggleBoutonFS + "\" \n" + "      souris=\""
                    + gestionnaireInterface.toggleBoutonSouris + "\" \n" + "      rotation=\""
                    + gestionnaireInterface.toggleBoutonRotation + "\" \n" + "      positionX=\""
                    + gestionnaireInterface.positionBarre.split(":")[1] + "\"\n" + "      positionY=\""
                    + gestionnaireInterface.positionBarre.split(":")[0] + "\" \n" + "      dX=\""
                    + gestionnaireInterface.dXBarre + "\" \n" + "      dY=\"" + gestionnaireInterface.dYBarre
                    + "\"\n" + "      espacement=\"" + Math.round(gestionnaireInterface.espacementBoutons)
                    + "\"\n" + "      visible=\"" + gestionnaireInterface.toggleBarreVisibilite + "\"\n"
                    + "   />\n";
            if (gestionnaireInterface.bAfficheBoussole) {
                String SAiguille = (gestionnaireInterface.bAiguilleMobileBoussole) ? "oui" : "non";
                contenuFichier += "<!--  Boussole -->\n" + "    <boussole \n" + "        affiche=\"oui\"\n"
                        + "        image=\"" + gestionnaireInterface.imageBoussole + "\"\n"
                        + "        taille=\"" + gestionnaireInterface.tailleBoussole + "\"\n"
                        + "        positionY=\"" + gestionnaireInterface.positionBoussole.split(":")[0] + "\"\n"
                        + "        positionX=\"" + gestionnaireInterface.positionBoussole.split(":")[1] + "\"\n"
                        + "        opacite=\"" + gestionnaireInterface.opaciteBoussole + "\"\n"
                        + "        dX=\"" + gestionnaireInterface.dXBoussole + "\"\n" + "        dY=\""
                        + gestionnaireInterface.dYBoussole + "\"\n" + "        aiguille=\"" + SAiguille + "\"\n"
                        + "    />\n";
            }
            if (gestionnaireInterface.bAfficheMenuContextuel) {
                String SPrecSuiv = (gestionnaireInterface.bAffichePrecSuivMC) ? "oui" : "non";
                String SPlanet = (gestionnaireInterface.bAffichePlanetNormalMC) ? "oui" : "non";
                String SPers1 = (gestionnaireInterface.bAffichePersMC1) ? "oui" : "non";
                String SPers2 = (gestionnaireInterface.bAffichePersMC2) ? "oui" : "non";
                contenuFichier += "<!--  MenuContextuel -->\n" + "    <menuContextuel \n"
                        + "        affiche=\"oui\"\n" + "        precSuiv=\"" + SPrecSuiv + "\"\n"
                        + "        planete=\"" + SPlanet + "\"\n" + "        pers1=\"" + SPers1 + "\"\n"
                        + "        lib1=\"" + gestionnaireInterface.stPersLib1 + "\"\n" + "        url1=\""
                        + gestionnaireInterface.stPersURL1 + "\"\n" + "        pers2=\"" + SPers2 + "\"\n"
                        + "        lib2=\"" + gestionnaireInterface.stPersLib2 + "\"\n" + "        url2=\""
                        + gestionnaireInterface.stPersURL2 + "\"\n" + "    />\n";
            }
            if (gestionnaireInterface.bSuivantPrecedent) {

                int panoPrecedent = (i == nombrePanoramiques - 1) ? 0 : i + 1;
                int panoSuivant = (i == 0) ? nombrePanoramiques - 1 : i - 1;
                String nomPano = panoramiquesProjet[panoSuivant].getNomFichier();
                String strPanoSuivant = "xml/"
                        + nomPano.substring(nomPano.lastIndexOf(File.separator) + 1, nomPano.lastIndexOf("."))
                        + ".xml";
                nomPano = panoramiquesProjet[panoPrecedent].getNomFichier();
                String strPanoPrecedent = "xml/"
                        + nomPano.substring(nomPano.lastIndexOf(File.separator) + 1, nomPano.lastIndexOf("."))
                        + ".xml";
                contenuFichier += "<!--  Bouton Suivant Precedent -->\n" + "    <suivantPrecedent\n"
                        + "        suivant=\"" + strPanoSuivant + "\"            \n" + "        precedent=\""
                        + strPanoPrecedent + "\"            \n" + "    />    \n" + "";
            }
            if (gestionnaireInterface.bAfficheMasque) {
                String SNavigation = (gestionnaireInterface.bMasqueNavigation) ? "oui" : "non";
                String SBoussole = (gestionnaireInterface.bMasqueBoussole) ? "oui" : "non";
                String STitre = (gestionnaireInterface.bMasqueTitre) ? "oui" : "non";
                String splan = (gestionnaireInterface.bMasquePlan) ? "oui" : "non";
                String SReseaux = (gestionnaireInterface.bMasqueReseaux) ? "oui" : "non";
                String SVignettes = (gestionnaireInterface.bMasqueVignettes) ? "oui" : "non";
                contenuFichier += "<!--  Bouton de Masquage -->\n" + "    <marcheArret \n"
                        + "        affiche=\"oui\"\n" + "        image=\"MA.png\"\n" + "        taille=\""
                        + gestionnaireInterface.tailleMasque + "\"\n" + "        positionY=\""
                        + gestionnaireInterface.positionMasque.split(":")[0] + "\"\n" + "        positionX=\""
                        + gestionnaireInterface.positionMasque.split(":")[1] + "\"\n" + "        opacite=\""
                        + gestionnaireInterface.opaciteMasque + "\"\n" + "        dX=\""
                        + gestionnaireInterface.dXMasque + "\"\n" + "        dy=\""
                        + gestionnaireInterface.dYMasque + "\"\n" + "        navigation=\"" + SNavigation
                        + "\"\n" + "        boussole=\"" + SBoussole + "\"\n" + "        titre=\"" + STitre
                        + "\"\n" + "        plan=\"" + splan + "\"\n" + "        reseaux=\"" + SReseaux + "\"\n"
                        + "        vignettes=\"" + SVignettes + "\"\n" + "    />\n";
            }

            if (gestionnaireInterface.bAfficheReseauxSociaux) {
                String STwitter = (gestionnaireInterface.bReseauxSociauxTwitter) ? "oui" : "non";
                String SGoogle = (gestionnaireInterface.bReseauxSociauxGoogle) ? "oui" : "non";
                String SFacebook = (gestionnaireInterface.bReseauxSociauxFacebook) ? "oui" : "non";
                String SEmail = (gestionnaireInterface.bReseauxSociauxEmail) ? "oui" : "non";
                contenuFichier += "<!--  Rseaux Sociaux -->\n" + "    <reseauxSociaux \n"
                        + "        affiche=\"oui\"\n" + "        taille=\""
                        + gestionnaireInterface.tailleReseauxSociaux + "\"\n" + "        positionY=\""
                        + gestionnaireInterface.positionReseauxSociaux.split(":")[0] + "\"\n"
                        + "        positionX=\"" + gestionnaireInterface.positionReseauxSociaux.split(":")[1]
                        + "\"\n" + "        opacite=\"" + gestionnaireInterface.opaciteReseauxSociaux + "\"\n"
                        + "        dX=\"" + gestionnaireInterface.dXReseauxSociaux + "\"\n" + "        dY=\""
                        + gestionnaireInterface.dYReseauxSociaux + "\"\n" + "        twitter=\"" + STwitter
                        + "\"\n" + "        google=\"" + SGoogle + "\"\n" + "        facebook=\"" + SFacebook
                        + "\"\n" + "        email=\"" + SEmail + "\"\n" + "    />\n";
            }
            if (gestionnaireInterface.bAfficheVignettes) {
                String SAfficheVignettes = (gestionnaireInterface.bAfficheVignettes) ? "oui" : "non";
                contenuFichier += "<!-- Barre des vignettes -->" + "    <vignettes \n" + "        affiche=\""
                        + SAfficheVignettes + "\"\n" + "        tailleImage=\""
                        + gestionnaireInterface.tailleImageVignettes + "\"\n" + "        fondCouleur=\""
                        + gestionnaireInterface.couleurFondVignettes + "\"\n" + "        texteCouleur=\""
                        + gestionnaireInterface.couleurTexteVignettes + "\"\n" + "        opacite=\""
                        + gestionnaireInterface.opaciteVignettes + "\"\n" + "        position=\""
                        + gestionnaireInterface.positionVignettes + "\"\n" + "    >\n";
                for (int j = 0; j < nombrePanoramiques; j++) {
                    String nomPano = panoramiquesProjet[j].getNomFichier();
                    String nFichier = nomPano.substring(nomPano.lastIndexOf(File.separator) + 1,
                            nomPano.lastIndexOf(".")) + "Vignette.jpg";
                    String nXML = nomPano.substring(nomPano.lastIndexOf(File.separator) + 1,
                            nomPano.lastIndexOf(".")) + ".xml";
                    ReadWriteImage.writeJpeg(panoramiquesProjet[j].getVignettePanoramique(),
                            repertTemp + "/panos/" + nFichier, 1.0f, false, 0.0f);
                    contenuFichier += "        <imageVignette \n" + "            image=\"panos/" + nFichier
                            + "\"\n" + "            xml=\"xml/" + nXML + "\"\n" + "        />\n";
                }
                contenuFichier += "    </vignettes>       \n" + "";

            }

            contenuFichier += "    <!--Dfinition des hotspots-->  \n" + "   <hotspots>\n";
            for (int j = 0; j < panoramiquesProjet[i].getNombreHotspots(); j++) {
                HotSpot HS = panoramiquesProjet[i].getHotspot(j);
                double longit;
                if (panoramiquesProjet[i].getTypePanoramique().equals(Panoramique.SPHERE)) {
                    longit = HS.getLongitude() - 180;
                } else {
                    longit = HS.getLongitude() + 90;
                }
                String txtAnime = (HS.isAnime()) ? "true" : "false";
                contenuFichier += "      <point \n" + "           type=\"panoramique\"\n" + "           long=\""
                        + longit + "\"\n" + "           lat=\"" + HS.getLatitude() + "\"\n"
                        + "           image=\"panovisu/images/hotspots/hotspot.png\"\n"
                        + "           xml=\"xml/" + HS.getFichierXML() + "\"\n" + "           info=\""
                        + HS.getInfo() + "\"\n" + "           anime=\"" + txtAnime + "\"\n" + "      />\n";
            }
            for (int j = 0; j < panoramiquesProjet[i].getNombreHotspotImage(); j++) {
                HotspotImage HS = panoramiquesProjet[i].getHotspotImage(j);
                double longit;
                if (panoramiquesProjet[i].getTypePanoramique().equals(Panoramique.SPHERE)) {
                    longit = HS.getLongitude() - 180;
                } else {
                    longit = HS.getLongitude() + 90;
                }
                String txtAnime = (HS.isAnime()) ? "true" : "false";
                contenuFichier += "      <point \n" + "           type=\"image\"\n" + "           long=\""
                        + longit + "\"\n" + "           lat=\"" + HS.getLatitude() + "\"\n"
                        + "           image=\"panovisu/images/hotspots/hotspotImage.png\"\n"
                        + "           img=\"images/" + HS.getLienImg() + "\"\n" + "           info=\""
                        + HS.getInfo() + "\"\n" + "           anime=\"" + txtAnime + "\"\n" + "      />\n";
            }
            contenuFichier += "   </hotspots>\n";
            contenuFichier += "\n" + "<!-- Dfinition des images de fond -->\n" + "\n";
            if (gestionnaireInterface.nombreImagesFond > 0) {
                for (int ii = 0; ii < gestionnaireInterface.nombreImagesFond; ii++) {
                    ImageFond imgFond = gestionnaireInterface.imagesFond[ii];
                    String strImgFond = "images/" + imgFond.getFichierImage().substring(
                            imgFond.getFichierImage().lastIndexOf(File.separator) + 1,
                            imgFond.getFichierImage().length());
                    String SMasquable = (imgFond.isMasquable()) ? "oui" : "non";

                    contenuFichier += "    <imageFond\n" + "        fichier=\"" + strImgFond + "\"\n"
                            + "        posX=\"" + imgFond.getPosX() + "\" \n" + "        posY=\""
                            + imgFond.getPosY() + "\" \n" + "        offsetX=\"" + imgFond.getOffsetX()
                            + "\" \n" + "        offsetY=\"" + imgFond.getOffsetY() + "\" \n"
                            + "        tailleX=\"" + imgFond.getTailleX() + "\" \n" + "        tailleY=\""
                            + imgFond.getTailleY() + "\" \n" + "        opacite=\"" + imgFond.getOpacite()
                            + "\" \n" + "        masquable=\"" + SMasquable + "\" \n" + "        url=\""
                            + imgFond.getUrl() + "\" \n" + "        infobulle=\"" + imgFond.getInfobulle()
                            + "\" \n" + "    />\n" + "";
                }
            }
            if (gestionnaireInterface.bAffichePlan && panoramiquesProjet[i].isAffichePlan()) {
                int numPlan = panoramiquesProjet[i].getNumeroPlan();
                Plan planPano = plans[numPlan];
                rouge = (int) (gestionnaireInterface.couleurFondPlan.getRed() * 255.d);
                bleu = (int) (gestionnaireInterface.couleurFondPlan.getBlue() * 255.d);
                vert = (int) (gestionnaireInterface.couleurFondPlan.getGreen() * 255.d);
                String SAfficheRadar = (gestionnaireInterface.bAfficheRadar) ? "oui" : "non";
                String coulFond = "rgba(" + rouge + "," + vert + "," + bleu + ","
                        + gestionnaireInterface.opacitePlan + ")";
                contenuFichier += "    <plan\n" + "        affiche=\"oui\" \n" + "        image=\"images/"
                        + planPano.getImagePlan() + "\"\n" + "        largeur=\""
                        + gestionnaireInterface.largeurPlan + "\"\n" + "        position=\""
                        + gestionnaireInterface.positionPlan + "\"\n" + "        couleurFond=\"" + coulFond
                        + "\"\n" + "        couleurTexte=\"#" + gestionnaireInterface.txtCouleurTextePlan
                        + "\"\n" + "        nord=\"" + planPano.getDirectionNord() + "\"\n"
                        + "        boussolePosition=\"" + planPano.getPosition() + "\"\n"
                        + "        boussoleX=\"" + planPano.getPositionX() + "\"\n" + "        boussoleY=\""
                        + planPano.getPositionX() + "\"\n" + "        radarAffiche=\"" + SAfficheRadar + "\"\n"
                        + "        radarTaille=\"" + Math.round(gestionnaireInterface.tailleRadar) + "\"\n"
                        + "        radarCouleurFond=\"#" + gestionnaireInterface.txtCouleurFondRadar + "\"\n"
                        + "        radarCouleurLigne=\"#" + gestionnaireInterface.txtCouleurLigneRadar + "\"\n"
                        + "        radarOpacite=\""
                        + Math.round(gestionnaireInterface.opaciteRadar * 100.d) / 100.d + "\"\n" + "    >\n";
                for (int iPoint = 0; iPoint < planPano.getNombreHotspots(); iPoint++) {
                    double posX = planPano.getHotspot(iPoint).getLongitude()
                            * gestionnaireInterface.largeurPlan;
                    double posY = planPano.getHotspot(iPoint).getLatitude() * planPano.getHauteurPlan()
                            * gestionnaireInterface.largeurPlan / planPano.getLargeurPlan();
                    if (planPano.getHotspot(iPoint).getNumeroPano() == i) {
                        contenuFichier += "        <pointPlan\n" + "            positX=\"" + posX + "\"\n"
                                + "            positY=\"" + posY + "\"\n" + "            xml=\"actif\"\n"
                                + "            />  \n";

                    } else {
                        contenuFichier += "        <pointPlan\n" + "            positX=\"" + posX + "\"\n"
                                + "            positY=\"" + posY + "\"\n" + "            xml=\"xml/"
                                + planPano.getHotspot(iPoint).getFichierXML() + "\"\n" + "            texte=\""
                                + planPano.getHotspot(iPoint).getInfo() + "\"\n" + "            />  \n";
                    }
                }
                contenuFichier += "    </plan>\n";
            }

            contenuFichier += "</scene>\n";
            String fichierPano = panoramiquesProjet[i].getNomFichier();
            String nomXMLFile = fichierPano
                    .substring(fichierPano.lastIndexOf(File.separator) + 1, fichierPano.length())
                    .split("\\.")[0] + ".xml";
            xmlFile = new File(xmlRepert + File.separator + nomXMLFile);
            xmlFile.setWritable(true);
            FileWriter fw = new FileWriter(xmlFile);
            try (BufferedWriter bw = new BufferedWriter(fw)) {
                bw.write(contenuFichier);
            }
        }
        Dimension tailleEcran = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        int hauteur = (int) tailleEcran.getHeight() - 200;
        String titreVis = "Panovisu - visualiseur 100% html5 (three.js)";
        TextArea tfVisite = (TextArea) paneChoixPanoramique.lookup("#titreVisite");
        if (!tfVisite.getText().equals("")) {
            titreVis = tfVisite.getText() + " - " + titreVis;
        }
        String fPano1 = "panos/niveau0/" + panoramiquesProjet[0].getNomFichier().substring(
                panoramiquesProjet[0].getNomFichier().lastIndexOf(File.separator) + 1,
                panoramiquesProjet[0].getNomFichier().length());

        String fichierHTML = "<!DOCTYPE html>\n" + "<html lang=\"fr\">\n" + "    <head>\n" + "        <title>"
                + titreVis + "</title>\n" + "        <meta charset=\"utf-8\">\n"
                + "        <meta name=\"viewport\" content=\"width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0\">\n"
                + "        <link rel=\"stylesheet\" media=\"screen\" href=\"panovisu/libs/jqueryMenu/jquery.contextMenu.css\" type=\"text/css\"/>\n"
                + "        <meta property=\"og:title\" content=\"" + titreVis + "\" />\n"
                + "        <meta property=\"og:description\" content=\"Une page cre avec panoVisu Editeur : 100% Libre 100% HTML5\" />\n"
                + "        <meta property=\"og:image\" content=\"" + fPano1 + "\" />" + "    </head>\n"
                + "    <body>\n" + "        <header>\n" + "\n" + "        </header>\n"
                + "        <article style=\"height : " + hauteur + "px;\">\n"
                + "            <div id=\"pano\">\n" + "            </div>\n" + "        </article>\n"
                + "        <script src=\"panovisu/panovisuInit.js\"></script>\n"
                + "        <script src=\"panovisu/panovisu.js\"></script>\n" + "        <script>\n" + "\n"
                + "            $(function() {\n" + "                $(window).resize(function(){\n"
                + "                    $(\"article\").height($(window).height()-10);\n"
                + "                    $(\"#pano\").height($(window).height()-10);\n" + "                })\n"
                + "                $(\"article\").height($(window).height()-10);\n"
                + "                $(\"#pano\").height($(window).height()-10);\n"
                + "                ajoutePano({\n" + "                    langue : \"" + locale.toString()
                + "\",\n" + "                    panoramique: \"pano\",\n" + "                    minFOV: 35,\n"
                + "                    maxFOV: 120,\n" + "                    fenX: \"100%\",\n"
                + "                    fenY: \"100%\",\n" + "                    xml: \"xml/PANO.xml\"\n"
                + "                });\n"
                + "                $(\".reseauSocial-twitter\").on(\"click\", function() {\n"
                + "                    window.open(\n"
                + "                            \"https://twitter.com/share?url=\" + document.location.href\n"
                + "                            );\n" + "                    return false;\n"
                + "                });\n"
                + "                $(\".reseauSocial-fb\").on(\"click\", function() {\n"
                + "                    window.open(\n"
                + "                            \"http://www.facebook.com/share.php?u=\" + document.location.href\n"
                + "                            );\n" + "                    return false;\n"
                + "                });\n"
                + "                $(\".reseauSocial-google\").on(\"click\", function() {\n"
                + "                    window.open(\n"
                + "                            \"https://plus.google.com/share?url=\" + document.location.href + \"&amp;hl=fr\"\n"
                + "                            );\n" + "                    return false;\n"
                + "                });\n"
                + "                $(\".reseauSocial-email\").attr(\"href\",\"mailto:?body=\" + document.location.href + \"&amp;hl=fr\");\n"
                //                    + "                images=new Array();\n"
                //                    + chargeImages
                //                    + "                prechargeImages(images); \n \n"
                + "            });\n" + "        </script>\n" + "    </body>\n" + "</html>\n";
        if (panoEntree.equals("")) {
            fichierHTML = fichierHTML
                    .replace("PANO",
                            panoramiquesProjet[0].getNomFichier()
                                    .substring(panoramiquesProjet[0].getNomFichier().lastIndexOf(File.separator)
                                            + 1, panoramiquesProjet[0].getNomFichier().length())
                                    .split("\\.")[0]);
        } else {
            fichierHTML = fichierHTML.replace("PANO", panoEntree);
        }
        File fichIndexHTML = new File(repertTemp + File.separator + "index.html");
        fichIndexHTML.setWritable(true);
        FileWriter fw1 = new FileWriter(fichIndexHTML);
        try (BufferedWriter bw1 = new BufferedWriter(fw1)) {
            bw1.write(fichierHTML);
        }
        DirectoryChooser repertChoix = new DirectoryChooser();
        repertChoix.setTitle("Choix du repertoire de sauvegarde de la visite");
        File repert = new File(EditeurPanovisu.repertoireProjet);
        repertChoix.setInitialDirectory(repert);
        File repertVisite = repertChoix.showDialog(null);

        String nomRepertVisite = repertVisite.getAbsolutePath();
        copieDirectory(repertTemp, nomRepertVisite);
        Dialogs.create().title("Gnration de la visite")
                .message("Votre visite a bien t gnr dans le rpertoire : " + nomRepertVisite)
                .showInformation();
        if (Desktop.isDesktopSupported()) {
            if (Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
                Desktop dt = Desktop.getDesktop();
                File fIndex = new File(nomRepertVisite + File.separator + "index.html");
                dt.browse(fIndex.toURI());
            }
        }
    } else {
        Dialogs.create().title("Gnration de la visite")
                .message("Votre visite n'a pu tre gnre, votre fichier n'tant pas sauvegard")
                .showError();

    }
}

From source file:eu.cassandra.training.gui.MainGUI.java

/**
 * Constructor of the Training Module GUI.
 * //from   w  ww  .j a v  a 2  s.  co  m
 * @throws UnsupportedLookAndFeelException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws ClassNotFoundException
 * @throws FileNotFoundException
 */
public MainGUI() throws ClassNotFoundException, InstantiationException, IllegalAccessException,
        UnsupportedLookAndFeelException, FileNotFoundException {
    setForeground(new Color(0, 204, 51));

    // Enable the closing of the frame when pressing the x on the upper corner
    // of the window
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            Utils.cleanFiles();
            System.exit(0);
        }
    });

    // Cleaning temporary files from the temp folder when starting the GUI.
    // Utils.cleanFiles();

    // Change the platforms look and feel to Nimbus
    LookAndFeel lnf = new javax.swing.plaf.nimbus.NimbusLookAndFeel();
    UIManager.put("NimbusLookAndFeel", Color.GREEN);
    UIManager.setLookAndFeel(lnf);

    // Setting the basic attributes of the Training Module GUI
    setTitle("Training Module (BETA)");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 1228, 799);

    // Creating the menu bar and adding the menu items
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenu mnNewMenu = new JMenu("File");
    menuBar.add(mnNewMenu);

    JMenuItem mntmExit = new JMenuItem("Exit");
    mntmExit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Utils.cleanFiles();
            System.exit(0);
        }
    });
    mnNewMenu.add(mntmExit);

    JMenu mnExit = new JMenu("Help");
    menuBar.add(mnExit);

    JMenuItem mntmManual = new JMenuItem("Manual");
    mnExit.add(mntmManual);

    JMenuItem mntmAbout = new JMenuItem("About");
    mnExit.add(mntmAbout);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);

    // Adding the tabbed pane to the content pane
    final JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    GroupLayout gl_contentPane = new GroupLayout(contentPane);
    gl_contentPane.setHorizontalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
            .addComponent(tabbedPane, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 1202, Short.MAX_VALUE));
    gl_contentPane.setVerticalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
            .addGroup(gl_contentPane.createSequentialGroup()
                    .addComponent(tabbedPane, GroupLayout.PREFERRED_SIZE, 736, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(47, Short.MAX_VALUE)));

    // TABS //

    final JPanel importTab = new JPanel();
    tabbedPane.addTab("Import Data", null, importTab, null);
    tabbedPane.setDisplayedMnemonicIndexAt(0, 0);
    tabbedPane.setEnabledAt(0, true);
    importTab.setLayout(null);

    final JPanel trainingTab = new JPanel();
    tabbedPane.addTab("Train Activity Models", null, trainingTab, null);
    tabbedPane.setDisplayedMnemonicIndexAt(1, 1);
    tabbedPane.setEnabledAt(1, false);
    trainingTab.setLayout(null);

    final JPanel createResponseTab = new JPanel();

    tabbedPane.addTab("Create Response Models", null, createResponseTab, null);
    tabbedPane.setEnabledAt(2, false);
    createResponseTab.setLayout(null);

    // RESPONSE MODEL TAB //

    final JPanel responseParametersPanel = new JPanel();
    responseParametersPanel.setLayout(null);
    responseParametersPanel.setBorder(
            new TitledBorder(null, "Response Parameters", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    responseParametersPanel.setBounds(6, 6, 394, 271);
    createResponseTab.add(responseParametersPanel);

    final JPanel activityModelSelectionPanel = new JPanel();
    activityModelSelectionPanel.setLayout(null);
    activityModelSelectionPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Activity Model Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    activityModelSelectionPanel.setBounds(6, 516, 394, 192);
    createResponseTab.add(activityModelSelectionPanel);

    final JPanel responsePanel = new JPanel();
    responsePanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Activity Model Change Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    responsePanel.setBounds(417, 6, 770, 385);
    createResponseTab.add(responsePanel);
    responsePanel.setLayout(new BorderLayout(0, 0));

    final JPanel pricingPreviewPanel = new JPanel();
    pricingPreviewPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Pricing Scheme Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    pricingPreviewPanel.setBounds(417, 438, 770, 259);
    createResponseTab.add(pricingPreviewPanel);
    pricingPreviewPanel.setLayout(new BorderLayout(0, 0));

    final JPanel pricingSchemePanel = new JPanel();
    pricingSchemePanel.setLayout(null);
    pricingSchemePanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Pricing Scheme Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    pricingSchemePanel.setBounds(6, 274, 394, 243);
    createResponseTab.add(pricingSchemePanel);

    // /////////////////
    // RESPONSE TAB //
    // ////////////////

    // RESPONSE PARAMETERS //

    final JLabel lblSensitivity = new JLabel("Sensitivity");
    lblSensitivity.setBounds(10, 28, 78, 16);
    responseParametersPanel.add(lblSensitivity);

    final JSlider sensitivitySlider = new JSlider();
    sensitivitySlider.setPaintLabels(true);
    sensitivitySlider.setSnapToTicks(true);
    sensitivitySlider.setPaintTicks(true);
    sensitivitySlider.setMinorTickSpacing(10);
    sensitivitySlider.setMajorTickSpacing(10);
    sensitivitySlider.setBounds(111, 28, 214, 45);
    responseParametersPanel.add(sensitivitySlider);

    final JLabel lblAwareness = new JLabel("Awareness");
    lblAwareness.setBounds(10, 79, 78, 16);
    responseParametersPanel.add(lblAwareness);

    final JSlider awarenessSlider = new JSlider();
    awarenessSlider.setPaintLabels(true);
    awarenessSlider.setPaintTicks(true);
    awarenessSlider.setMajorTickSpacing(10);
    awarenessSlider.setMinorTickSpacing(10);
    awarenessSlider.setSnapToTicks(true);
    awarenessSlider.setBounds(111, 79, 214, 45);
    responseParametersPanel.add(awarenessSlider);

    final JLabel label_7 = new JLabel("Response Model");
    label_7.setBounds(10, 153, 103, 16);
    responseParametersPanel.add(label_7);

    final JRadioButton optimalCaseRadioButton = new JRadioButton("Optimal Case Scenario");
    responseModelButtonGroup.add(optimalCaseRadioButton);
    optimalCaseRadioButton.setBounds(111, 131, 170, 18);
    responseParametersPanel.add(optimalCaseRadioButton);

    final JRadioButton normalCaseRadioButton = new JRadioButton("Normal Case Scenario");
    normalCaseRadioButton.setSelected(true);
    responseModelButtonGroup.add(normalCaseRadioButton);
    normalCaseRadioButton.setBounds(111, 152, 170, 18);
    responseParametersPanel.add(normalCaseRadioButton);

    final JRadioButton discreteCaseRadioButton = new JRadioButton("Discrete Case Scenario");
    discreteCaseRadioButton.setSelected(true);
    responseModelButtonGroup.add(discreteCaseRadioButton);
    discreteCaseRadioButton.setBounds(111, 173, 170, 18);
    responseParametersPanel.add(discreteCaseRadioButton);

    final JButton previewResponseButton = new JButton("Preview Response Model");
    previewResponseButton.setEnabled(false);
    previewResponseButton.setBounds(24, 198, 157, 28);
    responseParametersPanel.add(previewResponseButton);

    final JButton createResponseButton = new JButton("Create Response Model");
    createResponseButton.setEnabled(false);
    createResponseButton.setBounds(191, 198, 162, 28);
    responseParametersPanel.add(createResponseButton);

    final JButton createResponseAllButton = new JButton("Create Response All");
    createResponseAllButton.setEnabled(false);
    createResponseAllButton.setBounds(111, 232, 157, 28);
    responseParametersPanel.add(createResponseAllButton);

    // SELECT ACTIVITY MODEL //

    final JLabel lblSelectedActivity = new JLabel("Selected Activity");
    lblSelectedActivity.setBounds(10, 21, 130, 16);
    activityModelSelectionPanel.add(lblSelectedActivity);

    JScrollPane activityListScrollPane = new JScrollPane();
    activityListScrollPane.setBounds(20, 39, 355, 143);
    activityModelSelectionPanel.add(activityListScrollPane);

    final JList<String> activitySelectList = new JList<String>();
    activityListScrollPane.setViewportView(activitySelectList);
    activitySelectList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));

    final JButton commitButton = new JButton("Commit");
    commitButton.setEnabled(false);
    commitButton.setBounds(151, 209, 89, 23);
    pricingSchemePanel.add(commitButton);

    JLabel lblBasicSchema = new JLabel("Basic Schema (Start-End-Value)");
    lblBasicSchema.setBounds(10, 18, 182, 14);
    pricingSchemePanel.add(lblBasicSchema);

    JLabel lblNewSchemastart = new JLabel("New Schema (Start-End-Value)");
    lblNewSchemastart.setBounds(197, 18, 177, 14);
    pricingSchemePanel.add(lblNewSchemastart);

    JScrollPane basicPricingSchemeScrollPane = new JScrollPane();
    basicPricingSchemeScrollPane.setBounds(10, 43, 177, 161);
    pricingSchemePanel.add(basicPricingSchemeScrollPane);

    final JTextPane basicPricingSchemePane = new JTextPane();
    basicPricingSchemeScrollPane.setViewportView(basicPricingSchemePane);
    basicPricingSchemePane.setText("00:00-23:59-0.05");

    JScrollPane newPricingScrollPane = new JScrollPane();
    newPricingScrollPane.setBounds(197, 43, 177, 161);
    pricingSchemePanel.add(newPricingScrollPane);

    final JTextPane newPricingSchemePane = new JTextPane();

    newPricingScrollPane.setViewportView(newPricingSchemePane);

    JPanel buttonPanel = new JPanel();
    buttonPanel.setBounds(682, 390, 265, 33);
    createResponseTab.add(buttonPanel);

    final JButton dailyResponseButton = new JButton("Daily Times");
    dailyResponseButton.setEnabled(false);
    buttonPanel.add(dailyResponseButton);

    final JButton startResponseButton = new JButton("Start Time");

    startResponseButton.setEnabled(false);
    buttonPanel.add(startResponseButton);

    final JPanel exportTab = new JPanel();
    tabbedPane.addTab("Export Models", null, exportTab, null);
    tabbedPane.setEnabledAt(3, false);
    exportTab.setLayout(null);

    // PANELS //

    // DATA IMPORT TAB //

    final JPanel dataFilePanel = new JPanel();
    dataFilePanel
            .setBorder(new TitledBorder(null, "Data File", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    dataFilePanel.setBounds(6, 6, 622, 284);
    importTab.add(dataFilePanel);
    dataFilePanel.setLayout(null);

    final JPanel disaggregationPanel = new JPanel();
    disaggregationPanel.setLayout(null);
    disaggregationPanel.setBorder(
            new TitledBorder(null, "Disaggregation", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    disaggregationPanel.setBounds(629, 6, 567, 284);
    importTab.add(disaggregationPanel);

    final JPanel dataReviewPanel = new JPanel();
    dataReviewPanel.setBorder(
            new TitledBorder(null, "Data Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    dataReviewPanel.setBounds(6, 293, 622, 407);
    importTab.add(dataReviewPanel);
    dataReviewPanel.setLayout(new BorderLayout(0, 0));

    final JPanel consumptionModelPanel = new JPanel();
    consumptionModelPanel.setBounds(629, 293, 567, 407);
    importTab.add(consumptionModelPanel);
    consumptionModelPanel.setBorder(
            new TitledBorder(null, "Consumption Model", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    consumptionModelPanel.setLayout(new BorderLayout(0, 0));

    // TRAINING ACTIVITY TAB //

    final JPanel trainingParametersPanel = new JPanel();
    trainingParametersPanel.setLayout(null);
    trainingParametersPanel.setBorder(
            new TitledBorder(null, "Training Parameters", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    trainingParametersPanel.setBounds(6, 6, 621, 256);
    trainingTab.add(trainingParametersPanel);

    final JPanel applianceSelectionPanel = new JPanel();
    applianceSelectionPanel.setLayout(null);
    applianceSelectionPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Appliance/Activity Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    applianceSelectionPanel.setBounds(630, 6, 557, 256);
    trainingTab.add(applianceSelectionPanel);

    final JPanel expectedPowerPanel = new JPanel();
    expectedPowerPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Expected Power Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    expectedPowerPanel.setBounds(630, 261, 557, 447);
    trainingTab.add(expectedPowerPanel);
    expectedPowerPanel.setLayout(new BorderLayout(0, 0));
    contentPane.setLayout(gl_contentPane);

    // EXPORT TAB //

    JPanel modelExportPanel = new JPanel();
    modelExportPanel.setLayout(null);
    modelExportPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Model Export Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    modelExportPanel.setBounds(10, 11, 596, 267);
    exportTab.add(modelExportPanel);

    final JPanel exportPreviewPanel = new JPanel();
    exportPreviewPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Export Model Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    exportPreviewPanel.setBounds(10, 310, 1187, 387);
    exportTab.add(exportPreviewPanel);
    exportPreviewPanel.setLayout(new BorderLayout(0, 0));

    JPanel exportButtonsPanel = new JPanel();
    exportButtonsPanel.setBounds(322, 279, 536, 33);
    exportTab.add(exportButtonsPanel);

    JPanel connectionPanel = new JPanel();
    connectionPanel.setLayout(null);
    connectionPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Connection Properties", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    connectionPanel.setBounds(606, 11, 581, 267);
    exportTab.add(connectionPanel);

    // COMPONENTS //

    // IMPORT TAB //

    // DATA IMPORT //

    final JLabel lblSource = new JLabel("Data Source:");
    lblSource.setBounds(23, 47, 71, 16);
    dataFilePanel.add(lblSource);

    final JTextField pathField = new JTextField();
    pathField.setEditable(false);
    pathField.setBounds(99, 41, 405, 28);
    dataFilePanel.add(pathField);
    pathField.setColumns(10);

    final JButton dataBrowseButton = new JButton("Browse");
    dataBrowseButton.setBounds(516, 41, 87, 28);
    dataFilePanel.add(dataBrowseButton);

    final JButton resetButton = new JButton("Reset");
    resetButton.setBounds(516, 81, 87, 28);
    dataFilePanel.add(resetButton);

    final JLabel lblDataMeasurementsFrom = new JLabel("Data Measurements From:");
    lblDataMeasurementsFrom.setBounds(23, 90, 154, 16);
    dataFilePanel.add(lblDataMeasurementsFrom);

    final JRadioButton singleApplianceRadioButton = new JRadioButton("Single Appliance");
    singleApplianceRadioButton.setEnabled(false);
    dataMeasurementsButtonGroup.add(singleApplianceRadioButton);
    singleApplianceRadioButton.setBounds(242, 110, 115, 18);
    dataFilePanel.add(singleApplianceRadioButton);

    final JRadioButton installationRadioButton = new JRadioButton("Installation");
    installationRadioButton.setSelected(true);
    installationRadioButton.setEnabled(false);
    dataMeasurementsButtonGroup.add(installationRadioButton);
    installationRadioButton.setBounds(242, 89, 115, 18);
    dataFilePanel.add(installationRadioButton);

    final JLabel labelConsumptionModel = new JLabel("Consumption Model:");
    labelConsumptionModel.setBounds(23, 179, 120, 16);
    dataFilePanel.add(labelConsumptionModel);

    final JButton importDataButton = new JButton("Import Data");
    importDataButton.setEnabled(false);
    importDataButton.setBounds(23, 237, 126, 28);
    dataFilePanel.add(importDataButton);

    final JButton disaggregateButton = new JButton("Disaggregate");
    disaggregateButton.setEnabled(false);
    disaggregateButton.setBounds(216, 237, 147, 28);
    dataFilePanel.add(disaggregateButton);

    final JButton createEventsButton = new JButton("Create Events Dataset");
    createEventsButton.setEnabled(false);
    createEventsButton.setBounds(422, 237, 181, 28);
    dataFilePanel.add(createEventsButton);

    final JTextField consumptionPathField = new JTextField();
    consumptionPathField.setEnabled(false);
    consumptionPathField.setEditable(false);
    consumptionPathField.setColumns(10);
    consumptionPathField.setBounds(99, 197, 405, 28);
    dataFilePanel.add(consumptionPathField);

    final JButton consumptionBrowseButton = new JButton("Browse");
    consumptionBrowseButton.setEnabled(false);
    consumptionBrowseButton.setBounds(516, 197, 87, 28);
    dataFilePanel.add(consumptionBrowseButton);

    JLabel lblTypeOfMeasurements = new JLabel("Type of Measurements");
    lblTypeOfMeasurements.setBounds(23, 141, 154, 16);
    dataFilePanel.add(lblTypeOfMeasurements);

    final JRadioButton activePowerRadioButton = new JRadioButton("Active Power (P)");
    powerButtonGroup.add(activePowerRadioButton);
    activePowerRadioButton.setEnabled(false);
    activePowerRadioButton.setBounds(242, 140, 115, 18);
    dataFilePanel.add(activePowerRadioButton);

    final JRadioButton activeAndReactivePowerRadioButton = new JRadioButton("Active and Reactive Power (P, Q)");
    activeAndReactivePowerRadioButton.setSelected(true);
    powerButtonGroup.add(activeAndReactivePowerRadioButton);
    activeAndReactivePowerRadioButton.setEnabled(false);
    activeAndReactivePowerRadioButton.setBounds(242, 161, 262, 18);
    dataFilePanel.add(activeAndReactivePowerRadioButton);

    // //////////////////
    // DISAGGREGATION //
    // /////////////////

    final JLabel lblAppliancesDetected = new JLabel("Detected Appliances ");
    lblAppliancesDetected.setBounds(18, 33, 130, 16);
    disaggregationPanel.add(lblAppliancesDetected);

    JScrollPane scrollPane_2 = new JScrollPane();
    scrollPane_2.setBounds(145, 31, 396, 231);
    disaggregationPanel.add(scrollPane_2);

    final JList<String> detectedApplianceList = new JList<String>();
    scrollPane_2.setViewportView(detectedApplianceList);
    detectedApplianceList.setEnabled(false);
    detectedApplianceList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));

    // ////////////////
    // TRAINING TAB //
    // ////////////////

    // TRAINING PARAMETERS //

    final JLabel label_1 = new JLabel("Times Per Day");
    label_1.setBounds(19, 40, 103, 16);
    trainingParametersPanel.add(label_1);

    final JRadioButton timesHistogramRadioButton = new JRadioButton("Histogram");
    timesHistogramRadioButton.setSelected(true);
    timesDailyButtonGroup.add(timesHistogramRadioButton);
    timesHistogramRadioButton.setBounds(160, 38, 87, 18);
    trainingParametersPanel.add(timesHistogramRadioButton);

    final JRadioButton timesNormalRadioButton = new JRadioButton("Normal Distribution");
    timesNormalRadioButton.setEnabled(false);
    timesDailyButtonGroup.add(timesNormalRadioButton);
    timesNormalRadioButton.setBounds(304, 40, 137, 18);
    trainingParametersPanel.add(timesNormalRadioButton);

    JRadioButton timesGaussianRadioButton = new JRadioButton("Gaussian Mixture");
    timesGaussianRadioButton.setEnabled(false);
    timesDailyButtonGroup.add(timesGaussianRadioButton);
    timesGaussianRadioButton.setBounds(478, 38, 137, 18);
    trainingParametersPanel.add(timesGaussianRadioButton);

    final JLabel label_2 = new JLabel("Start Time");
    label_2.setBounds(19, 133, 103, 16);
    trainingParametersPanel.add(label_2);

    final JRadioButton startHistogramRadioButton = new JRadioButton("Histogram");
    startHistogramRadioButton.setSelected(true);
    startTimeButtonGroup.add(startHistogramRadioButton);
    startHistogramRadioButton.setBounds(160, 131, 87, 18);
    trainingParametersPanel.add(startHistogramRadioButton);

    final JRadioButton startNormalRadioButton = new JRadioButton("Normal Distribution");
    // startNormalRadioButton.setEnabled(false);
    startTimeButtonGroup.add(startNormalRadioButton);
    startNormalRadioButton.setBounds(304, 133, 137, 18);
    trainingParametersPanel.add(startNormalRadioButton);

    final JRadioButton startGaussianRadioButton = new JRadioButton("Gaussian Mixture");
    startGaussianRadioButton.setSelected(true);
    startTimeButtonGroup.add(startGaussianRadioButton);
    startGaussianRadioButton.setBounds(478, 131, 137, 18);
    trainingParametersPanel.add(startGaussianRadioButton);

    final JLabel label_3 = new JLabel("Duration");
    label_3.setBounds(19, 86, 103, 16);
    trainingParametersPanel.add(label_3);

    final JRadioButton durationHistogramRadioButton = new JRadioButton("Histogram");
    durationHistogramRadioButton.setSelected(true);
    durationButtonGroup.add(durationHistogramRadioButton);
    durationHistogramRadioButton.setBounds(160, 84, 87, 18);
    trainingParametersPanel.add(durationHistogramRadioButton);

    final JRadioButton durationNormalRadioButton = new JRadioButton("Normal Distribution");
    durationNormalRadioButton.setSelected(true);
    durationButtonGroup.add(durationNormalRadioButton);
    durationNormalRadioButton.setBounds(304, 86, 137, 18);
    trainingParametersPanel.add(durationNormalRadioButton);

    final JRadioButton durationGaussianRadioButton = new JRadioButton("Gaussian Mixture");
    durationButtonGroup.add(durationGaussianRadioButton);
    durationGaussianRadioButton.setBounds(478, 84, 137, 18);
    trainingParametersPanel.add(durationGaussianRadioButton);

    final JButton trainingButton = new JButton("Train");
    trainingButton.setBounds(125, 194, 115, 28);
    trainingParametersPanel.add(trainingButton);

    final JButton trainAllButton = new JButton("Train All");
    trainAllButton.setBounds(366, 194, 115, 28);
    trainingParametersPanel.add(trainAllButton);

    // APPLIANCE SELECTION //

    final JLabel label_4 = new JLabel("Selected Appliance");
    label_4.setBounds(18, 33, 130, 16);
    applianceSelectionPanel.add(label_4);

    JScrollPane scrollPane_1 = new JScrollPane();
    scrollPane_1.setBounds(128, 29, 419, 216);
    applianceSelectionPanel.add(scrollPane_1);

    final JList<String> selectedApplianceList = new JList<String>();
    scrollPane_1.setViewportView(selectedApplianceList);
    selectedApplianceList.setEnabled(false);
    selectedApplianceList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));

    // DISTRIBUTION SELECTION //

    JPanel distributionSelectionPanel = new JPanel();
    distributionSelectionPanel.setBounds(80, 261, 482, 33);
    trainingTab.add(distributionSelectionPanel);

    final JButton dailyTimesButton = new JButton("Daily Times");
    dailyTimesButton.setEnabled(false);
    distributionSelectionPanel.add(dailyTimesButton);

    final JButton durationButton = new JButton("Duration");
    durationButton.setEnabled(false);
    distributionSelectionPanel.add(durationButton);

    final JButton startTimeButton = new JButton("Start Time");
    startTimeButton.setEnabled(false);
    distributionSelectionPanel.add(startTimeButton);

    final JButton startTimeBinnedButton = new JButton("Start Time Binned");
    startTimeBinnedButton.setEnabled(false);
    distributionSelectionPanel.add(startTimeBinnedButton);

    final JPanel distributionPreviewPanel = new JPanel();
    distributionPreviewPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Distribution Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    distributionPreviewPanel.setBounds(6, 299, 621, 409);
    trainingTab.add(distributionPreviewPanel);
    distributionPreviewPanel.setLayout(new BorderLayout(0, 0));

    // //////////////////
    // EXPORT TAB ///////
    // /////////////////

    JLabel exportModelLabel = new JLabel("Select Model");
    exportModelLabel.setBounds(10, 34, 151, 16);
    modelExportPanel.add(exportModelLabel);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(83, 32, 503, 212);
    modelExportPanel.add(scrollPane);

    final JList<String> exportModelList = new JList<String>();
    scrollPane.setViewportView(exportModelList);
    exportModelList.setEnabled(false);
    exportModelList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));

    // EXPORT TAB //

    final JButton exportDailyButton = new JButton("Daily Times");
    exportDailyButton.setEnabled(false);
    exportButtonsPanel.add(exportDailyButton);

    final JButton exportDurationButton = new JButton("Duration");
    exportDurationButton.setEnabled(false);
    exportButtonsPanel.add(exportDurationButton);

    final JButton exportStartButton = new JButton("Start Time");
    exportStartButton.setEnabled(false);
    exportButtonsPanel.add(exportStartButton);

    final JButton exportStartBinnedButton = new JButton("Start Time Binned");
    exportStartBinnedButton.setEnabled(false);
    exportButtonsPanel.add(exportStartBinnedButton);

    final JButton exportExpectedPowerButton = new JButton("Expected Power");
    exportExpectedPowerButton.setEnabled(false);
    exportButtonsPanel.add(exportExpectedPowerButton);

    JLabel usernameLabel = new JLabel("Username:");
    usernameLabel.setBounds(46, 27, 71, 16);
    connectionPanel.add(usernameLabel);

    final JTextField usernameTextField;
    usernameTextField = new JTextField();
    usernameTextField.setText("user");
    usernameTextField.setColumns(10);
    usernameTextField.setBounds(122, 21, 405, 28);
    connectionPanel.add(usernameTextField);

    final JButton exportButton = new JButton("Export Entity");
    exportButton.setEnabled(false);
    exportButton.setBounds(46, 178, 147, 28);
    connectionPanel.add(exportButton);

    final JButton exportAllBaseButton = new JButton("Export All Base");
    exportAllBaseButton.setEnabled(false);
    exportAllBaseButton.setBounds(203, 178, 177, 28);
    connectionPanel.add(exportAllBaseButton);

    final JButton exportAllResponseButton = new JButton("Export All Response");
    exportAllResponseButton.setEnabled(false);
    exportAllResponseButton.setBounds(390, 178, 181, 28);
    connectionPanel.add(exportAllResponseButton);

    JLabel passwordLabel = new JLabel("Password:");
    passwordLabel.setBounds(46, 62, 71, 16);
    connectionPanel.add(passwordLabel);

    JLabel UrlLabel = new JLabel("URL:");
    UrlLabel.setBounds(46, 105, 71, 16);
    connectionPanel.add(UrlLabel);

    final JTextField urlTextField;
    urlTextField = new JTextField();
    urlTextField.setText("https://160.40.50.233:8443/cassandra/api");
    urlTextField.setColumns(10);
    urlTextField.setBounds(122, 99, 405, 28);
    connectionPanel.add(urlTextField);

    final JButton connectButton = new JButton("Connect");
    connectButton.setEnabled(false);
    connectButton.setBounds(217, 138, 147, 28);
    connectionPanel.add(connectButton);

    final JPasswordField passwordField;
    passwordField = new JPasswordField();
    passwordField.setBounds(122, 60, 405, 28);
    connectionPanel.add(passwordField);

    final JTextField householdNameTextField;
    householdNameTextField = new JTextField();
    householdNameTextField.setEnabled(false);
    householdNameTextField.setBounds(166, 225, 405, 31);
    connectionPanel.add(householdNameTextField);
    householdNameTextField.setColumns(10);

    final JLabel householdNameLabel = new JLabel("Export Household Name:");
    householdNameLabel.setBounds(24, 233, 147, 14);
    connectionPanel.add(householdNameLabel);

    JButton btnOpenPlatform = new JButton("Open Platform");
    btnOpenPlatform.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Desktop.getDesktop()
                        .browse(new URL("https://cassandra.iti.gr:8443/cassandra/app.html").toURI());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    btnOpenPlatform.setBounds(401, 138, 147, 28);
    connectionPanel.add(btnOpenPlatform);

    // //////////////////
    // ACTIONS ///////
    // /////////////////

    // IMPORT TAB //

    // DATA IMPORT ////

    dataBrowseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the browse button to
         * input the data file on the Data File panel of the Import Data tab.
         * 
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            // Opens the browse panel to find the data set file
            JFileChooser fc = new JFileChooser("./");

            // Adds a filter to the type of files acceptable for selection
            fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fc.setFileFilter(new MyFilter2());

            int returnVal = fc.showOpenDialog(contentPane);

            // After choosing the file some of the options in the Data File panel
            // are unlocked
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();

                pathField.setText(file.getAbsolutePath());
                importDataButton.setEnabled(true);
                activePowerRadioButton.setEnabled(true);
                activeAndReactivePowerRadioButton.setEnabled(true);
                installationRadioButton.setEnabled(true);
                singleApplianceRadioButton.setEnabled(true);
            }

        }
    });

    consumptionBrowseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the browse button to
         * input the consumption model file on the Data File panel of the Import
         * Data tab.
         * 
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            // Opens the browse panel to find the consumption model file
            JFileChooser fc = new JFileChooser("./");

            // Adds a filter to the type of files acceptable for selection
            fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fc.setFileFilter(new MyFilter());

            int returnVal = fc.showOpenDialog(contentPane);

            // After choosing the file some of the options in the Data File panel
            // are unlocked
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();

                consumptionPathField.setText(file.getAbsolutePath());
                createEventsButton.setEnabled(true);
            }

        }
    });

    resetButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the reset button
         * on the Data File panel of the Import Data tab. All the imported and
         * created entities are removed and the Training Module goes back to its
         * initial state.
         * 
         */
        @Override
        public void actionPerformed(ActionEvent e) {

            // Cleaning the Import Data tab components
            pathField.setText("");
            consumptionPathField.setText("");
            importDataButton.setEnabled(false);
            disaggregateButton.setEnabled(false);
            createEventsButton.setEnabled(false);
            installation = new Installation();
            dataBrowseButton.setEnabled(true);
            consumptionBrowseButton.setEnabled(false);
            installationRadioButton.setEnabled(false);
            installationRadioButton.setSelected(true);
            singleApplianceRadioButton.setEnabled(false);
            activePowerRadioButton.setEnabled(false);
            activeAndReactivePowerRadioButton.setEnabled(false);
            activeAndReactivePowerRadioButton.setSelected(true);
            dataReviewPanel.removeAll();
            dataReviewPanel.updateUI();
            consumptionModelPanel.removeAll();
            consumptionModelPanel.updateUI();
            detectedApplianceList.setSelectedIndex(-1);
            detectedAppliances.clear();
            detectedApplianceList.setListData(new String[0]);
            detectedApplianceList.repaint();

            // Cleaning the Training Activity Models tab components
            distributionPreviewPanel.removeAll();
            distributionPreviewPanel.updateUI();
            expectedPowerPanel.removeAll();
            expectedPowerPanel.updateUI();
            selectedApplianceList.setSelectedIndex(-1);
            selectedAppliances.clear();
            selectedApplianceList.setListData(new String[0]);
            selectedApplianceList.repaint();
            timesHistogramRadioButton.setSelected(true);
            durationNormalRadioButton.setSelected(true);
            startGaussianRadioButton.setSelected(true);

            // Cleaning the Create Response Models tab components
            sensitivitySlider.setValue(50);
            awarenessSlider.setValue(50);
            normalCaseRadioButton.setSelected(true);
            previewResponseButton.setEnabled(false);
            createResponseButton.setEnabled(false);
            createResponseAllButton.setEnabled(false);
            pricingPreviewPanel.removeAll();
            pricingPreviewPanel.updateUI();
            responsePanel.removeAll();
            responsePanel.updateUI();
            activitySelectList.setSelectedIndex(-1);
            activityModels.clear();
            activitySelectList.setListData(new String[0]);
            activitySelectList.repaint();
            basicPricingSchemePane.setText("00:00-23:59-0.05");
            newPricingSchemePane.setText("");
            commitButton.setEnabled(false);
            dailyResponseButton.setEnabled(false);
            startResponseButton.setEnabled(false);

            // Cleaning the Export Models tab components
            exportModelList.setSelectedIndex(-1);
            exportModels.clear();
            exportModelList.setListData(new String[0]);
            exportModelList.repaint();
            exportPreviewPanel.removeAll();
            exportPreviewPanel.updateUI();
            exportDailyButton.setEnabled(false);
            exportDurationButton.setEnabled(false);
            exportStartButton.setEnabled(false);
            exportStartBinnedButton.setEnabled(false);
            exportExpectedPowerButton.setEnabled(false);
            exportButton.setEnabled(false);
            exportAllBaseButton.setEnabled(false);
            exportAllResponseButton.setEnabled(false);
            householdNameTextField.setEnabled(false);

            // Disabling the necessary tabs
            tabbedPane.setEnabledAt(1, false);
            tabbedPane.setEnabledAt(2, false);
            tabbedPane.setEnabledAt(3, false);

            // Clearing the arrayList in need
            tempAppliances.clear();
            tempActivities.clear();

            // Removing temporary files
            Utils.cleanFiles();
            trained = false;

        }
    });

    singleApplianceRadioButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Single Appliance
         * radio button on the Data File panel of the Import Data tab.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            consumptionPathField.setEnabled(false);
            consumptionBrowseButton.setEnabled(false);
            consumptionPathField.setText("");
        }
    });

    installationRadioButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Installation
         * radio button on the Data File panel of the Import Data tab.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            consumptionPathField.setEnabled(false);
            consumptionBrowseButton.setEnabled(false);
            consumptionPathField.setText("");
        }
    });

    importDataButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Import Data
         * button on the Data File panel of the Import Data tab.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                // Change the state of some components
                installationRadioButton.setEnabled(false);
                singleApplianceRadioButton.setEnabled(false);
                importDataButton.setEnabled(false);
                dataBrowseButton.setEnabled(false);
                activePowerRadioButton.setEnabled(false);
                activeAndReactivePowerRadioButton.setEnabled(false);

                // Check if both active and reactive activeOnly data set are available
                boolean power = activePowerRadioButton.isSelected();
                int parse = -1;

                // Parsing the measurements file
                try {
                    parse = Utils.parseMeasurementsFile(pathField.getText(), power);
                } catch (IOException e2) {
                    e2.printStackTrace();
                }

                // If everything is OK
                if (parse == -1) {
                    try {
                        // Creating new installation
                        installation = new Installation(pathField.getText(), power);
                    } catch (IOException e2) {
                        e2.printStackTrace();
                    }

                    // Show the measurements in the preview chart
                    ChartPanel chartPanel = null;
                    try {
                        chartPanel = installation.measurementsChart();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }

                    dataReviewPanel.add(chartPanel, BorderLayout.CENTER);
                    dataReviewPanel.validate();

                    disaggregateButton.setEnabled(false);
                    createEventsButton.setEnabled(false);

                    // Enable the appropriate buttons given source of measurements
                    if (installationRadioButton.isSelected()) {
                        disaggregateButton.setEnabled(true);
                    } else if (singleApplianceRadioButton.isSelected()) {
                        consumptionPathField.setEnabled(true);
                        consumptionBrowseButton.setEnabled(true);

                    }

                    // Add installation to the export models list
                    exportModels.addElement(installation.toString());
                    exportModels.addElement(installation.getPerson().getName());
                    householdNameTextField.setText(installation.getName());

                    // Enable Export Models tab
                    exportModelList.setEnabled(true);
                    exportModelList.setModel(exportModels);
                    tabbedPane.setEnabledAt(3, true);

                }
                // In case of an error during the measurement parsing show the line of
                // error and reset settings.
                else {
                    JFrame error = new JFrame();

                    JOptionPane.showMessageDialog(error,
                            "Parsing measurements file failed. The problem seems to be in line " + parse
                                    + ".Check the selected buttons and the file provided and try again.",
                            "Inane error", JOptionPane.ERROR_MESSAGE);
                    resetButton.doClick();
                }
            } finally {
                root.setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    disaggregateButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Disaggregate
         * button on the Data File panel of the Import Data tab in order to
         * automatically analyse the data set and extract the appliances and
         * activities within.
         */
        @Override
        public void actionPerformed(ActionEvent e) {

            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                // Get auxiliary files containing appliances and activities which are
                // the output of the disaggregation process.
                String filename = pathField.getText();

                File file = new File(filename);

                String folder = file.getParent() + "/";

                String fileNameWithExtension = file.getName();

                String fileName = file.getName().substring(0, file.getName().length() - 4);

                filename = pathField.getText().substring(0, pathField.getText().length() - 4);
                File appliancesFile = new File(Constants.resultFolder + fileName + "ApplianceList.csv");
                File activitiesFile = new File(Constants.resultFolder + fileName + "ActivityList.csv");

                if ((Constants.USE_FILES == false) || (!appliancesFile.exists() && !activitiesFile.exists())) {
                    try {
                        System.out.println("IN!!!");

                        Disaggregate dis = new Disaggregate(folder, fileNameWithExtension);

                        appliancesFile = new File(Constants.resultFolder + fileName + "ApplianceList.csv");
                        activitiesFile = new File(Constants.resultFolder + fileName + "ActivityList.csv");
                    } catch (Exception e2) {
                        System.out.println("Missing File");
                        e2.printStackTrace();
                    }
                }

                // If these exist, disaggregation was successful and the procedure can
                // continue
                if (appliancesFile.exists() && activitiesFile.exists()) {

                    // Read appliance file and start appliance parsing
                    Scanner input = null;
                    try {
                        input = new Scanner(appliancesFile);
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                    }
                    String nextLine;
                    String[] line;

                    while (input.hasNext()) {
                        nextLine = input.nextLine();
                        line = nextLine.split(",");

                        String name = line[1] + " " + line[0];
                        // String activity = line[1];
                        String activity = name;
                        String[] temp = line[0].split(" ");

                        String type = "";

                        if (temp.length == 1)
                            type = temp[0];
                        else {
                            for (int i = 0; i < temp.length - 1; i++)
                                type += temp[i] + " ";
                            type = type.trim();

                        }

                        boolean refFlag = activity.contains("Refrigeration");
                        boolean wmFlag = name.contains("Washing");

                        double p = 0, q = 0;
                        int distance = 0, duration = 0;

                        if (refFlag) {
                            p = Double.parseDouble(line[2]);
                            q = Double.parseDouble(line[3]);
                            duration = Integer.parseInt(line[4]);
                            distance = Integer.parseInt(line[5]);
                            // For each appliance found in the file, an temporary Appliance
                            // Entity is created.

                            tempAppliances.add(new ApplianceTemp(name, installation.getName(), type, activity,
                                    p, q, duration, distance));
                        } else if (wmFlag) {
                            double[] pValues = new double[line.length / 2 - 1];
                            double[] qValues = new double[line.length / 2 - 1];
                            // For each appliance found in the file, an temporary Appliance
                            // Entity is created.

                            for (int i = 0; i < pValues.length; i++) {
                                pValues[i] = Double.parseDouble(line[2 + 2 * i]);
                                qValues[i] = Double.parseDouble(line[3 + 2 * i]);
                            }

                            tempAppliances.add(new ApplianceTemp(name, installation.getName(), type, activity,
                                    pValues, qValues));
                        } else {
                            p = Double.parseDouble(line[2]);
                            q = Double.parseDouble(line[3]);
                            // For each appliance found in the file, an temporary Appliance
                            // Entity is created.

                            tempAppliances
                                    .add(new ApplianceTemp(name, installation.getName(), type, activity, p, q));
                        }
                    }

                    System.out.println("Appliances:" + tempAppliances.size());

                    input.close();

                    // Read activity file and start activity parsing

                    try {
                        input = new Scanner(activitiesFile);
                    } catch (FileNotFoundException e1) {
                        System.out.println("Problem with activity file.");
                        e1.printStackTrace();
                    }

                    while (input.hasNext()) {
                        nextLine = input.nextLine();
                        line = nextLine.split(",");

                        // System.out.println(Arrays.toString(line));
                        // String name = line[0];
                        // String activity = line[1];
                        String activity = line[1] + " " + line[0];
                        String type = line[1];
                        int start = Integer.parseInt(line[2]);
                        int end = Integer.parseInt(line[3]);

                        // Search for existing activity
                        int activityIndex = findActivity(activity);

                        // if not found, create a new one
                        if (activityIndex == -1) {
                            // System.out.println("In!");
                            ActivityTemp newActivity = new ActivityTemp(activity, type);
                            newActivity.addEvent(start, end);
                            tempActivities.add(newActivity);
                            // System.out.println(tempActivities.toString());

                        }
                        // else add data to the found activity
                        else
                            tempActivities.get(activityIndex).addEvent(start, end);
                    }

                    // This is hard copied for now
                    ArrayList<ActivityTemp> activities = findAllActivity("Refrigeration");
                    for (ActivityTemp activityTemp : activities) {
                        tempActivities.remove(activityTemp);
                        System.out.println("Refrigeration Removed");
                    }

                    int index = findActivity("Standby");
                    if (index != -1) {
                        tempActivities.remove(index);
                        System.out.println("Standby Consumption Removed");
                    }
                    // TODO Add these lines in case we want to remove activities with
                    // small sampling number

                    // System.out.println(tempActivities.size());
                    // for (int i = tempActivities.size() - 1; i >= 0; i--)
                    // if (tempActivities.get(i).getEvents().size() < threshold)
                    // tempActivities.remove(i);

                    // Create an event file for each activity, in order to be able to
                    // use
                    // it for training the behaviour models if asked from the user
                    for (int i = 0; i < tempActivities.size(); i++) {
                        // tempActivities.get(i).status();
                        try {
                            tempActivities.get(i).createEventFile();
                        } catch (IOException e1) {
                            System.out.println("Problem with creating events file.");
                            e1.printStackTrace();
                        }
                    }

                    input.close();

                    // Add each found appliance (after converting temporary appliance to
                    // normal appliance) in the installation Entity, to the detected
                    // appliance and export models list
                    for (ApplianceTemp temp : tempAppliances) {

                        Appliance tempAppliance = temp.toAppliance();

                        installation.addAppliance(tempAppliance);
                        detectedAppliances.addElement(tempAppliance.toString());
                        exportModels.addElement(tempAppliance.toString());

                    }

                    // Add appliances corresponding to each activity, remove activities
                    // without appliances and add activities to the selected activities
                    // list.
                    for (int i = tempActivities.size() - 1; i >= 0; i--) {

                        tempActivities.get(i).setAppliances(findAppliances(tempActivities.get(i)));
                        if (tempActivities.get(i).getAppliances().size() == 0) {
                            tempActivities.remove(i);
                        } else
                            selectedAppliances.addElement(tempActivities.get(i).toString());

                    }

                }
                // In case of an error.
                else {

                    int temp = 8 + ((int) (Math.random() * 2));

                    for (int i = 0; i < temp; i++) {

                        String name = "Appliance " + i;
                        String powerModel = "";
                        String reactiveModel = "";
                        int tempIndex = i % 5;
                        switch (tempIndex) {
                        case 0:
                            powerModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"p\":1900,\"d\":1,\"s\":0}]},{\"n\":0,\"values\":[{\"p\":300,\"d\":1,\"s\":0}]}]}";
                            reactiveModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"q\":-40,\"d\":1,\"s\":0}]},{\"n\":0,\"values\":[{\"q\":-10,\"d\":1,\"s\":0}]}]}";
                            break;
                        case 1:
                            powerModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"p\" : 140.0, \"d\" : 20, \"s\": 0.0}]}]}";
                            reactiveModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"q\" : 120.0, \"d\" : 20, \"s\": 0.0}]}]}";
                            break;
                        case 2:
                            powerModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"p\" : 95.0, \"d\" : 20, \"s\": 0.0}, {\"p\" :80.0, \"d\" : 18, \"s\": 0.0}, {\"p\" : 0.0, \"d\" : 73, \"s\": 0.0}]}]}]}";
                            reactiveModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"q\" : 0.0, \"d\" : 20, \"s\": 0.0}, {\"q\" : 0.0, \"d\" : 18, \"s\": 0.0}, {\"q\" : 0.0, \"d\" : 73, \"s\": 0.0}]}]}]}";
                            break;
                        case 3:
                            powerModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"p\" : 30.0, \"d\" : 20, \"s\": 0.0}]}]}";
                            reactiveModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"q\" : -5.0, \"d\" : 20, \"s\": 0.0}]}]}";
                            break;
                        case 4:
                            powerModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"p\":150,\"d\":25,\"s\":0},{\"p\":2000,\"d\":13,\"s\":0},{\"p\":100,\"d\":62,\"s\":0}]}]}";
                            reactiveModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"q\":400,\"d\":25,\"s\":0},{\"q\":200,\"d\":13,\"s\":0},{\"q\":300,\"d\":62,\"s\":0}]}]}";
                            break;
                        }

                        Appliance tempAppliance = new Appliance(name, installation.getName(), powerModel,
                                reactiveModel, "Demo/eventsAll" + tempIndex + ".csv");

                        installation.addAppliance(tempAppliance);
                        detectedAppliances.addElement(tempAppliance.toString());
                        selectedAppliances.addElement(tempAppliance.toString());
                        exportModels.addElement(tempAppliance.toString());
                    }
                }

                // Enable all appliance/activity lists
                detectedApplianceList.setEnabled(true);
                detectedApplianceList.setModel(detectedAppliances);
                detectedApplianceList.setSelectedIndex(0);

                tabbedPane.setEnabledAt(1, true);
                selectedApplianceList.setEnabled(true);
                selectedApplianceList.setModel(selectedAppliances);

                // exportModelList.setEnabled(true);
                // exportModelList.setModel(exportModels);
                // tabbedPane.setEnabledAt(3, true);

                // Disable unnecessary buttons.
                disaggregateButton.setEnabled(false);
                createEventsButton.setEnabled(false);
            } finally {
                root.setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    createEventsButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Create Events
         * button on the Data File panel of the Import Data tab. This button is
         * used when there is a single appliance with an known consumption model
         * so that the events can be extracted automatically from the data set.
         * Used for presentation purposes only since is depricated by the
         * disaggregation function.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                // Parse the consumption model file
                File file = new File(consumptionPathField.getText());
                String temp = file.getName();
                temp = temp.replace(".", " ");
                String name = temp.split(" ")[0];

                Appliance appliance = null;
                try {

                    int rand = (int) (Math.random() * 5);

                    appliance = new Appliance(name, consumptionPathField.getText(),
                            consumptionPathField.getText(), "Demo/eventsAll" + rand + ".csv", installation,
                            activePowerRadioButton.isSelected());
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                // Add appliance to the installation entity
                installation.addAppliance(appliance);

                // Enable all appliance/activity lists
                detectedAppliances.addElement(appliance.toString());
                selectedAppliances.addElement(appliance.toString());
                exportModels.addElement(appliance.toString());

                detectedApplianceList.setEnabled(true);
                detectedApplianceList.setModel(detectedAppliances);
                detectedApplianceList.setSelectedIndex(0);

                tabbedPane.setEnabledAt(1, true);
                selectedApplianceList.setEnabled(true);
                selectedApplianceList.setModel(selectedAppliances);

                // exportModelList.setEnabled(true);
                // exportModelList.setModel(exportModels);
                // tabbedPane.setEnabledAt(3, true);

                // Disable unnecessary buttons.
                disaggregateButton.setEnabled(false);
                createEventsButton.setEnabled(false);
            } finally {
                root.setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    // APPLIANCE DETECTION //
    detectedApplianceList.addListSelectionListener(new ListSelectionListener() {
        /**
         * This function is called when the user selects an appliance from the
         * list of Detected Appliances on the Disaggregation panel of the Import
         * Data tab. Then the corresponding consumption model is presented in the
         * Consumption Model Preview panel.
         */
        @Override
        public void valueChanged(ListSelectionEvent e) {

            consumptionModelPanel.removeAll();
            consumptionModelPanel.updateUI();

            if (detectedAppliances.size() >= 1) {

                String selection = detectedApplianceList.getSelectedValue();

                Appliance current = installation.findAppliance(selection);

                ChartPanel chartPanel = current.consumptionGraph();

                consumptionModelPanel.add(chartPanel, BorderLayout.CENTER);
                consumptionModelPanel.validate();

            }
        }
    });

    // // TRAINING TAB //
    trainingTab.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentShown(ComponentEvent arg0) {
            selectedApplianceList.setSelectedIndex(0);
        }
    });

    trainingButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Train button on
         * the Training Parameters panel of the Train Activity Models tab. It
         * contains the procedure needed to create an activity model based on the
         * event set of the appliance or activity.
         */
        @Override
        public void actionPerformed(ActionEvent e) {

            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            responsePanel.removeAll();
            responsePanel.validate();
            pricingPreviewPanel.removeAll();
            pricingPreviewPanel.validate();
            previewResponseButton.setEnabled(false);
            createResponseButton.setEnabled(false);
            createResponseAllButton.setEnabled(false);
            dailyResponseButton.setEnabled(false);
            startResponseButton.setEnabled(false);

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                // Searching for existing activity or appliance.
                String selection = selectedApplianceList.getSelectedValue();
                ActivityTemp activity = null;

                if (tempActivities.size() > 0)
                    activity = tempActivities.get(findActivity(selection));

                Appliance current = installation.findAppliance(selection);

                String startTime, duration, dailyTimes;

                // Check for the selected distribution methods for training.
                if (timesHistogramRadioButton.isSelected())
                    dailyTimes = "Histogram";
                else if (timesNormalRadioButton.isSelected())
                    dailyTimes = "Normal";
                else
                    dailyTimes = "GMM";

                if (durationHistogramRadioButton.isSelected())
                    duration = "Histogram";
                else if (durationNormalRadioButton.isSelected())
                    duration = "Normal";
                else
                    duration = "GMM";

                if (startHistogramRadioButton.isSelected())
                    startTime = "Histogram";
                else if (startNormalRadioButton.isSelected())
                    startTime = "Normal";
                else
                    startTime = "GMM";

                String[] distributions = { dailyTimes, duration, startTime, "Histogram" };

                // If the selected object from the list is an appliance the training
                // procedure for the appliance begins.
                if (activity == null) {

                    try {
                        installation.getPerson().train(current, distributions);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                // If the selected object from the list is an activity the training
                // procedure for the activity begins.
                else {

                    try {
                        installation.getPerson().train(activity, distributions);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }

                }

                // System.out.println("Training OK!");

                distributionPreviewPanel.removeAll();
                distributionPreviewPanel.updateUI();

                expectedPowerPanel.removeAll();
                expectedPowerPanel.updateUI();

                // Show the distribution created on the Distribution Preview Panel
                ActivityModel activityModel = installation.getPerson().findActivity(selection, true);

                if (activityModel == null)
                    activityModel = installation.getPerson().findActivity(current);

                ChartPanel chartPanel = activityModel.createDailyTimesDistributionChart();
                distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER);
                distributionPreviewPanel.validate();

                chartPanel = activityModel.createExpectedPowerChart();
                expectedPowerPanel.add(chartPanel, BorderLayout.CENTER);
                expectedPowerPanel.validate();

                // Add the Activity model to the list of trained Activity models of
                // the Create Response Models tab
                int size = activitySelectList.getModel().getSize();

                if (size > 0) {
                    activityModels = (DefaultListModel<String>) activitySelectList.getModel();
                    if (activityModels.contains(activityModel.getName()) == false)
                        activityModels.addElement(activityModel.getName());
                } else {
                    activityModels = new DefaultListModel<String>();
                    activityModels.addElement(activityModel.getName());
                    activitySelectList.setEnabled(true);
                }

                activitySelectList.setModel(activityModels);

                // Add the trained model to the export list also.
                size = exportModelList.getModel().getSize();
                if (size > 0) {
                    exportModels = (DefaultListModel<String>) exportModelList.getModel();
                    if (exportModels.contains(activityModel.getName()) == false)
                        exportModels.addElement(activityModel.getName());
                } else {
                    exportModels = new DefaultListModel<String>();
                    exportModels.addElement(activityModel.getName());
                    exportModelList.setEnabled(true);
                }

                // Enable some buttons necessary to show the results.
                dailyTimesButton.setEnabled(true);
                durationButton.setEnabled(true);
                startTimeButton.setEnabled(true);
                startTimeBinnedButton.setEnabled(true);

                exportModelList.setModel(exportModels);

                exportDailyButton.setEnabled(true);
                exportDurationButton.setEnabled(true);
                exportStartButton.setEnabled(true);
                exportStartBinnedButton.setEnabled(true);

                tabbedPane.setEnabledAt(2, true);
            }

            finally {
                root.setCursor(Cursor.getDefaultCursor());
                trained = true;
            }
        }
    });

    trainAllButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Train All button on
         * the Training Parameters panel of the Train Activity Models tab. It
         * is iterating the aforementioned training procedure to each of the
         * objects on the list.
         */
        @Override
        public void actionPerformed(ActionEvent e) {

            responsePanel.removeAll();
            responsePanel.validate();
            pricingPreviewPanel.removeAll();
            pricingPreviewPanel.validate();
            previewResponseButton.setEnabled(false);
            createResponseButton.setEnabled(false);
            createResponseAllButton.setEnabled(false);
            dailyResponseButton.setEnabled(false);
            startResponseButton.setEnabled(false);

            for (int i = 0; i < selectedApplianceList.getModel().getSize(); i++) {
                selectedApplianceList.setSelectedIndex(i);
                trainingButton.doClick();
            }
        }
    });

    dailyTimesButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Daily Times button on
         * the Distribution Preview panel of the Train Activity Models tab. It
         * shows the Daily Times Distribution for the selected object from the
         * list if available.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            distributionPreviewPanel.removeAll();
            distributionPreviewPanel.updateUI();

            String selection = selectedApplianceList.getSelectedValue();

            Appliance current = installation.findAppliance(selection);

            ActivityModel activityModel = installation.getPerson().findActivity(selection, true);

            if (activityModel == null)
                activityModel = installation.getPerson().findActivity(current);

            ChartPanel chartPanel = activityModel.createDailyTimesDistributionChart();
            distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            distributionPreviewPanel.validate();

        }
    });

    startTimeBinnedButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Start Time Binned
         * button on the Distribution Preview panel of the Train Activity
         * Models tab. It shows the Start Time Binned Distribution for the
         * selected object from the list if available.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            distributionPreviewPanel.removeAll();
            distributionPreviewPanel.updateUI();

            String selection = selectedApplianceList.getSelectedValue();

            Appliance current = installation.findAppliance(selection);

            ActivityModel activityModel = installation.getPerson().findActivity(selection, true);

            if (activityModel == null)
                activityModel = installation.getPerson().findActivity(current);

            ChartPanel chartPanel = activityModel.createStartTimeBinnedDistributionChart();
            distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            distributionPreviewPanel.validate();

        }
    });

    startTimeButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Start Time
         * button on the Distribution Preview panel of the Train Activity
         * Models tab. It shows the Start Time Distribution for the selected
         * object from the list if available.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            distributionPreviewPanel.removeAll();
            distributionPreviewPanel.updateUI();

            String selection = selectedApplianceList.getSelectedValue();

            Appliance current = installation.findAppliance(selection);

            ActivityModel activityModel = installation.getPerson().findActivity(selection, true);

            if (activityModel == null)
                activityModel = installation.getPerson().findActivity(current);

            ChartPanel chartPanel = activityModel.createStartTimeDistributionChart();
            distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            distributionPreviewPanel.validate();

        }
    });

    durationButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Duration
         * button on the Distribution Preview panel of the Train Activity
         * Models tab. It shows the Duration Distribution for the selected
         * object from the list if available.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            distributionPreviewPanel.removeAll();
            distributionPreviewPanel.updateUI();

            String selection = selectedApplianceList.getSelectedValue();

            Appliance current = installation.findAppliance(selection);

            ActivityModel activityModel = installation.getPerson().findActivity(selection, true);

            if (activityModel == null)
                activityModel = installation.getPerson().findActivity(current);

            ChartPanel chartPanel = activityModel.createDurationDistributionChart();
            distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            distributionPreviewPanel.validate();

        }
    });

    selectedApplianceList.addListSelectionListener(new ListSelectionListener() {
        /**
         * This function is called when the user selects an appliance or activity
         * from the list of Selected Appliances on the Appliance / Activity
         * Selection panel of the Train Activity Models tab. Then an example
         * corresponding consumption model is presented in the Consumption Model
         * Preview panel.
         */
        @Override
        public void valueChanged(ListSelectionEvent arg0) {

            ChartPanel chartPanel = null, chartPanel2 = null, chartPanel3 = null;
            expectedPowerPanel.removeAll();
            expectedPowerPanel.updateUI();
            distributionPreviewPanel.removeAll();
            distributionPreviewPanel.updateUI();

            // If there are any appliances / activities on the list
            if (selectedAppliances.size() >= 1) {

                // Find the corresponding appliance / activity and show its
                // consumption model
                String selection = selectedApplianceList.getSelectedValue();

                Appliance currentAppliance = installation.findAppliance(selection);

                ActivityModel activityModel = installation.getPerson().findActivity(selection, true);

                // If there is also an Activity model trained, show the corresponding
                // distribution charts on the Distribution Preview panel

                if (currentAppliance != null)
                    activityModel = installation.getPerson().findActivity(currentAppliance);

                if (activityModel == null)
                    activityModel = installation.getPerson().findActivity(selection, true);

                if (activityModel != null) {

                    dailyTimesButton.setEnabled(true);
                    durationButton.setEnabled(true);
                    startTimeButton.setEnabled(true);
                    startTimeBinnedButton.setEnabled(true);

                    chartPanel2 = activityModel.createDailyTimesDistributionChart();
                    distributionPreviewPanel.add(chartPanel2, BorderLayout.CENTER);
                    distributionPreviewPanel.validate();
                    distributionPreviewPanel.updateUI();

                    chartPanel3 = activityModel.createExpectedPowerChart();
                    expectedPowerPanel.add(chartPanel3, BorderLayout.CENTER);
                    expectedPowerPanel.validate();
                    expectedPowerPanel.updateUI();

                } else {
                    dailyTimesButton.setEnabled(false);
                    durationButton.setEnabled(false);
                    startTimeButton.setEnabled(false);
                    startTimeBinnedButton.setEnabled(false);
                }
            }

        }
    });

    // RESPONSE TAB //

    createResponseTab.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentHidden(ComponentEvent arg0) {
            activitySelectList.setSelectedIndex(0);

        }

        @Override
        public void componentShown(ComponentEvent arg0) {
            activitySelectList.setSelectedIndex(0);
        }
    });

    previewResponseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Preview Response
         * button on the Response Parameters panel of the Create Response Models
         * tab. This button is enabled after selecting activity model, response
         * type and pricing for testing and presents a preview of the response
         * model that may be extracted.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                responsePanel.removeAll();

                // Find the selected activity
                ActivityModel activity = installation.getPerson()
                        .findActivity(activitySelectList.getSelectedValue(), false);

                int response = -1;

                // Check for the selected response type
                if (optimalCaseRadioButton.isSelected())
                    response = 0;
                else if (normalCaseRadioButton.isSelected())
                    response = 1;
                else
                    response = 2;

                // Parse the pricing schemes
                double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText());
                double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText());

                float awareness = (float) (awarenessSlider.getValue()) / 100;
                float sensitivity = (float) (sensitivitySlider.getValue()) / 100;

                System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity);

                // Create a preview chart of the response model
                ChartPanel chartPanel = installation.getPerson().previewResponse(activity, response,
                        basicScheme, newScheme, awareness, sensitivity);

                responsePanel.add(chartPanel, BorderLayout.CENTER);
                responsePanel.validate();

                createResponseButton.setEnabled(true);
                createResponseAllButton.setEnabled(true);
                dailyResponseButton.setEnabled(true);
                startResponseButton.setEnabled(true);
            } finally {
                root.setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    createResponseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Create Response Model
         * button on the Response Parameters panel of the Create Response Models
         * tab. This button is enabled after preview results of the selected
         * activity model, response type and pricing for testing and creates the
         * response model for the user.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                exportPreviewPanel.removeAll();
                exportPreviewPanel.updateUI();

                int responseType = -1;
                String responseString = "";
                // Check for the selected response type
                if (optimalCaseRadioButton.isSelected()) {
                    responseType = 0;
                    responseString = "Optimal";
                } else if (normalCaseRadioButton.isSelected()) {
                    responseType = 1;
                    responseString = "Normal";
                } else if (discreteCaseRadioButton.isSelected()) {
                    responseType = 2;
                    responseString = "Discrete";
                }

                // Parse the pricing schemes
                double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText());
                double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText());

                // Create the response model
                ActivityModel activity = installation.getPerson()
                        .findActivity(activitySelectList.getSelectedValue(), false);

                String response = "";

                float awareness = (float) (awarenessSlider.getValue()) / 100;
                float sensitivity = (float) (sensitivitySlider.getValue()) / 100;

                System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity);

                try {
                    response = installation.getPerson().createResponse(activity, responseType, basicScheme,
                            newScheme, awareness, sensitivity);
                } catch (IOException exc) {

                    exc.printStackTrace();
                }

                // Add the response model extracted to the export model list.
                int size = exportModelList.getModel().getSize();
                // System.out.println(size);

                if (size > 0) {
                    exportModels = (DefaultListModel<String>) exportModelList.getModel();

                    String response2 = "", response3 = "";
                    if (responseString.equalsIgnoreCase("Optimal")) {
                        response2 = response.replace(responseString, "Normal");
                        response3 = response.replace(responseString, "Discrete");
                    } else if (responseString.equalsIgnoreCase("Normal")) {
                        response2 = response.replace(responseString, "Optimal");
                        response3 = response.replace(responseString, "Discrete");
                    } else {
                        response2 = response.replace(responseString, "Optimal");
                        response3 = response.replace(responseString, "Normal");
                    }

                    if (exportModels.contains(response2))
                        exportModels.removeElement(response2);
                    if (exportModels.contains(response3))
                        exportModels.removeElement(response3);

                    if (exportModels.contains(response) == false)
                        exportModels.addElement(response);
                } else {
                    exportModels = new DefaultListModel<String>();
                    exportModels.addElement(response);
                    exportModelList.setEnabled(true);
                }
                exportModelList.setModel(exportModels);

                if (manyFlag == false) {

                    JFrame success = new JFrame();

                    JOptionPane.showMessageDialog(success,
                            "The response model " + response + " was created successfully",
                            "Response Model Created", JOptionPane.INFORMATION_MESSAGE);
                }
            }

            finally {
                root.setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    createResponseAllButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Create Response All
         * button on the Response Parameters panel of the Create Response Models
         * tab. This is achieved by iterating the procedure above for all the
         * available activity models in the list.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {
            manyFlag = true;

            for (int i = 0; i < activitySelectList.getModel().getSize(); i++) {
                activitySelectList.setSelectedIndex(i);
                createResponseButton.doClick();
            }

            JFrame success = new JFrame();

            JOptionPane.showMessageDialog(success, "The response models were created successfully",
                    "Response Models Created", JOptionPane.INFORMATION_MESSAGE);

            manyFlag = false;
        }
    });

    newPricingSchemePane.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent arg0) {
            commitButton.setEnabled(true);
        }
    });

    basicPricingSchemePane.addCaretListener(new CaretListener() {
        @Override
        public void caretUpdate(CaretEvent arg0) {
            commitButton.setEnabled(true);
        }
    });

    commitButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Commit button on the
         * Pricing Scheme panel of the Create Response Models tab. This button is
         * enabled after adding the two pricing schemes that are prerequisites for
         * the creation of a response model.
         */
        @Override
        public void actionPerformed(ActionEvent e) {

            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                boolean basicScheme = false;
                boolean newScheme = false;
                int parseBasic = 0;
                int parseNew = 0;

                pricingPreviewPanel.removeAll();

                // Check if both pricing schemes are entered
                if (basicPricingSchemePane.getText().equalsIgnoreCase("") == false)
                    basicScheme = true;

                if (newPricingSchemePane.getText().equalsIgnoreCase("") == false)
                    newScheme = true;

                // Parse the pricing schemes for errors
                if (basicScheme)
                    parseBasic = Utils.parsePricingScheme(basicPricingSchemePane.getText());

                if (newScheme)
                    parseNew = Utils.parsePricingScheme(newPricingSchemePane.getText());

                // If errors are found then present the line the error may be at
                if (parseBasic != -1) {
                    JFrame error = new JFrame();

                    JOptionPane.showMessageDialog(error,
                            "Basic Pricing Scheme is not defined correctly. Please check your input in line "
                                    + parseBasic + " and try again.",
                            "Inane error", JOptionPane.ERROR_MESSAGE);
                } else if (parseNew != -1) {
                    JFrame error = new JFrame();

                    JOptionPane.showMessageDialog(error,
                            "New Pricing Scheme is not defined correctly. Please check your input in line "
                                    + parseNew + " and try again.",
                            "Inane error", JOptionPane.ERROR_MESSAGE);
                }
                // If no errors are found make a preview chart of the two pricing
                // schemes
                else {
                    if (basicScheme && newScheme) {
                        ChartPanel chartPanel = ChartUtils.parsePricingScheme(basicPricingSchemePane.getText(),
                                newPricingSchemePane.getText());

                        pricingPreviewPanel.add(chartPanel, BorderLayout.CENTER);
                        pricingPreviewPanel.validate();

                        previewResponseButton.setEnabled(true);

                    } else {
                        JFrame error = new JFrame();

                        JOptionPane.showMessageDialog(error,
                                "You have not defined both pricing schemes.Please check your input and try again.",
                                "Inane error", JOptionPane.ERROR_MESSAGE);
                        previewResponseButton.setEnabled(false);
                    }
                }

                responsePanel.removeAll();
                responsePanel.validate();
                createResponseButton.setEnabled(false);
                createResponseAllButton.setEnabled(false);
                dailyResponseButton.setEnabled(false);
                startResponseButton.setEnabled(false);

            }

            finally {
                root.setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    startResponseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the start time button on
         * the Preview Response panel of the Create Response Models tab. This
         * button is enabled after the user has pressed the Response Preview
         * button in order to see the results of his pricing scheme on a activity
         * model. It shows the changes in the start time distribution.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                responsePanel.removeAll();

                // Find the selected activity
                ActivityModel activity = installation.getPerson()
                        .findActivity(activitySelectList.getSelectedValue(), false);

                int response = -1;

                // Check for the selected response type
                if (optimalCaseRadioButton.isSelected())
                    response = 0;
                else if (normalCaseRadioButton.isSelected())
                    response = 1;
                else
                    response = 2;

                // Parse the pricing schemes
                double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText());
                double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText());

                float awareness = (float) (awarenessSlider.getValue()) / 100;
                float sensitivity = (float) (sensitivitySlider.getValue()) / 100;

                System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity);

                // Create a preview chart of the response model
                ChartPanel chartPanel = installation.getPerson().previewResponse(activity, response,
                        basicScheme, newScheme, awareness, sensitivity);

                responsePanel.add(chartPanel, BorderLayout.CENTER);
                responsePanel.validate();

                createResponseButton.setEnabled(true);
                createResponseAllButton.setEnabled(true);
                dailyResponseButton.setEnabled(true);
                startResponseButton.setEnabled(true);
            } finally {
                root.setCursor(Cursor.getDefaultCursor());
            }

        }
    });

    dailyResponseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the start time button on
         * the Preview Response panel of the Create Response Models tab. This
         * button is enabled after the user has pressed the Response Preview
         * button in order to see the results of his pricing scheme on a activity
         * model. It shows the changes in the daily times distribution.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                responsePanel.removeAll();

                // Find the selected activity
                ActivityModel activity = installation.getPerson()
                        .findActivity(activitySelectList.getSelectedValue(), false);

                // Parse the pricing schemes
                double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText());
                double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText());

                float awareness = (float) (awarenessSlider.getValue()) / 100;
                float sensitivity = (float) (sensitivitySlider.getValue()) / 100;

                System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity);

                // Create a preview chart of the response model
                ChartPanel chartPanel = installation.getPerson().previewDailyResponse(activity, basicScheme,
                        newScheme, awareness, sensitivity);

                responsePanel.add(chartPanel, BorderLayout.CENTER);
                responsePanel.validate();

                createResponseButton.setEnabled(true);
                createResponseAllButton.setEnabled(true);
                dailyResponseButton.setEnabled(true);
                startResponseButton.setEnabled(true);
            } finally {
                root.setCursor(Cursor.getDefaultCursor());
            }

        }
    });

    // EXPORT TAB //

    exportTab.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentShown(ComponentEvent arg0) {
            exportModelList.setSelectedIndex(0);
        }
    });

    exportModelList.addListSelectionListener(new ListSelectionListener() {
        /**
         * This function is called when the user selects an entity from the
         * list of models on the Model Export Selection panel of the Export Models
         * tab. Then the corresponding preview of the entity model is presented in
         * the
         * Export Model Preview panel.
         */
        @Override
        public void valueChanged(ListSelectionEvent arg0) {
            if (tabbedPane.getSelectedIndex() == 3) {
                exportPreviewPanel.removeAll();
                exportPreviewPanel.updateUI();

                // Checking if the list has any object
                if (exportModels.size() > 1) {
                    String selection = exportModelList.getSelectedValue();

                    // Check to see what type of entity is selected (Installation,
                    // Person, Appliance, Activity, Response)
                    Appliance appliance = installation.findAppliance(selection);

                    ActivityModel activity = installation.getPerson().findActivity(selection, false);

                    ResponseModel response = installation.getPerson().findResponse(selection);

                    // Create the appropriate chart for the selected entity and show it.
                    ChartPanel chartPanel = null;

                    if (selection.equalsIgnoreCase(installation.getName())) {

                        try {
                            chartPanel = installation.measurementsChart();

                            exportDailyButton.setEnabled(false);
                            exportDurationButton.setEnabled(false);
                            exportStartButton.setEnabled(false);
                            exportStartBinnedButton.setEnabled(false);
                            if (trained)
                                exportExpectedPowerButton.setEnabled(true);
                            else
                                exportExpectedPowerButton.setEnabled(false);
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }

                    } else if (selection.equalsIgnoreCase(installation.getPerson().getName())) {

                        chartPanel = installation.getPerson().statisticGraphs();

                        exportDailyButton.setEnabled(false);
                        exportDurationButton.setEnabled(false);
                        exportStartButton.setEnabled(false);
                        exportStartBinnedButton.setEnabled(false);
                        exportExpectedPowerButton.setEnabled(false);

                    } else if (appliance != null) {

                        chartPanel = appliance.consumptionGraph();

                        exportDailyButton.setEnabled(false);
                        exportDurationButton.setEnabled(false);
                        exportStartButton.setEnabled(false);
                        exportStartBinnedButton.setEnabled(false);
                        exportExpectedPowerButton.setEnabled(false);

                    } else if (activity != null) {

                        chartPanel = activity.createDailyTimesDistributionChart();
                        activity.status();
                        exportDailyButton.setEnabled(true);
                        exportDurationButton.setEnabled(true);
                        exportStartButton.setEnabled(true);
                        exportStartBinnedButton.setEnabled(true);
                        exportExpectedPowerButton.setEnabled(true);
                    } else if (response != null) {

                        chartPanel = response.createDailyTimesDistributionChart();

                        exportDailyButton.setEnabled(true);
                        exportDurationButton.setEnabled(true);
                        exportStartButton.setEnabled(true);
                        exportStartBinnedButton.setEnabled(true);
                        exportExpectedPowerButton.setEnabled(true);
                    }

                    exportPreviewPanel.add(chartPanel, BorderLayout.CENTER);
                    exportPreviewPanel.validate();
                }
            }
        }
    });

    exportDailyButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Daily Times
         * button on the Entity Preview panel of the Export Models tab. It shows
         * the Daily Times Distribution for the selected object from the list.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            exportPreviewPanel.removeAll();
            exportPreviewPanel.updateUI();

            String selection = exportModelList.getSelectedValue();

            ActivityModel activity = installation.getPerson().findActivity(selection, false);

            ResponseModel response = installation.getPerson().findResponse(selection);

            ChartPanel chartPanel = null;

            if (activity != null)
                chartPanel = activity.createDailyTimesDistributionChart();

            else
                chartPanel = response.createDailyTimesDistributionChart();

            exportPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            exportPreviewPanel.validate();
        }
    });

    exportStartBinnedButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Start Time Binned
         * button on the Entity Preview panel of the Export Models tab. It shows
         * the Start Time Binned Distribution for the selected object from the
         * list.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            exportPreviewPanel.removeAll();
            exportPreviewPanel.updateUI();

            String selection = exportModelList.getSelectedValue();

            ActivityModel activity = installation.getPerson().findActivity(selection, false);

            ResponseModel response = installation.getPerson().findResponse(selection);

            ChartPanel chartPanel = null;

            if (activity != null)
                chartPanel = activity.createStartTimeBinnedDistributionChart();

            else
                chartPanel = response.createStartTimeBinnedDistributionChart();

            exportPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            exportPreviewPanel.validate();

        }
    });

    exportStartButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Start Time
         * button on the Entity Preview panel of the Export Models tab. It shows
         * the Start Time Distribution for the selected object from the list.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            exportPreviewPanel.removeAll();
            exportPreviewPanel.updateUI();

            String selection = exportModelList.getSelectedValue();

            ActivityModel activity = installation.getPerson().findActivity(selection, false);

            ResponseModel response = installation.getPerson().findResponse(selection);

            ChartPanel chartPanel = null;

            if (activity != null)
                chartPanel = activity.createStartTimeDistributionChart();
            else
                chartPanel = response.createStartTimeDistributionChart();

            exportPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            exportPreviewPanel.validate();

        }
    });

    exportDurationButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Duration
         * button on the Entity Preview panel of the Export Models tab. It shows
         * the Duration Distribution for the selected object from the list.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            exportPreviewPanel.removeAll();
            exportPreviewPanel.updateUI();

            String selection = exportModelList.getSelectedValue();

            ActivityModel activity = installation.getPerson().findActivity(selection, false);

            ResponseModel response = installation.getPerson().findResponse(selection);

            ChartPanel chartPanel = null;

            if (activity != null)
                chartPanel = activity.createDurationDistributionChart();
            else
                chartPanel = response.createDurationDistributionChart();

            exportPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            exportPreviewPanel.validate();

        }
    });

    exportExpectedPowerButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            exportPreviewPanel.removeAll();
            exportPreviewPanel.updateUI();

            String selection = exportModelList.getSelectedValue();

            ActivityModel activity = installation.getPerson().findActivity(selection, false);

            ResponseModel response = installation.getPerson().findResponse(selection);

            ChartPanel chartPanel = null;

            if (selection.equalsIgnoreCase(installation.getName()))
                chartPanel = installation.createExpectedPowerChart();
            else if (activity != null)
                chartPanel = activity.createExpectedPowerChart();
            else
                chartPanel = response.createExpectedPowerChart();

            exportPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            exportPreviewPanel.validate();

        }
    });

    connectButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Connect button on the
         * Connection Properties panel of the Export Models tab. It helps the user
         * to connect to his Cassandra Library and export the models he created
         * there.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            boolean result = false;

            // Reads the user credentials and the server to connect to.
            try {
                APIUtilities.setUrl(urlTextField.getText());

                result = APIUtilities.sendUserCredentials(usernameTextField.getText(),
                        passwordField.getPassword());
            } catch (Exception e1) {
                e1.printStackTrace();
            }

            // If the use credentials are correct
            if (result) {
                exportButton.setEnabled(true);
                exportAllBaseButton.setEnabled(true);
                exportAllResponseButton.setEnabled(true);
                householdNameTextField.setEnabled(true);
            }
            // Else a error message appears.
            else {
                JFrame error = new JFrame();

                JOptionPane.showMessageDialog(error, "User Credentials are not correct! Please try again.",
                        "Inane error", JOptionPane.ERROR_MESSAGE);
                passwordField.setText("");
            }

        }
    });

    passwordField.addCaretListener(new CaretListener() {
        @Override
        public void caretUpdate(CaretEvent e) {
            String pass = String.valueOf(passwordField.getPassword());

            if (pass.equals("")) {
                connectButton.setEnabled(false);
            } else
                connectButton.setEnabled(true);
        }
    });

    exportButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Export button on the
         * Connection Properties panel of the Export Models tab. The entity model
         * selected from the list is then exported to the User Library in
         * Cassandra Platform.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                // Parsing the selected entity and find out what type of entity it is.
                String selection = exportModelList.getSelectedValue();

                Appliance appliance = installation.findAppliance(selection);

                ActivityModel activity = installation.getPerson().findActivity(selection, false);

                ResponseModel response = installation.getPerson().findResponse(selection);

                // If it is installation
                if (selection.equalsIgnoreCase(installation.getName())) {
                    String oldName = installation.getName();
                    installation.setName(householdNameTextField.getText());

                    try {
                        installation.setInstallationID(APIUtilities
                                .sendEntity(installation.toJSON(APIUtilities.getUserID()).toString(), "/inst"));

                    } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                        e1.printStackTrace();
                    }

                    installation.setName(oldName);

                    JFrame success = new JFrame();

                    JOptionPane.showMessageDialog(success,
                            "The installation model " + installation.getName() + " was exported successfully",
                            "Installation Model Exported", JOptionPane.INFORMATION_MESSAGE);

                }
                // If it is person
                else if (selection.equalsIgnoreCase(installation.getPerson().getName())) {

                    try {
                        installation.getPerson().setPersonID(APIUtilities.sendEntity(
                                installation.getPerson().toJSON(APIUtilities.getUserID()).toString(), "/pers"));
                    } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                        e1.printStackTrace();
                    }

                    JFrame success = new JFrame();

                    JOptionPane.showMessageDialog(success,
                            "The person model " + installation.getPerson().getName()
                                    + " was exported successfully",
                            "Person Model Exported", JOptionPane.INFORMATION_MESSAGE);

                }
                // If it is appliance
                else if (appliance != null) {

                    try {
                        appliance.setApplianceID(APIUtilities
                                .sendEntity(appliance.toJSON(APIUtilities.getUserID()).toString(), "/app"));

                        APIUtilities.sendEntity(appliance.powerConsumptionModelToJSON().toString(), "/consmod");

                    } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                        e1.printStackTrace();
                    }

                    JFrame success = new JFrame();

                    JOptionPane.showMessageDialog(success,
                            "The appliance model " + appliance.getName() + " was exported successfully",
                            "Appliance Model Exported", JOptionPane.INFORMATION_MESSAGE);

                }
                // If it is activity
                else if (activity != null) {

                    String[] applianceTemp = new String[activity.getAppliancesOf().length];
                    String activityTemp = "";
                    String durationTemp = "";
                    String dailyTemp = "";
                    String startTemp = "";

                    // For each appliance that participates in the activity
                    for (int i = 0; i < activity.getAppliancesOf().length; i++) {

                        Appliance activityAppliance = activity.getAppliancesOf()[i];

                        try {
                            // In case the appliances contained in the Activity model are
                            // not
                            // in the database, we create the object there before sending
                            // the
                            // activity model
                            if (activityAppliance.getApplianceID().equalsIgnoreCase("")) {

                                activityAppliance.setApplianceID(APIUtilities.sendEntity(
                                        activityAppliance.toJSON(APIUtilities.getUserID()).toString(), "/app"));

                                APIUtilities.sendEntity(
                                        activityAppliance.powerConsumptionModelToJSON().toString(), "/consmod");
                            }
                            applianceTemp[i] = activityAppliance.getApplianceID();
                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    }

                    try {

                        String[] appliancesID = applianceTemp;

                        // Creating the JSON of the activity model
                        activity.setActivityModelID(APIUtilities.sendEntity(
                                activity.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod"));

                        activityTemp = activity.getActivityModelID();

                        // Creating the JSON of the distributions
                        activity.getDailyTimes().setDistributionID(APIUtilities.sendEntity(
                                activity.getDailyTimes().toJSON(activityTemp).toString(), "/distr"));

                        activity.setDailyID(activity.getDailyTimes().getDistributionID());
                        dailyTemp = activity.getDailyID();

                        activity.getDuration().setDistributionID(APIUtilities
                                .sendEntity(activity.getDuration().toJSON(activityTemp).toString(), "/distr"));

                        activity.setDurationID(activity.getDuration().getDistributionID());
                        durationTemp = activity.getDurationID();

                        activity.getStartTime().setDistributionID(APIUtilities
                                .sendEntity(activity.getStartTime().toJSON(activityTemp).toString(), "/distr"));

                        activity.setStartID(activity.getStartTime().getDistributionID());
                        startTemp = activity.getStartID();

                        // Adding the JSON of the distributions to the activity model
                        APIUtilities.updateEntity(
                                activity.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod",
                                activityTemp);

                    } catch (AuthenticationException | NoSuchAlgorithmException | IOException e1) {

                        e1.printStackTrace();
                    }

                    JFrame success = new JFrame();

                    JOptionPane.showMessageDialog(success,
                            "The activity model " + activity.getName() + " was exported successfully",
                            "Activity Model Exported", JOptionPane.INFORMATION_MESSAGE);

                }
                // If it is response
                else if (response != null) {
                    String[] applianceTemp = new String[response.getAppliancesOf().length];

                    String responseTemp = "";
                    String durationTemp = "";
                    String dailyTemp = "";
                    String startTemp = "";

                    // For each appliance that participates in the activity
                    for (int i = 0; i < response.getAppliancesOf().length; i++) {

                        Appliance responseAppliance = response.getAppliancesOf()[i];

                        try {
                            // In case the appliances contained in the Activity model are
                            // not
                            // in the database, we create the object there before sending
                            // the
                            // activity model
                            if (responseAppliance.getApplianceID().equalsIgnoreCase("")) {

                                responseAppliance.setApplianceID(APIUtilities.sendEntity(
                                        responseAppliance.toJSON(APIUtilities.getUserID()).toString(), "/app"));

                                APIUtilities.sendEntity(
                                        responseAppliance.powerConsumptionModelToJSON().toString(), "/consmod");
                            }
                            applianceTemp[i] = responseAppliance.getApplianceID();
                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }
                    }

                    try {

                        String[] appliancesID = applianceTemp;

                        // Creating the JSON of the response
                        response.setActivityModelID(APIUtilities.sendEntity(
                                response.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod"));

                        responseTemp = response.getActivityModelID();

                        // Creating the JSON of the distributions
                        response.getDailyTimes().setDistributionID(APIUtilities.sendEntity(
                                response.getDailyTimes().toJSON(responseTemp).toString(), "/distr"));

                        response.setDailyID(response.getDailyTimes().getDistributionID());
                        dailyTemp = response.getDailyID();

                        response.getDuration().setDistributionID(APIUtilities
                                .sendEntity(response.getDuration().toJSON(responseTemp).toString(), "/distr"));

                        response.setDurationID(response.getDuration().getDistributionID());
                        durationTemp = response.getDurationID();

                        response.getStartTime().setDistributionID(APIUtilities
                                .sendEntity(response.getStartTime().toJSON(responseTemp).toString(), "/distr"));

                        response.setStartID(response.getStartTime().getDistributionID());
                        startTemp = response.getStartID();

                        // Adding the JSON of the distributions to the activity model
                        APIUtilities.updateEntity(
                                response.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod",
                                responseTemp);

                    } catch (AuthenticationException | NoSuchAlgorithmException | IOException e1) {

                        e1.printStackTrace();
                    }

                    JFrame success = new JFrame();

                    JOptionPane.showMessageDialog(success,
                            "The response model " + response.getName() + " was exported successfully",
                            "Response Model Exported", JOptionPane.INFORMATION_MESSAGE);

                }
            }

            finally {
                root.setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    exportAllBaseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Export All Base
         * button on the Connection Properties panel of the Export Models tab. The
         * export procedure above is iterated through all the entities available
         * on the list except for the response models.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                for (int i = 0; i < exportModelList.getModel().getSize(); i++) {
                    exportModelList.setSelectedIndex(i);

                    String selection = exportModelList.getSelectedValue();

                    Appliance appliance = installation.findAppliance(selection);

                    ActivityModel activity = installation.getPerson().findActivity(selection, false);

                    ResponseModel response = installation.getPerson().findResponse(selection);

                    if (selection.equalsIgnoreCase(installation.getName())) {

                        String oldName = installation.getName();

                        try {

                            installation.setName(householdNameTextField.getText() + " Base");

                            installation.setInstallationID(APIUtilities.sendEntity(
                                    installation.toJSON(APIUtilities.getUserID()).toString(), "/inst"));

                            installation.setName(oldName);
                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    } else if (selection.equalsIgnoreCase(installation.getPerson().getName())) {

                        try {
                            installation.getPerson().setPersonID(APIUtilities.sendEntity(installation
                                    .getPerson().toJSON(installation.getInstallationID()).toString(), "/pers"));
                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    } else if (appliance != null) {

                        try {
                            appliance.setApplianceID(APIUtilities.sendEntity(
                                    appliance.toJSON(installation.getInstallationID().toString()).toString(),
                                    "/app"));

                            APIUtilities.sendEntity(appliance.powerConsumptionModelToJSON().toString(),
                                    "/consmod");

                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    } else if (activity != null) {

                        String[] applianceTemp = new String[activity.getAppliancesOf().length];

                        String personTemp = "";
                        String activityTemp = "";
                        String durationTemp = "";
                        String dailyTemp = "";
                        String startTemp = "";

                        // For each appliance that participates in the activity
                        for (int j = 0; j < activity.getAppliancesOf().length; j++) {

                            Appliance activityAppliance = activity.getAppliancesOf()[j];
                            applianceTemp[j] = activityAppliance.getApplianceID();
                        }

                        personTemp = installation.getPerson().getPersonID();

                        try {

                            activity.setActivityID(APIUtilities
                                    .sendEntity(activity.activityToJSON(personTemp).toString(), "/act"));

                            String[] appliancesID = applianceTemp;

                            activity.setActivityModelID(APIUtilities
                                    .sendEntity(activity.toJSON(appliancesID).toString(), "/actmod"));
                            activityTemp = activity.getActivityModelID();

                            activity.getDailyTimes().setDistributionID(APIUtilities.sendEntity(
                                    activity.getDailyTimes().toJSON(activityTemp).toString(), "/distr"));
                            activity.setDailyID(activity.getDailyTimes().getDistributionID());
                            dailyTemp = activity.getDailyID();

                            activity.getDuration().setDistributionID(APIUtilities.sendEntity(
                                    activity.getDuration().toJSON(activityTemp).toString(), "/distr"));

                            activity.setDurationID(activity.getDuration().getDistributionID());
                            durationTemp = activity.getDurationID();

                            activity.getStartTime().setDistributionID(APIUtilities.sendEntity(
                                    activity.getStartTime().toJSON(activityTemp).toString(), "/distr"));

                            activity.setStartID(activity.getStartTime().getDistributionID());
                            startTemp = activity.getStartID();

                            APIUtilities.updateEntity(activity.toJSON(appliancesID).toString(), "/actmod",
                                    activityTemp);

                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    } else if (response != null) {

                    }
                }

            }

            finally {
                root.setCursor(Cursor.getDefaultCursor());
            }

            JFrame success = new JFrame();

            JOptionPane.showMessageDialog(success, "The installation model " + installation.getName()
                    + " for the base pricing scheme and all the entities contained within were exported successfully",
                    "Installation Model Exported", JOptionPane.INFORMATION_MESSAGE);

        }
    });

    exportAllResponseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Export All Base
         * button on the Connection Properties panel of the Export Models tab. The
         * export procedure above is iterated through all the entities available
         * on the list except for the activity models.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                for (int i = 0; i < exportModelList.getModel().getSize(); i++) {
                    exportModelList.setSelectedIndex(i);

                    String selection = exportModelList.getSelectedValue();

                    Appliance appliance = installation.findAppliance(selection);

                    ActivityModel activity = installation.getPerson().findActivity(selection, false);

                    ResponseModel response = installation.getPerson().findResponse(selection);

                    if (selection.equalsIgnoreCase(installation.getName())) {

                        String oldName = installation.getName();

                        try {

                            installation.setName(householdNameTextField.getText() + " Response");

                            installation.setInstallationID(APIUtilities.sendEntity(
                                    installation.toJSON(APIUtilities.getUserID()).toString(), "/inst"));

                            installation.setName(oldName);

                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    } else if (selection.equalsIgnoreCase(installation.getPerson().getName())) {

                        try {
                            installation.getPerson().setPersonID(APIUtilities.sendEntity(installation
                                    .getPerson().toJSON(installation.getInstallationID()).toString(), "/pers"));
                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    } else if (appliance != null) {

                        try {
                            appliance.setApplianceID(APIUtilities.sendEntity(
                                    appliance.toJSON(installation.getInstallationID().toString()).toString(),
                                    "/app"));

                            APIUtilities.sendEntity(appliance.powerConsumptionModelToJSON().toString(),
                                    "/consmod");

                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    } else if (activity != null) {

                    } else if (response != null) {
                        String[] applianceTemp = new String[response.getAppliancesOf().length];

                        String personTemp = "";
                        String responseTemp = "";
                        String durationTemp = "";
                        String dailyTemp = "";
                        String startTemp = "";

                        // For each appliance that participates in the activity
                        for (int j = 0; j < response.getAppliancesOf().length; j++) {

                            Appliance responseAppliance = response.getAppliancesOf()[j];

                            applianceTemp[j] = responseAppliance.getApplianceID();
                        }
                        personTemp = installation.getPerson().getPersonID();

                        try {

                            response.setActivityID(APIUtilities
                                    .sendEntity(response.activityToJSON(personTemp).toString(), "/act"));

                            String[] appliancesID = applianceTemp;

                            response.setActivityModelID(APIUtilities
                                    .sendEntity(response.toJSON(appliancesID).toString(), "/actmod"));
                            responseTemp = response.getActivityModelID();

                            response.getDailyTimes().setDistributionID(APIUtilities.sendEntity(
                                    response.getDailyTimes().toJSON(responseTemp).toString(), "/distr"));
                            response.setDailyID(response.getDailyTimes().getDistributionID());
                            dailyTemp = response.getDailyID();

                            response.getDuration().setDistributionID(APIUtilities.sendEntity(
                                    response.getDuration().toJSON(responseTemp).toString(), "/distr"));

                            response.setDurationID(response.getDuration().getDistributionID());
                            durationTemp = response.getDurationID();

                            response.getStartTime().setDistributionID(APIUtilities.sendEntity(
                                    response.getStartTime().toJSON(responseTemp).toString(), "/distr"));

                            response.setStartID(response.getStartTime().getDistributionID());
                            startTemp = response.getStartID();

                            APIUtilities.updateEntity(response.toJSON(appliancesID).toString(), "/actmod",
                                    responseTemp);

                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }

            finally {
                root.setCursor(Cursor.getDefaultCursor());
            }

            JFrame success = new JFrame();

            JOptionPane.showMessageDialog(success, "The installation model " + installation.getName()
                    + " for the new pricing scheme and all the entities contained within were exported successfully",
                    "Installation Model Exported", JOptionPane.INFORMATION_MESSAGE);
        }
    });
}

From source file:userinterface.properties.GUIGraphHandler.java

public void plotNewFunction() {

    JDialog dialog;//from   w w w.  java  2s .  c o  m
    JRadioButton radio2d, radio3d, newGraph, existingGraph;
    JTextField functionField, seriesName;
    JButton ok, cancel;
    JComboBox<String> chartOptions;
    JLabel example;

    //init all the fields of the dialog
    dialog = new JDialog(GUIPrism.getGUI());
    radio2d = new JRadioButton("2D");
    radio3d = new JRadioButton("3D");
    newGraph = new JRadioButton("New Graph");
    existingGraph = new JRadioButton("Exisiting");
    chartOptions = new JComboBox<String>();
    functionField = new JTextField();
    ok = new JButton("Plot");
    cancel = new JButton("Cancel");
    seriesName = new JTextField();
    example = new JLabel("<html><font size=3 color=red>Example:</font><font size=3>x/2 + 5</font></html>");
    example.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseEntered(MouseEvent e) {
            example.setCursor(new Cursor(Cursor.HAND_CURSOR));
            example.setForeground(Color.BLUE);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            example.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            example.setForeground(Color.BLACK);
        }

        @Override
        public void mouseClicked(MouseEvent e) {

            if (e.getButton() == MouseEvent.BUTTON1) {

                if (radio2d.isSelected()) {
                    functionField.setText("x/2 + 5");
                } else {
                    functionField.setText("x+y+5");
                }

                functionField.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
                functionField.setForeground(Color.BLACK);

            }
        }

    });

    //set dialog properties
    dialog.setSize(400, 350);
    dialog.setTitle("Plot a new function");
    dialog.setModal(true);
    dialog.setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
    dialog.setLocationRelativeTo(GUIPrism.getGUI());

    //add every component to their dedicated panels
    JPanel graphTypePanel = new JPanel(new FlowLayout());
    graphTypePanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Function type"));
    graphTypePanel.add(radio2d);
    graphTypePanel.add(radio3d);

    JPanel functionFieldPanel = new JPanel(new BorderLayout());
    functionFieldPanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Function"));
    functionFieldPanel.add(functionField, BorderLayout.CENTER);
    functionFieldPanel.add(example, BorderLayout.SOUTH);

    JPanel chartSelectPanel = new JPanel();
    chartSelectPanel.setLayout(new BoxLayout(chartSelectPanel, BoxLayout.Y_AXIS));
    chartSelectPanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Plot function to"));
    JPanel radioPlotPanel = new JPanel(new FlowLayout());
    radioPlotPanel.add(newGraph);
    radioPlotPanel.add(existingGraph);
    JPanel chartOptionsPanel = new JPanel(new FlowLayout());
    chartOptionsPanel.add(chartOptions);
    chartSelectPanel.add(radioPlotPanel);
    chartSelectPanel.add(chartOptionsPanel);

    JPanel bottomControlPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    bottomControlPanel.add(ok);
    bottomControlPanel.add(cancel);

    JPanel seriesNamePanel = new JPanel(new BorderLayout());
    seriesNamePanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Series name"));
    seriesNamePanel.add(seriesName, BorderLayout.CENTER);

    // add all the panels to the dialog

    dialog.add(graphTypePanel);
    dialog.add(functionFieldPanel);
    dialog.add(chartSelectPanel);
    dialog.add(seriesNamePanel);
    dialog.add(bottomControlPanel);

    // do all the enables and set properties

    radio2d.setSelected(true);
    newGraph.setSelected(true);
    chartOptions.setEnabled(false);
    functionField.setText("Add function expression here....");
    functionField.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 15));
    functionField.setForeground(Color.GRAY);
    seriesName.setText("New function");
    ok.setMnemonic('P');
    cancel.setMnemonic('C');
    example.setToolTipText("click to try out");

    ok.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ok");
    ok.getActionMap().put("ok", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            ok.doClick();
        }
    });

    cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            "cancel");
    cancel.getActionMap().put("cancel", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            cancel.doClick();
        }
    });

    boolean found = false;

    for (int i = 0; i < theTabs.getTabCount(); i++) {

        if (theTabs.getComponentAt(i) instanceof Graph) {
            chartOptions.addItem(getGraphName(i));
            found = true;
        }
    }

    if (!found) {

        existingGraph.setEnabled(false);
        chartOptions.setEnabled(false);
    }

    //add all the action listeners

    radio2d.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (radio2d.isSelected()) {

                radio3d.setSelected(false);

                if (chartOptions.getItemCount() > 0) {
                    existingGraph.setEnabled(true);
                    chartOptions.setEnabled(true);
                }

                example.setText(
                        "<html><font size=3 color=red>Example:</font><font size=3>x/2 + 5</font></html>");
            }
        }
    });

    radio3d.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (radio3d.isSelected()) {

                radio2d.setSelected(false);
                newGraph.setSelected(true);
                existingGraph.setEnabled(false);
                chartOptions.setEnabled(false);
                example.setText("<html><font size=3 color=red>Example:</font><font size=3>x+y+5</font></html>");

            }

        }
    });

    newGraph.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (newGraph.isSelected()) {
                existingGraph.setSelected(false);
                chartOptions.setEnabled(false);
            }
        }
    });

    existingGraph.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (existingGraph.isSelected()) {

                newGraph.setSelected(false);
                chartOptions.setEnabled(true);
            }
        }
    });

    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            String function = functionField.getText();

            Expression expr = null;

            try {

                expr = GUIPrism.getGUI().getPrism().parseSingleExpressionString(function);
                expr = (Expression) expr.accept(new ASTTraverseModify() {

                    @Override
                    public Object visit(ExpressionIdent e) throws PrismLangException {
                        return new ExpressionConstant(e.getName(), TypeDouble.getInstance());
                    }

                });

                expr.typeCheck();
                expr.semanticCheck();

            } catch (PrismLangException e1) {

                // for copying style
                JLabel label = new JLabel();

                // html content in our case the error we want to show
                JEditorPane ep = new JEditorPane("text/html",
                        "<html> There was an error parsing the function. To read about what built-in"
                                + " functions are supported <br>and some more information on the functions, visit "
                                + "<a href='http://www.prismmodelchecker.org/manual/ThePRISMLanguage/Expressions'>Prism expressions site</a>."
                                + "<br><br><font color=red>Error: </font>" + e1.getMessage() + " </html>");

                // handle link events
                ep.addHyperlinkListener(new HyperlinkListener() {
                    @Override
                    public void hyperlinkUpdate(HyperlinkEvent e) {
                        if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
                            try {
                                Desktop.getDesktop().browse(e.getURL().toURI());
                            } catch (IOException | URISyntaxException e1) {

                                e1.printStackTrace();
                            }
                        }
                    }
                });
                ep.setEditable(false);
                ep.setBackground(label.getBackground());

                // show the error dialog
                JOptionPane.showMessageDialog(dialog, ep, "Parse Error", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (radio2d.isSelected()) {

                ParametricGraph graph = null;

                if (newGraph.isSelected()) {

                    graph = new ParametricGraph("");
                } else {

                    for (int i = 0; i < theTabs.getComponentCount(); i++) {

                        if (theTabs.getTitleAt(i).equals(chartOptions.getSelectedItem())) {

                            graph = (ParametricGraph) theTabs.getComponent(i);
                        }
                    }

                }

                dialog.dispose();
                defineConstantsAndPlot(expr, graph, seriesName.getText(), newGraph.isSelected(), true);

            } else if (radio3d.isSelected()) {

                try {

                    expr = (Expression) expr.accept(new ASTTraverseModify() {
                        @Override
                        public Object visit(ExpressionIdent e) throws PrismLangException {
                            return new ExpressionConstant(e.getName(), TypeDouble.getInstance());
                        }

                    });

                    expr.semanticCheck();
                    expr.typeCheck();

                } catch (PrismLangException e1) {
                    e1.printStackTrace();
                }

                if (expr.getAllConstants().size() < 2) {

                    JOptionPane.showMessageDialog(dialog,
                            "There are not enough variables in the function to plot a 3D chart!", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // its always a new graph
                ParametricGraph3D graph = new ParametricGraph3D(expr);
                dialog.dispose();
                defineConstantsAndPlot(expr, graph, seriesName.getText(), true, false);
            }

            dialog.dispose();
        }
    });

    cancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.dispose();
        }
    });

    // we will show info about the function when field is out of focus
    functionField.addFocusListener(new FocusListener() {

        @Override
        public void focusLost(FocusEvent e) {

            if (!functionField.getText().equals("")) {
                return;
            }

            functionField.setText("Add function expression here....");
            functionField.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 15));
            functionField.setForeground(Color.GRAY);
        }

        @Override
        public void focusGained(FocusEvent e) {

            if (!functionField.getText().equals("Add function expression here....")) {
                return;
            }

            functionField.setForeground(Color.BLACK);
            functionField.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
            functionField.setText("");
        }
    });

    // show the dialog
    dialog.setVisible(true);
}

From source file:org.kuali.test.creator.TestCreator.java

public void showHelp(ActionEvent e) {
    if (Desktop.isDesktopSupported()) {
        try {/*from  w  w  w . j a  va2 s .c o m*/
            File file = new File(getConfiguration().getRepositoryLocation() + Constants.HELP_FILE_PATH);

            if (StringUtils.isNotBlank(getConfiguration().getPdfViewerPath())) {
                Runtime.getRuntime().exec(getConfiguration().getPdfViewerPath() + " " + file.getPath());
            } else {
                Desktop.getDesktop().open(file);
            }
        }

        catch (Exception ex) {
            LOG.warn("Error ocurred opening help PDF file - " + ex.toString());
        }
    }
}

From source file:org.jajuk.util.UtilSystem.java

/**
 * Return whether the Desktop BROWSE action is actually supported
 * Note this bug : http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6486393
 * under KDE : isSupported returns true but we get an exception when actually browsing
 * //from   ww  w .j av a  2  s  .c  om
 * @return true, if checks if is browser supported
 */
public static boolean isBrowserSupported() {
    // value stored for perf
    if (browserSupported != null) {
        return browserSupported;
    }
    // In server UT mode, just return false
    if (GraphicsEnvironment.isHeadless()) {
        return false;
    } else {
        if (Desktop.isDesktopSupported()) {
            // If under Linux, check if we're under KDE because of a sun bug,
            // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6486393 and #1612
            if (isUnderLinux() && isUnderKDE()) {
                return false;
            } else {
                return (Desktop.getDesktop().isSupported(Desktop.Action.BROWSE));
            }
        } else {
            return false;
        }
    }
}

From source file:ui.main.MainViewController.java

private synchronized void paintReceivedPhotoLoad(Chat chat, File recievedFile, String time) {
    //this method paints the recieved picture message
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override//from   w w  w .  ja  va  2 s.  c  o  m
        protected HBox call() throws Exception {
            Thread.sleep(100);
            VBox vbox = new VBox(); //to add text

            ImageView imageRec = new ImageView(chatterAvatar.getImage()); //image
            imageRec.setFitHeight(60);
            imageRec.setFitWidth(50);

            String strChatterName = chat.getParticipant(); //add name of the chatter with light color
            strChatterName = Character.toUpperCase(strChatterName.charAt(0))
                    + strChatterName.substring(1, strChatterName.indexOf("@"));
            Label chatterName = new Label(strChatterName);
            chatterName.setDisable(true);

            Label timeL = new Label(time);
            timeL.setDisable(true);
            timeL.setFont(new Font("Arial", 10));

            try {
                Image recievedImage = SwingFXUtils.toFXImage(ImageIO.read(recievedFile), null);
                ImageView receivedImageView = new ImageView(recievedImage);
                receivedImageView.setFitHeight(300);
                receivedImageView.setFitWidth(300);
                receivedImageView.setPreserveRatio(true);

                receivedImageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        if (event.getButton() == MouseButton.PRIMARY) {
                            Desktop dt = Desktop.getDesktop();
                            try {
                                dt.open(recievedFile);
                            } catch (IOException ex) {
                                Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null,
                                        ex);
                            }
                        }
                    }
                });

                receivedImageView.setOnMouseEntered(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        chatList.getScene().setCursor(Cursor.HAND);
                    }
                });

                receivedImageView.setOnMouseExited(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        chatList.getScene().setCursor(Cursor.DEFAULT);
                    }
                });

                vbox.getChildren().addAll(chatterName, receivedImageView, timeL);
            } catch (IOException e) {
                e.printStackTrace();
            }
            vbox.setAlignment(Pos.CENTER_RIGHT);
            HBox hbox = new HBox();
            //bbl.setBubbleSpec(BubbleSpec.FACE_LEFT_CENTER);
            hbox.getChildren().addAll(imageRec, vbox);
            return hbox;
        }
    };

    recievedMessages.setOnSucceeded(event -> {
        chatList.getChildren().add(recievedMessages.getValue());
    });

    if (chat.getParticipant().contains(currentChat.getParticipant())) {
        Thread t = new Thread(recievedMessages);
        t.start();
        try {
            t.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}