Example usage for org.jfree.chart ChartFactory createPieChart

List of usage examples for org.jfree.chart ChartFactory createPieChart

Introduction

In this page you can find the example usage for org.jfree.chart ChartFactory createPieChart.

Prototype

public static JFreeChart createPieChart(String title, PieDataset dataset, boolean legend, boolean tooltips,
        boolean urls) 

Source Link

Document

Creates a pie chart with default settings.

Usage

From source file:org.talend.dataprofiler.chart.util.TopChartFactory.java

public static JFreeChart createDuplicateRecordPieChart(String title, PieDataset dataset, boolean showLegend,
        boolean toolTips, boolean urls) {
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
    JFreeChart pieChart = ChartFactory.createPieChart(title, dataset, showLegend, toolTips, urls);
    ChartDecorator.decorateDuplicatePieChart(pieChart);
    return pieChart;
}

From source file:com.qspin.qtaste.reporter.testresults.html.HTMLReportFormatter.java

private void generatePieChart() {
    if (currentTestSuite == null) {
        return;/*www .  j  av a2  s .  c om*/
    }

    File testSummaryFile = new File(reportFile.getParentFile(), testSummaryFileName);
    File tempTestSummaryFile = new File(testSummaryFile.getPath() + ".tmp");

    final DefaultPieDataset pieDataSet = new DefaultPieDataset();

    pieDataSet.setValue("Passed", new Integer(currentTestSuite.getNbTestsPassed()));
    pieDataSet.setValue("Failed", new Integer(currentTestSuite.getNbTestsFailed()));
    pieDataSet.setValue("Tests in error", new Integer(currentTestSuite.getNbTestsNotAvailable()));
    pieDataSet.setValue("Not executed",
            new Integer(currentTestSuite.getNbTestsToExecute() - currentTestSuite.getNbTestsExecuted()));
    JFreeChart chart = null;
    final boolean drilldown = true;

    // create the chart...
    if (drilldown) {
        final PiePlot plot = new PiePlot(pieDataSet);

        Color[] colors = { new Color(100, 230, 40), new Color(210, 35, 35), new Color(230, 210, 40),
                new Color(100, 90, 40) };
        PieRenderer renderer = new PieRenderer(colors);
        renderer.setColor(plot, (DefaultPieDataset) pieDataSet);

        plot.setURLGenerator(new StandardPieURLGenerator("pie_chart_detail.jsp"));
        plot.setLabelGenerator(new TestSectiontLabelPieGenerator());
        chart = new JFreeChart("Test summary", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    } else {
        chart = ChartFactory.createPieChart("Test summary", // chart title
                pieDataSet, // data
                true, // include legend
                true, false);
    }

    chart.setBackgroundPaint(java.awt.Color.white);

    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        ChartUtilities.saveChartAsPNG(tempTestSummaryFile, chart, 600, 400, info);
    } catch (IOException e) {
        logger.error("Problem saving png chart", e);
    }

    testSummaryFile.delete();
    if (!tempTestSummaryFile.renameTo(testSummaryFile)) {
        logger.error("Couldn't rename test summary file " + tempTestSummaryFile + " into " + testSummaryFile);
    }
}

From source file:com.modeln.build.ctrl.charts.CMnBuildListChart.java

/**
 * Generate a pie graph representing test counts for each product area. 
 *
 * @param   suites   List of test suites
 * @param   areas    List of product areas 
 * /*  ww  w  .j a v  a2s .c  o  m*/
 * @return  Pie graph representing build execution times across all builds 
 */
public static final JFreeChart getAverageAreaTestTimeChart(Vector<CMnDbBuildData> builds,
        Vector<CMnDbTestSuite> suites, Vector<CMnDbFeatureOwnerData> areas) {
    JFreeChart chart = null;

    // Collect the average of all test types 
    Hashtable timeAvg = new Hashtable();

    DefaultPieDataset dataset = new DefaultPieDataset();
    if ((suites != null) && (suites.size() > 0)) {

        // Collect test data for each of the suites in the list 
        Enumeration suiteList = suites.elements();
        while (suiteList.hasMoreElements()) {

            // Process the data for the current suite
            CMnDbTestSuite suite = (CMnDbTestSuite) suiteList.nextElement();
            Long elapsedTime = new Long(suite.getElapsedTime() / (1000 * 60));
            CMnDbFeatureOwnerData area = null;

            // Iterate through each product area to determine who owns this suite
            CMnDbFeatureOwnerData currentArea = null;
            Iterator iter = areas.iterator();
            while (iter.hasNext()) {
                currentArea = (CMnDbFeatureOwnerData) iter.next();
                if (currentArea.hasFeature(suite.getGroupName())) {
                    Long avgValue = null;
                    String areaName = currentArea.getDisplayName();
                    if (timeAvg.containsKey(areaName)) {
                        Long oldAvg = (Long) timeAvg.get(areaName);
                        avgValue = oldAvg + elapsedTime;
                    } else {
                        avgValue = elapsedTime;
                    }
                    timeAvg.put(areaName, avgValue);

                }
            }

        } // while list has elements

        // Populate the data set with the average values for each metric
        Enumeration keys = timeAvg.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            Long total = (Long) timeAvg.get(key);
            Long avg = new Long(total.longValue() / builds.size());
            dataset.setValue(key, avg);
        }

    } // if list has elements

    // API: ChartFactory.createPieChart(title, data, legend, tooltips, urls)
    chart = ChartFactory.createPieChart("Avg Test Time by Area", dataset, true, true, false);

    // get a reference to the plot for further customization...
    PiePlot plot = (PiePlot) chart.getPlot();
    chartFormatter.formatAreaChart(plot, "min");

    return chart;
}

