Example usage for javax.swing.table DefaultTableModel getRowCount

List of usage examples for javax.swing.table DefaultTableModel getRowCount

Introduction

In this page you can find the example usage for javax.swing.table DefaultTableModel getRowCount.

Prototype

public int getRowCount() 

Source Link

Document

Returns the number of rows in this data table.

Usage

From source file:interfaces.InterfazPrincipal.java

private void botonRegistrarAbonoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonRegistrarAbonoActionPerformed
    // TODO add your handling code here:
    try {//w w  w  .  ja v a2 s.c  o m

        String identificacionCliente = mostrarIdentificacionCliente.getText();
        Double abono = Double.parseDouble(abonoClente.getText());

        if (abono <= 0.0) {
            throw new Exception();
        }

        ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();
        ControladorFactura controladorFactura = new ControladorFactura();

        Calendar calendario = Calendar.getInstance();
        String dia = Integer.toString(calendario.get(Calendar.DATE));
        String mes = Integer.toString(calendario.get(Calendar.MONTH));
        String annio = Integer.toString(calendario.get(Calendar.YEAR));
        Date date = new Date();
        DateFormat hourFormat = new SimpleDateFormat("HH:mm:ss");
        String hora = hourFormat.format(date);

        String fecha = annio + "-" + mes + "-" + dia + " " + hora;
        /*
         * -----------------Tomar el abono y los pagos-----------------
         * Procedimiento
         * 1 Tomar flujos de deuda de cada factura con estado fiado
         * 2 Tomar abonos de abono de cada factura con estado fiado
         * 3 Calcular la resta de estos dos para deteminar lo que se debe por factura
         * 4 Cancelar con el flujo la factura y si lo debido es 0 colocar estado pagado
         * 5 Mostrar una informacin en un JOptionPane y recalcular la deuda
         * 
         */
        DefaultTableModel modeloClientes = (DefaultTableModel) TablaDeSaldoClientes.getModel();
        ArrayList<String> codigoFactura = new ArrayList<>();
        ArrayList<Double> totalDebe = new ArrayList<>();

        JTextArea area = new JTextArea(10, 30);
        String informe = "\t Registro flujo pago del abono \n\n";
        informe += "Factura \t Pago \t Queda pagada? \n\n";

        int numeroRegistros = -1;
        for (int i = 0; i < modeloClientes.getRowCount(); i++) {
            //System.out.println("Entro al for " + i);
            //Se necesita 0: Factura ID, 1 Tipo, 3 Valor
            // Codigofactura contiene los cogidos de las facturas
            // totalDebe contiene lo que debe de las facturas, la posicion coincide con la lista CodigoFactura
            String factura_id = String.valueOf(modeloClientes.getValueAt(i, 0));
            String tipo_flujo = String.valueOf(modeloClientes.getValueAt(i, 1));
            Double valor = Double.parseDouble(String.valueOf(modeloClientes.getValueAt(i, 3)));
            if (codigoFactura.contains(factura_id)) {

                if (tipo_flujo.equals("abono")) {
                    totalDebe.set(numeroRegistros, totalDebe.get(numeroRegistros) - valor);
                } else {
                    totalDebe.set(numeroRegistros, totalDebe.get(numeroRegistros) + valor);
                }
            } else {
                numeroRegistros++;
                codigoFactura.add(factura_id);
                if (tipo_flujo.equals("abono")) {
                    totalDebe.add(-valor);
                } else {
                    totalDebe.add(valor);
                }
            }

        }
        //System.out.println(Arrays.toString(codigoFactura.toArray()));
        //System.out.println(Arrays.toString(totalDebe.toArray()));
        Double debeTotal = 0d;
        for (int i = 0; i < totalDebe.size(); i++) {
            debeTotal += totalDebe.get(i);

        }

        if (debeTotal < abono) {
            JOptionPane.showMessageDialog(this,
                    "El monto es superior a lo que debe el cliente, por favor indique otro monto", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        for (int i = 0; i < totalDebe.size(); i++) {
            //Tomar flujos
            if (abono > 0.0) {
                Double pago = totalDebe.get(i) - abono;

                //Pago igual a 0 significa que se pag la factura
                if (pago == 0) {
                    //Registrar flujo
                    String[] value = { codigoFactura.get(i), "abono", fecha, String.valueOf(abono) };
                    //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                    controladorFlujoFactura.insertFlujo_Factura(value);

                    controladorFactura.cambiarEstadoFactura(codigoFactura.get(i), "pagada");
                    informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tSI\n";
                    //Romper el for
                    break;
                } else {

                    //Pago mayor que 0, es decir se queda debiendo
                    if (pago > 0) {

                        //Registrar flujo
                        String[] value = { codigoFactura.get(i), "abono", fecha, String.valueOf(abono) };
                        //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                        controladorFlujoFactura.insertFlujo_Factura(value);
                        //Como el abono ahora es menor que 0 debe romperse el for
                        informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tNO\n";

                        break;

                    } else {
                        //Caso final pago menor 0, es decir el abono paga la factura pero queda disponible para otras facturas
                        //Registrar flujo
                        String[] value = { codigoFactura.get(i), "abono", fecha,
                                String.valueOf(totalDebe.get(i)) };
                        //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                        controladorFlujoFactura.insertFlujo_Factura(value);

                        controladorFactura.cambiarEstadoFactura(codigoFactura.get(i), "pagada");

                        //Ajustamos ahora el abono restando lo que debe la factura
                        informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tSI\n";
                        abono -= totalDebe.get(i);
                    }

                }
            } else {
                //Romper el for
                break;
            }

        }

        //Reordenar y volver a consultar
        for (int i = 0; i < modeloClientes.getRowCount(); i++) {
            modeloClientes.removeRow(i);
        }

        modeloClientes.setRowCount(0);

        //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
        ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                " where factura_id in (select factura_id from Factura where cliente_id = "
                        + String.valueOf(identificacionCliente) + " and estado=\"fiado\") order by factura_id");
        double pago = 0.0;

        for (int i = 0; i < flujosCliente.size(); i++) {
            String[] datos = flujosCliente.get(i);
            Object[] rowData = { datos[1], datos[2], datos[3], datos[4] };
            modeloClientes.addRow(rowData);
            if (datos[2].equals("deuda")) {
                pago += Double.parseDouble(datos[4]);
            } else {
                pago -= Double.parseDouble(datos[4]);
            }
        }

        textoTotalDebe.setText(String.valueOf(pago));
        TablaDeSaldoClientes.setModel(modeloClientes);
        area.setText(informe);
        JScrollPane panelInformePago = new JScrollPane(area);
        JOptionPane.showMessageDialog(this, panelInformePago);

    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Debe ingresar un valor numrico mayor que 0 en el abono ");
    }
}

From source file:interfaces.InterfazPrincipal.java

