Example usage for java.util ArrayList set

List of usage examples for java.util ArrayList set

Introduction

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

Prototype

public E set(int index, E element) 

Source Link

Document

Replaces the element at the specified position in this list with the specified element.

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 {//  ww  w . j  ava2  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  va  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:structuredPredictionNLG.SFX.java

/**
 * Populates the predicate, attribute, attribute/value pair, and value alignment collections
 * @param dataFile The dataset file.//from  w w w. java 2 s  .co m
 */
public void createLists(File dataFile) {
    try {
        // Initialize the collections
        setPredicates(new ArrayList<>());
        setAttributes(new HashMap<>());
        setAttributeValuePairs(new HashMap<>());
        setValueAlignments(new HashMap<>());

        // Obtain the dataset portion of the file
        String dataPart = new String();
        boolean begin = false;
        try (BufferedReader br = new BufferedReader(new FileReader(dataFile))) {
            String s;
            while ((s = br.readLine()) != null) {
                if (s.startsWith("[")) {
                    begin = true;
                }
                if (begin) {
                    dataPart += s;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Bagel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Bagel.class.getName()).log(Level.SEVERE, null, ex);
        }

        // Parse the dataset with JSON
        JSONArray overArray = new JSONArray(dataPart);
        for (int o = 0; o < overArray.length(); o++) {
            // "dial" notes each seperate dialog
            JSONArray arr = overArray.getJSONObject(o).getJSONArray("dial");
            for (int i = 0; i < arr.length(); i++) {
                String MRstr;
                String ref;
                // "dact" notes every meaning representation
                MRstr = arr.getJSONObject(i).getJSONObject("S").getString("dact");
                // "ref" notes every corresponding reference
                ref = arr.getJSONObject(i).getJSONObject("S").getString("ref").replaceAll("-s", "s");

                //We split some composite words (based on Wen et al's (2016) code)
                ref = (" " + ref + " ").replaceAll(" it's ", " it is ").replaceAll(" don't ", " do not ")
                        .replaceAll(" doesn't ", " does not ").replaceAll(" didn't ", " did not ")
                        .replaceAll(" you'd ", " you would ").replaceAll(" you're ", " you are ")
                        .replaceAll(" you'll ", " you will ").replaceAll(" i'm ", " i am ")
                        .replaceAll(" they're ", " they are ").replaceAll(" that's ", " that is ")
                        .replaceAll(" what's ", " what is ").replaceAll(" couldn't ", " could not ")
                        .replaceAll(" i've ", " i have ").replaceAll(" we've ", " we have ")
                        .replaceAll(" can't ", " cannot ").replaceAll(" i'd ", " i would ")
                        .replaceAll(" i'd ", " i would ").replaceAll(" aren't ", " are not ")
                        .replaceAll(" isn't ", " is not ").replaceAll(" wasn't ", " was not ")
                        .replaceAll(" weren't ", " were not ").replaceAll(" won't ", " will not ")
                        .replaceAll(" there's ", " there is ").replaceAll(" there're ", " there are ")
                        .replaceAll(" \\. \\. ", " \\. ").replaceAll(" restaurants ", " restaurant -s ")
                        .replaceAll(" hotels ", " hotel -s ").replaceAll(" laptops ", " laptop -s ")
                        .replaceAll(" cheaper ", " cheap -er ").replaceAll(" dinners ", " dinner -s ")
                        .replaceAll(" lunches ", " lunch -s ").replaceAll(" breakfasts ", " breakfast -s ")
                        .replaceAll(" expensively ", " expensive -ly ")
                        .replaceAll(" moderately ", " moderate -ly ").replaceAll(" cheaply ", " cheap -ly ")
                        .replaceAll(" prices ", " price -s ").replaceAll(" places ", " place -s ")
                        .replaceAll(" venues ", " venue -s ").replaceAll(" ranges ", " range -s ")
                        .replaceAll(" meals ", " meal -s ").replaceAll(" locations ", " location -s ")
                        .replaceAll(" areas ", " area -s ").replaceAll(" policies ", " policy -s ")
                        .replaceAll(" children ", " child -s ").replaceAll(" kids ", " kid -s ")
                        .replaceAll(" kidfriendly ", " kid friendly ").replaceAll(" cards ", " card -s ")
                        .replaceAll(" st ", " street ").replaceAll(" ave ", " avenue ")
                        .replaceAll(" upmarket ", " expensive ").replaceAll(" inpricey ", " cheap ")
                        .replaceAll(" inches ", " inch -s ").replaceAll(" uses ", " use -s ")
                        .replaceAll(" dimensions ", " dimension -s ")
                        .replaceAll(" driverange ", " drive range ").replaceAll(" includes ", " include -s ")
                        .replaceAll(" computers ", " computer -s ").replaceAll(" machines ", " machine -s ")
                        .replaceAll(" ecorating ", " eco rating ").replaceAll(" families ", " family -s ")
                        .replaceAll(" ratings ", " rating -s ").replaceAll(" constraints ", " constraint -s ")
                        .replaceAll(" pricerange ", " price range ")
                        .replaceAll(" batteryrating ", " battery rating ")
                        .replaceAll(" requirements ", " requirement -s ").replaceAll(" drives ", " drive -s ")
                        .replaceAll(" specifications ", " specification -s ")
                        .replaceAll(" weightrange ", " weight range ").replaceAll(" harddrive ", " hard drive ")
                        .replaceAll(" batterylife ", " battery life ")
                        .replaceAll(" businesses ", " business -s ").replaceAll(" hours ", " hour -s ")
                        .replaceAll(" accessories ", " accessory -s ").replaceAll(" ports ", " port -s ")
                        .replaceAll(" televisions ", " television -s ")
                        .replaceAll(" restrictions ", " restriction -s ")
                        .replaceAll(" extremely ", " extreme -ly ").replaceAll(" actually ", " actual -ly ")
                        .replaceAll(" typically ", " typical -ly ").replaceAll(" drivers ", " driver -s ")
                        .replaceAll(" teh ", " the ").replaceAll(" definitely ", " definite -ly ")
                        .replaceAll(" factors ", " factor -s ").replaceAll(" truly ", " true -ly ")
                        .replaceAll(" mostly ", " most -ly ").replaceAll(" nicely ", " nice -ly ")
                        .replaceAll(" surely ", " sure -ly ").replaceAll(" certainly ", " certain -ly ")
                        .replaceAll(" totally ", " total -ly ").replaceAll(" \\# ", " number ")
                        .replaceAll(" \\& ", " and ").replaceAll(" avenue ", " ave ").replaceAll(" -s ", " s ")
                        .trim();

                // If the MR concerns one of the following predicates, and a ref is available
                if ((MRstr.startsWith("inform(") || MRstr.startsWith("inform_only")
                        || MRstr.startsWith("inform_no_match(") || MRstr.startsWith("?confirm(")
                        || MRstr.startsWith("?select(") || MRstr.startsWith("?request(")
                        || MRstr.startsWith("?reqmore(") || MRstr.startsWith("goodbye(")) && !ref.isEmpty()) {
                    // Obtain the predicate
                    String predicate = MRstr.substring(0, MRstr.indexOf('('));
                    if (!getPredicates().contains(predicate) && predicate != null) {
                        getPredicates().add(predicate);

                        if (!getAttributes().containsKey(predicate)) {
                            getAttributes().put(predicate, new HashSet<String>());
                        }
                        if (!getDatasetInstances().containsKey(predicate)) {
                            getDatasetInstances().put(predicate, new ArrayList<DatasetInstance>());
                        }
                    }

                    // Obtain the attributes
                    String attributesStr = MRstr.substring(MRstr.indexOf('(') + 1, MRstr.length() - 1);
                    HashMap<String, HashSet<String>> attributeValues = new HashMap<>();
                    // Track the indexes used for variables identifiers (seperately for each attribute)
                    HashMap<String, Integer> attrXIndeces = new HashMap<>();
                    if (!attributesStr.isEmpty()) {
                        // Parse the attributes and their values
                        String[] args = attributesStr.split(";");
                        for (String arg : args) {
                            String attr;
                            String value = "";
                            // If the attribute has corresponding values
                            if (arg.contains("=")) {
                                String[] subAttr = arg.split("=");
                                value = subAttr[1].toLowerCase();
                                attr = subAttr[0].toLowerCase().replaceAll("_", "");

                                if (value.startsWith("\'")) {
                                    value = value.substring(1, value.length() - 1);
                                }
                                // Normalize some closed set values
                                if (value.equals("true")) {
                                    value = "yes";
                                }
                                if (value.equals("false")) {
                                    value = "no";
                                }
                                if (value.equals("dontcare")) {
                                    value = "dont_care";
                                }
                                if ((" " + value + " ").contains(" avenue ")) {
                                    value = (" " + value + " ").replace(" avenue ", " ave ").trim();
                                }
                                // Treat these values as seperate attributes since they are expressed quite differently
                                if (value.equals("no") || value.equals("yes") || value.equals("yes or no")
                                        || value.equals("none") || value.equals("empty")) {
                                    attr += "_" + value.replaceAll(" ", "_");
                                    value = attr;
                                }
                                // Treat "dont_care" instances, as if "dont_care" is the attribute, and the original attribute is the value
                                // We do this because the phrasing is very similar between different "dont_care" realizations
                                if (value.equals("dont_care")) {
                                    String v = value;
                                    value = attr;
                                    attr = v;
                                }
                            } else {
                                attr = arg.replaceAll("_", "");
                            }
                            if (!getAttributes().get(predicate).contains(attr)) {
                                getAttributes().get(predicate).add(attr);
                            }
                            if (!attributeValues.containsKey(attr)) {
                                attributeValues.put(attr, new HashSet<String>());
                            }
                            // If the attribute has no corresponding value, we encode it by using the attibute identifier as the value
                            if (value.isEmpty()) {
                                value = attr;
                            }

                            // If the value is a variable, we name it as {@X@ + attribute identifier + variable index (for this attribute)}
                            // This occurs when values are already set as variables in the MR, before any delexicalization happens
                            if (value.toLowerCase().startsWith("x")) {
                                int index = 0;
                                if (!attrXIndeces.containsKey(attr)) {
                                    attrXIndeces.put(attr, 1);
                                } else {
                                    index = attrXIndeces.get(attr);
                                    attrXIndeces.put(attr, index + 1);
                                }
                                value = "x" + index;
                            }
                            attributeValues.get(attr).add(value.trim().toLowerCase());
                        }
                    }

                    // Delexicalizing the attribute/value pairs
                    HashMap<String, HashSet<String>> delexicalizedAttributeValues = new HashMap<>();
                    HashMap<String, HashMap<String, Integer>> attrValuePriorities = new HashMap<>();
                    int maximumPriority = 0;
                    /* Delixalization of values needs to happen incrementally with priority given to the values of greater lenth, to avoid overlap of values in the reference
                     * e.g. for the MR: inform{name="inn on castro", near="castro"}, with the reference "inn on castro is a nice restaurant",
                     *      we need to first align and delexicalize the "inn on castro" value, before the "castro" value 
                     *      (in this case because "castro" doesn't appear in the reference, but even if it appeared later the priorities would help align it with the correct one)
                    */
                    // We begin by determining which values may require delexicalization, and which not
                    for (String attr : attributeValues.keySet()) {
                        if (!attr.isEmpty()) {
                            delexicalizedAttributeValues.put(attr, new HashSet<String>());
                            attrValuePriorities.put(attr, new HashMap<String, Integer>());
                            for (String value : attributeValues.get(attr)) {
                                if (!value.equals("none") && !value.equals("empty") && !value.equals("yes")
                                        && !value.equals("yes or no") && !value.equals("no")
                                        && !value.equals(attr)) {
                                    // Initially priorities are given according to value order
                                    attrValuePriorities.get(attr).put(value, maximumPriority);
                                    maximumPriority++;
                                } else {
                                    // No delexicalization is needed here
                                    delexicalizedAttributeValues.get(attr).add(value);
                                }
                            }
                        }
                    }
                    // We shift the priorities of different values, according to their perspective lengths (i.e. longer values have higher priority)
                    boolean change = true;
                    while (change) {
                        change = false;
                        for (String attr1 : attrValuePriorities.keySet()) {
                            for (String value1 : attrValuePriorities.get(attr1).keySet()) {
                                for (String attr2 : attrValuePriorities.keySet()) {
                                    for (String value2 : attrValuePriorities.get(attr2).keySet()) {
                                        if (!value1.equals(value2) && value1.contains(value2)
                                                && attrValuePriorities.get(attr1).get(
                                                        value1) > attrValuePriorities.get(attr2).get(value2)) {
                                            int prio1 = attrValuePriorities.get(attr1).get(value1);
                                            int prio2 = attrValuePriorities.get(attr2).get(value2);
                                            attrValuePriorities.get(attr1).put(value1, prio2);
                                            attrValuePriorities.get(attr2).put(value2, prio1);
                                            change = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // Map between variables and their lexicalized values, required for relexicalization during postprocessing after the sentence generation
                    HashMap<String, String> delexicalizationMap = new HashMap<>();
                    ref = " " + ref + " ";
                    // Delexicalization occurs, in order of priority
                    for (int priority = 0; priority < maximumPriority; priority++) {
                        for (String attr : attrValuePriorities.keySet()) {
                            if (!attrXIndeces.containsKey(attr)) {
                                attrXIndeces.put(attr, 0);
                            }
                            for (String value : attrValuePriorities.get(attr).keySet()) {
                                if (attrValuePriorities.get(attr).get(value) == priority) {
                                    // If the value doesn't appear verbatim in the reference, and the value is not composed of multiple subvalues (i.e. doesn't contain connectives)
                                    if (!ref.contains(" " + value + " ") && !value.contains(" and ")
                                            && !value.contains(" or ")) {
                                        if (value.equals("restaurant") && ref.contains(" place ")) {
                                            ref = ref.replace(" place ", " " + Action.TOKEN_X + attr + "_"
                                                    + attrXIndeces.get(attr) + " ");
                                            ref = ref.replaceAll("  ", " ");
                                            delexicalizedAttributeValues.get(attr)
                                                    .add(Action.TOKEN_X + attr + "_" + attrXIndeces.get(attr));
                                            delexicalizationMap.put(
                                                    Action.TOKEN_X + attr + "_" + attrXIndeces.get(attr),
                                                    "place");
                                            attrXIndeces.put(attr, attrXIndeces.get(attr) + 1);
                                        } else {
                                            delexicalizedAttributeValues.get(attr).add(value);
                                        }
                                        // If the value doesn't appear verbatim in the reference, but the value is composed of multiple sub-values
                                    } else if (!ref.contains(" " + value + " ")
                                            && (value.contains(" and ") || value.contains(" or "))) {
                                        // We first check if the value appears verbatim when we switch "and" with "or" and vice versa
                                        // We do this due to some inconsistencies in the dataset on how conjuctions are treated
                                        String tempValue = value;
                                        if (value.contains(" and ")) {
                                            tempValue = value.replace(" and ", " or ");
                                        } else if (value.contains(" or ")) {
                                            tempValue = value.replace(" or ", " and ");
                                        }

                                        if (ref.contains(" " + tempValue + " ")) {
                                            ref = ref.replace(" " + tempValue + " ", " " + Action.TOKEN_X + attr
                                                    + "_" + attrXIndeces.get(attr) + " ");
                                            ref = ref.replaceAll("  ", " ");
                                            delexicalizedAttributeValues.get(attr)
                                                    .add(Action.TOKEN_X + attr + "_" + attrXIndeces.get(attr));
                                            delexicalizationMap.put(
                                                    Action.TOKEN_X + attr + "_" + attrXIndeces.get(attr),
                                                    value);
                                            attrXIndeces.put(attr, attrXIndeces.get(attr) + 1);
                                        } else {
                                            // We split the conjunction into the seperate values; so far the code supports only 2 sub-values
                                            String[] values = new String[2];
                                            if (value.contains(" and ")) {
                                                values = value.split(" and ");
                                            } else if (value.contains(" or ")) {
                                                values = value.split(" or ");
                                            }
                                            // And check if the conjunction appears verbatim when we switch the position of the sub-values
                                            String newValue1 = values[1] + " and " + values[0];
                                            String newValue2 = values[1] + " or " + values[0];
                                            if (ref.contains(" " + newValue1 + " ")) {
                                                ref = ref.replace(" " + newValue1 + " ", " " + Action.TOKEN_X
                                                        + attr + "_" + attrXIndeces.get(attr) + " ");
                                                ref = ref.replaceAll("  ", " ");
                                                delexicalizedAttributeValues.get(attr).add(
                                                        Action.TOKEN_X + attr + "_" + attrXIndeces.get(attr));
                                                delexicalizationMap.put(
                                                        Action.TOKEN_X + attr + "_" + attrXIndeces.get(attr),
                                                        value);
                                                attrXIndeces.put(attr, attrXIndeces.get(attr) + 1);
                                            } else if (ref.contains(" " + newValue2 + " ")) {
                                                ref = ref.replace(" " + newValue2 + " ", " " + Action.TOKEN_X
                                                        + attr + "_" + attrXIndeces.get(attr) + " ");
                                                ref = ref.replaceAll("  ", " ");
                                                delexicalizedAttributeValues.get(attr).add(
                                                        Action.TOKEN_X + attr + "_" + attrXIndeces.get(attr));
                                                delexicalizationMap.put(
                                                        Action.TOKEN_X + attr + "_" + attrXIndeces.get(attr),
                                                        value);
                                                attrXIndeces.put(attr, attrXIndeces.get(attr) + 1);
                                            }
                                        }
                                        // If the value appears verbatim in the reference, delexicalize it
                                    } else {
                                        ref = ref.replace(" " + value + " ", " " + Action.TOKEN_X + attr + "_"
                                                + attrXIndeces.get(attr) + " ");
                                        ref = ref.replaceAll("  ", " ");
                                        delexicalizedAttributeValues.get(attr)
                                                .add(Action.TOKEN_X + attr + "_" + attrXIndeces.get(attr));
                                        delexicalizationMap.put(
                                                Action.TOKEN_X + attr + "_" + attrXIndeces.get(attr), value);
                                        attrXIndeces.put(attr, attrXIndeces.get(attr) + 1);
                                    }
                                }
                            }
                        }
                    }
                    ref = ref.trim();

                    // We construct the MeaningRepresentation
                    MeaningRepresentation MR = new MeaningRepresentation(predicate,
                            delexicalizedAttributeValues, MRstr, delexicalizationMap);

                    // Sequences of attribute/values pairs and words in the order we observe this in the reference
                    ArrayList<String> observedAttrValueSequence = new ArrayList<>();
                    ArrayList<String> observedWordSequence = new ArrayList<>();

                    // The observed word sequence does not include punctuation
                    String[] words = ref.replaceAll("([,.?!;:'])", " $1").split(" ");

                    // We construct the observed word sequence (and fix some orthographical errors along the way)
                    for (int w = 0; w < words.length; w++) {
                        if (!words[w].trim().isEmpty()) {
                            if (!words[w].trim().isEmpty()
                                    && (observedWordSequence.isEmpty() || !words[w].trim().equals(
                                            observedWordSequence.get(observedWordSequence.size() - 1)))) {
                                if (words[w].trim().equals("s") && (observedWordSequence
                                        .get(observedWordSequence.size() - 1).equals("child"))) {
                                    observedWordSequence.set(observedWordSequence.size() - 1, "children");
                                } else if (words[w].trim().equals("addres")
                                        || words[w].trim().equals("adress")) {
                                    observedWordSequence.add("address");
                                } else if (words[w].trim().equals("mathch")) {
                                    observedWordSequence.add("match");
                                } else if (words[w].trim().equals("prefered")) {
                                    observedWordSequence.add("preferred");
                                } else if (words[w].trim().equals("relevent")) {
                                    observedWordSequence.add("relevant");
                                } else if (words[w].trim().equals("alloed")) {
                                    observedWordSequence.add("allowed");
                                } else if (words[w].trim().equals("avalible")
                                        || words[w].trim().equals("avalable")) {
                                    observedWordSequence.add("available");
                                } else if (words[w].trim().equals("tha") || words[w].trim().equals("te")) {
                                    observedWordSequence.add("the");
                                } else if (words[w].trim().equals("internect")) {
                                    observedWordSequence.add("internet");
                                } else if (words[w].trim().equals("wether")) {
                                    observedWordSequence.add("whether");
                                } else if (words[w].trim().equals("aplogize")) {
                                    observedWordSequence.add("apologize");
                                } else if (words[w].trim().equals("accomodations")) {
                                    observedWordSequence.add("accommodations");
                                } else if (words[w].trim().equals("whould")) {
                                    observedWordSequence.add("would");
                                } else if (words[w].trim().equals("aceepted")) {
                                    observedWordSequence.add("accepted");
                                } else if (words[w].trim().equals("postode")) {
                                    observedWordSequence.add("postcode");
                                } else if (words[w].trim().equals("ive")) {
                                    observedWordSequence.add("i");
                                    observedWordSequence.add("have");
                                } else if (words[w].trim().equals("waht")) {
                                    observedWordSequence.add("what");
                                } else if (words[w].trim().equals("neighborhood")) {
                                    observedWordSequence.add("neighbourhood");
                                } else if (words[w].trim().equals("prefernce")) {
                                    observedWordSequence.add("preference");
                                } else if (words[w].trim().equals("dont")) {
                                    observedWordSequence.add("don't");
                                } else if (words[w].trim().equals("isnt")) {
                                    observedWordSequence.add("isn't");
                                } else if (words[w].trim().equals("intenet")
                                        || words[w].trim().equals("internetn")) {
                                    observedWordSequence.add("internet");
                                } else if (words[w].trim().equals("cannote")) {
                                    observedWordSequence.add("cannot");
                                } else if (words[w].trim().equals("notels")) {
                                    observedWordSequence.add("hotels");
                                } else if (words[w].trim().equals("phne")) {
                                    observedWordSequence.add("phone");
                                } else if (words[w].trim().equals("taht")) {
                                    observedWordSequence.add("that");
                                } else if (words[w].trim().equals("postdocde")) {
                                    observedWordSequence.add("postcode");
                                } else if (words[w].trim().equals("accpects")) {
                                    observedWordSequence.add("accepts");
                                } else if (words[w].trim().equals("doesn") || words[w].trim().equals("doesnt")
                                        || words[w].trim().equals("doesn")) {
                                    observedWordSequence.add("doesn't");
                                } else if (words[w].trim().equals("restaurnats")) {
                                    observedWordSequence.add("restarnauts");
                                } else if (words[w].trim().equals("ther") || words[w].trim().equals("thers")) {
                                    observedWordSequence.add("there");

                                    // The dataset treats the suffixes "s" and "-ly" as separate words
                                    // We combine these suffixes with their preceding words but keep a cache with these changes to revert them before evaluation (we have to do this so that the token-based evaluation metrics are calculated in a consistent manner with Wen et al.'s)
                                } else if (words[w].trim().equals("s")) {
                                    if (observedWordSequence.isEmpty()) {
                                        observedWordSequence.add(words[w].trim().toLowerCase());
                                    } else if (observedWordSequence.get(observedWordSequence.size() - 1)
                                            .startsWith(Action.TOKEN_X)) {
                                        observedWordSequence.add(words[w].trim().toLowerCase());
                                    } else {
                                        getCompositeSuffixesInData().put(
                                                observedWordSequence.get(observedWordSequence.size() - 1) + "s",
                                                observedWordSequence.get(observedWordSequence.size() - 1)
                                                        + " s");
                                        observedWordSequence.set(observedWordSequence.size() - 1,
                                                observedWordSequence.get(observedWordSequence.size() - 1)
                                                        + "s");
                                    }
                                } else if (words[w].trim().equals("-ly")) {
                                    if (observedWordSequence.isEmpty()) {
                                        observedWordSequence.add(words[w].trim().toLowerCase());
                                    } else if (observedWordSequence.get(observedWordSequence.size() - 1)
                                            .startsWith(Action.TOKEN_X)) {
                                        observedWordSequence.add(words[w].trim().toLowerCase());
                                    } else {
                                        getCompositeSuffixesInData().put(
                                                observedWordSequence.get(observedWordSequence.size() - 1)
                                                        + "ly",
                                                observedWordSequence.get(observedWordSequence.size() - 1)
                                                        + " -ly");
                                        observedWordSequence.set(observedWordSequence.size() - 1,
                                                observedWordSequence.get(observedWordSequence.size() - 1)
                                                        + "ly");
                                    }
                                } else {
                                    observedWordSequence.add(words[w].trim().toLowerCase());
                                }
                            }
                        }
                    }

                    //Probably deprecated, need to do some more tests
                    MR.getAttributeValues().keySet().forEach((attr) -> {
                        MR.getAttributeValues().get(attr).stream()
                                .filter((value) -> (attr.equals("name") && value.equals("none")))
                                .forEachOrdered((value) -> {
                                    observedAttrValueSequence.add(0,
                                            attr.toLowerCase() + "=" + value.toLowerCase());
                                });
                    });
                    observedAttrValueSequence.add(Action.TOKEN_END);

                    // We store the maximum observed word sequence length, to use as a limit during generation
                    if (observedWordSequence.size() > getMaxWordSequenceLength()) {
                        setMaxWordSequenceLength(observedWordSequence.size());
                    }

                    // We initialize the alignments between words and attribute/value pairs
                    ArrayList<String> wordToAttrValueAlignment = new ArrayList<>();
                    // And populate them with "unaligned" tokens (i.e. "[]") and punctuation alignments; we do the latter so we know to filter out punctuation when estimating the alignments in later stages
                    observedWordSequence.forEach((word) -> {
                        if (word.trim().matches("[,.?!;:']")) {
                            wordToAttrValueAlignment.add(Action.TOKEN_PUNCT);
                        } else {
                            wordToAttrValueAlignment.add("[]");
                        }
                    });
                    // And using both word sequence and initial alignments, we construct a draft sequence of word actions corresponding to the reference
                    ArrayList<Action> directReferenceSequence = new ArrayList<>();
                    for (int r = 0; r < observedWordSequence.size(); r++) {
                        directReferenceSequence
                                .add(new Action(observedWordSequence.get(r), wordToAttrValueAlignment.get(r)));
                    }
                    // Finally, we construct the DatasetInstance
                    DatasetInstance DI = new DatasetInstance(MR, directReferenceSequence,
                            postProcessRef(MR, directReferenceSequence));
                    // We add the evaluation references of all previously constructed DatasetInstances (that are identical to this one) as available evaluation references 
                    getDatasetInstances().get(predicate).stream()
                            .filter((existingDI) -> (existingDI.getMeaningRepresentation().getAbstractMR()
                                    .equals(DI.getMeaningRepresentation().getAbstractMR())))
                            .map((existingDI) -> {
                                existingDI.getEvaluationReferences().addAll(DI.getEvaluationReferences());
                                return existingDI;
                            }).forEachOrdered((existingDI) -> {
                                // We add the direct reference of this DatasetInstance as an available evaluation reference to all previously constructed DatasetInstance that are identical to this one
                                DI.getEvaluationReferences().addAll(existingDI.getEvaluationReferences());
                            });
                    getDatasetInstances().get(predicate).add(DI);

                    // Calculate the possible alignments between (non-delexicalized) attribute values and reference subphrases
                    // We do this by comparing the values with n-gram subphrases of the reference, using character-level Levenshtein distance
                    // These are used during the estimation of naive alignments, but also for tracking which values have possibly been expressed during generation
                    HashMap<String, HashMap<String, Double>> observedValueAlignments = new HashMap<>();
                    MR.getAttributeValues().keySet().forEach((attr) -> {
                        MR.getAttributeValues().get(attr).stream()
                                .filter((value) -> (!value.equals("name=none")
                                        && !value.startsWith(Action.TOKEN_X)
                                        && !(value.matches("\"[xX][0-9]+\"") || value.matches("[xX][0-9]+"))))
                                .forEachOrdered((value) -> {
                                    String valueToCompare = value;
                                    if (value.equals("no") || value.equals("yes") || value.equals("yes or no")
                                            || value.equals("none") || value.equals("empty")) {
                                        // If the value is boolean or non-existant, we also compare using the attribute name
                                        valueToCompare = attr;
                                        observedValueAlignments.put(valueToCompare + ":" + value,
                                                new HashMap<String, Double>());
                                    } else {
                                        observedValueAlignments.put(valueToCompare,
                                                new HashMap<String, Double>());
                                    }
                                    //For all n-grams in the referenec
                                    for (int n = 1; n < observedWordSequence.size(); n++) {
                                        //Calculate the similaritie between them and valueToCompare
                                        for (int r = 0; r <= observedWordSequence.size() - n; r++) {
                                            boolean compareAgainstNGram = true;
                                            for (int j = 0; j < n; j++) {
                                                if (observedWordSequence.get(r + j).startsWith(Action.TOKEN_X)
                                                        || wordToAttrValueAlignment.get(r + j)
                                                                .equals(Action.TOKEN_PUNCT)
                                                        || StringNLPUtilities
                                                                .isArticle(observedWordSequence.get(r + j))
                                                        || observedWordSequence.get(r + j)
                                                                .equalsIgnoreCase("and")
                                                        || observedWordSequence.get(r + j)
                                                                .equalsIgnoreCase("or")) {
                                                    // We ignore n-grams that contain variables, punctuation, articles, or conjuctions
                                                    // In other words, we do not allow values to align with such n-grams
                                                    compareAgainstNGram = false;
                                                }
                                            }
                                            if (compareAgainstNGram) {
                                                String align = "";
                                                String compare = "";
                                                String backwardCompare = "";
                                                for (int j = 0; j < n; j++) {
                                                    // The coordinates of the alignment
                                                    align += (r + j) + " ";
                                                    compare += observedWordSequence.get(r + j);
                                                    backwardCompare = observedWordSequence.get(r + j)
                                                            + backwardCompare;
                                                }
                                                align = align.trim();

                                                // Calculate the character-level distance between the value and the nGram (in its original and reversed order)
                                                Double distance = Levenshtein.getSimilarity(
                                                        valueToCompare.toLowerCase(), compare.toLowerCase(),
                                                        true);
                                                Double backwardDistance = Levenshtein.getSimilarity(
                                                        valueToCompare.toLowerCase(),
                                                        backwardCompare.toLowerCase(), true);

                                                // We keep the best distance score; note that the Levenshtein distance is normalized so that greater is better 
                                                if (backwardDistance > distance) {
                                                    distance = backwardDistance;
                                                }
                                                // We ignore all nGrams that are less similar than a threshold
                                                if (distance > 0.3) {
                                                    if (value.equals("no") || value.equals("yes")
                                                            || value.equals("yes or no") || value.equals("none")
                                                            || value.equals("empty")) {
                                                        observedValueAlignments
                                                                .get(valueToCompare + ":" + value)
                                                                .put(align, distance);
                                                    } else {
                                                        observedValueAlignments.get(valueToCompare).put(align,
                                                                distance);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                });
                    });

                    // We filter out any values that haven't been aligned
                    HashSet<String> toRemove = new HashSet<>();
                    for (String value : observedValueAlignments.keySet()) {
                        if (observedValueAlignments.get(value).isEmpty()) {
                            toRemove.add(value);
                        }
                    }
                    for (String value : toRemove) {
                        observedValueAlignments.remove(value);
                    }

                    // We keep the best aligned nGrams; since we do not want the aligned nGrams to be overlapping, we remove any overlapping alignments after we pick each one
                    while (!observedValueAlignments.keySet().isEmpty()) {
                        // Find the best aligned nGram
                        Double max = Double.NEGATIVE_INFINITY;
                        String[] bestAlignment = new String[2];
                        for (String value : observedValueAlignments.keySet()) {
                            for (String alignment : observedValueAlignments.get(value).keySet()) {
                                if (observedValueAlignments.get(value).get(alignment) > max) {
                                    max = observedValueAlignments.get(value).get(alignment);
                                    bestAlignment[0] = value;
                                    bestAlignment[1] = alignment;
                                }
                            }
                        }

                        // Find the subphrase that corresponds to the best aligned nGram, according to the coordinates
                        ArrayList<String> alignedStr = new ArrayList<>();
                        String[] coords = bestAlignment[1].split(" ");
                        if (coords.length == 1) {
                            alignedStr.add(observedWordSequence.get(Integer.parseInt(coords[0].trim())));
                        } else {
                            for (int a = Integer.parseInt(coords[0].trim()); a <= Integer
                                    .parseInt(coords[coords.length - 1].trim()); a++) {
                                alignedStr.add(observedWordSequence.get(a));
                            }
                        }

                        // Store the best aligned nGram
                        if (!getValueAlignments().containsKey(bestAlignment[0])) {
                            getValueAlignments().put(bestAlignment[0],
                                    new HashMap<ArrayList<String>, Double>());
                        }
                        getValueAlignments().get(bestAlignment[0]).put(alignedStr, max);

                        // And remove it from the observed ones for this instance
                        observedValueAlignments.remove(bestAlignment[0]);
                        // And also remove any other aligned nGrams that are overlapping with the best aligned nGram
                        observedValueAlignments.keySet().forEach((value) -> {
                            HashSet<String> alignmentsToBeRemoved = new HashSet<>();
                            observedValueAlignments.get(value).keySet().forEach((alignment) -> {
                                String[] othCoords = alignment.split(" ");
                                if (Integer.parseInt(coords[0].trim()) <= Integer.parseInt(othCoords[0].trim())
                                        && (Integer.parseInt(coords[coords.length - 1].trim()) >= Integer
                                                .parseInt(othCoords[0].trim()))
                                        || (Integer.parseInt(othCoords[0].trim()) <= Integer
                                                .parseInt(coords[0].trim())
                                                && Integer.parseInt(
                                                        othCoords[othCoords.length - 1].trim()) >= Integer
                                                                .parseInt(coords[0].trim()))) {
                                    alignmentsToBeRemoved.add(alignment);
                                }
                            });
                            alignmentsToBeRemoved.forEach((alignment) -> {
                                observedValueAlignments.get(value).remove(alignment);
                            });
                        });
                        // We filter out any values that are no logner aligned (due to overlapping conflicts)
                        toRemove = new HashSet<>();
                        for (String value : observedValueAlignments.keySet()) {
                            if (observedValueAlignments.get(value).isEmpty()) {
                                toRemove.add(value);
                            }
                        }
                        for (String value : toRemove) {
                            observedValueAlignments.remove(value);
                        }
                    }
                    getObservedAttrValueSequences().add(observedAttrValueSequence);
                }
            }
        }
    } catch (JSONException ex) {
    }
}

From source file:com.androidaq.AndroiDAQTCPAdapter.java

public void setProp() {

    //Below is where the code for setting the inputs/outputs, states etc. and get readings from inputs.
    //((AndroiDAQTCPMain) context).setPage(6); // this statement is used for development convenience
    chsAreInputs = getInputChannels(); // Inputs are read
    ArrayList<String> isInputPulsed = getPulsedInputs(chsAreInputs);// which inputs are pulse reads
    ArrayList<String> chsAreOutputs = getOutputChannels(); // Outputs can be digital or frequency
    ArrayList<String> isOutputDigital = getDigitalOutputs(chsAreOutputs); // which output channels are digital
    ArrayList<String> digitalOutState = getDigitalOutputState(isOutputDigital);// get output desired state
    ArrayList<String> isOutputPulsed = getPulsedOutputs(chsAreOutputs); // which output channels are pulsed
    ArrayList<String> desiredFreq = getDesiredFreqs(isOutputPulsed); // for channels not digital, what is the desired frequency
    ArrayList<String> desiredDuty = getDesiredDuty(isOutputPulsed); // for channels not digital, what is the desired duty
    //ArrayList<String> voltChsRead = getVoltageChannel(); // Get voltage channels read
    /*setText("\n" + "Inputs are: " + chsAreInputs 
     + "\n" + "Input Pins that are pulsed are: " + isInputPulsed
     + "\n" + "Outputs Pins are: " + chsAreOutputs 
     + "\n" + "Outputs that are Digital: " + isOutputDigital
     +  "\n" + "Digital output states are: " + digitalOutState
     + "\n" + "Pulsed output pins are: " + isOutputPulsed
     + "\n" + "Desired output frequencies are: " + desiredFreq 
     + "\n" + "Voltage Channels Read are: " + voltChsRead  + "\n"); */

    ((AndroiDAQTCPMain) context).sendMessage("00\r"); // Send to AndroidDAQ menu command and Array(s) of information. 

    String[] temp = new String[16];
    Arrays.fill(temp, "NS"); // NS = Not Set
    ArrayList<String> SendToProp = new ArrayList<String>(Arrays.asList(temp));

    //set input channels
    int x0 = chsAreInputs.size();
    // for each channel in chsAreInput, put zero in SendToProp channel location
    for (int i = 0; i < x0; i++) {
        String channel = chsAreInputs.get(i);
        SendToProp.set(Integer.valueOf(channel), "0");
    }/*from   w  ww .  j a va 2s  .  co  m*/
    // set input channels that are pulsed
    int x1 = isInputPulsed.size();
    for (int i = 0; i < x1; i++) {
        String channel = isInputPulsed.get(i);
        SendToProp.set(Integer.valueOf(channel), "1");
    }
    // set output channels that are pulsed
    int x2 = isOutputPulsed.size();
    //Log.e("test", "isOutputPulsed size is:" + x2);
    for (int i = 0; i < x2; i++) {
        String channel = isOutputPulsed.get(i);
        String freq = desiredFreq.get(i);
        String duty = desiredDuty.get(i);
        SendToProp.set(Integer.valueOf(channel), "4-" + freq + "_" + duty);
    }
    //Log.e("test", "SendToProp after pulsed Outputs set is:" + SendToProp.toString());
    // set output channels that are not pulsed to their appropriate state
    int x3 = Math.abs(chsAreOutputs.size() - isOutputPulsed.size());
    //Log.e("test", "Math.abs is:" + x3);
    for (int i = 0; i < x3; i++) {
        String channel = isOutputDigital.get(i);
        String state = digitalOutState.get(i);
        if (state == "true") {
            SendToProp.set(Integer.valueOf(channel), "3");
        } else {
            SendToProp.set(Integer.valueOf(channel), "2");
        }

    }
    Log.e("test", "SendToProp after insert is:" + SendToProp.toString());
    // create string to send to prop via BT
    int x4 = SendToProp.size();
    //Log.e("test", "SendToProp size is:" + SendToProp.size());
    String propMessage = "";
    for (int i = 0; i < x4; i++) {
        String whatIsString = SendToProp.get(i);
        if (whatIsString.contains("4-")) {
            String[] freqString = whatIsString.split("-");
            String[] dutyString = freqString[1].split("_");
            Log.e("test", "freqString[0] is:" + freqString[0]);
            Log.e("test", "freqString[1] is:" + freqString[1]);
            Log.e("test", "dutyString[0] is:" + dutyString[0]);
            Log.e("test", "dutyString[1] is:" + dutyString[1]);
            propMessage = propMessage.concat(
                    "0" + freqString[0] + "\r" + "0" + dutyString[0] + "\r" + "0" + dutyString[1] + "\r");
        } else {
            propMessage = propMessage + "0" + whatIsString + "\r";
        }
    }
    Log.e("test", "propMessage after insert is:" + propMessage);
    //((AndroiDAQTCPMain) context).sendMessage(propMessage + "\r");
    String[] subMessages = propMessage.split("\\r"); // break message into sub-messages so data isn't lost in transmission
    int numOfArrays = subMessages.length;
    for (int i = 0; i < numOfArrays; i++) {
        Log.e("test", "subMessages after insert is:" + subMessages[i]);
        ((AndroiDAQTCPMain) context).sendMessage(subMessages[i] + "\r");
        try {
            Thread.sleep(9);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //TODO
    Log.e("test", "runVolts is:" + runVolts);
    Log.e("test", "runInputs is:" + runInputs);
    Log.e("test", "runAll is:" + runAll);
    if (sendOutputs) {
        sendOutputs = false;
        ((AndroiDAQTCPMain) context).setOutputs();
    }
    if (runVolts) {
        ((AndroiDAQTCPMain) context).getVolts(true);
        runVolts = false;
    }
    if (runInputs) {
        ((AndroiDAQTCPMain) context).getInputs(true);
        runInputs = false;
    }
    if (runContInputs) {
        ((AndroiDAQTCPMain) context).getInputsCont(true);
        // TODO runInputs = false;
    }
    if (runAll) {
        ((AndroiDAQTCPMain) context).setOutputs();
        try {
            Thread.sleep(250);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ((AndroiDAQTCPMain) context).getAll(true);
    }
}

From source file:com.androidaq.AndroiDAQAdapter.java

public void setProp() {

    //Below is where the code for setting the inputs/outputs, states etc. and get readings from inputs.
    //((AndroiDAQMain) context).setPage(6); // this statement is used for development convenience
    chsAreInputs = getInputChannels(); // Inputs are read
    ArrayList<String> isInputPulsed = getPulsedInputs(chsAreInputs);// which inputs are pulse reads
    ArrayList<String> chsAreOutputs = getOutputChannels(); // Outputs can be digital or frequency
    ArrayList<String> isOutputDigital = getDigitalOutputs(chsAreOutputs); // which output channels are digital
    ArrayList<String> digitalOutState = getDigitalOutputState(isOutputDigital);// get output desired state
    ArrayList<String> isOutputPulsed = getPulsedOutputs(chsAreOutputs); // which output channels are pulsed
    ArrayList<String> desiredFreq = getDesiredFreqs(isOutputPulsed); // for channels not digital, what is the desired frequency
    ArrayList<String> desiredDuty = getDesiredDuty(isOutputPulsed); // for channels not digital, what is the desired duty
    //ArrayList<String> voltChsRead = getVoltageChannel(); // Get voltage channels read
    /*setText("\n" + "Inputs are: " + chsAreInputs 
     + "\n" + "Input Pins that are pulsed are: " + isInputPulsed
     + "\n" + "Outputs Pins are: " + chsAreOutputs 
     + "\n" + "Outputs that are Digital: " + isOutputDigital
     +  "\n" + "Digital output states are: " + digitalOutState
     + "\n" + "Pulsed output pins are: " + isOutputPulsed
     + "\n" + "Desired output frequencies are: " + desiredFreq 
     + "\n" + "Voltage Channels Read are: " + voltChsRead  + "\n"); */

    ((AndroiDAQMain) context).sendMessage("00\r"); // Send to AndroidDAQ menu command and Array(s) of information. 

    String[] temp = new String[16];
    Arrays.fill(temp, "NS"); // NS = Not Set
    ArrayList<String> SendToProp = new ArrayList<String>(Arrays.asList(temp));

    //set input channels
    int x0 = chsAreInputs.size();
    // for each channel in chsAreInput, put zero in SendToProp channel location
    for (int i = 0; i < x0; i++) {
        String channel = chsAreInputs.get(i);
        SendToProp.set(Integer.valueOf(channel), "0");
    }/*from  w  w  w. j a  v a2 s  .c om*/
    // set input channels that are pulsed
    int x1 = isInputPulsed.size();
    for (int i = 0; i < x1; i++) {
        String channel = isInputPulsed.get(i);
        SendToProp.set(Integer.valueOf(channel), "1");
    }
    // set output channels that are pulsed
    int x2 = isOutputPulsed.size();
    //Log.e("test", "isOutputPulsed size is:" + x2);
    for (int i = 0; i < x2; i++) {
        String channel = isOutputPulsed.get(i);
        String freq = desiredFreq.get(i);
        String duty = desiredDuty.get(i);
        SendToProp.set(Integer.valueOf(channel), "4-" + freq + "_" + duty);
    }
    //Log.e("test", "SendToProp after pulsed Outputs set is:" + SendToProp.toString());
    // set output channels that are not pulsed to their appropriate state
    int x3 = Math.abs(chsAreOutputs.size() - isOutputPulsed.size());
    //Log.e("test", "Math.abs is:" + x3);
    for (int i = 0; i < x3; i++) {
        String channel = isOutputDigital.get(i);
        String state = digitalOutState.get(i);
        if (state == "true") {
            SendToProp.set(Integer.valueOf(channel), "3");
        } else {
            SendToProp.set(Integer.valueOf(channel), "2");
        }

    }
    //Log.e("test", "SendToProp after insert is:" + SendToProp.toString());
    // create string to send to prop via BT
    int x4 = SendToProp.size();
    //Log.e("test", "SendToProp size is:" + SendToProp.size());
    String propMessage = "";
    for (int i = 0; i < x4; i++) {
        String whatIsString = SendToProp.get(i);
        if (whatIsString.contains("4-")) {
            String[] freqString = whatIsString.split("-");
            String[] dutyString = freqString[1].split("_");
            Log.e("test", "freqString[0] is:" + freqString[0]);
            Log.e("test", "freqString[1] is:" + freqString[1]);
            Log.e("test", "dutyString[0] is:" + dutyString[0]);
            Log.e("test", "dutyString[1] is:" + dutyString[1]);
            propMessage = propMessage.concat(
                    "0" + freqString[0] + "\r" + "0" + dutyString[0] + "\r" + "0" + dutyString[1] + "\r");
        } else {
            propMessage = propMessage + "0" + whatIsString + "\r";
        }
    }
    Log.e("test", "propMessage after insert is:" + propMessage);
    //((AndroiDAQMain) context).sendMessage(propMessage + "\r");
    String[] subMessages = propMessage.split("\\r"); // break message into sub-messages so data isn't lost in transmission
    int numOfArrays = subMessages.length;
    for (int i = 0; i < numOfArrays; i++) {
        //Log.e("test", "subMessages after insert is:" + subMessages[i]);
        ((AndroiDAQMain) context).sendMessage(subMessages[i] + "\r");
        try {
            Thread.sleep(9);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //TODO
    //Log.e("test", "runVolts is:" + runVolts);
    //Log.e("test", "runInputs is:" + runInputs);
    //Log.e("test", "runAll is:" + runAll);
    if (sendOutputs) {
        sendOutputs = false;
        ((AndroiDAQMain) context).setOutputs();
    }
    if (runVolts) {
        ((AndroiDAQMain) context).getVolts(true);
        runVolts = false;
    }
    if (runInputs) {
        ((AndroiDAQMain) context).getInputs(true);
        runInputs = false;
    }
    if (runContInputs) {
        ((AndroiDAQMain) context).getInputsCont(true);
        // TODO runInputs = false;
    }
    if (runAll) {
        ((AndroiDAQMain) context).setOutputs();
        try {
            Thread.sleep(250);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ((AndroiDAQMain) context).getAll(true);
    }
}

From source file:org.akaza.openclinica.control.submit.DataEntryServlet.java

protected DisplaySectionBean populateNotesWithDBNoteCounts(FormDiscrepancyNotes discNotes,
        DisplaySectionBean section, HttpServletRequest request) {
    DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(getDataSource());
    // ArrayList items = section.getItems();
    EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF);
    ArrayList<DiscrepancyNoteBean> ecNotes = dndao.findEventCRFDNotesFromEventCRF(ecb);
    ArrayList<DiscrepancyNoteBean> existingNameNotes = new ArrayList(), nameNotes = new ArrayList();
    ArrayList<DiscrepancyNoteBean> existingIntrvDateNotes = new ArrayList(), dateNotes = new ArrayList();
    long t = System.currentTimeMillis();
    logMe("Method:populateNotesWithDBNoteCounts" + t);
    int intNew = 0, intRes = 0, intUpdated = 0, intClosed = 0, intNA = 0;
    int dateNew = 0, dateRes = 0, dateUpdated = 0, dateClosed = 0, dateNA = 0;
    boolean hasMoreThreads = false;
    for (int i = 0; i < ecNotes.size(); i++) {
        DiscrepancyNoteBean dn = ecNotes.get(i);
        if (INTERVIEWER_NAME.equalsIgnoreCase(dn.getColumn())) {
            discNotes.setNumExistingFieldNotes(INPUT_INTERVIEWER, 1);
            request.setAttribute("hasNameNote", "yes");
            request.setAttribute(INTERVIEWER_NAME_NOTE, dn);
            if (dn.getParentDnId() == 0)
                existingNameNotes.add(dn);

        }//from   w w w .  j ava 2 s  . c  o  m

        if (DATE_INTERVIEWED.equalsIgnoreCase(dn.getColumn())) {
            discNotes.setNumExistingFieldNotes(INPUT_INTERVIEW_DATE, 1);
            request.setAttribute("hasDateNote", "yes");
            request.setAttribute(INTERVIEWER_DATE_NOTE, dn);
            if (dn.getParentDnId() == 0)
                existingIntrvDateNotes.add(dn);
        }
    }
    logMe("Method:populateNotesWithDBNoteCounts before calling setToolTipEventNotes"
            + System.currentTimeMillis() + "time took:" + (System.currentTimeMillis() - t));
    setToolTipEventNotes(request);

    request.setAttribute("nameNoteResStatus", getDiscrepancyNoteResolutionStatus(existingNameNotes));
    request.setAttribute("IntrvDateNoteResStatus", getDiscrepancyNoteResolutionStatus(existingIntrvDateNotes));

    request.setAttribute("existingNameNotes", existingNameNotes);

    request.setAttribute("existingIntrvDateNotes", existingIntrvDateNotes);

    List<DisplayItemWithGroupBean> allItems = section.getDisplayItemGroups();
    LOGGER.debug("start to populate notes: " + section.getDisplayItemGroups().size());
    this.output(allItems);
    logMe("Looping through allItems time:" + System.currentTimeMillis() + "time took from the begining"
            + (System.currentTimeMillis() - t));
    for (int k = 0; k < allItems.size(); k++) {
        DisplayItemWithGroupBean itemWithGroup = allItems.get(k);

        if (itemWithGroup.isInGroup()) {
            LOGGER.debug("group item DNote...");
            List<DisplayItemGroupBean> digbs = itemWithGroup.getItemGroups();
            LOGGER.trace("digbs size: " + digbs.size());
            for (int i = 0; i < digbs.size(); i++) {
                DisplayItemGroupBean displayGroup = digbs.get(i);
                List<DisplayItemBean> items = displayGroup.getItems();
                for (int j = 0; j < items.size(); j++) {
                    DisplayItemBean dib = items.get(j);
                    int itemDataId = dib.getData().getId();
                    int numNotes = dndao.findNumExistingNotesForItem(itemDataId);
                    int numNotes1 = dndao.findNumOfActiveExistingNotesForItemData(itemDataId);

                    int ordinal = this.getManualRows(digbs);
                    String inputName = getGroupItemInputName(displayGroup, displayGroup.getFormInputOrdinal(),
                            dib);
                    if (!displayGroup.isAuto()) {
                        inputName = getGroupItemManualInputName(displayGroup, i, dib);
                    }

                    discNotes.setNumExistingFieldNotes(inputName, numNotes1);
                    ArrayList notes = discNotes.getNotes(inputName);
                    dib.setNumDiscrepancyNotes(numNotes + notes.size());// + notes2.size());
                    dib.setDiscrepancyNoteStatus(getDiscrepancyNoteResolutionStatus(itemDataId, notes));

                    dib = setTotals(dib, itemDataId, notes, ecb.getId());
                    LOGGER.debug("dib note size:" + dib.getNumDiscrepancyNotes() + " " + dib.getData().getId()
                            + " " + inputName);
                    items.set(j, dib);
                }
                displayGroup.setItems(items);
                digbs.set(i, displayGroup);
            }
            itemWithGroup.setItemGroups(digbs);

        } else {
            LOGGER.trace("single item db note");
            DisplayItemBean dib = itemWithGroup.getSingleItem();
            try {
                ResponseOptionBean rob = (ResponseOptionBean) dib.getMetadata().getResponseSet().getOptions()
                        .get(0);
                LOGGER.trace("test print of options for coding: " + rob.getValue());
            } catch (NullPointerException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            }
            int itemDataId = dib.getData().getId();
            int itemId = dib.getItem().getId();
            int numNotes = dndao.findNumExistingNotesForItem(itemDataId);
            int numNotes1 = dndao.findNumOfActiveExistingNotesForItemData(itemDataId);

            String inputFieldName = "input" + itemId;

            discNotes.setNumExistingFieldNotes(inputFieldName, numNotes1);
            dib.setNumDiscrepancyNotes(numNotes + discNotes.getNotes(inputFieldName).size());
            dib.setDiscrepancyNoteStatus(
                    getDiscrepancyNoteResolutionStatus(itemDataId, discNotes.getNotes(inputFieldName)));
            dib = setTotals(dib, itemDataId, discNotes.getNotes(inputFieldName), ecb.getId());

            ArrayList childItems = dib.getChildren();
            for (int j = 0; j < childItems.size(); j++) {
                DisplayItemBean child = (DisplayItemBean) childItems.get(j);
                int childItemDataId = child.getData().getId();
                int childItemId = child.getItem().getId();
                int childNumNotes = dndao.findNumExistingNotesForItem(childItemDataId);
                String childInputFieldName = "input" + childItemId;

                LOGGER.debug("*** setting " + childInputFieldName);
                discNotes.setNumExistingFieldNotes(childInputFieldName, childNumNotes);
                child.setNumDiscrepancyNotes(childNumNotes + discNotes.getNotes(childInputFieldName).size());
                child.setDiscrepancyNoteStatus(getDiscrepancyNoteResolutionStatus(childItemDataId,
                        discNotes.getNotes(childInputFieldName)));
                child = setTotals(child, childItemDataId, discNotes.getNotes(childInputFieldName), ecb.getId());
                childItems.set(j, child);
            }
            dib.setChildren(childItems);
            itemWithGroup.setSingleItem(runDynamicsItemCheck(dib, null, request));
        }
        // missing piece of the puzzle - reset the itemgroup into all items?
        allItems.set(k, itemWithGroup);
    }

    section.setDisplayItemGroups(allItems);
    return section;
}

From source file:com.ardhi.businessgame.services.BusinessGameService.java

public String loadHeadquarterData(HttpServletRequest req) {
    String val = "0", contractType, user, zone;
    SqlRowSet srs1 = db.getJdbc().queryForRowSet("select name,[level] from info_sector"), srs2, srs3;
    ArrayList<String> sectors = new ArrayList<String>();
    ArrayList<Integer> sectorsLvl = new ArrayList<Integer>();
    while (srs1.next()) {
        sectors.add(srs1.getString("name"));
        sectorsLvl.add(srs1.getInt("level"));
    }/*  w ww .j a v a2  s  .c om*/

    srs1 = db.getJdbc().queryForRowSet("select [value] from info_values where name='sector'");
    double price;
    if (srs1.next()) {
        price = Double.parseDouble(srs1.getString("value"));
    } else
        return "0";

    srs1 = db.getJdbc().queryForRowSet(
            "select user_contract.id,request_storage,supplier_storage,product,quality,size,user_contract.price,turn from user_contract,storage,desc_product where accept='1' and [user]='"
                    + req.getParameter("user")
                    + "' and product_desc=desc_product.id and (request_storage=storage.id or supplier_storage=storage.id)");
    ArrayList<Contract> contracts = new ArrayList<Contract>();
    while (srs1.next()) {
        srs2 = db.getJdbc().queryForRowSet("select [user],[zone] from storage where id='"
                + srs1.getString("request_storage") + "' union select [user],[zone] from storage where id='"
                + srs1.getString("supplier_storage") + "'");
        if (srs2.next()) {
            if (srs2.getString("user").equals(req.getParameter("user"))) {
                contractType = "from";
                srs2.next();
                user = srs2.getString("user");
                zone = srs2.getString("zone");
            } else {
                contractType = "to";
                user = srs2.getString("user");
                zone = srs2.getString("zone");
            }
            contracts
                    .add(new Contract(srs1.getString("id"), user, zone, contractType, srs1.getString("product"),
                            srs1.getInt("quality"), srs1.getDouble("size"), srs1.getDouble("price")));
        } else
            return "0";
    }

    srs1 = db.getJdbc().queryForRowSet(
            "select user_contract.id,request_storage,supplier_storage,product,quality,size,user_contract.price,turn from user_contract,storage,desc_product where accept='0' and [user]='"
                    + req.getParameter("user")
                    + "' and product_desc=desc_product.id and (request_storage=storage.id or supplier_storage=storage.id)");
    ArrayList<Contract> pendingContracts = new ArrayList<Contract>();
    while (srs1.next()) {
        srs2 = db.getJdbc().queryForRowSet("select [user],[zone] from storage where id='"
                + srs1.getString("request_storage") + "' union select [user],[zone] from storage where id='"
                + srs1.getString("supplier_storage") + "'");
        if (srs2.next()) {
            if (srs2.getString("user").equals(req.getParameter("user"))) {
                contractType = "from";
                srs2.next();
                user = srs2.getString("user");
                zone = srs2.getString("zone");
            } else {
                contractType = "to";
                user = srs2.getString("user");
                zone = srs2.getString("zone");
            }
            pendingContracts
                    .add(new Contract(srs1.getString("id"), user, zone, contractType, srs1.getString("product"),
                            srs1.getInt("quality"), srs1.getDouble("size"), srs1.getDouble("price")));
        } else
            return "0";
    }

    double sales = 0, raw = 0, electricity = 0, fixed = 0, wage = 0, operation = 0, transport = 0,
            retribution = 0, advertisement = 0, interest = 0, depreciation = 0, tax = 0;
    srs1 = db.getJdbc().queryForRowSet(
            "select type,total from user_finance where [user]='" + req.getParameter("user") + "'");
    while (srs1.next()) {
        if (srs1.getString("type").equals("Sales"))
            sales = srs1.getDouble("total");
        else if (srs1.getString("type").equals("Raw Material"))
            raw = srs1.getDouble("total");
        else if (srs1.getString("type").equals("Electricity"))
            electricity = srs1.getDouble("total");
        else if (srs1.getString("type").equals("Fixed"))
            fixed = srs1.getDouble("total");
        else if (srs1.getString("type").equals("Wage"))
            wage = srs1.getDouble("total");
        else if (srs1.getString("type").equals("Operation"))
            operation = srs1.getDouble("total");
        else if (srs1.getString("type").equals("Transport"))
            transport = srs1.getDouble("total");
        else if (srs1.getString("type").equals("Retribution"))
            retribution = srs1.getDouble("total");
        else if (srs1.getString("type").equals("Advertisement"))
            advertisement = srs1.getDouble("total");
        else if (srs1.getString("type").equals("Interest"))
            interest = srs1.getDouble("total");
        else if (srs1.getString("type").equals("Depreciation"))
            depreciation = srs1.getDouble("total");
    }

    srs1 = db.getJdbc().queryForRowSet("select [value] from info_values where name='tax'");
    if (srs1.next())
        tax = Double.parseDouble(srs1.getString("value"));
    else
        return "0";

    double cash, rawOnStorage = 0, equipmentOnStorage = 0, loan = 0, storage = 0, equipment = 0, sector = 0,
            tmpd1, tmpd2, tmpd3;
    srs1 = db.getJdbc().queryForRowSet(
            "select money from businessgame.dbo.[user] where name='" + req.getParameter("user") + "'");
    if (srs1.next())
        cash = srs1.getDouble("money");
    else
        return "0";

    srs1 = db.getJdbc().queryForRowSet(
            "select [value] from info_values where name='cost_storage' union select [value] from info_values where name='cost_storage_upgrade'");
    if (srs1.next())
        tmpd1 = Double.parseDouble(srs1.getString("value"));
    else
        return "0";
    if (srs1.next())
        tmpd2 = Double.parseDouble(srs1.getString("value"));
    else
        return "0";

    srs1 = db.getJdbc()
            .queryForRowSet("select id,[level] from storage where [user]='" + req.getParameter("user") + "'");
    while (srs1.next()) {
        srs2 = db.getJdbc().queryForRowSet(
                "select size,avg_price from storage_product where storage='" + srs1.getString("id") + "'");
        while (srs2.next()) {
            rawOnStorage += (srs2.getDouble("size") * srs2.getDouble("avg_price"));
        }
        srs2 = db.getJdbc().queryForRowSet(
                "select buy_price,durability from storage_equipment,list_equipment where storage='"
                        + srs1.getString("id") + "' and storage_equipment.id=list_equipment.id");
        while (srs2.next()) {
            equipmentOnStorage += srs2.getDouble("buy_price") * (srs2.getDouble("durability") / 100.00);
        }

        storage += tmpd1;
        for (int i = 1; i < srs1.getLong("level"); i++) {
            storage += tmpd2;
        }
    }

    srs1 = db.getJdbc()
            .queryForRowSet("select borrow from borrow_bank where [user]='" + req.getParameter("user") + "'");
    while (srs1.next()) {
        loan += srs1.getDouble("borrow") * -1;
    }

    srs1 = db.getJdbc().queryForRowSet(
            "select installment.id,info_zone.cost,info_sector.cost from installment,info_zone,info_sector where [user]='"
                    + req.getParameter("user") + "' and info_zone.id=[zone] and info_sector.name=type");
    while (srs1.next()) {
        sector += srs1.getDouble(2) + srs1.getDouble(3);
        srs2 = db.getJdbc().queryForRowSet(
                "select buy_price,durability from installment_equipment,list_equipment where installment='"
                        + srs1.getString(1) + "' and installment_equipment.id=list_equipment.id");
        while (srs2.next()) {
            equipment += srs2.getDouble("buy_price") * (srs2.getDouble("durability") / 100.00);
        }
    }

    srs1 = db.getJdbc().queryForRowSet("select name from info_product");
    ArrayList<String> products = new ArrayList<String>();
    while (srs1.next()) {
        products.add(srs1.getString("name"));
    }

    srs1 = db.getJdbc().queryForRowSet("select id,advertise,price from desc_advertisement");
    ArrayList<String> advertises = new ArrayList<String>(), idAds = new ArrayList<String>();
    ArrayList<Double> prices = new ArrayList<Double>();
    while (srs1.next()) {
        idAds.add(srs1.getString("id"));
        advertises.add(srs1.getString("advertise"));
        prices.add(srs1.getDouble("price"));
    }

    srs1 = db.getJdbc().queryForRowSet(
            "select name from businessgame.dbo.[user] where [zone]=(select [zone] from businessgame.dbo.[user] where name='"
                    + req.getParameter("user") + "')");
    ArrayList<String> players = new ArrayList<String>();
    ArrayList<Double> assets = new ArrayList<Double>();
    while (srs1.next()) {
        tmpd3 = 0;
        srs2 = db.getJdbc().queryForRowSet(
                "select money from businessgame.dbo.[user] where name='" + srs1.getString("name") + "'");
        if (srs2.next())
            tmpd3 += srs2.getDouble("money");
        else
            return "0";

        srs2 = db.getJdbc()
                .queryForRowSet("select id,[level] from storage where [user]='" + srs1.getString("name") + "'");
        while (srs2.next()) {
            srs3 = db.getJdbc().queryForRowSet(
                    "select size,avg_price from storage_product where storage='" + srs2.getString("id") + "'");
            while (srs3.next()) {
                tmpd3 += (srs3.getDouble("size") * srs3.getDouble("avg_price"));
            }
            srs3 = db.getJdbc().queryForRowSet(
                    "select buy_price,durability from storage_equipment,list_equipment where storage='"
                            + srs2.getString("id") + "' and storage_equipment.id=list_equipment.id");
            while (srs3.next()) {
                tmpd3 += srs3.getDouble("buy_price") * (srs3.getDouble("durability") / 100.00);
            }

            tmpd3 += tmpd1;
            for (int i = 1; i < srs2.getLong("level"); i++) {
                tmpd3 += tmpd2 * i;
            }
        }

        srs2 = db.getJdbc()
                .queryForRowSet("select borrow from borrow_bank where [user]='" + srs1.getString("name") + "'");
        while (srs2.next()) {
            tmpd3 += srs2.getDouble("borrow") * -1;
        }

        srs2 = db.getJdbc().queryForRowSet(
                "select installment.id,info_zone.cost,info_sector.cost from installment,info_zone,info_sector where [user]='"
                        + srs1.getString("name") + "' and info_zone.id=[zone] and info_sector.name=type");
        while (srs2.next()) {
            tmpd3 += srs2.getDouble(2) + srs2.getDouble(3);
            srs3 = db.getJdbc().queryForRowSet(
                    "select buy_price,durability from installment_equipment,list_equipment where installment='"
                            + srs2.getString(1) + "' and installment_equipment.id=list_equipment.id");
            while (srs3.next()) {
                tmpd3 += srs3.getDouble("buy_price") * (srs3.getDouble("durability") / 100.00);
            }
        }
        players.add(srs1.getString("name"));
        assets.add(tmpd3);
    }

    for (int i = 0; i < assets.size(); i++) {
        for (int j = i + 1; j < assets.size(); j++) {
            if (assets.get(i) < assets.get(j)) {
                user = players.get(i);
                tmpd3 = assets.get(i);
                players.set(i, players.get(j));
                assets.set(i, assets.get(j));
                players.set(j, user);
                assets.set(j, tmpd3);
            }
        }
    }

    ArrayList<String> data = new ArrayList<String>();
    data.add(gson.toJson(sectors));
    data.add(gson.toJson(sectorsLvl));
    data.add(gson.toJson(price));
    data.add(gson.toJson(contracts));
    data.add(gson.toJson(pendingContracts));
    data.add(gson.toJson(sales));
    data.add(gson.toJson(raw));
    data.add(gson.toJson(electricity));
    data.add(gson.toJson(fixed));
    data.add(gson.toJson(wage));
    data.add(gson.toJson(operation));
    data.add(gson.toJson(transport));
    data.add(gson.toJson(retribution));
    data.add(gson.toJson(advertisement));
    data.add(gson.toJson(interest));
    data.add(gson.toJson(depreciation));
    data.add(gson.toJson(tax));
    data.add(gson.toJson(cash));
    data.add(gson.toJson(rawOnStorage));
    data.add(gson.toJson(equipmentOnStorage));
    data.add(gson.toJson(loan));
    data.add(gson.toJson(storage));
    data.add(gson.toJson(equipment));
    data.add(gson.toJson(sector));
    data.add(gson.toJson(products));
    data.add(gson.toJson(idAds));
    data.add(gson.toJson(advertises));
    data.add(gson.toJson(prices));
    data.add(gson.toJson(players));

    val = gson.toJson(data);

    sectors = null;
    sectorsLvl = null;
    contracts = null;
    pendingContracts = null;
    data = null;
    contractType = null;
    user = null;
    products = null;
    advertises = null;
    prices = null;
    players = null;
    assets = null;
    zone = null;
    srs1 = null;
    srs2 = null;

    gc();

    return val;
}

From source file:org.jab.docsearch.Index.java

/**
 * Updates a DocSearcherIndex/*from  w w w  .j a va2 s  .co  m*/
 *
 * @param di  DocSearcherIndex
 */
public void updateIndex(final DocSearcherIndex di) {
    notesBuf = new StringBuffer();
    newItsBuf = new StringBuffer();
    modItsItsBuf = new StringBuffer();
    delItsItsBuf = new StringBuffer();
    totalChanges = 0;
    long curFileSizeBytes = 0;
    int errNum = 0;
    StringBuffer noRobotsBuf = new StringBuffer();
    int numNoIndex = 0;
    // int numErrors = 0;
    StringBuffer failedBuf = new StringBuffer();
    int addedSuccessFully = 0;
    failedBuf.append("\n");
    synchronized (this) {
        if (di.isCdrom()) {
            // do nothing
        } else if (di.getIsSpider()) {
            doSpiderUpdate(di);
        } else if (!di.getPath().toLowerCase().endsWith(".zip")) { // not a zip
                                                                   // archive
            int numUpdates = 0;
            int numRemovals = 0;
            int numNew = 0;
            try {
                IndexReader ir = IndexReader.open(di.getIndexPath());
                int numDocs = ir.maxDoc();
                ds.setStatus(
                        "There are " + numDocs + " docs in index " + di.getName() + "(" + di.getPath() + ")");
                addHeader(di.getName());
                //ArrayList<String> allDocsInIndexx = new ArrayList<String>(); // indexed files
                // ArrayList allDocsInFolder = new ArrayList(); // current files
                // ArrayList newDocsToAdd = new ArrayList(); // files to be added that are new
                ds.setIsWorking(true);
                ds.setProgressMax(numDocs);
                ds.setCurProgressMSG("Updating Modified Files...");
                setInsertMode(1); // note we are looking for modified files

                logger.info("updateIndex() updating " + numDocs + " document from index");

                for (int i = 0; i < numDocs; i++) {
                    if (!ds.getIsWorking()) {
                        break;
                    }
                    if (!ir.isDeleted(i)) {
                        ds.setCurProgress(i);
                        Document doc = ir.document(i);
                        if (doc != null) {
                            String curFiName = doc.get(FIELD_PATH);
                            String curFiModDate = doc.get(FIELD_MODDATE);
                            File testFi = new File(curFiName);

                            // check file not found
                            if (testFi.exists()) {
                                //allDocsInIndex.add(curFiName);
                                String realFileModDate = DateTimeUtils
                                        .getTimeStringForIndex(testFi.lastModified());

                                // check file is changed
                                if (!realFileModDate.equals(curFiModDate)) {
                                    logger.info("updateIndex() updating " + curFiName + " in index");

                                    numUpdates++;
                                    // remove old document
                                    ir.deleteDocument(i);
                                    ir.close();
                                    // open writer to add document once again
                                    ds.setStatus("Reindexing: " + curFiName);
                                    IndexWriter iw = new IndexWriter(di.getIndexPath(), new StandardAnalyzer(),
                                            false);
                                    // next line should remove too many files open errors
                                    // iw.setUseCompoundFile(true);
                                    addedSuccessFully = addDocToIndex(curFiName, iw, di, di.isCdrom(), null);
                                    iw.close();
                                    // reopen
                                    ir = IndexReader.open(di.getIndexPath());
                                    switch (addedSuccessFully) {
                                    case 1: // error
                                        errNum++;
                                        if (errNum < 8) {
                                            failedBuf.append("\n");
                                            failedBuf.append(curFiName);
                                        }
                                        ds.setStatus(DocSearch.dsErrIdxgFi + " " + curFiName);
                                        break;
                                    case 2: // meta robots = noindex
                                        numNoIndex++;
                                        if (numNoIndex < 8) {
                                            noRobotsBuf.append("\n");
                                            noRobotsBuf.append(curFiName);
                                        }
                                        ds.setStatus("No Indexing Meta Requirement found in : " + curFiName);
                                        break;
                                    default: // OK
                                        numUpdates++;
                                        ds.setStatus("Indexing " + curFiName + " complete.");
                                        break;
                                    } // end of switch
                                }
                            } else {
                                ds.setStatus("Deleting: " + curFiName);
                                logger.info("updateIndex() remove " + curFiName + " from index");
                                ir.deleteDocument(i);
                                addDelNote(doc);
                                numRemovals++;
                            }
                        }
                    }
                    // end for not deleted
                    // else System.out.println("Document was null or
                    // deleted:"+i);
                }
                // end for getting gocs
                ds.resetProgress();

                // now add the new files
                setInsertMode(0);
                ArrayList<String> folderList = new ArrayList<String>();
                folderList.add(di.getPath());
                int startSubNum = Utils.countSlash(di.getPath());
                int maxSubNum = startSubNum + di.getDepth();
                int lastItemNo = 0;
                int curItemNo = 0;
                int lastFound = 0;
                do {
                    // create our folder file
                    if (!ds.getIsWorking()) {
                        break;
                    }
                    String curFolderString = folderList.get(curItemNo);
                    logger.debug("updateIndex() folder=" + curFolderString);

                    File curFolderFile = new File(curFolderString);
                    int curSubNum = Utils.countSlash(curFolderString);
                    // handle any subfolders --> add them to our folderlist
                    String[] foldersString = curFolderFile.list(DocSearch.ff);
                    int numFolders = foldersString.length;
                    for (int i = 0; i < numFolders; i++) {
                        // add them to our folderlist
                        String curFold = curFolderString + pathSep + foldersString[i] + pathSep;
                        curFold = Utils.replaceAll(pathSep + pathSep, curFold, pathSep);
                        folderList.add(curFold);
                        lastItemNo++;
                        // debug output
                    }
                    // end for having more than 0 folder
                    // add our files
                    String[] filesString = curFolderFile.list(DocSearch.wf);
                    int numFiles = filesString.length;
                    ds.setProgressMax(numDocs);
                    ds.setCurProgressMSG("Updating new Files...");

                    for (int i = 0; i < numFiles; i++) {
                        // add them to our folderlist
                        if (!ds.getIsWorking()) {
                            break;
                        }
                        String curFi = curFolderString + pathSep + filesString[i];
                        curFi = Utils.replaceAll(pathSep + pathSep, curFi, pathSep);
                        curFileSizeBytes = FileUtils.getFileSize(curFi);
                        if (curFileSizeBytes > ds.getMaxFileSize()) {
                            logger.debug("updateIndex() skipping " + curFi + " because is to big");
                            ds.setStatus(I18n.getString("skipping_file_too_big") + " (" + curFileSizeBytes
                                    + ") " + filesString[i]);
                        } else {
                            lastFound = indexNum(lastFound, curFi, ir);
                            if (lastFound == -1) {
                                logger.info("updateIndex() adding " + curFi + " to index");

                                ir.close();
                                // open writer to add document once again
                                IndexWriter iw = new IndexWriter(di.getIndexPath(), new StandardAnalyzer(),
                                        false);
                                addedSuccessFully = addDocToIndex(curFi, iw, di, di.isCdrom(), null);
                                switch (addedSuccessFully) {
                                case 1: // error
                                    errNum++;
                                    if (errNum < 8) {
                                        failedBuf.append("\n");
                                        failedBuf.append(curFi);
                                    }
                                    ds.setStatus(DocSearch.dsErrIdxg + " " + curFi);
                                    break;
                                case 2: // meta robots = noindex
                                    numNoIndex++;
                                    if (numNoIndex < 8) {
                                        noRobotsBuf.append("\n");
                                        noRobotsBuf.append(curFi);
                                    }
                                    ds.setStatus("Document Exlusion (robots = NOINDEX) : " + curFi);
                                    break;
                                default: // OK
                                    numNew++;
                                    ds.setStatus("New Document Added : " + curFi);
                                    break;
                                } // end of switch
                                iw.close();
                                // reopen
                                ir = IndexReader.open(di.getIndexPath());
                            } // end for lastfound not -1
                        } // end for file size not too big
                        ds.setCurProgress(i);
                        ds.resetProgress();
                    }
                    // end for having more than 0 folder
                    // increment our curItem
                    folderList.set(curItemNo, null); // remove memory overhead as you go!
                    curItemNo++;
                    if (curSubNum >= maxSubNum) {
                        break;
                    }
                    if (!ds.getIsWorking()) {
                        break;
                    }
                } while (curItemNo <= lastItemNo);
                //
                ir.close(); // always close!
                StringBuffer updateMSGBuf = new StringBuffer();
                updateMSGBuf.append('\n');
                updateMSGBuf.append(numRemovals).append(" files were removed from index.\n");
                updateMSGBuf.append(numUpdates).append(" files were reindexed.\n");
                updateMSGBuf.append(numNew).append(" new files were added to the index.\n");
                //
                totalChanges = numRemovals + numUpdates + numNew;
                // all our stuff to the notesBuf
                addNote(updateMSGBuf.toString(), "", true);
                // add our new and modified files
                if (numNew > 0) {
                    addNote(I18n.getString("new_files"), "", true);
                    notesBuf.append(newItsBuf);
                }
                //
                if (numUpdates > 0) {
                    addNote(I18n.getString("updated_files"), "", true);
                    notesBuf.append(modItsItsBuf);
                }
                //
                //
                if (numRemovals > 0) {
                    addNote(I18n.getString("deleted_files"), "", true);
                    notesBuf.append(delItsItsBuf);
                }
                //

                addFooter();
                if (errNum == 0) {
                    updateMSGBuf.append("No errors were encountered during this process.");
                    if (numNoIndex > 0) {
                        updateMSGBuf.append("\n\n").append(numNoIndex).append(
                                " files were not indexed due to meta data constraints (robots = NOINDEX), including:\n");
                        updateMSGBuf.append(noRobotsBuf);
                    }
                    ds.showMessage("Update of index " + di.getName() + " Completed", updateMSGBuf.toString());
                } else {
                    updateMSGBuf.append(errNum).append(
                            " errors were encountered during this process.\nThe following files had problems being indexed or re-indexed:\n")
                            .append(failedBuf);
                    if (numNoIndex > 0) {
                        updateMSGBuf.append("\n\n").append(numNoIndex).append(
                                " files were not indexed due to meta data constraints (robots = NOINDEX), including:\n");
                        updateMSGBuf.append(noRobotsBuf);
                    }

                    ds.showMessage("Errors during Update of index " + di.getName(), updateMSGBuf.toString());
                }
            }
            // end of try
            catch (Exception e) {
                logger.error("updateIndex() error during update index " + di.getName(), e);
                ds.showMessage("Error updating index " + di.getName(), e.toString());
            }

            addFooter();
            di.setLastIndexed(DateTimeUtils.getToday());
            ds.setStatus("Update of index " + di.getName() + " completed.");
            ds.setIsWorking(false);
        } else {
            ds.doZipArchiveUpdate(di);
        }
    }
}

From source file:com.emc.plants.web.servlets.ShoppingServlet.java

/**
 * Main service method for ShoppingServlet
 *
 * @param req Object that encapsulates the request to the servlet
 * @param resp Object that encapsulates the response from the servlet
 *//* www . j a  va  2  s . c o  m*/
public void performTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action = null;
    action = req.getParameter(Util.ATTR_ACTION);
    Util.debug("action=" + action);
    if (action.equals(ACTION_SHOPPING)) {
        String category = (String) req.getParameter("category");
        HttpSession session = req.getSession(true);
        // Get session category if none on request, such as
        // 'Continue Shopping' from the Shopping Cart jsp.
        if ((category == null) || (category.equals("null"))) {
            category = (String) session.getAttribute(Util.ATTR_CATEGORY);
        }
        // If categoyr still null, default to first category.
        if ((category == null) || (category.equals("null"))) {
            category = "0";
        }
        session.setAttribute(Util.ATTR_CATEGORY, category);
        // Get the shopping items from the catalog.
        Collection c = catalog.getItemsByCategory(Integer.parseInt(category));
        ArrayList items = new ArrayList(c);
        for (int i = 0; i < items.size();) {
            if (((Inventory) items.get(i)).isPublic())
                i++;
            else
                items.remove(i);
        }
        req.setAttribute(Util.ATTR_INVITEMS, items);
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_SHOPPING);
    } else if (action.equals(ACTION_PRODUCTDETAIL)) {
        String invID = (String) req.getParameter("itemID");
        req.setAttribute(Util.ATTR_INVITEM, catalog.getItemInventory(invID));
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_PRODUCT);
    } else if (action.equals(ACTION_GOTOCART)) {
        HttpSession session = req.getSession(true);
        // Get shopping cart.
        ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        if (shoppingCart != null) {
            // Make sure ShopingCart reference has not timed out.
            try {
                shoppingCart.getItems();
            }
            // TODO: what exception would be thrown?
            catch (RuntimeException e) {
                Util.debug("gotocart: shopping cart ref must have timed out");
                ShoppingCartContents cartContents = (ShoppingCartContents) session
                        .getAttribute(Util.ATTR_CART_CONTENTS);
                shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
                session.setAttribute(Util.ATTR_CART, shoppingCart);
            }
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_CART);
    } else if (action.equals(ACTION_ADDTOCART)) {
        ShoppingCart shoppingCart = null;
        // Get shopping cart.
        HttpSession session = req.getSession(true);
        shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        if (shoppingCart == null) {
            Util.debug("shopping cart is NULL, must create it");
            shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
            System.out.println(
                    "Items:: " + shoppingCart.getItems() + " Size :: " + shoppingCart.getItems().size());
            shoppingCart.setItems(new ArrayList<ShoppingCartItem>());
        } else {
            // Make sure ShopingCart reference has not timed out.
            try {
                Util.debug("shopping cart is not null, check items, size=" + shoppingCart.getItems().size());
                shoppingCart.getItems();
            }
            // TODO: what exception would be thrown?
            catch (RuntimeException e) {
                // ShoppingCart timed out, so create a new one.
                Util.debug("addtocart: shopping cart ref must have timed out, create a new one");
                ShoppingCartContents cartContents = (ShoppingCartContents) session
                        .getAttribute(Util.ATTR_CART_CONTENTS);
                shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
                if (cartContents != null) {
                    shoppingCart.setCartContents(cartContents);
                }
            }
        }
        // Add item to cart.
        if (shoppingCart != null) {
            String invID = req.getParameter("itemID");

            // Gets detached instance
            Inventory inv = catalog.getItemInventory(invID);
            ShoppingCartItem si = new ShoppingCartItem(inv);
            si.setQuantity(Integer.parseInt(req.getParameter("qty").trim()));
            shoppingCart.addItem(si);
            session.setAttribute(Util.ATTR_CART, shoppingCart);
            session.setAttribute(Util.ATTR_CART_CONTENTS, shoppingCart.getCartContents());
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_CART);
    } else if (action.equals(ACTION_UPDATEQUANTITY)) {
        // Get shopping cart.
        HttpSession session = req.getSession(true);
        ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        // Make sure ShopingCart reference has not timed out.
        try {
            shoppingCart.getItems();
        }
        // TODO: what exception gets thrown?
        catch (RuntimeException e) {
            // ShoppingCart timed out, so create a new one.
            Util.debug("updatequantity: shopping cart ref must have timed out, create a new one");
            ShoppingCartContents cartContents = (ShoppingCartContents) session
                    .getAttribute(Util.ATTR_CART_CONTENTS);
            shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");

            if (cartContents != null) {
                shoppingCart.setCartContents(cartContents);
            }
        }
        // Update item quantity in cart.
        if (shoppingCart != null) {
            try {
                int cnt = 0;
                Collection c = shoppingCart.getItems();
                ArrayList items;

                if (c instanceof ArrayList)
                    items = (ArrayList) c;
                else
                    items = new ArrayList(c);
                ShoppingCartItem si;
                String parm, parmval;
                // Check all quantity values from cart form.
                for (int parmcnt = 0;; parmcnt++) {
                    parm = "itemqty" + String.valueOf(parmcnt);
                    parmval = req.getParameter(parm);
                    // No more quantity fields, so break out.
                    if ((parmval == null) || parmval.equals("null")) {
                        break;
                    } else // Check quantity value of cart item.
                    {
                        int quantity = Integer.parseInt(parmval);
                        // Quantity set to 0, so remove from cart.
                        if (quantity == 0) {
                            items.remove(cnt);
                        } else // Change quantity of cart item.
                        {
                            si = (ShoppingCartItem) items.get(cnt);
                            si.setQuantity(quantity);
                            items.set(cnt, si);
                            cnt++;
                        }
                    }
                }
                // Are items in cart? Yes, set the session attributes.
                if (items.size() > 0) {
                    shoppingCart.setItems(items);
                    session.setAttribute(Util.ATTR_CART, shoppingCart);
                    session.setAttribute(Util.ATTR_CART_CONTENTS, shoppingCart.getCartContents());
                } else // No items in cart, so remove attributes from session.
                {
                    session.removeAttribute(Util.ATTR_CART);
                    session.removeAttribute(Util.ATTR_CART_CONTENTS);
                }
            } catch (Exception e) {
                //  Log the exception but try to continue.
                Util.debug("ShoppingServlet.performAction() -> Exception caught: " + e);
                // This should take us to the error page.
                throw new ServletException(e.getMessage());
            }
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_CART);
    } else if (action.equals(ACTION_INITCHECKOUT)) {
        String url;
        HttpSession session = req.getSession(true);
        CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Util.ATTR_CUSTOMER);
        if (customerInfo == null) {
            req.setAttribute(Util.ATTR_RESULTS, "You must login or register before checking out.");
            session.setAttribute(Util.ATTR_CHECKOUT, new Boolean(true));
            url = Util.PAGE_LOGIN;
        } else {
            url = Util.PAGE_ORDERINFO;
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, url);
    } else if (action.equals(ACTION_ORDERINFODONE)) {
        OrderInfo orderinfo = null;
        ShoppingCart shoppingCart = null;
        HttpSession session = req.getSession(true);
        CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Util.ATTR_CUSTOMER);
        String customerID = customerInfo.getCustomerID();
        shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        // Make sure ShopingCart reference has not timed out.
        try {
            Util.debug("orderinfodone: ShoppingCart timeout? check getItems() method");
            shoppingCart.getItems();
        }
        // TODO: what exception gets thrown?
        catch (RuntimeException e) {
            // ShoppingCart timed out, so create a new one.
            Util.debug("orderinfodone: ShoppingCart ref must have timed out");
            ShoppingCartContents cartContents = (ShoppingCartContents) session
                    .getAttribute(Util.ATTR_CART_CONTENTS);
            if (cartContents != null) {
                shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
                shoppingCart.setCartContents(cartContents);
            } else {
                Util.debug("NoSuchObject Exception!!!");
                Util.debug("Major Problem!!!");
                shoppingCart = null;
            }
        }
        Util.debug("orderinfodone: got cart?");
        if (shoppingCart != null) {
            Util.debug("orderinfodone: cart not NULL");
            String billName = req.getParameter("bname");
            String billAddr1 = req.getParameter("baddr1");
            String billAddr2 = req.getParameter("baddr2");
            String billCity = req.getParameter("bcity");
            String billState = req.getParameter("bstate");
            String billZip = req.getParameter("bzip");
            String billPhone = req.getParameter("bphone");
            String shipName = req.getParameter("sname");
            String shipAddr1 = req.getParameter("saddr1");
            String shipAddr2 = req.getParameter("saddr2");
            String shipCity = req.getParameter("scity");
            String shipState = req.getParameter("sstate");
            String shipZip = req.getParameter("szip");
            String shipPhone = req.getParameter("sphone");
            int shippingMethod = Integer.parseInt(req.getParameter("shippingMethod"));
            String creditCard = req.getParameter("ccardname");
            String ccNum = req.getParameter("ccardnum");
            String ccExpireMonth = req.getParameter("ccexpiresmonth");
            String ccExpireYear = req.getParameter("ccexpiresyear");
            String cardHolder = req.getParameter("ccholdername");
            orderinfo = shoppingCart.createOrder(customerID, billName, billAddr1, billAddr2, billCity,
                    billState, billZip, billPhone, shipName, shipAddr1, shipAddr2, shipCity, shipState, shipZip,
                    shipPhone, creditCard, ccNum, ccExpireMonth, ccExpireYear, cardHolder, shippingMethod,
                    shoppingCart.getItems());
            Util.debug("orderinfodone: order created");
        }
        if (orderinfo != null) {
            req.setAttribute(Util.ATTR_ORDERINFO, orderinfo);
            req.setAttribute(Util.ATTR_CARTITEMS, shoppingCart.getItems());
            session.setAttribute(Util.ATTR_ORDERKEY, orderinfo.getID());
            requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_CHECKOUTFINAL);
        }
    } else if (action.equals(ACTION_COMPLETECHECKOUT)) {
        ShoppingCart shoppingCart = null;
        HttpSession session = req.getSession(true);
        long key = (Long) session.getAttribute(Util.ATTR_ORDERKEY);
        req.setAttribute(Util.ATTR_ORDERID, key);
        long orderKey = key;
        Util.debug("completecheckout: order id =" + orderKey);
        CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Util.ATTR_CUSTOMER);
        // Check the available inventory and backorder if necessary.
        shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        // Make sure ShopingCart reference has not timed out.
        try {
            Util.debug("completecheckout: ShoppingCart timeout? check getItems() method");
            shoppingCart.getItems();
        }
        // TODO: what exception gets thrown?
        catch (RuntimeException e) {
            // ShoppingCart timed out, so create a new one.
            Util.debug("completecheckout: ShoppingCart ref must have timed out");
            ShoppingCartContents cartContents = (ShoppingCartContents) session
                    .getAttribute(Util.ATTR_CART_CONTENTS);
            if (cartContents != null) {
                shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
                shoppingCart.setCartContents(cartContents);
            } else {
                Util.debug("NoSuchObject Exception!!!");
                Util.debug("Major Problem!!!");
                shoppingCart = null;
            }
        }
        if (shoppingCart != null) {
            ShoppingCartItem si;
            Collection items = shoppingCart.getItems();
            for (Object o : items) {
                si = (ShoppingCartItem) o;
                shoppingCart.checkInventory(si);
                Util.debug(
                        "ShoppingCart.checkInventory() - checking Inventory quantity of item: " + si.getID());
            }
        }

        try {
            mailer.createAndSendMail(customerInfo, orderKey);
        } catch (MailerAppException e) {
            System.out.println("MailerAppException:" + e);
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("Exception during create and send mail :" + e);
            e.printStackTrace();
        }
        // Remove items saved in HttpSession.
        session.removeAttribute(Util.ATTR_CART);
        session.removeAttribute(Util.ATTR_CART_CONTENTS);
        session.removeAttribute(Util.ATTR_CATEGORY);
        session.removeAttribute(Util.ATTR_ORDERKEY);
        session.removeAttribute(Util.ATTR_CHECKOUT);
        HttpSession httpSession = req.getSession(true);

        //httpSession.invalidate();
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_ORDERDONE);
    }
}

From source file:org.akaza.openclinica.control.submit.DataEntryServlet.java

/**
 * Retrieve the DisplaySectionBean which will be used to display the Event CRF Section on the JSP, and also is used to controll processRequest.
 * @param request TODO//from  ww w. ja  v a 2 s. c o  m
 * @param isSubmitted TODO
 */
protected DisplaySectionBean getDisplayBean(boolean hasGroup, boolean includeUngroupedItems,
        HttpServletRequest request, boolean isSubmitted) throws Exception {
    DisplaySectionBean section = new DisplaySectionBean();
    FormProcessor fp = new FormProcessor(request);
    HttpSession session = request.getSession();
    Locale loc = this.locale == null ? LocaleResolver.getLocale(request) : this.locale;
    StudyBean study = (StudyBean) session.getAttribute("study");
    SessionManager sm = (SessionManager) request.getSession().getAttribute("sm");
    EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF);
    SectionBean sb = (SectionBean) request.getAttribute(SECTION_BEAN);
    EventDefinitionCRFBean edcb = (EventDefinitionCRFBean) request.getAttribute(EVENT_DEF_CRF_BEAN);
    SectionDAO sdao;
    // Find out whether there are ungrouped items in this section
    boolean hasUngroupedItems = false;
    int eventDefinitionCRFId = fp.getInt("eventDefinitionCRFId");

    if (eventDefinitionCRFId <= 0) { // TODO: this block of code repeats
        // many times, need to clean up
        //synchronized(this)
        {
            EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(getDataSource());
            EventDefinitionCRFBean edcBean = edcdao.findByStudyEventIdAndCRFVersionId(study,
                    ecb.getStudyEventId(), ecb.getCRFVersionId());
            eventDefinitionCRFId = edcBean.getId();
        }
    }
    LOGGER.trace("eventDefinitionCRFId " + eventDefinitionCRFId);
    // Use this class to find out whether there are ungrouped items in this
    // section
    FormBeanUtil formBeanUtil = new FormBeanUtil();
    List<DisplayItemGroupBean> itemGroups = new ArrayList<DisplayItemGroupBean>();
    if (hasGroup) {
        DisplaySectionBean newDisplayBean = new DisplaySectionBean();
        if (includeUngroupedItems) {
            // Null values: this method adds null values to the
            // displayitembeans
            newDisplayBean = formBeanUtil.createDisplaySectionBWithFormGroups(sb.getId(), ecb.getCRFVersionId(),
                    getDataSource(), eventDefinitionCRFId, ecb, getServletContext());
        } else {
            newDisplayBean = formBeanUtil.createDisplaySectionWithItemGroups(study, sb.getId(), ecb,
                    ecb.getStudyEventId(), sm, eventDefinitionCRFId, getServletContext());
        }
        itemGroups = newDisplayBean.getDisplayFormGroups();
        // setDataForDisplayItemGroups(itemGroups, sb,ecb,sm);
        LOGGER.trace(
                "found item group size: " + itemGroups.size() + " and to string: " + itemGroups.toString());
        section.setDisplayFormGroups(itemGroups);

    }

    // Find out whether any display items are *not* grouped; see issue 1689
    hasUngroupedItems = formBeanUtil.sectionHasUngroupedItems(getDataSource(), sb.getId(), itemGroups);

    sdao = new SectionDAO(getDataSource());
    //
    sb.setHasSCDItem(hasUngroupedItems ? sdao.hasSCDItem(sb.getId()) : false);

    section.setEventCRF(ecb);

    if (sb.getParentId() > 0) {
        SectionBean parent = (SectionBean) sdao.findByPK(sb.getParentId());
        sb.setParent(parent);
    }

    section.setSection(sb);

    CRFVersionDAO cvdao = new CRFVersionDAO(getDataSource());
    CRFVersionBean cvb = (CRFVersionBean) cvdao.findByPK(ecb.getCRFVersionId());
    section.setCrfVersion(cvb);

    CRFDAO cdao = new CRFDAO(getDataSource());
    CRFBean cb = (CRFBean) cdao.findByPK(cvb.getCrfId());
    section.setCrf(cb);

    EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(getDataSource());
    // EventDefinitionCRFBean edcb =
    // edcdao.findByStudyEventIdAndCRFVersionId(study,
    // ecb.getStudyEventId(), cvb.getId());
    section.setEventDefinitionCRF(edcb);

    // setup DAO's here to avoid creating too many objects
    ItemDAO idao = new ItemDAO(getDataSource());
    ItemFormMetadataDAO ifmdao = new ItemFormMetadataDAO(getDataSource());
    ItemDataDAO iddao = new ItemDataDAO(getDataSource(), loc);

    // Use itemGroups to determine if there are any ungrouped items

    // get all the parent display item beans not in group
    logMe("Entering getParentDisplayItems::: Thread is? " + Thread.currentThread());
    ArrayList displayItems = getParentDisplayItems(hasGroup, sb, edcb, idao, ifmdao, iddao, hasUngroupedItems,
            request);
    logMe("Entering getParentDisplayItems::: Done and Thread is? " + Thread.currentThread());

    LOGGER.debug("just ran get parent display, has group " + hasGroup + " has ungrouped " + hasUngroupedItems);
    // now sort them by ordinal,
    //JN: Commenting out this logic, its wrong and will give erroneous results.
    Collections.sort(displayItems);

    // now get the child DisplayItemBeans
    for (int i = 0; i < displayItems.size(); i++) {
        DisplayItemBean dib = (DisplayItemBean) displayItems.get(i);
        dib.setChildren(getChildrenDisplayItems(dib, edcb, request));

        // TODO use the setData command here to make sure we get a value?
        //On Submition of the Admin Editing form the loadDBValue does not required
        //
        if (ecb.getStage() == DataEntryStage.INITIAL_DATA_ENTRY_COMPLETE
                || ecb.getStage() == DataEntryStage.DOUBLE_DATA_ENTRY_COMPLETE) {
            if (shouldLoadDBValues(dib) && !isSubmitted) {
                dib.loadDBValue();
            }
        } else {
            if (shouldLoadDBValues(dib)) {
                LOGGER.trace("should load db values is true, set value");
                dib.loadDBValue();
                LOGGER.trace("just got data loaded: " + dib.getData().getValue());
            }
        }

        displayItems.set(i, dib);
    }

    section.setItems(displayItems);

    return section;
}