From source file:UserInterface.ViewPatientJPanel.java

private void btnViewPieChartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewPieChartActionPerformed

    String weight = txtWeight.getText();
    String hrtRate = txtHeartRate.getText();
    String bp = txtSystolicBloodPressure.getText();
    String respiRate = txtRespiratoryRate.getText();

    DefaultPieDataset pieDataset = new DefaultPieDataset();

    pieDataset.setValue("Respiratory Rate", new Float(respiRate));
    pieDataset.setValue("Heart Rate", new Float(hrtRate));
    pieDataset.setValue("Blood Pressure", new Float(bp));
    pieDataset.setValue("Weight", new Float(weight));

    JFreeChart chart = ChartFactory.createPieChart("Pie chart", pieDataset, true, true, true);

    PiePlot P = (PiePlot) chart.getPlot();

    ChartFrame frame = new ChartFrame("Pie Charrt", chart);
    frame.setVisible(true);// w w  w .j  a v a2s.  c o m
    frame.setSize(450, 500);

}

From source file:ca.myewb.frame.servlet.GraphServlet.java

private JFreeChart getPost2Pie(Session s) {
    JFreeChart chart;/*from   w ww .j a v  a2  s  . com*/
    DefaultPieDataset ds = new DefaultPieDataset();

    int numPosts = 0;
    int numTypePosts = 0;

    String query = "select count(*) from PostModel as p where p.group.id=1 and p.date>?";
    numTypePosts = ((Long) s.createQuery(query).setDate(0, GraphServlet.getStartDate()).list().get(0))
            .intValue();
    ds.setValue("Org List", numTypePosts);
    numPosts += numTypePosts;

    query = "select count(*) from PostModel as p where p.group.admin=false and p.group.postName not like 'anyone in the%' and "
            + "p.group.public=true and p.group.parent is null and p.date>?";
    numTypePosts = ((Long) s.createQuery(query).setDate(0, GraphServlet.getStartDate()).list().get(0))
            .intValue();
    ds.setValue("General Public Lists", numTypePosts);
    numPosts += numTypePosts;

    query = "select count(*) from PostModel as p where p.group.admin=false and "
            + "p.group.public=false and p.group.parent is null and p.date>?";
    numTypePosts = ((Long) s.createQuery(query).setDate(0, GraphServlet.getStartDate()).list().get(0))
            .intValue();
    ds.setValue("General Private Lists", numTypePosts);
    numPosts += numTypePosts;

    query = "select count(*) from PostModel as p where p.group.admin=true and p.group.visible=true"
            + " and p.group.id != 1 and p.date>?";
    numTypePosts = ((Long) s.createQuery(query).setDate(0, GraphServlet.getStartDate()).list().get(0))
            .intValue();
    ds.setValue("All-exec Lists", numTypePosts);
    numPosts += numTypePosts;

    query = "select count(*) from PostModel as p where p.group.id = 14 and p.date>?";
    numTypePosts = ((Long) s.createQuery(query).setDate(0, GraphServlet.getStartDate()).list().get(0))
            .intValue();
    ds.setValue("Deleted Posts", numTypePosts);
    numPosts += numTypePosts;

    query = "select count(*) from PostModel as p where p.group.postName like 'anyone in the%' and p.date>?";
    numTypePosts = ((Long) s.createQuery(query).setDate(0, GraphServlet.getStartDate()).list().get(0))
            .intValue();
    ds.setValue("Chapter Lists", numTypePosts);
    numPosts += numTypePosts;

    query = "select count(*) from PostModel as p where p.group.parent!=null and "
            + "p.group.shortname='exec' and p.date>?";
    numTypePosts = ((Long) s.createQuery(query).setDate(0, GraphServlet.getStartDate()).list().get(0))
            .intValue();
    ds.setValue("Chapter-exec Lists", numTypePosts);
    numPosts += numTypePosts;

    query = "select count(*) from PostModel as p where p.group.parent!=null and "
            + "p.group.shortname!='exec' and p.group.public=true and p.date>?";
    numTypePosts = ((Long) s.createQuery(query).setDate(0, GraphServlet.getStartDate()).list().get(0))
            .intValue();
    ds.setValue("Chapter Public Lists", numTypePosts);
    numPosts += numTypePosts;

    query = "select count(*) from PostModel as p where p.group.parent!=null and "
            + "p.group.shortname!='exec' and p.group.public=false and p.date>?";
    numTypePosts = ((Long) s.createQuery(query).setDate(0, GraphServlet.getStartDate()).list().get(0))
            .intValue();
    ds.setValue("Chapter Private Lists", numTypePosts);
    numPosts += numTypePosts;

    chart = ChartFactory.createPieChart("Post Group Breakdown (for " + numPosts + " posts)", ds, false, false,
            false);

    PiePlot plot = ((PiePlot) chart.getPlot());
    StandardPieItemLabelGenerator n = new StandardPieItemLabelGenerator("{0} = {1} ({2})",
            new DecimalFormat("0"), new DecimalFormat("0.0%"));
    plot.setLabelGenerator(n);
    return chart;
}