private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
    // TODO add your handling code here:

    try {/*ww  w  .j a v  a  2 s. co  m*/

        String identificacionCliente = mostrarIDProveedor.getText();
        Double abono = Double.parseDouble(jTextFieldAbonoProveedor.getText());

        if (abono <= 0.0 || identificacionCliente.equals("")) {
            throw new Exception();
        }

        ControladorFlujoCompras controladorFlujoFactura = new ControladorFlujoCompras();
        ControladorCompraProveedor controladorCompraProveedor = new ControladorCompraProveedor();

        Calendar calendario = Calendar.getInstance();
        String dia = Integer.toString(calendario.get(Calendar.DATE));
        String mes = Integer.toString(calendario.get(Calendar.MONTH));
        String annio = Integer.toString(calendario.get(Calendar.YEAR));
        Date date = new Date();
        DateFormat hourFormat = new SimpleDateFormat("HH:mm:ss");
        String hora = hourFormat.format(date);

        String fecha = annio + "-" + mes + "-" + dia + " " + hora;
        /*
         * -----------------Tomar el abono y los pagos-----------------
         * Procedimiento
         * 1 Tomar flujos de deuda de cada factura con estado fiado
         * 2 Tomar abonos de abono de cada factura con estado fiado
         * 3 Calcular la resta de estos dos para deteminar lo que se debe por factura
         * 4 Cancelar con el flujo la factura y si lo debido es 0 colocar estado pagado
         * 5 Mostrar una informacin en un JOptionPane y recalcular la deuda
         * 
         */
        DefaultTableModel modeloClientes = (DefaultTableModel) TablaDeSaldoProveedor.getModel();
        ArrayList<String> codigoFactura = new ArrayList<>();
        ArrayList<Double> totalDebe = new ArrayList<>();

        JTextArea area = new JTextArea(10, 30);
        String informe = "\t Registro flujo pago del abono \n\n";
        informe += "Factura \t Pago \t Queda pagada? \n\n";

        int numeroRegistros = -1;
        for (int i = 0; i < modeloClientes.getRowCount(); i++) {
            //System.out.println("Entro al for " + i);
            //Se necesita 0: Factura ID, 1 Tipo, 3 Valor
            // Codigofactura contiene los cogidos de las facturas
            // totalDebe contiene lo que debe de las facturas, la posicion coincide con la lista CodigoFactura
            String factura_id = String.valueOf(modeloClientes.getValueAt(i, 0));
            String tipo_flujo = String.valueOf(modeloClientes.getValueAt(i, 1));
            Double valor = Double.parseDouble(String.valueOf(modeloClientes.getValueAt(i, 3)));
            if (codigoFactura.contains(factura_id)) {

                if (tipo_flujo.equals("abono")) {
                    totalDebe.set(numeroRegistros, totalDebe.get(numeroRegistros) - valor);
                } else {
                    totalDebe.set(numeroRegistros, totalDebe.get(numeroRegistros) + valor);
                }
            } else {
                numeroRegistros++;
                codigoFactura.add(factura_id);
                if (tipo_flujo.equals("abono")) {
                    totalDebe.add(-valor);
                } else {
                    totalDebe.add(valor);
                }
            }

        }
        //System.out.println(Arrays.toString(codigoFactura.toArray()));
        //System.out.println(Arrays.toString(totalDebe.toArray()));
        System.out.println(totalDebe);
        double debeTotal = 0d;
        for (int i = 0; i < totalDebe.size(); i++) {
            debeTotal += totalDebe.get(i);
        }

        if (debeTotal < abono) {
            JOptionPane.showMessageDialog(this, "El monto a pagar no puede ser superior a lo que se debe",
                    "Error del sistema", JOptionPane.ERROR_MESSAGE);
            return;
        }
        for (int i = 0; i < totalDebe.size(); i++) {
            //Tomar flujos
            if (abono > 0.0) {
                Double pago = totalDebe.get(i) - abono;

                //Pago igual a 0 significa que se pag la factura
                if (pago == 0) {
                    //Registrar flujo
                    //String[] value = {codigoFactura.get(i), "abono", fecha, String.valueOf(abono)};
                    //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                    controladorFlujoFactura.registrarFlujoAbono(codigoFactura.get(i), String.valueOf(abono));

                    //controladorFactura.cambiarEstadoFactura(codigoFactura.get(i), "pagada");
                    informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tSI\n";
                    //Romper el for
                    break;
                } else {

                    //Pago mayor que 0, es decir se queda debiendo
                    if (pago > 0) {

                        //Registrar flujo
                        //String[] value = {codigoFactura.get(i), "abono", fecha, String.valueOf(abono)};
                        //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                        controladorFlujoFactura.registrarFlujoAbono(codigoFactura.get(i),
                                String.valueOf(abono));
                        //Como el abono ahora es menor que 0 debe romperse el for
                        informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tNO\n";

                        break;

                    } else {
                        //Caso final pago menor 0, es decir el abono paga la factura pero queda disponible para otras facturas
                        //Registrar flujo
                        //String[] value = {codigoFactura.get(i), "abono", fecha, String.valueOf(totalDebe.get(i))};
                        //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                        controladorFlujoFactura.registrarFlujoAbono(codigoFactura.get(i),
                                String.valueOf(totalDebe.get(i)));

                        //controladorFactura.cambiarEstadoFactura(codigoFactura.get(i), "pagada");
                        //Ajustamos ahora el abono restando lo que debe la factura
                        informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tSI\n";
                        abono -= totalDebe.get(i);
                    }

                }
            } else {
                //Romper el for
                break;
            }

        }

        //Reordenar y volver a consultar
        for (int i = 0; i < modeloClientes.getRowCount(); i++) {
            modeloClientes.removeRow(i);
        }

        modeloClientes.setRowCount(0);

        //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
        ArrayList<Flujo_Compra> flujosProveedor = controladorFlujoFactura.obtenerFlujosCompras(
                " where ID_CompraProveedor in (select ID_CompraProveedor from Compra_Proveedores where IDProveedor = "
                        + String.valueOf(identificacionCliente) + ") order by ID_CompraProveedor");
        double pago = 0.0;

        for (int i = 0; i < flujosProveedor.size(); i++) {
            Flujo_Compra datos = flujosProveedor.get(i);
            Object[] rowData = { datos.getID_CompraProveedor(), datos.getTipo_flujo(), datos.getFecha(),
                    datos.getMonto() };

            if (datos.getTipo_flujo().equals("deuda")) {
                pago += Double.parseDouble(datos.getMonto() + "");
            } else {
                pago -= Double.parseDouble(datos.getMonto() + "");
            }

            modeloClientes.addRow(rowData);
        }

        TablaDeSaldoProveedor.setModel(modeloClientes);
        deudaActualProveedor.setText(String.valueOf(pago));

        //Mostrar en table de clientes los datos
        botonRegistrarAbono.setEnabled(true);

        area.setText(informe);
        JScrollPane panelInformePago = new JScrollPane(area);
        JOptionPane.showMessageDialog(this, panelInformePago);

    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Debe ingresar un valor numrico mayor que 0 en el abono ");
    }

}

From source file:interfaces.InterfazPrincipal.java