From source file:com.intel.stl.ui.common.view.ComponentFactory.java

/**
 * Create a simple pie chart without title, legend, label etc.
 * //from ww w  . ja v  a  2  s .  c  o m
 * @param dataset
 *            the dataset to be renderer
 * @param colors
 *            an color array specify each item's color. The order of the
 *            array correspond to the item order in dataset
 * @return a pie chart
 */
public static JFreeChart createPlainPieChart(PieDataset dataset, Color[] colors) {
    if (dataset == null) {
        throw new IllegalArgumentException("No dataset.");
    }
    if (colors != null && colors.length != dataset.getItemCount()) {
        throw new IllegalArgumentException("Data have " + dataset.getItemCount() + " values, while we have "
                + colors.length + " colors for them.");
    }

    JFreeChart jfreechart = ChartFactory.createPieChart(null, dataset, false, true, false);
    PiePlot pieplot = (PiePlot) jfreechart.getPlot();
    if (colors != null) {
        for (int i = 0; i < colors.length; i++) {
            pieplot.setSectionPaint(dataset.getKey(i), colors[i]);
        }
    }
    pieplot.setBackgroundPaint(null);
    pieplot.setOutlineStroke(null);
    pieplot.setLabelGenerator(null);
    pieplot.setNoDataMessage(UILabels.STL40001_ERROR_No_DATA.getDescription());
    pieplot.setCircular(true);
    pieplot.setInteriorGap(0.000001);
    return jfreechart;
}

From source file:View.DialogoEstadisticas.java

private void creaGraficaIndicadores(int selectedIndex) {
    EdoRes e;// w ww.  java 2 s  . com

    DefaultCategoryDataset dataset;
    CategoryPlot p;
    switch (selectedIndex) {
    case 0:
        if (rdIntervalo.isSelected()) {
            rdIntervalo.doClick();
        }
        DefaultPieDataset data = new DefaultPieDataset();
        data.setValue("Efectivo: " + uts.formatPorcentaje(i.getPorLiq()) + " ("
                + uts.formatDinero(i.getEfectivo()) + ")", i.getPorLiq());
        data.setValue("Clientes: " + uts.formatPorcentaje(i.getPorDebClientes()) + " ("
                + uts.formatDinero(i.getSaldoClientes()) + ")", i.getPorDebClientes());
        data.setValue("Deudores Div: " + uts.formatPorcentaje(i.getPorDebDiv()) + " ("
                + uts.formatDinero(i.getSaldoDeuDiv()) + ")", i.getPorDebDiv());
        data.setValue("Inversion: " + uts.formatPorcentaje(i.getPorInv()) + " ("
                + uts.formatDinero(i.getInversion()) + ")", i.getPorInv());
        // Creando el Grafico
        chart = ChartFactory.createPieChart("Distribucin de Activo", data, true, true, false);
        chart.setBackgroundPaint(Color.lightGray);

        break;
    case 1: //Efectivo
        // Fuente de Datos
        dataset = new DefaultCategoryDataset();
        for (Indicador ind : indicadores) {
            if (ind.getNombre().equals("Efectivo")) {
                if (combrobarIntervalo(ind.getPeriodo())) {
                    dataset.setValue(ind.getValor(), "Efectivo", formatPeriodo(ind.getPeriodo()));
                }
            }
        }

        // Creando el Grafico
        chart = ChartFactory.createBarChart3D("Flujo de Efectivo", "Efectivo", "Periodos", dataset,
                PlotOrientation.VERTICAL, true, true, false);
        chart.setBackgroundPaint(Color.lightGray);
        chart.getTitle().setPaint(Color.black);
        p = chart.getCategoryPlot();
        p.setRangeGridlinePaint(Color.blue);
        //titulos de eje y en vertical
        p = chart.getCategoryPlot();
        CategoryAxis domainAxis = ((CategoryPlot) p).getDomainAxis();
        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
        break;

    case 2: //Margen
        // Fuente de Datos
        dataset = new DefaultCategoryDataset();
        h.buscaPeriodos();
        String[] periodos = h.getPeriodos();
        for (String per : periodos) {
            if (combrobarIntervalo(per)) {
                System.out.println("------------------SI");
                e = new EdoRes(per);
                dataset.setValue(e.getMargen(), formatPeriodo(per) + ": %" + uts.format2(e.getMargen()),
                        formatPeriodo(per));
            } else {

                System.out.println("-" + per + "-----NO");
            }
        }
        // Creando el Grafico
        chart = ChartFactory.createBarChart3D("Margen de ganancia", "margen (%)", "periodos", dataset,
                PlotOrientation.VERTICAL, true, true, false);
        chart.setBackgroundPaint(Color.lightGray);
        chart.getTitle().setPaint(Color.black);
        p = chart.getCategoryPlot();
        p.setRangeGridlinePaint(Color.blue);
        //titulos de eje y en vertical
        p = chart.getCategoryPlot();
        CategoryAxis domainAxis2 = ((CategoryPlot) p).getDomainAxis();
        domainAxis2.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
        break;

    }

    chartPanel = new ChartPanel(chart);
    chartPanel.setVisible(true);
    chartPanel.setSize(723, 456);
    panelG.add(chartPanel);
    panelG.revalidate();
    panelG.repaint();
}

From source file:ro.nextreports.engine.chart.JFreeChartExporter.java

private JFreeChart createPieChart() throws QueryException {
    pieDataset = new DefaultPieDataset();
    String chartTitle = replaceParameters(chart.getTitle().getTitle());
    chartTitle = StringUtil.getI18nString(chartTitle, I18nUtil.getLanguageByName(chart, language));
    JFreeChart jfreechart = ChartFactory.createPieChart(chartTitle, pieDataset, true, true, false);

    // hide border
    jfreechart.setBorderVisible(false);//from  ww  w  .  j a  va2s.com

    // title
    setTitle(jfreechart);

    PiePlot plot = (PiePlot) jfreechart.getPlot();
    plot.setForegroundAlpha(transparency);
    // a start angle used to create similarities between flash chart and this jfreechart
    plot.setStartAngle(330);
    // legend label will contain the text and the value
    plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0} = {1}"));

    // no shadow
    plot.setShadowXOffset(0);
    plot.setShadowYOffset(0);

    DecimalFormat decimalformat;
    DecimalFormat percentageFormat;
    if (chart.getYTooltipPattern() == null) {
        decimalformat = new DecimalFormat("#");
        percentageFormat = new DecimalFormat("0.00%");
    } else {
        decimalformat = new DecimalFormat(chart.getYTooltipPattern());
        percentageFormat = decimalformat;
    }
    boolean showValues = (chart.getShowYValuesOnChart() == null) ? false : chart.getShowYValuesOnChart();
    if (showValues) {
        // label will contain also the percentage formatted with two decimals
        plot.setLabelGenerator(
                new StandardPieSectionLabelGenerator("{0} ({2})", decimalformat, percentageFormat));
    }

    // chart background
    plot.setBackgroundPaint(chart.getBackground());

    createChart(null, new Object[1]);

    // after chart creation we can set slices colors
    List<Comparable> keys = pieDataset.getKeys();
    List<Color> colors = chart.getForegrounds();
    for (int i = 0, size = colors.size(); i < keys.size(); i++) {
        plot.setSectionPaint(keys.get(i), colors.get(i % size));
        plot.setLabelFont(chart.getFont());
    }

    return jfreechart;
}

From source file:ca.myewb.frame.servlet.GraphServlet.java