private void botonGenerarReporteClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonGenerarReporteClienteActionPerformed
    // TODO add your handling code here:
    try {/*from   w  w  w.  j  ava 2s.com*/
        if (clienteReporteClienteFechaFinal.getSelectedDate().getTime()
                .compareTo(clienteReporteClienteFechaInicial.getSelectedDate().getTime()) < 0) {
            JOptionPane.showMessageDialog(this, "La fecha final debe ser posterior al dia de inicio");
        } else {
            final ArrayList<Integer> listaIDFlujos = new ArrayList<>();
            final JDialog dialogoEditar = new JDialog();
            dialogoEditar.setTitle("Reporte cliente");
            dialogoEditar.setSize(350, 610);
            dialogoEditar.setResizable(false);

            JPanel panelDialogo = new JPanel();
            panelDialogo.setLayout(new GridBagLayout());

            GridBagConstraints c = new GridBagConstraints();
            //c.fill = GridBagConstraints.HORIZONTAL;

            JLabel ediitarTextoPrincipalDialogo = new JLabel("Informe cliente");
            c.gridx = 0;
            c.gridy = 0;
            c.gridwidth = 1;
            c.insets = new Insets(10, 45, 10, 10);
            Font textoGrande = new Font("Arial", 1, 18);
            ediitarTextoPrincipalDialogo.setFont(textoGrande);
            panelDialogo.add(ediitarTextoPrincipalDialogo, c);

            final JTable tablaDialogo = new JTable();
            DefaultTableModel modeloTabla = new DefaultTableModel() {

                @Override
                public boolean isCellEditable(int row, int column) {
                    //all cells false
                    return false;
                }
            };
            ;

            modeloTabla.addColumn("Factura");
            modeloTabla.addColumn("Tipo Flujo");
            modeloTabla.addColumn("Fecha");
            modeloTabla.addColumn("Valor");

            //Llenar tabla
            ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();
            ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                    " where factura_id in (select factura_id from Factura where cliente_id = "
                            + String.valueOf(jTextFieldIdentificacionClienteReporte.getText())
                            + ") order by factura_id");
            // {"flujo_id","factura_id","tipo_flujo","fecha","valor"};
            ArrayList<Calendar> fechasFlujos = new ArrayList<>();

            for (int i = 0; i < flujosCliente.size(); i++) {
                String fila[] = new String[4];
                String[] objeto = flujosCliente.get(i);
                fila[0] = objeto[1];
                fila[1] = objeto[2];
                fila[2] = objeto[3];
                fila[3] = objeto[4];

                //Filtrar, mirar las fechas
                String[] partirEspacios = objeto[3].split("\\s");
                //El primer string es la fecha sin hora
                //Ahora esparamos por -
                String[] tomarAgeMesDia = partirEspacios[0].split("-");

                //Realizar filtro
                int ageConsulta = Integer.parseInt(tomarAgeMesDia[0]);
                int mesConsulta = Integer.parseInt(tomarAgeMesDia[1]);
                int diaConsulta = Integer.parseInt(tomarAgeMesDia[2]);

                //Obtenemos dias, mes y ao de la consulta
                //Inicial
                int anioInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.YEAR);
                int mesInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.MONTH) + 1;
                int diaInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.DAY_OF_MONTH);
                //Final
                int anioFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.YEAR);
                int mesFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.MONTH) + 1;
                int diaFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.DAY_OF_MONTH);

                //Construir fechas
                Calendar fechaDeLaBD = new GregorianCalendar(ageConsulta, mesConsulta, diaConsulta);
                //Set year, month, day)

                Calendar fechaInicialRango = new GregorianCalendar(anioInicial, mesInicial, diaInicial);
                Calendar fechaFinalRango = new GregorianCalendar(anioFinal, mesFinal, diaFinal);

                if (fechaDeLaBD.compareTo(fechaInicialRango) <= 0
                        && fechaDeLaBD.compareTo(fechaFinalRango) >= 0) {
                    fechasFlujos.add(fechaDeLaBD);
                    modeloTabla.addRow(fila);
                }

            }

            if (modeloTabla.getRowCount() > 0) {
                tablaDialogo.setModel(modeloTabla);
                tablaDialogo.getColumn("Factura").setMinWidth(80);
                tablaDialogo.getColumn("Tipo Flujo").setMinWidth(80);
                tablaDialogo.getColumn("Fecha").setMinWidth(90);
                tablaDialogo.getColumn("Valor").setMinWidth(80);
                tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                JScrollPane scroll = new JScrollPane(tablaDialogo);
                scroll.setPreferredSize(new Dimension(330, 150));

                c.gridx = 0;
                c.gridy = 1;
                c.gridwidth = 1;
                c.insets = new Insets(0, 0, 0, 0);
                panelDialogo.add(scroll, c);

                TimeSeries localTimeSeries = new TimeSeries("Compras del cliente en el periodo");

                Map listaAbonos = new HashMap();

                for (int i = 0; i < modeloTabla.getRowCount(); i++) {
                    listaIDFlujos.add(Integer.parseInt(flujosCliente.get(i)[0]));

                    if (modeloTabla.getValueAt(i, 1).equals("abono")) {
                        Calendar fechaFlujo = fechasFlujos.get(i);
                        double valor = Double.parseDouble(String.valueOf(modeloTabla.getValueAt(i, 3)));

                        int anoDato = fechaFlujo.get(Calendar.YEAR);
                        int mesDato = fechaFlujo.get(Calendar.MONTH) + 1;
                        int diaDato = fechaFlujo.get(Calendar.DAY_OF_MONTH);
                        Day FechaDato = new Day(diaDato, mesDato, anoDato);

                        if (listaAbonos.get(FechaDato) != null) {
                            double valorAbono = (double) listaAbonos.get(FechaDato);
                            listaAbonos.remove(FechaDato);
                            listaAbonos.put(FechaDato, valorAbono + valor);
                        } else {
                            listaAbonos.put(FechaDato, valor);

                        }

                    }

                }
                Double maximo = 0.0;
                Iterator iterator = listaAbonos.keySet().iterator();
                while (iterator.hasNext()) {
                    Day key = (Day) iterator.next();
                    Double value = (double) listaAbonos.get(key);
                    maximo = Math.max(maximo, value);
                    localTimeSeries.add(key, value);
                }

                //localTimeSeries.add();
                TimeSeriesCollection datos = new TimeSeriesCollection(localTimeSeries);

                JFreeChart chart = ChartFactory.createTimeSeriesChart("Compras del cliente en el periodo", // Title
                        "Tiempo", // x-axis Label
                        "Total ($)", // y-axis Label
                        datos, // Dataset
                        true, // Show Legend
                        true, // Use tooltips
                        false // Configure chart to generate URLs?
                );
                /*Altering the graph */
                XYPlot plot = (XYPlot) chart.getPlot();
                plot.setAxisOffset(new RectangleInsets(5.0, 10.0, 10.0, 5.0));
                plot.setDomainCrosshairVisible(true);
                plot.setRangeCrosshairVisible(true);

                XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
                renderer.setBaseShapesVisible(true);
                renderer.setBaseShapesFilled(true);

                NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis();
                numberAxis.setRange(new Range(0, maximo * 1.2));
                Font font = new Font("Dialog", Font.PLAIN, 9);
                numberAxis.setTickLabelFont(font);
                numberAxis.setLabelFont(font);

                DateAxis axis = (DateAxis) plot.getDomainAxis();
                axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy"));
                axis.setAutoTickUnitSelection(false);
                axis.setVerticalTickLabels(true);

                axis.setTickLabelFont(font);
                axis.setLabelFont(font);

                LegendTitle leyendaChart = chart.getLegend();
                leyendaChart.setItemFont(font);

                Font fontTitulo = new Font("Dialog", Font.BOLD, 12);
                TextTitle tituloChart = chart.getTitle();
                tituloChart.setFont(fontTitulo);

                ChartPanel CP = new ChartPanel(chart);
                Dimension D = new Dimension(330, 300);
                CP.setPreferredSize(D);
                CP.setVisible(true);
                c.gridx = 0;
                c.gridy = 2;
                c.gridwidth = 1;
                c.insets = new Insets(10, 0, 0, 0);
                panelDialogo.add(CP, c);

                c.gridx = 0;
                c.gridy = 3;
                c.gridwidth = 1;
                c.anchor = GridBagConstraints.WEST;
                c.insets = new Insets(10, 30, 0, 0);

                JButton botonCerrar = new JButton("Cerrar");
                botonCerrar.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dialogoEditar.dispose();
                    }
                });
                panelDialogo.add(botonCerrar, c);

                JButton botonGenerarPDF = new JButton("Guardar archivo");
                botonGenerarPDF.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ReporteFlujosCliente reporteFlujosCliente = new ReporteFlujosCliente();
                        reporteFlujosCliente.guardarDocumentoDialogo(dialogoEditar, listaIDFlujos,
                                Integer.parseInt(jTextFieldIdentificacionClienteReporte.getText()),
                                clienteReporteClienteFechaInicial.getSelectedDate(),
                                clienteReporteClienteFechaFinal.getSelectedDate());

                    }
                });
                c.insets = new Insets(10, 100, 0, 0);

                panelDialogo.add(botonGenerarPDF, c);

                JButton botonImprimir = new JButton("Imprimir");
                botonImprimir.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ReporteFlujosCliente reporteFlujosCliente = new ReporteFlujosCliente();
                        reporteFlujosCliente.imprimirFlujo(listaIDFlujos,
                                Integer.parseInt(jTextFieldIdentificacionClienteReporte.getText()),
                                clienteReporteClienteFechaInicial.getSelectedDate(),
                                clienteReporteClienteFechaFinal.getSelectedDate());

                    }
                });
                c.insets = new Insets(10, 230, 0, 0);

                panelDialogo.add(botonImprimir, c);
                dialogoEditar.add(panelDialogo);

                dialogoEditar.setVisible(true);

            } else {
                JOptionPane.showMessageDialog(this,
                        "El cliente no registra movimientos en el rango de fechas seleccionado");
            }

        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Debe seleccionar un da inicial y final de fechas");
    }

}

From source file:com.peterbochs.PeterBochsDebugger.java

protected void updateAddressTranslate() {
    try {//from   w  ww . j  a  v a2  s .  c  om
        jStatusLabel.setText("Updating Address translate");
        // commandReceiver.setCommandNoOfLine(-1);
        commandReceiver.clearBuffer();
        commandReceiver.shouldShow = false;
        sendCommand("info tab");
        Thread.currentThread();
        String result = commandReceiver.getCommandResultUntilEnd();
        String[] lines = result.split("\n");
        DefaultTableModel model = (DefaultTableModel) jAddressTranslateTable.getModel();
        while (model.getRowCount() > 0) {
            model.removeRow(0);
        }
        for (int x = 1; x < lines.length; x++) {
            Vector<String> strs = new Vector<String>(Arrays.asList(lines[x].trim().split("->")));
            model.addRow(strs);
        }
        ((DefaultTableModel) jAddressTranslateTable.getModel()).fireTableDataChanged();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.peterbochs.PeterBochsDebugger.java

private void updateBreakpoint() {
    try {/*from w ww.  j  a  va 2 s  .co  m*/
        jStatusLabel.setText("Updating breakpoint");
        // commandReceiver.setCommandNoOfLine(-1);
        commandReceiver.clearBuffer();
        sendCommand("info break");
        Thread.currentThread();
        String result = commandReceiver.getCommandResultUntilEnd();
        String[] lines = result.split("\n");
        DefaultTableModel model = (DefaultTableModel) breakpointTable.getModel();
        while (model.getRowCount() > 0) {
            model.removeRow(0);
        }

        for (int x = 1; x < lines.length; x++) {
            if (lines[x].contains("breakpoint")) {
                Vector<String> strs = new Vector<String>(Arrays.asList(lines[x].trim().split(" \\s")));
                strs.add("0"); // hit count
                if (strs.size() > 1) {
                    strs.remove(1);
                    model.addRow(strs);
                }
            }
        }

        this.jRefreshELFBreakpointButtonActionPerformed(null);
        jStatusLabel.setText("");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.peterbochs.PeterBochsDebugger.java

@SuppressWarnings("unused")
private void updateInstructionUsingNasm(BigInteger address) {
    try {/*from ww w. j av a2s . c o m*/
        if (address == null) {
            address = BigInteger.valueOf(0);
        }
        jStatusLabel.setText("Updating instruction");
        String result = Disassemble.disassemble(address, 32);
        String lines[] = result.split("\n");
        if (lines.length > 0) {
            DefaultTableModel model = (DefaultTableModel) instructionTable.getModel();
            while (model.getRowCount() > 0) {
                model.removeRow(0);
            }
            jStatusProgressBar.setMaximum(lines.length - 1);
            for (int x = 0; x < lines.length; x++) {
                jStatusProgressBar.setValue(x);
                try {
                    model.addRow(new String[] { lines[x].substring(0, 10).trim(), lines[x].substring(20).trim(),
                            lines[x].substring(10, 20).trim() });
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.peterbochs.PeterBochsDebugger.java

public void updatePageTable(BigInteger pageDirectoryBaseAddress) {
    Vector<IA32PageDirectory> ia32_pageDirectories = new Vector<IA32PageDirectory>();
    try {//from   w  w w  .  j a v a2  s.co  m
        commandReceiver.clearBuffer();
        commandReceiver.shouldShow = false;
        jStatusLabel.setText("Updating page table");
        // commandReceiver.setCommandNoOfLine(512);
        sendCommand("xp /4096bx " + pageDirectoryBaseAddress);
        float totalByte2 = 4096 - 1;
        totalByte2 = totalByte2 / 8;
        int totalByte3 = (int) Math.floor(totalByte2);
        String realEndAddressStr;
        String realStartAddressStr;
        BigInteger realStartAddress = pageDirectoryBaseAddress;
        realStartAddressStr = realStartAddress.toString(16);
        BigInteger realEndAddress = realStartAddress.add(BigInteger.valueOf(totalByte3 * 8));
        realEndAddressStr = String.format("%08x", realEndAddress);
        String result = commandReceiver.getCommandResult(realStartAddressStr, realEndAddressStr, null);
        if (result != null) {
            String[] lines = result.split("\n");
            DefaultTableModel model = (DefaultTableModel) jPageDirectoryTable.getModel();
            while (model.getRowCount() > 0) {
                model.removeRow(0);
            }
            jStatusProgressBar.setMaximum(lines.length - 1);

            for (int y = 0; y < lines.length; y++) {
                jStatusProgressBar.setValue(y);
                String[] b = lines[y].replaceFirst("^.*:", "").trim().split("\t");

                for (int z = 0; z < 2; z++) {
                    try {
                        int bytes[] = new int[4];
                        for (int x = 0; x < 4; x++) {
                            bytes[x] = CommonLib.string2BigInteger(b[x + z * 4].substring(2).trim()).intValue();
                        }
                        long value = CommonLib.getInt(bytes, 0);
                        // "No.", "PT base", "AVL", "G",
                        // "D", "A", "PCD", "PWT",
                        // "U/S", "W/R", "P"

                        long baseL = value & 0xfffff000;
                        // if (baseL != 0) {
                        String base = "0x" + Long.toHexString(baseL);
                        String avl = String.valueOf((value >> 9) & 3);
                        String g = String.valueOf((value >> 8) & 1);
                        String d = String.valueOf((value >> 6) & 1);
                        String a = String.valueOf((value >> 5) & 1);
                        String pcd = String.valueOf((value >> 4) & 1);
                        String pwt = String.valueOf((value >> 3) & 1);
                        String us = String.valueOf((value >> 2) & 1);
                        String wr = String.valueOf((value >> 1) & 1);
                        String p = String.valueOf((value >> 0) & 1);

                        ia32_pageDirectories
                                .add(new IA32PageDirectory(base, avl, g, d, a, pcd, pwt, us, wr, p));

                        model.addRow(new String[] { String.valueOf(y * 2 + z), base, avl, g, d, a, pcd, pwt, us,
                                wr, p });
                        // }
                    } catch (Exception ex) {
                    }
                }
                jStatusLabel.setText("Updating page table " + (y + 1) + "/" + lines.length);
            }
            jPageDirectoryTable.setModel(model);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    /*
     * if (false && Global.debug &&
     * jAutoRefreshPageTableGraphCheckBox.isSelected()) {
     * System.out.println("aa"); GraphModel model = new DefaultGraphModel();
     * GraphLayoutCache view = new GraphLayoutCache(model, new
     * DefaultCellViewFactory() { public CellView createView(GraphModel
     * model, Object cell) { CellView view = null; if (model.isPort(cell)) {
     * view = new PortView(cell); } else if (model.isEdge(cell)) { view =
     * new EdgeView(cell); } else { if (cell instanceof IA32PageDirectory) {
     * view = new PageDirectoryView(cell); } else if (cell instanceof
     * IA32PageTable) { view = new JButtonView(cell, 1); } else { view = new
     * VertexView(cell); } } return view; } }); JGraph graph = new
     * JGraph(model, view);
     * 
     * // add cells
     * 
     * // DefaultGraphCell[] cells = new //
     * DefaultGraphCell[ia32_pageDirectories.size() + 1];
     * Vector<DefaultGraphCell> cells = new Vector<DefaultGraphCell>();
     * DefaultGraphCell root = new DefaultGraphCell("cr3 " +
     * jRegisterPanel1.jCR3TextField.getText());
     * GraphConstants.setGradientColor(root.getAttributes(), Color.red);
     * GraphConstants.setOpaque(root.getAttributes(), true);
     * GraphConstants.setBounds(root.getAttributes(), new
     * Rectangle2D.Double(0, 0, 140, 20)); root.add(new DefaultPort());
     * cells.add(root);
     * 
     * Vector<IA32PageDirectory> pageDirectoryCells = new
     * Vector<IA32PageDirectory>(); for (int x = 0; x <
     * ia32_pageDirectories.size(); x++) { IA32PageDirectory cell =
     * ia32_pageDirectories.get(x);
     * GraphConstants.setGradientColor(cell.getAttributes(), Color.orange);
     * GraphConstants.setOpaque(cell.getAttributes(), true);
     * GraphConstants.setBounds(cell.getAttributes(), new
     * Rectangle2D.Double(0, x * 20, 140, 20)); cell.add(new DefaultPort());
     * pageDirectoryCells.add(cell);
     * 
     * // page table String pageTableAddress =
     * ia32_pageDirectories.get(x).base; sendCommand("xp /4096bx " +
     * pageTableAddress);
     * 
     * float totalByte2 = 4096 - 1; totalByte2 = totalByte2 / 8; int
     * totalByte3 = (int) Math.floor(totalByte2); String realEndAddressStr;
     * String realStartAddressStr; String baseAddress = pageTableAddress;
     * long realStartAddress = CommonLib.string2BigInteger(baseAddress);
     * 
     * realStartAddressStr = String.format("%08x", realStartAddress); long
     * realEndAddress = realStartAddress + totalByte3 * 8; realEndAddressStr
     * = String.format("%08x", realEndAddress);
     * 
     * String result = commandReceiver.getCommandResult(realStartAddressStr,
     * realEndAddressStr); String[] lines = result.split("\n");
     * 
     * Vector<DefaultGraphCell> pageTables = new Vector<DefaultGraphCell>();
     * for (int y = 1; y < 4; y++) { String[] b =
     * lines[y].replaceFirst("         cell.add(new DefaultPort());^.*:",
     * "").trim().split("\t");
     * 
     * for (int z = 0; z < 2; z++) { try { int bytes[] = new int[4]; for
     * (int x2 = 0; x2 < 4; x2++) { bytes[x2] =
     * CommonLib.string2BigInteger(b[x2 + z *
     * 4].substring(2).trim()).intValue(); } long value =
     * CommonLib.getInt(bytes, 0);
     * 
     * String base = Long.toHexString(value & 0xfffff000); String avl =
     * String.valueOf((value >> 9) & 3); String g = String.valueOf((value >>
     * 8) & 1); String d = String.valueOf((value >> 6) & 1); String a =
     * String.valueOf((value >> 5) & 1); String pcd = String.valueOf((value
     * >> 4) & 1); String pwt = String.valueOf((value >> 3) & 1); String us
     * = String.valueOf((value >> 2) & 1); String wr = String.valueOf((value
     * >> 1) & 1); String p = String.valueOf((value >> 0) & 1);
     * IA32PageTable pageTableCell = new IA32PageTable(base, avl, g, d, a,
     * pcd, pwt, us, wr, p);
     * GraphConstants.setGradientColor(pageTableCell.getAttributes(),
     * Color.orange);
     * GraphConstants.setOpaque(pageTableCell.getAttributes(), true);
     * GraphConstants.setBounds(pageTableCell.getAttributes(), new
     * Rectangle2D.Double(0, (z + y) * 20, 140, 20)); pageTableCell.add(new
     * DefaultPort()); pageTables.add(pageTableCell); } catch (Exception ex)
     * { } } }
     * 
     * // group it and link it DefaultGraphCell pt[] =
     * pageTables.toArray(new DefaultGraphCell[] {}); DefaultGraphCell
     * vertex1 = new DefaultGraphCell(new String("page table" + x), null,
     * pt); vertex1.add(new DefaultPort()); cells.add(vertex1);
     * 
     * DefaultEdge edge = new DefaultEdge();
     * edge.setSource(cell.getChildAt(0));
     * edge.setTarget(vertex1.getLastChild());
     * 
     * GraphConstants.setLineStyle(edge.getAttributes(),
     * GraphConstants.STYLE_ORTHOGONAL);
     * GraphConstants.setRouting(edge.getAttributes(),
     * GraphConstants.ROUTING_DEFAULT); int arrow =
     * GraphConstants.ARROW_CLASSIC;
     * GraphConstants.setLineEnd(edge.getAttributes(), arrow);
     * GraphConstants.setEndFill(edge.getAttributes(), true);
     * 
     * cells.add(edge); }
     * 
     * if (pageDirectoryCells.toArray().length > 0) { IA32PageDirectory pt[]
     * = pageDirectoryCells.toArray(new IA32PageDirectory[] {});
     * DefaultGraphCell vertex1 = new DefaultGraphCell(new
     * String("Vertex1"), null, pt); vertex1.add(new DefaultPort());
     * cells.add(vertex1);
     * 
     * DefaultEdge edge = new DefaultEdge();
     * edge.setSource(root.getChildAt(0));
     * edge.setTarget(vertex1.getLastChild()); int arrow =
     * GraphConstants.ARROW_CLASSIC;
     * GraphConstants.setLineEnd(edge.getAttributes(), arrow);
     * GraphConstants.setEndFill(edge.getAttributes(), true);
     * 
     * // lastObj = cells[index]; cells.add(edge); }
     * 
     * graph.getGraphLayoutCache().insert(cells.toArray());
     * graph.setDisconnectable(false);
     * 
     * JGraphFacade facade = new JGraphFacade(graph); JGraphLayout layout =
     * new JGraphTreeLayout(); ((JGraphTreeLayout)
     * layout).setOrientation(SwingConstants.WEST); //
     * ((JGraphHierarchicalLayout) layout).setNodeDistance(100);
     * layout.run(facade); Map nested = facade.createNestedMap(true, true);
     * graph.getGraphLayoutCache().edit(nested);
     * 
     * // JGraphFacade facade = new JGraphFacade(graph); // JGraphLayout
     * layout = new JGraphFastOrganicLayout(); // layout.run(facade); // Map
     * nested = facade.createNestedMap(true, true); //
     * graph.getGraphLayoutCache().edit(nested);
     * 
     * jPageTableGraphPanel.removeAll(); jPageTableGraphPanel.add(new
     * JScrollPane(graph), BorderLayout.CENTER); }
     */

}

From source file:com.peterbochs.PeterBochsDebugger.java

private void parseELF(File elfFile) {
    jELFDumpPanel.remove(jTabbedPane4);/*from   w  w  w.ja  va 2 s .c  om*/
    jTabbedPane4 = null;
    jELFDumpPanel.add(getJTabbedPane4(), BorderLayout.CENTER);

    HashMap map = ElfUtil.getELFDetail(elfFile);
    if (map != null) {
        // header
        DefaultTableModel model = (DefaultTableModel) jELFHeaderTable.getModel();
        while (model.getRowCount() > 0) {
            model.removeRow(0);
        }
        Set entries = ((HashMap) map.get("header")).entrySet();
        Iterator it = entries.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();

            Vector<String> v = new Vector<String>();
            v.add(entry.getKey().toString());

            String bytesStr = "";

            if (entry.getValue().getClass() == Short.class) {
                jStatusLabel.setText("header " + Long.toHexString((Short) entry.getValue()));
                bytesStr += "0x" + Long.toHexString((Short) entry.getValue());
            } else if (entry.getValue().getClass() == Integer.class) {
                bytesStr += "0x" + Long.toHexString((Integer) entry.getValue());
            } else if (entry.getValue().getClass() == Long.class) {
                bytesStr += "0x" + Long.toHexString((Long) entry.getValue());
            } else {
                int b[] = (int[]) entry.getValue();
                for (int x = 0; x < b.length; x++) {
                    bytesStr += "0x" + Long.toHexString(b[x]) + " ";
                }
            }

            v.add(bytesStr);
            model.addRow(v);
        }
        // end header

        // section
        model = (DefaultTableModel) jELFSectionTable.getModel();
        while (model.getRowCount() > 0) {
            model.removeRow(0);
        }
        int sectionNo = 0;
        while (map.get("section" + sectionNo) != null) {
            entries = ((HashMap) map.get("section" + sectionNo)).entrySet();
            it = entries.iterator();
            Vector<String> v = new Vector<String>();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();

                String bytesStr = "";
                if (entry.getValue().getClass() == Short.class) {
                    jStatusLabel.setText("section " + Long.toHexString((Short) entry.getValue()));
                    bytesStr += "0x" + Long.toHexString((Short) entry.getValue());
                } else if (entry.getValue().getClass() == Integer.class) {
                    bytesStr += "0x" + Long.toHexString((Integer) entry.getValue());
                } else if (entry.getValue().getClass() == String.class) {
                    bytesStr = (String) entry.getValue();
                } else if (entry.getValue().getClass() == Long.class) {
                    bytesStr += "0x" + Long.toHexString((Long) entry.getValue());
                } else {
                    int b[] = (int[]) entry.getValue();
                    for (int x = 0; x < b.length; x++) {
                        bytesStr += "0x" + Long.toHexString(b[x]) + " ";
                    }
                }

                v.add(bytesStr);
            }
            model.addRow(v);
            sectionNo++;
        }
        // end section

        // program header
        model = (DefaultTableModel) jProgramHeaderTable.getModel();
        while (model.getRowCount() > 0) {
            model.removeRow(0);
        }
        int programHeaderNo = 0;
        while (map.get("programHeader" + programHeaderNo) != null) {
            entries = ((HashMap) map.get("programHeader" + programHeaderNo)).entrySet();
            it = entries.iterator();
            Vector<String> v = new Vector<String>();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();

                String bytesStr = "";
                if (entry.getValue().getClass() == Short.class) {
                    jStatusLabel.setText("Program header " + Long.toHexString((Short) entry.getValue()));
                    bytesStr += "0x" + Long.toHexString((Short) entry.getValue());
                } else if (entry.getValue().getClass() == Integer.class) {
                    bytesStr += "0x" + Long.toHexString((Integer) entry.getValue());
                } else if (entry.getValue().getClass() == Long.class) {
                    bytesStr += "0x" + Long.toHexString((Long) entry.getValue());
                } else if (entry.getValue().getClass() == String.class) {
                    bytesStr += "0x" + entry.getValue();
                } else {
                    int b[] = (int[]) entry.getValue();
                    for (int x = 0; x < b.length; x++) {
                        bytesStr += "0x" + Long.toHexString(b[x]) + " ";
                    }
                }

                v.add(bytesStr);
            }
            model.addRow(v);
            programHeaderNo++;
        }
        // program header

        // symbol table
        int symbolTableNo = 0;
        while (map.get("symbolTable" + symbolTableNo) != null) {
            DefaultTableModel tempTableModel = new DefaultTableModel(null, new String[] { "No.", "st_name",
                    "st_value", "st_size", "st_info", "st_other", "p_st_shndx" });
            JTable tempTable = new JTable();
            HashMap tempMap = (HashMap) map.get("symbolTable" + symbolTableNo);
            Vector<LinkedHashMap> v = (Vector<LinkedHashMap>) tempMap.get("vector");
            for (int x = 0; x < v.size(); x++) {
                Vector tempV = new Vector();
                jStatusLabel.setText("Symbol table " + x);
                tempV.add("0x" + Long.toHexString((Integer) v.get(x).get("No.")));
                tempV.add(v.get(x).get("st_name"));
                tempV.add("0x" + Long.toHexString((Long) v.get(x).get("st_value")));
                tempV.add("0x" + Long.toHexString((Long) v.get(x).get("st_size")));
                tempV.add("0x" + Long.toHexString((Integer) v.get(x).get("st_info")));
                tempV.add("0x" + Long.toHexString((Integer) v.get(x).get("st_other")));
                tempV.add("0x" + Long.toHexString((Integer) v.get(x).get("p_st_shndx")));

                tempTableModel.addRow(tempV);
            }

            tempTable.setModel(tempTableModel);
            JScrollPane tempScrollPane = new JScrollPane();
            tempScrollPane.setViewportView(tempTable);
            jTabbedPane4.addTab(tempMap.get("name").toString(), null, tempScrollPane, null);

            symbolTableNo++;
        }
        // end symbol table

        // note
        int noteSectionNo = 0;
        while (map.get("note" + noteSectionNo) != null) {
            DefaultTableModel tempTableModel = new DefaultTableModel(null,
                    new String[] { "No.", "namesz", "descsz", "type", "name", "desc" });
            JTable tempTable = new JTable();
            HashMap tempMap = (HashMap) map.get("note" + noteSectionNo);
            Vector<LinkedHashMap> v = (Vector<LinkedHashMap>) tempMap.get("vector");
            for (int x = 0; x < v.size(); x++) {
                Vector tempV = new Vector();
                jStatusLabel.setText("Note " + x);
                tempV.add("0x" + Long.toHexString((Integer) v.get(x).get("No.")));
                tempV.add("0x" + Long.toHexString((Long) v.get(x).get("namesz")));
                tempV.add("0x" + Long.toHexString((Long) v.get(x).get("descsz")));
                tempV.add("0x" + Long.toHexString((Long) v.get(x).get("type")));
                tempV.add(v.get(x).get("name"));
                tempV.add(v.get(x).get("desc"));

                tempTableModel.addRow(tempV);
            }

            tempTable.setModel(tempTableModel);
            JScrollPane tempScrollPane = new JScrollPane();
            tempScrollPane.setViewportView(tempTable);
            jTabbedPane4.addTab(tempMap.get("name").toString(), null, tempScrollPane, null);

            noteSectionNo++;
        }
        // end note
    }

    try {
        jStatusLabel.setText("running objdump -DS");
        Process process = Runtime.getRuntime().exec("objdump -DS " + elfFile.getAbsolutePath());
        InputStream input = process.getInputStream();
        String str = "";
        byte b[] = new byte[102400];
        int len;
        while ((len = input.read(b)) > 0) {
            str += new String(b, 0, len);
        }
        jEditorPane1.setText(str);

        jStatusLabel.setText("readelf -r");
        process = Runtime.getRuntime().exec("readelf -r " + elfFile.getAbsolutePath());
        input = process.getInputStream();
        str = "";
        b = new byte[102400];
        while ((len = input.read(b)) > 0) {
            str += new String(b, 0, len);
        }
        jSearchRelPltEditorPane.setText(str);

        jStatusLabel.setText("readelf -d");
        process = Runtime.getRuntime().exec("readelf -d " + elfFile.getAbsolutePath());
        input = process.getInputStream();
        str = "";
        b = new byte[102400];
        while ((len = input.read(b)) > 0) {
            str += new String(b, 0, len);
        }
        input.close();
        jSearchDynamicEditorPane.setText(str);

        jStatusLabel.setText("");
    } catch (IOException e) {
        e.printStackTrace();
    }
    // end symbol table
}

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

/**
 * @return//  w  ww .  ja  v a 2  s  . co m
 */
public CollectionResultType initialize() {

    collectionInfoList = CollectionInfo.getCollectionInfoList(oldDBConn, false);
    //fixIdaho();
    if (collectionInfoList == null) {
        if (CollectionInfo.isAskForFix()) {
            if (ConvertTaxonHelper.fixTaxonomicUnitType(oldDBConn)) {
                collectionInfoList = CollectionInfo.getCollectionInfoList(oldDBConn, true);
            } else {
                try {
                    oldDBConn.close();
                } catch (SQLException e) {
                }
                System.exit(0);
            }
        } else {
            try {
                oldDBConn.close();
            } catch (SQLException e) {
            }
            System.exit(0);
        }
    }

    collectionInfoShortList = CollectionInfo.getFilteredCollectionInfoList();

    if (collectionInfoList != null && collectionInfoList.size() > 0) {
        int paleoCnt = 0;

        // This is a Hash of TaxonObjectType to see how many collections use the same TaxonObjectType
        HashMap<Integer, HashSet<CollectionInfo>> taxonomyTypeHash = new HashMap<Integer, HashSet<CollectionInfo>>();

        // Get a List for each type of Paleo Collection, hashed by the Root Id
        HashMap<Integer, Vector<CollectionInfo>> paleoColInfoHash = new HashMap<Integer, Vector<CollectionInfo>>();
        HashMap<Integer, HashSet<DisciplineType.STD_DISCIPLINES>> paleoDispTypeHash = new HashMap<Integer, HashSet<DisciplineType.STD_DISCIPLINES>>();

        for (CollectionInfo colInfo : collectionInfoShortList) {
            // Tracks a 'set' of CollectionInfo objects for each TaxonomyTypeId
            HashSet<CollectionInfo> taxonomyTypeSet = taxonomyTypeHash.get(colInfo.getTaxonomyTypeId());
            if (taxonomyTypeSet == null) {
                System.out.println("Creating TxTypeID: " + colInfo.getTaxonomyTypeId() + "  From "
                        + colInfo.getCatSeriesName());

                taxonomyTypeSet = new HashSet<CollectionInfo>();
                taxonomyTypeHash.put(colInfo.getTaxonomyTypeId(), taxonomyTypeSet);
            } else {
                System.out.println("Adding TxTypeID: " + colInfo.getTaxonomyTypeId() + "  From "
                        + colInfo.getCatSeriesName() + "  " + taxonomyTypeSet.size());
            }
            taxonomyTypeSet.add(colInfo);

            //---
            DisciplineType dType = getStandardDisciplineName(colInfo.getTaxonomyTypeName(),
                    colInfo.getColObjTypeName(), colInfo.getCatSeriesName());
            colInfo.setDisciplineTypeObj(dType);

            if (dType != null && dType.isPaleo()) {
                Vector<CollectionInfo> ciList = paleoColInfoHash.get(colInfo.getTaxonNameId());
                if (ciList == null) {
                    ciList = new Vector<CollectionInfo>();
                    paleoColInfoHash.put(colInfo.getTaxonNameId(), ciList);
                }
                ciList.add(colInfo);

                HashSet<DisciplineType.STD_DISCIPLINES> typeDispSet = paleoDispTypeHash
                        .get(colInfo.getTaxonNameId());
                if (typeDispSet == null) {
                    typeDispSet = new HashSet<DisciplineType.STD_DISCIPLINES>();
                    paleoDispTypeHash.put(colInfo.getTaxonNameId(), typeDispSet);
                }
                typeDispSet.add(colInfo.getDisciplineTypeObj().getDisciplineType());

                paleoCnt++;
            }
            System.out.println("--------------------------------------");
            //System.out.println(colInfo.toString()+"\n");
        } // for loop

        int cnt = 0;
        StringBuilder msg = new StringBuilder();
        for (Integer taxonomyTypId : taxonomyTypeHash.keySet()) {
            HashSet<CollectionInfo> taxonomyTypeSet = taxonomyTypeHash.get(taxonomyTypId);
            if (taxonomyTypeSet.size() > 1) {
                msg.append(
                        String.format("<html>TaxonomyTypeId %d has more than one Discpline/Collection:<br><OL>",
                                taxonomyTypId));
                for (CollectionInfo ci : taxonomyTypeSet) {
                    msg.append(String.format("<LI>%s - %s - %s</LI>", ci.getCatSeriesName(),
                            ci.getColObjTypeName(), ci.getTaxonomyTypeName()));
                }
                msg.append("</OL>");
                cnt++;
            }
        }

        if (cnt > 0) {
            JOptionPane.showConfirmDialog(null, msg.toString(), "Taxomony Type Issues",
                    JOptionPane.CLOSED_OPTION, JOptionPane.QUESTION_MESSAGE);
        }

        // Will be zero for no Paleo collections
        if (paleoCnt > 1) {
            // Check to see if they all use the same tree
            if (paleoColInfoHash.size() > 1) {
                msg.setLength(0);
                // We get here when there is more than one Taxon Tree for the Paleo Collections
                for (Integer treeId : paleoColInfoHash.keySet()) {
                    Vector<CollectionInfo> ciList = paleoColInfoHash.get(treeId);
                    CollectionInfo colInfo = ciList.get(0);
                    msg.append(String.format("The following collections use Taxon Tree '%s':\n",
                            colInfo.getTaxonomyTypeName()));
                    for (CollectionInfo ci : paleoColInfoHash.get(treeId)) {
                        DisciplineType dType = getStandardDisciplineName(ci.getTaxonomyTypeName(),
                                ci.getColObjTypeName(), ci.getCatSeriesName());

                        String name = String.format("%s / %s / %s / %s / %s", ci.getCatSeriesPrefix(),
                                ci.getCatSeriesName(), ci.getColObjTypeName(), ci.getTaxonomyTypeName(),
                                dType.toString());
                        msg.append(name);
                        msg.append("\n");
                    }
                    msg.append("\n");
                }

                JOptionPane.showConfirmDialog(null, msg.toString(), "Paleo Taxon Tree Issues",
                        JOptionPane.OK_OPTION, JOptionPane.QUESTION_MESSAGE);

            } else {
                StringBuilder colNames = new StringBuilder();
                for (Integer treeId : paleoColInfoHash.keySet()) {
                    for (CollectionInfo ci : paleoColInfoHash.get(treeId)) {
                        colNames.append("<LI>");
                        colNames.append(ci.getCatSeriesName());
                        colNames.append("</LI>");
                    }
                }

                // You get here when all the Paleo Disciplines use the same tree
                String msgStr = "<html>All the Paleo Collections need to use the same Taxon Tree and<br>therefore needs to be in the same discipline:<br><ol>";
                JOptionPane.showConfirmDialog(null, msgStr + colNames.toString(), "Paleo Taxon Tree Issues",
                        JOptionPane.CLOSED_OPTION, JOptionPane.QUESTION_MESSAGE);

                for (Integer treeId : paleoColInfoHash.keySet()) {
                    Vector<CollectionInfo> ciList = paleoColInfoHash.get(treeId);
                    CollectionInfo colInfo = ciList.get(0);
                    for (CollectionInfo ci : paleoColInfoHash.get(treeId)) {
                        ci.setDisciplineTypeObj(colInfo.getDisciplineTypeObj());
                    }
                }
            }
            //
        }

        DefaultTableModel model = CollectionInfo.getCollectionInfoTableModel(false);
        if (model.getRowCount() > 1) {
            TableWriter colInfoTblWriter = convLogger.getWriter("colinfo.html", "Collection Info");

            colInfoTblWriter.startTable();
            colInfoTblWriter.logHdr(CollectionInfoModel.getHeaders());

            Object[] row = new Object[model.getColumnCount()];
            for (int r = 0; r < model.getRowCount(); r++) {
                for (int i = 0; i < model.getColumnCount(); i++) {
                    row[i] = model.getValueAt(r, i);
                }
                colInfoTblWriter.logObjRow(row);
            }
            colInfoTblWriter.endTable();
            colInfoTblWriter.println("<BR><h3>Collections to be Created.</h3>");
            colInfoTblWriter.startTable();
            colInfoTblWriter.logHdr(CollectionInfoModel.getHeaders());

            model = CollectionInfo.getCollectionInfoTableModel(true);
            row = new Object[model.getColumnCount()];
            for (int r = 0; r < model.getRowCount(); r++) {
                for (int i = 0; i < model.getColumnCount(); i++) {
                    row[i] = model.getValueAt(r, i);
                }
                colInfoTblWriter.logObjRow(row);
            }
            colInfoTblWriter.endTable();
            colInfoTblWriter.close();

            File file = new File(colInfoTblWriter.getFileName());
            if (file != null && file.exists()) {
                try {
                    AttachmentUtils.openURI(file.toURI());

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

        for (CollectionInfo ci : CollectionInfo.getFilteredCollectionInfoList()) {
            String sql = "select preparationmethod, ct.* from usyscollobjprepmeth pt inner join usysmetafieldsetsubtype st on st.fieldsetsubtypeid = pt.fieldsetsubtypeid "
                    + "inner join collectionobjecttype ct1 on ct1.collectionobjecttypeid = st.fieldvalue "
                    + "inner join collectionobjecttype ct on ct.collectionobjecttypename = replace(ct1.collectionobjecttypename, ' Preparation', '') "
                    + "inner join catalogseriesdefinition csd on csd.objecttypeid = ct.collectionobjecttypeid "
                    + "inner join catalogseries cs on cs.catalogseriesid = csd.catalogseriesid "
                    + "WHERE csd.catalogseriesid = " + ci.getCatSeriesId();

            System.out.println("\n------------------");
            System.out.println(ci.getCatSeriesName());
            System.out.println(sql);
            System.out.println("------------------");

            int i = 0;
            Vector<Object[]> list = BasicSQLUtils.query(oldDBConn, sql);
            if (list.size() > 0) {
                for (Object[] row : list) {
                    System.out.print(i + " - ");
                    for (Object col : row) {
                        System.out.print(col != null ? col.toString() : "null");
                        System.out.print(", ");
                    }
                    System.out.println();
                    i++;
                }
            } else {
                System.out.println("No Results");
            }

            sql = "select ct.*, (select relatedsubtypevalues from usysmetacontrol c "
                    + "left join usysmetafieldsetsubtype fst on fst.fieldsetsubtypeid = c.fieldsetsubtypeid "
                    + "where objectid = 10290 and ct.taxonomytypeid = c.relatedsubtypevalues) as DeterminationTaxonType "
                    + "from collectiontaxonomytypes ct where ct.biologicalobjecttypeid = "
                    + ci.getColObjTypeId();

            sql = String.format(
                    "SELECT CollectionTaxonomyTypesID, BiologicalObjectTypeID, CollectionObjectTypeName FROM (select ct.*, "
                            + "(SELECT distinct relatedsubtypevalues FROM usysmetacontrol c "
                            + "LEFT JOIN usysmetafieldsetsubtype fst ON fst.fieldsetsubtypeid = c.fieldsetsubtypeid "
                            + "WHERE objectid = 10290 AND ct.taxonomytypeid = c.relatedsubtypevalues) AS DeterminationTaxonType "
                            + "FROM collectiontaxonomytypes ct WHERE ct.biologicalobjecttypeid = %d) T1 "
                            + "INNER JOIN collectionobjecttype cot ON T1.biologicalobjecttypeid = cot.CollectionObjectTypeID",
                    ci.getColObjTypeId());

            System.out.println("\n------------------");
            System.out.println(ci.getColObjTypeName());
            System.out.println(sql);
            System.out.println("------------------");

            i = 0;
            list = BasicSQLUtils.query(oldDBConn, sql);
            if (list.size() > 0) {
                for (Object[] row : list) {
                    System.out.print(i + " - ");
                    for (Object col : row) {
                        System.out.print(col != null ? col.toString() : "null");
                        System.out.print(", ");
                    }
                    System.out.println();
                    i++;
                }
            } else {
                System.out.println("No Results");
            }
        }

        /*
                
        String sql = " select ct.*, (select relatedsubtypevalues from usysmetacontrol c " +
          "left join usysmetafieldsetsubtype fst on fst.fieldsetsubtypeid = c.fieldsetsubtypeid " +
          "where objectid = 10290 and ct.taxonomytypeid = c.relatedsubtypevalues) as DeterminationTaxonType " +
          "from collectiontaxonomytypes ct where ct.biologicalobjecttypeid = 13";
                
        System.out.println("\n------------------");
        System.out.println("List of the taxonomytypes associated with a CollectionObjectTypeID");
        System.out.println(sql);
        System.out.println("------------------");
                
        int i = 0;
        Vector<Object[]> list = BasicSQLUtils.query(oldDBConn, sql);
        if (list.size() > 0)
        {
        for (Object[] row : list)
        {
            System.out.print(i+" - ");
            for (Object col: row)
            {
                System.out.print(col != null ? col.toString() : "null");
                System.out.print(", ");
            }
            System.out.println();
        }
        } else
        {
        System.out.println("No Results");
        }*/

        CellConstraints cc = new CellConstraints();
        PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "p,2px,f:p:g,10px,p,2px,p:g,8px"));

        JTable tableTop = new JTable(CollectionInfo.getCollectionInfoTableModel(false));
        JTable tableBot = new JTable(
                CollectionInfo.getCollectionInfoTableModel(!CollectionInfo.DOING_ACCESSSION));

        int rows = 10;
        tableTop.setPreferredScrollableViewportSize(new Dimension(
                tableTop.getPreferredScrollableViewportSize().width, rows * tableTop.getRowHeight()));
        tableBot.setPreferredScrollableViewportSize(new Dimension(
                tableBot.getPreferredScrollableViewportSize().width, rows * tableBot.getRowHeight()));

        pb.add(UIHelper.createLabel("Available Specify 5 Taxononmic Types", SwingConstants.CENTER),
                cc.xy(1, 1));
        pb.add(UIHelper.createScrollPane(tableTop), cc.xy(1, 3));

        pb.add(UIHelper.createLabel("Specify 5 Collections to be Created", SwingConstants.CENTER), cc.xy(1, 5));
        pb.add(UIHelper.createScrollPane(tableBot), cc.xy(1, 7));

        pb.setDefaultDialogBorder();
        CustomDialog dlg = new CustomDialog(null, "Taxononic Types", true, pb.getPanel());
        dlg.createUI();

        dlg.setSize(1024, 500);

        UIHelper.centerWindow(dlg);
        dlg.setAlwaysOnTop(true);
        dlg.setVisible(true);

        if (dlg.isCancelled()) {
            return CollectionResultType.eCancel;
        }

        Pair<CollectionInfo, DisciplineType> pair = CollectionInfo.getDisciplineType(oldDBConn);
        if (pair == null || pair.second == null) {
            CollectionInfo colInfo = pair.first;
            disciplineType = getStandardDisciplineName(colInfo.getTaxonomyTypeName(),
                    colInfo.getColObjTypeName(), colInfo.getCatSeriesName());
        } else {
            disciplineType = pair.second;
        }

        return disciplineType != null ? CollectionResultType.eOK : CollectionResultType.eError;
    }
    return CollectionResultType.eError;
}

From source file:org.apache.jmeter.save.CSVSaveService.java

/**
 * Method saves aggregate statistics as CSV from a table model. Same as
 * {@link #saveCSVStats(List, FileWriter, String[])} except that there is no
 * need to create a List containing the data.
 * /*from  w ww  .j a  v a2 s  .  c o m*/
 * @param model
 *            table model containing the data
 * @param writer
 *            output file
 * @param saveHeaders
 *            whether or not to save headers
 * @throws IOException
 *             when writing to <code>writer</code> fails
 */
public static void saveCSVStats(DefaultTableModel model, FileWriter writer, boolean saveHeaders)
        throws IOException {
    final char DELIM = ',';
    final char[] SPECIALS = new char[] { DELIM, QUOTING_CHAR };
    final int columns = model.getColumnCount();
    final int rows = model.getRowCount();
    if (saveHeaders) {
        for (int i = 0; i < columns; i++) {
            if (i > 0) {
                writer.write(DELIM);
            }
            writer.write(quoteDelimiters(model.getColumnName(i), SPECIALS));
        }
        writer.write(LINE_SEP);
    }
    for (int row = 0; row < rows; row++) {
        for (int column = 0; column < columns; column++) {
            if (column > 0) {
                writer.write(DELIM);
            }
            Object item = model.getValueAt(row, column);
            writer.write(quoteDelimiters(String.valueOf(item), SPECIALS));
        }
        writer.write(LINE_SEP);
    }
}