private JFreeChart getNoChapterPie() {
    JFreeChart chart;/*ww  w  . j  a v  a2s .c  o  m*/
    DefaultPieDataset ds = new DefaultPieDataset();

    Integer numChapter = Helpers.getGroup("Chapter").getNumMembers();
    ds.setValue("in a chapter", numChapter);

    ds.setValue("not in a chapter", Helpers.getGroup("Org").getNumMembers() - numChapter);

    chart = ChartFactory.createPieChart("Chapter Membership Breakdown", ds, false, false, false);

    PiePlot plot = ((PiePlot) chart.getPlot());
    StandardPieItemLabelGenerator n = new StandardPieItemLabelGenerator("{0} = {1} ({2})",
            new DecimalFormat("0"), new DecimalFormat("0.0%"));
    plot.setLabelGenerator(n);
    return chart;
}

From source file:kobytest.KobyTest.java

public static void conectar() {
    final int clientId = 1;
    final int port = 4001;
    final String host = "127.0.0.1";

    //EReader ereader = new EReader();
    final EWrapper anyWrapper = new EWrapper() {

        @Override/*  w  w  w .  j a  va  2  s  .  com*/
        public void error(Exception e) {
            System.out.println("error(exception):" + e.toString());
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void error(String str) {
            System.out.println("error(string):" + str);
            //throw new UnsupportedOperationException("Not error yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void error(int id, int errorCode, String errorMsg) {
            //  System.out.println("id:" + id + ". errorcode:" + errorCode + ". msg: " + errorMsg);

            // throw new UnsupportedOperationException(errorMsg); //To change body of generated methods, choose Tools | Templates.
            wrapper_error(id, errorCode, errorMsg);
        }

        @Override
        public void connectionClosed() {
            //JOptionPane.showMessageDialog(null,"Tws cerro flujo de datos", "DATA NULL", JOptionPane.ERROR_MESSAGE);
            System.out.println("Connection closed");
            //   throw new UnsupportedOperationException("Not connectionClosed yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void tickPrice(int tickerId, int field, double price, int canAutoExecute) {
            if (isDebugConsoleMode)
                System.out.println("Entra tickPrice");
            wrapper_valor(tickerId, field, price);

            if (isDebugConsoleMode)
                System.out.println(
                        "Returned tickPrice for :" + tickerId + ". field:" + field + ". Price" + price);
            //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void tickSize(int tickerId, int field, int size) {
            if (isDebugConsoleMode)
                System.out.println("Returned tickSize for :" + tickerId + ". field:" + field + ". size" + size);
            //   throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void tickOptionComputation(int tickerId, int field, double impliedVol, double delta,
                double optPrice, double pvDividend, double gamma, double vega, double theta, double undPrice) {
            if (isDebugConsoleMode)
                System.out.println("Returned tickOptionComputation for :" + tickerId + ". " + "field:" + field
                        + ". " + "impliedVol" + impliedVol + ". " + "delta " + delta + ".  " + "optPrice"
                        + optPrice + ".  " + "pvDividend" + pvDividend + ".  " + "gamma" + gamma + ".  "
                        + "vega" + vega + ".  " + "theta" + theta + ".  " + "undPrice" + undPrice + ".  ");

            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void tickGeneric(int tickerId, int tickType, double value) {
            System.out.println(
                    "Returned tickGeneric for :" + tickerId + ". tickType:" + tickType + ". value" + value);
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void tickString(int tickerId, int tickType, String value) {
            System.out.println(
                    "Returned tickString for :" + tickerId + ". tickType:" + tickType + ". value" + value);
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void tickEFP(int tickerId, int tickType, double basisPoints, String formattedBasisPoints,
                double impliedFuture, int holdDays, String futureExpiry, double dividendImpact,
                double dividendsToExpiry) {
            if (isDebugConsoleMode)
                System.out.println("Returned tickGeneric for :" + tickerId + ". " + "basisPoints:" + basisPoints
                        + ". " + "formattedBasisPoints:" + formattedBasisPoints + ". " + "impliedFuture:"
                        + impliedFuture + ". " + "holdDays:" + holdDays + ". " + "futureExpiry:" + futureExpiry
                        + ". " + "dividendImpact:" + dividendImpact + ". " + "dividendsToExpiry:"
                        + dividendsToExpiry + ". ");
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void orderStatus(int orderId, String status, int filled, int remaining, double avgFillPrice,
                int permId, int parentId, double lastFillPrice, int clientId, String whyHeld) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void openOrder(int orderId, Contract contract, Order order, OrderState orderState) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void openOrderEnd() {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
        // ==================================================  
        // ==================================================  
        // ==================================================      
        // ==================================================    

        Double netLiquidation = 0.0;
        Double excessLiquidation = 0.0;

        @Override
        public void updateAccountValue(String key, String value, String currency, String accountName) {
            if (semaforo.Semaforo.isDebugMode)
                System.out.println("TWSClientInterface:updateAccountValue: Key: " + key + " value:" + value
                        + " currency:" + currency + " accountName:" + accountName);

            switch (key) {
            case "NetLiquidation":
                netLiquidation = Double.parseDouble(value);
                break;
            case "ExcessLiquidity":
                excessLiquidation = Double.parseDouble(value);
                break;
            }

            //                if (netLiquidation <> 0 && excessLiquidation <> 0 ) {
            Double temp = ((netLiquidation - excessLiquidation) / netLiquidation) * 100;
            Controller.getSettings().setPorcentCapital(temp);
            //                    
            //                } 

            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
        // ==================================================  
        // ==================================================  
        // ==================================================      
        // ==================================================    

        // ==================================================  
        // ==================================================  
        // ==================================================      
        // ==================================================    
        @Override
        public void updateAccountTime(String timeStamp) {
            if (semaforo.Semaforo.isDebugMode)
                System.out.println("TWSClientInterface:updateAccountTime: " + timeStamp);
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void accountDownloadEnd(String accountName) {
            if (semaforo.Semaforo.isDebugMode)
                System.out.println("TWSClientInterface:accountDownloadEnd: " + accountName);
            //listener.guardaNumPos(78);
        }

        @Override
        public void nextValidId(int orderId) {
            System.out.println("Ya estamos coenctados con el orderId: " + orderId);

            try {
                conexion_aceptada_wrapper();
            } catch (SQLException ex) {
                Logger.getLogger(KobyTest.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParseException ex) {
                Logger.getLogger(KobyTest.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        @Override
        public void contractDetails(int reqId, ContractDetails contractDetails) {
            System.out.println(
                    ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + contractDetails.m_summary.m_secType); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void bondContractDetails(int reqId, ContractDetails contractDetails) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void contractDetailsEnd(int reqId) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void execDetails(int reqId, Contract contract, Execution execution) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void execDetailsEnd(int reqId) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void updateMktDepth(int tickerId, int position, int operation, int side, double price,
                int size) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void updateMktDepthL2(int tickerId, int position, String marketMaker, int operation, int side,
                double price, int size) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void updateNewsBulletin(int msgId, int msgType, String message, String origExchange) {
            System.out.println("Bulletin news");
            //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void managedAccounts(String accountsList) {
            System.out.println("Cuentas: " + accountsList);

            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void receiveFA(int faDataType, String xml) {
            System.out.println("Received FA");
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void historicalData(int reqId, String date, double open, double high, double low, double close,
                int volume, int count, double WAP, boolean hasGaps) {
            if (count >= 0) {
                if (!date.equals(strWeek)) {
                    Calendar cal = Calendar.getInstance();
                    int current_day = cal.get(Calendar.DAY_OF_MONTH);
                    int current_month = cal.get(Calendar.MONTH) + 1;
                    int current_year = cal.get(Calendar.YEAR);
                    String fecha = current_year + "-" + current_month + "-" + current_day;
                    DDBB.deleteLowHighFecha(fecha);
                    DDBB.insertLowHigh(symbol_current, fecha, "" + low, "" + high);
                    System.out.println("-------------------------------------" + strWeek);
                    System.out.println("HISTORICAL DATA for order_id: " + reqId);
                    System.out.println("Historical Date: " + date);
                    System.out.println("Historical Open: " + open);
                    System.out.println("Historical high: " + high);
                    System.out.println("Historical low: " + low);
                    System.out.println("Historical close: " + close);
                    System.out.println("Historical volume: " + volume);
                    System.out.println("Historical count: " + count);
                    System.out.println("Historical WAP: " + WAP);
                    System.out.println("Historical hasGaps: " + hasGaps);
                    System.out.println("-------------------------------------");
                } else {
                    ResultSet ticks = DDBB.Tickers();
                    try {
                        while (ticks.next()) {
                            if (reqId == Settings.getTickerID(ticks.getString("name"))) {
                                DDBB.updateHighHighTicker(ticks.getString("name"), high + "");
                                DDBB.updateLowLowTicker(ticks.getString("name"), low + "");
                                System.out.println(ticks.getString("name")
                                        + "-------------------------------------" + strWeek);
                                System.out.println("HISTORICAL DATA for order_id: " + reqId);
                                System.out.println("Historical Date: " + date);
                                System.out.println("Historical Open: " + open);
                                System.out.println("Historical high: " + high);
                                System.out.println("Historical low: " + low);
                                System.out.println("Historical close: " + close);
                                System.out.println("Historical volume: " + volume);
                                System.out.println("Historical count: " + count);
                                System.out.println("Historical WAP: " + WAP);
                                System.out.println("Historical hasGaps: " + hasGaps);
                                System.out.println("-------------------------------------");
                            }
                        }
                    } catch (SQLException ex) {
                        Logger.getLogger(KobyTest.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }
            }
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            //wrapper_historico(reqId, date, high, low, open, close);
        }

        @Override
        public void scannerParameters(String xml) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void scannerData(int reqId, int rank, ContractDetails contractDetails, String distance,
                String benchmark, String projection, String legsStr) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void scannerDataEnd(int reqId) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void realtimeBar(int reqId, long time, double open, double high, double low, double close,
                long volume, double wap, int count) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void currentTime(long time) {
            System.out.println("Current time is: " + time);
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void fundamentalData(int reqId, String data) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void deltaNeutralValidation(int reqId, UnderComp underComp) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void tickSnapshotEnd(int reqId) {
            System.out.println("tickSnapshotEnd: " + reqId);
            wrapper_snapshot_ended(reqId);
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void marketDataType(int reqId, int marketDataType) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void commissionReport(CommissionReport commissionReport) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        //######################################     
        //######################################        
        //######################################    
        //######################################         
        //######################################    
        //######################################     
        //######################################  
        //######################################      
        //######################################   
        //######################################  
        //######################################  
        //######################################
        //######################################     
        //######################################     

        //############ POSITION ################           

        int numPosiciones = 0;
        public int numPosicionesTotal = 0;
        public Map valorPosiciones = new HashMap();

        @Override
        public void updatePortfolio(Contract contract, int position, double marketPrice, double marketValue,
                double averageCost, double unrealizedPNL, double realizedPNL, String accountName) {
            if (contract.m_secType.equals("CFD")) {
                Semaforo.countCfd++;
            }

            if (ticP.isEmpty()) {
                ticP = contract.m_symbol;
                positionP = position;
                strikeP = contract.m_strike;
            } else {
                if (ticP.equals(contract.m_symbol)) {
                    if (strikeP > contract.m_strike) {
                        if (positionP > 0) {
                            //el mayor es positivo Bear  
                            Semaforo.countBear++;
                            System.out.println(">>>>>countBear>>>>>" + Semaforo.countBear);
                        } else {
                            //ll mayor es negativo Bull
                            Semaforo.countBull++;
                            System.out.println(">>>>>countBull>>>>>" + Semaforo.countBull);
                        }
                    } else {
                        if (position > 0) {
                            //el mayor es positivo Bear  
                            Semaforo.countBear++;
                            System.out.println(">>>>>countBear>>>>>" + Semaforo.countBear);
                        } else {
                            //ll mayor es negativo Bull
                            Semaforo.countBull++;
                            System.out.println(">>>>>countBull>>>>>" + Semaforo.countBull);
                        }
                    }
                } else {
                    ticP = contract.m_symbol;
                    positionP = position;
                    strikeP = contract.m_strike;
                }
            }

            System.out.println("TWSClientInterface:updatePortfolio: " + accountName + " " + contract.m_secType
                    + " " + contract.m_symbol + " " + position + " " + marketPrice + " " + marketValue + " "
                    + averageCost + " " + unrealizedPNL + " " + realizedPNL);
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.

        }

        @Override
        public void position(String account, Contract contract, int pos, double avgCost) {

            semaforo.LogFile.logFile("#### INVOCANDO position: " + contract.m_symbol + " y posicion: " + pos);
            double avg = (avgCost * pos) + 0.2;
            ResultSet resGruposOld = DDBB.GruposTickersTicker(contract.m_symbol);
            try {
                if (resGruposOld.next()) {

                    DDBB.updateGroupTickerInvertido(contract.m_symbol, (int) avg);

                } else {
                    DDBB.insertGroupsTickers("", contract.m_symbol, (int) avg);
                }
            } catch (SQLException ex) {
                Logger.getLogger(Groups.class.getName()).log(Level.SEVERE, null, ex);
            }

            //                System.out.println("ESTE ES EL POS TRAIDO POR TWS: ACCION: " + contract.m_symbol + " y posicion: " + pos);

            String msg = " ---- Position begin ----\n" + "account = " + account + "\n" + "conid = "
                    + contract.m_conId + "\n" + "symbol = " + contract.m_symbol + "\n" + "secType = "
                    + contract.m_secType + "\n" + "expiry = " + contract.m_expiry + "\n" + "strike = "
                    + contract.m_strike + "\n" + "right = " + contract.m_right + "\n" + "multiplier = "
                    + contract.m_multiplier + "\n" + "exchange = " + contract.m_exchange + "\n"
                    + "primaryExch = " + contract.m_primaryExch + "\n" + "currency = " + contract.m_currency
                    + "\n" + "localSymbol = " + contract.m_localSymbol + "\n" + "tradingClass = "
                    + contract.m_tradingClass + "\n" + "position = " + Util.IntMaxString(pos) + "\n"
                    + "averageCost = " + Util.DoubleMaxString(avgCost) + "\n" + " ---- Position end ----\n";

            System.out.println(msg);

            if (pos > 0) {
                numPosiciones++;
                if (contract.m_secType.compareTo("CFD") == 0)
                    valorPosiciones.put(contract.m_symbol, pos);
            }

            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void positionEnd() {

            semaforo.LogFile.logFile("#### INVOCANDO positionEnd");
            segundaPasada++;
            //                    
            connection.reqAccountUpdates(false, "U1523016");

            numPosicionesTotal = numPosiciones;
            if (segundaPasada > 1 && !graficopaint) {
                Semaforo.cfd = false;
                Semaforo.bull = false;
                Semaforo.bear = false;

                DecimalFormat df = new DecimalFormat();
                df.setMaximumFractionDigits(2);
                double cfd = 0.0;
                double bull = 0.0;
                double bear = 0.0;
                if (countCfd != 0)
                    cfd = (countCfd * 100) / (countBear + countBull + countCfd);
                if (countBull != 0)
                    bull = ((countBull * 100) / (countBear + countBull + countCfd));
                if (countBear != 0)
                    bear = ((countBear * 100) / (countBear + countBull + countCfd));
                Semaforo.l1.setText("CFD (" + String.format("%.2f", cfd) + "%)");
                Semaforo.l2.setText("BULL (" + String.format("%.2f", bull) + "%)");
                Semaforo.l3.setText("BEAR (" + String.format("%.2f", bear) + "%)");
                DefaultPieDataset pieDataset = new DefaultPieDataset();
                pieDataset.setValue("CFD (" + cfd + "%)", new Integer((int) countCfd));
                pieDataset.setValue("BULL (" + bull + "%)", new Integer((int) countBull));
                pieDataset.setValue("BEAR (" + bear + "%)", new Integer((int) countBear));
                JFreeChart chart = null;
                chart = ChartFactory.createPieChart("", // chart title
                        pieDataset, // data
                        false, // no legend
                        false, // tooltips
                        false // no URL generation
                );
                Semaforo.SemaforoGrafico(chart);

                graficopaint = true;
                Semaforo.countBear = 0.0;
                Semaforo.countBull = 0.0;
                Semaforo.countCfd = 0.0;
                System.out.println(":::::::::::::::::::::::::::::::::::::::::::::::::::::::" + segundaPasada
                        + Semaforo.countBear + Semaforo.countBull + Semaforo.countCfd);
            } else if (segundaPasada >= 2) {
                Semaforo.cfd = false;
                Semaforo.bull = false;
                Semaforo.bear = false;

                Semaforo.editGrafico();
                Semaforo.countBear = 0.0;
                Semaforo.countBull = 0.0;
                Semaforo.countCfd = 0.0;
                //                    Semaforo.countBear=Semaforo.countBear+5;
            }

            System.out.println("+++++" + posiciones);
            if (semaforo.Semaforo.edit == 0) {

                Semaforo.finalcountBear = Semaforo.countBear;
                Semaforo.finalcountBull = Semaforo.countBull;
                Semaforo.finalcountCfd = Semaforo.countCfd;

            }
            semaforo.Semaforo.edit = 1;
            listener.guardaNumPos(numPosicionesTotal);
            listener.guardaPosiciones(valorPosiciones);
            valorPosiciones = new HashMap(); // %30
            numPosiciones = 0;

            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void accountSummary(int reqId, String account, String tag, String value, String currency) {
            System.out.println("account summary");
            //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void accountSummaryEnd(int reqId) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void verifyMessageAPI(String apiData) {
            System.out.println("verifyMessageAPI: " + apiData);
            // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void verifyCompleted(boolean isSuccessful, String errorText) {
            System.out.println("verifyCompleted: " + errorText);
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void displayGroupList(int reqId, String groups) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void displayGroupUpdated(int reqId, String contractInfo) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    };

    // System.out.println("Enter something here : ");

    new Thread() {

        @Override
        public void run() {
            // super.run(); //To change body of generated methods, choose Tools | Templates.

            connection = new EClientSocket(anyWrapper);
            //connection.eConnect(host, port, clientId);
            connection.eConnect(host, port, clientId);
            //esperar conexion
            while (true) {
                System.out.println("Testing if there's connection");
                boolean connected = connection.isConnected();
                if (connected) {
                    System.out.println("Conectados ! :");
                    conexion_iniciada_wrapper();
                    break;
                }

                try {
                    Thread.sleep(50);
                } catch (InterruptedException ex) {
                    Logger.getLogger(KobyTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }.start();

}