Example usage for java.sql Date toString

List of usage examples for java.sql Date toString

Introduction

In this page you can find the example usage for java.sql Date toString.

Prototype

@SuppressWarnings("deprecation")
public String toString() 

Source Link

Document

Formats a date in the date escape format yyyy-mm-dd.

Usage

From source file:org.jtotus.database.LocalJDBC.java

public double[] fetchPeriod(String tableName, DateTime startDate, DateTime endDate, String type) {
    BigDecimal retValue = null;/*  w ww  .  j  av  a2s . c o m*/
    PreparedStatement pstm = null;
    java.sql.Date retDate = null;
    ResultSet results = null;
    ArrayList<Double> closingPrices = new ArrayList<Double>(600);
    Connection connection = null;

    try {
        String query = "SELECT " + type + ", DATE FROM " + this.normTableName(tableName)
                + " WHERE DATE>=? AND DATE<=? ORDER BY DATE ASC";
        // this.createTable(connection, this.normTableName(tableName));

        connection = this.getConnection();
        pstm = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

        java.sql.Date startSqlDate = new java.sql.Date(startDate.getMillis());
        pstm.setDate(1, startSqlDate);

        java.sql.Date endSqlDate = new java.sql.Date(endDate.getMillis());
        pstm.setDate(2, endSqlDate);

        DateIterator dateIter = new DateIterator(startDate, endDate);

        results = pstm.executeQuery();
        DateTime dateCheck;

        if (debug) {
            System.out.printf("start data %s end date: %s\n", startSqlDate.toString(), endSqlDate.toString());
        }

        while (dateIter.hasNext()) {
            dateCheck = dateIter.nextInCalendar();

            if (results.next()) {
                retValue = results.getBigDecimal(1);
                retDate = results.getDate(2);

                DateTime compCal = new DateTime(retDate.getTime());
                if (compCal.getDayOfMonth() == dateCheck.getDayOfMonth()
                        && compCal.getMonthOfYear() == dateCheck.getMonthOfYear()
                        && compCal.getYear() == dateCheck.getYear()) {
                    closingPrices.add(retValue.doubleValue());
                    continue;
                } else {
                    results.previous();
                }
            }

            BigDecimal failOverValue = getFetcher().fetchData(tableName, dateCheck, type);
            if (failOverValue != null) {
                closingPrices.add(failOverValue.doubleValue());
            }
        }

    } catch (SQLException ex) {
        System.err.printf("LocalJDBC Unable to find date for:'%s' from'%s' Time" + startDate.toDate() + "\n",
                "Cosing Price", tableName);
        ex.printStackTrace();
        SQLException xp = null;
        while ((xp = ex.getNextException()) != null) {
            xp.printStackTrace();
        }

    } finally {
        try {
            if (results != null)
                results.close();
            if (pstm != null)
                pstm.close();
            if (connection != null)
                connection.close();
            //                System.out.printf("Max connect:%d in use:%d\n",mainPool.getMaxConnections(), mainPool.getActiveConnections());
            //                mainPool.dispose();

        } catch (SQLException ex) {
            Logger.getLogger(LocalJDBC.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return ArrayUtils.toPrimitive(closingPrices.toArray(new Double[0]));
}

From source file:org.kuali.kfs.module.ar.batch.service.impl.LockboxServiceImpl.java

protected void writeBatchGroupSectionTitle(com.lowagie.text.Document pdfDoc, String batchSeqNbr,
        java.sql.Date procInvDt, String cashControlDocNumber) {
    Font font = FontFactory.getFont(FontFactory.COURIER, 10, Font.BOLD);

    String lineText = "CASHCTL " + rightPad(cashControlDocNumber, 12) + " " + "BATCH GROUP: "
            + rightPad(batchSeqNbr, 5) + " "
            + rightPad((procInvDt == null ? "NONE" : procInvDt.toString()), 35);

    Paragraph paragraph = new Paragraph();
    paragraph.setAlignment(com.lowagie.text.Element.ALIGN_LEFT);
    Chunk chunk = new Chunk(lineText, font);
    chunk.setBackground(Color.LIGHT_GRAY, 5, 5, 5, 5);
    paragraph.add(chunk);//from  w ww.  ja  v  a  2  s.  co  m

    //  blank line
    paragraph.add(new Chunk("", font));

    try {
        pdfDoc.add(paragraph);
    } catch (DocumentException e) {
        LOG.error("iText DocumentException thrown when trying to write content.", e);
        throw new RuntimeException("iText DocumentException thrown when trying to write content.", e);
    }
}

From source file:org.rti.zcore.dar.dao.InventoryDAO.java

/**
 * Creates Out-of-stock record.//from   w ww .ja va2 s .co  m
 * @param conn
 * @param formDef
 * @param formId
 * @param patientId
 * @param siteId
 * @param username
 * @param sessionPatient
 * @param vo
 * @param itemId
 * @param quantityDispensed
 * @param visitDateD
 * @throws ClassNotFoundException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws IOException
 * @throws Exception
 */
public static void createOutOfStockRecord(Connection conn, Form formDef, String formId, Long patientId,
        Long siteId, String username, SessionSubject sessionPatient, EncounterData vo, Long itemId,
        Integer quantityDispensed, Date visitDateD) throws ClassNotFoundException, InstantiationException,
        IllegalAccessException, InvocationTargetException, IOException, Exception {
    Long encounterId;
    Form formDef2 = (Form) DynaSiteObjects.getForms().get(new Long("161"));
    String classname = "org.rti.zcore.dar.gen.StockControl";
    Class formClass = Class.forName(classname);
    BaseEncounter stockControl = (BaseEncounter) formClass.newInstance();
    // don't set patient_id or pregnancy_id - this will cause constraint errors when a patient is deleted.
    stockControl.setPatientId(null);
    stockControl.setPregnancyId(null);
    stockControl.setFormId(formDef2.getId());
    stockControl.setDateVisit(visitDateD);
    // current flow is set in the session by BasePatientAction
    // but we need the flow of the form
    stockControl.setFlowId(formDef.getFlow().getId());
    Map stockControlMap = new HashMap();
    stockControlMap.put("date_of_record", visitDateD.toString());
    stockControlMap.put("item_id", itemId.toString());
    stockControlMap.put("type_of_change", "3279"); //type_of_change
    stockControlMap.put("change_value", quantityDispensed.toString()); //change_value
    stockControlMap.put("balance", "0"); //balance
    stockControlMap.put("last_patient_item_id", vo.getId()); //last_patient_item_id
    EncounterData vo2 = PopulatePatientRecord.populateEncounterData(formDef, formId, siteId, username,
            stockControl, stockControlMap);
    Map genQueries = QueryLoader.instance().load("/" + Constants.SQL_GENERATED_PROPERTIES);

    /**
     * Persist the encounter
     */
    encounterId = org.rti.zcore.dao.FormDAO.createEncounter(conn, genQueries, vo2, formDef2, username, siteId,
            stockControlMap);
}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

@Test
public void testDatetime() throws SQLException {
    trace("test DATETIME");
    ResultSet rs;//from   w  w w . j  a  v  a2  s. c  o  m
    Object o;

    // rs = stat.executeQuery("call date '99999-12-23'");
    // rs.next();
    // assertEquals("99999-12-23", rs.getString(1));
    // rs = stat.executeQuery("call timestamp '99999-12-23 01:02:03.000'");
    // rs.next();
    // assertEquals("99999-12-23 01:02:03.0", rs.getString(1));
    // rs = stat.executeQuery("call date '-99999-12-23'");
    // rs.next();
    // assertEquals("-99999-12-23", rs.getString(1));
    // rs = stat.executeQuery("call timestamp '-99999-12-23 01:02:03.000'");
    // rs.next();
    // assertEquals("-99999-12-23 01:02:03.0", rs.getString(1));

    stat = conn.createStatement();
    // stat.execute("CREATE TABLE test(ID INT PRIMARY KEY,VALUE DATETIME)");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (1,'2011-11-11 0:0:0', 13, 'testDatetime')");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (2,'2002-02-02 02:02:02', 13, 'testDatetime')");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (3,'1800-01-01 0:0:0', 13, 'testDatetime')");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (4,'9999-12-31 23:59:59', 13, 'testDatetime')");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (5,'9999-12-31 23:59:59', 13, 'testDatetime')");
    // stat.execute("INSERT INTO test (column1,column6,column2,column3) VALUES(5,NULL)");
    rs = stat.executeQuery("SELECT column1,column6 FROM test where column3='testDatetime' ORDER BY column1");
    // assertResultSetMeta(rs, 2, new String[] { "ID", "VALUE" }, new int[] {
    // Types.INTEGER, Types.TIMESTAMP }, new int[] { 10, 23 }, new int[] { 0,
    // 10 });
    // rs = stat.executeQuery("SELECT * FROM test ORDER BY ID");
    // assertResultSetMeta(rs, 2, new String[] { "ID", "VALUE" }, new int[] {
    // Types.INTEGER, Types.TIMESTAMP }, new int[] { 10, 23 }, new int[] { 0,
    // 10 });
    rs.next();
    java.sql.Date date;
    java.sql.Time time;
    Timestamp ts;
    date = rs.getDate(2);
    assertTrue(!rs.wasNull());
    time = rs.getTime(2);
    assertTrue(!rs.wasNull());
    ts = rs.getTimestamp(2);
    assertTrue(!rs.wasNull());
    trace("Date: " + date.toString() + " Time:" + time.toString() + " Timestamp:" + ts.toString());
    trace("Date ms: " + date.getTime() + " Time ms:" + time.getTime() + " Timestamp ms:" + ts.getTime());
    trace("1970 ms: " + Timestamp.valueOf("1970-01-01 00:00:00.0").getTime());
    assertEquals(Timestamp.valueOf("2011-11-11 00:00:00.0").getTime(), date.getTime());
    assertEquals(Timestamp.valueOf("1970-01-01 00:00:00.0").getTime(), time.getTime());
    assertEquals(Timestamp.valueOf("2011-11-11 00:00:00.0").getTime(), ts.getTime());
    assertTrue(date.equals(java.sql.Date.valueOf("2011-11-11")));
    assertTrue(time.equals(java.sql.Time.valueOf("00:00:00")));
    assertTrue(ts.equals(Timestamp.valueOf("2011-11-11 00:00:00.0")));
    assertFalse(rs.wasNull());
    o = rs.getObject(2);
    trace(o.getClass().getName());
    assertTrue(o instanceof Timestamp);
    assertTrue(((Timestamp) o).equals(Timestamp.valueOf("2011-11-11 00:00:00")));
    assertFalse(rs.wasNull());
    rs.next();
    date = rs.getDate("COLUMN6");
    assertTrue(!rs.wasNull());
    time = rs.getTime("COLUMN6");
    assertTrue(!rs.wasNull());
    ts = rs.getTimestamp("COLUMN6");
    assertTrue(!rs.wasNull());
    trace("Date: " + date.toString() + " Time:" + time.toString() + " Timestamp:" + ts.toString());
    assertEquals("2002-02-02", date.toString());
    assertEquals("02:02:02", time.toString());
    assertEquals("2002-02-02 02:02:02.0", ts.toString());
    rs.next();
    assertEquals("1800-01-01", rs.getDate("column6").toString());
    assertEquals("00:00:00", rs.getTime("column6").toString());
    assertEquals("1800-01-01 00:00:00.0", rs.getTimestamp("column6").toString());
    rs.next();
    assertEquals("9999-12-31", rs.getDate("Column6").toString());
    assertEquals("23:59:59", rs.getTime("Column6").toString());
    assertEquals("9999-12-31 23:59:59.0", rs.getTimestamp("Column6").toString());
    // assertTrue(!rs.next());
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    }
}

From source file:org.openmrs.module.spreadsheetimport.DatabaseBackend.java

public static String importData(Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData,
        boolean rollbackTransaction) throws Exception {
    Connection conn = null;/*from w  w w  .ja v a2 s .  c o m*/
    Statement s = null;
    Exception exception = null;
    String sql = null;

    String encounterId = null;

    try {

        // Connect to db
        Class.forName("com.mysql.jdbc.Driver").newInstance();

        Properties p = Context.getRuntimeProperties();
        String url = p.getProperty("connection.url");

        conn = DriverManager.getConnection(url, p.getProperty("connection.username"),
                p.getProperty("connection.password"));

        conn.setAutoCommit(false);

        s = conn.createStatement();

        List<String> importedTables = new ArrayList<String>();

        // Import
        for (UniqueImport uniqueImport : rowData.keySet()) {

            String tableName = uniqueImport.getTableName();
            boolean isEncounter = "encounter".equals(tableName);
            boolean isPerson = "person".equals(tableName);
            boolean isPatientIdentifier = "patient_identifier".equals(tableName);
            boolean isObservation = "obs".equals(tableName);

            boolean skip = false;

            // SPECIAL TREATMENT
            // for encounter, if the data is available in the row, it means we're UPDATING observations for an EXISTING encounter, so we don't have to create encounter
            // otherwise, we need to create a new encounter            
            if (isEncounter) {
                Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
                for (SpreadsheetImportTemplateColumn column : columnSet) {
                    Object columnValue = column.getValue();
                    if (!columnValue.equals("")) {
                        column.setGeneratedKey(columnValue.toString());
                        skip = true;
                        importedTables.add("encounter"); // fake as just imported encounter
                        break;
                    }
                }
                if (skip)
                    continue;
            }

            // SPECIAL TREATMENT
            // for observation, if the data to be inserted is empty, then simply skip
            if (isObservation) {
                Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
                for (SpreadsheetImportTemplateColumn column : columnSet) {
                    Object columnValue = column.getValue();
                    if (columnValue.equals("")) {
                        skip = true;
                        importedTables.add("observation"); // fake as just imported observation, not meaningful, just for consistency purpose
                        break;
                    }
                }
                if (skip)
                    continue;
            }

            if (isPerson) {
                boolean isIdentifierExist = false;

                // SPECIAL TREATMENT 1
                // if the patient_identifier.identifier is specified and it is linked to a person, then use that person instead
                // note: patient.patient_id == person.person_id (http://forum.openmrs.org/viewtopic.php?f=2&t=436)            
                UniqueImport patientIdentifier = new UniqueImport("patient_identifier", null);
                if (rowData.containsKey(patientIdentifier)) {
                    Set<SpreadsheetImportTemplateColumn> patientIdentifierColumns = rowData
                            .get(patientIdentifier);
                    for (SpreadsheetImportTemplateColumn patientIdentifierColumn : patientIdentifierColumns) {
                        String columnName = patientIdentifierColumn.getColumnName();
                        if ("identifier".equals(columnName)) {
                            isIdentifierExist = true;

                            sql = "select patient_id from patient_identifier where identifier = "
                                    + patientIdentifierColumn.getValue();

                            System.out.println("Searching for existing patient of id "
                                    + patientIdentifierColumn.getValue());

                            ResultSet rs = s.executeQuery(sql);
                            if (rs.next()) {
                                String patientId = rs.getString(1);

                                System.out.println("Found patient with patient_id = " + patientId);

                                // no need to insert person, use the found patient_id as person_id
                                Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
                                for (SpreadsheetImportTemplateColumn column : columnSet) {
                                    column.setGeneratedKey(patientId);
                                }

                                importedTables.add("person"); // fake as just imported person
                                importedTables.add("patient"); // fake as just imported patient
                                importedTables.add("patient_identifier"); // fake as just imported patient_identifier
                                importedTables.add("person_name"); // fake as just imported person_name
                                importedTables.add("person_address"); // fake as just imported person_address

                                skip = true;
                            }
                            rs.close();
                            break;
                        }
                    }
                }
                if (skip)
                    continue;

                // now, if we proceed to this point, it means patient identifier, if exists, does not match, and in that case, no point to match with person name

                // SPECIAL TREATMENT 2
                // if first name, last name, middle name, gender, and birthdate match existing record, then use that record instead
                UniqueImport personName = new UniqueImport("person_name", null);
                if (rowData.containsKey(personName) && !isIdentifierExist) {
                    Set<SpreadsheetImportTemplateColumn> personNameColumns = rowData.get(personName);

                    // getting gender, birthdate from person
                    Object gender = null;
                    Object birthdate = null;
                    for (SpreadsheetImportTemplateColumn personColumn : rowData.get(uniqueImport)) {
                        String columnName = personColumn.getColumnName();
                        if ("birth_date".equals(columnName))
                            birthdate = personColumn.getValue();
                        if ("gender".equals(columnName))
                            gender = personColumn.getValue();
                    }

                    // getting first name, last name, middle name from person
                    Object givenName = null;
                    Object familyName = null;
                    Object middleName = null;
                    for (SpreadsheetImportTemplateColumn personNameColumn : personNameColumns) {
                        String columnName = personNameColumn.getColumnName();
                        if ("given_name".equals(columnName))
                            givenName = personNameColumn.getValue();
                        if ("family_name".equals(columnName))
                            familyName = personNameColumn.getValue();
                        if ("middle_name".equals(columnName))
                            middleName = personNameColumn.getValue();
                    }

                    // find matching person name
                    sql = "select person.person_id from person_name join person where gender "
                            + (gender == null ? "is NULL" : "= " + gender) + " and birthdate "
                            + (birthdate == null ? "is NULL" : "= " + birthdate) + " and given_name "
                            + (givenName == null ? "is NULL" : "= " + givenName) + " and family_name "
                            + (familyName == null ? "is NULL" : "= " + familyName) + " and middle_name "
                            + (middleName == null ? "is NULL" : "= " + middleName);
                    ResultSet rs = s.executeQuery(sql);
                    String personId = null;
                    if (rs.next()) {
                        // matched => no need to insert person, use the found patient_id as person_id
                        Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
                        for (SpreadsheetImportTemplateColumn column : columnSet) {
                            column.setGeneratedKey(personId);
                        }

                        importedTables.add("person"); // fake as just imported person
                        importedTables.add("patient"); // fake as just imported patient
                        importedTables.add("person_name"); // fake as just imported person_name
                        importedTables.add("person_address"); // fake as just imported person_address

                        skip = true;

                    }
                }
                if (skip)
                    continue;
            }

            if (isPatientIdentifier && importedTables.contains("patient_identifier"))
                continue;

            // Data from columns
            Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
            String columnNames = "";
            String columnValues = "";
            Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = null;
            Set<SpreadsheetImportTemplateColumnColumn> columnColumnsImportBefore = null;
            boolean isFirst = true;
            for (SpreadsheetImportTemplateColumn column : columnSet) {
                // special treatment for encounter: simply ignore this loop since we don't want to insert encounter_id
                if (isEncounter) {
                    columnPrespecifiedValueSet = column.getColumnPrespecifiedValues();
                    columnColumnsImportBefore = column.getColumnColumnsImportBefore();

                    // inject date_created
                    columnNames += "date_created";
                    columnValues += "now()";

                    // find encounter_datetime based on observation date time
                    java.sql.Date encounterDatetime = new java.sql.Date(System.currentTimeMillis());
                    Set<UniqueImport> uniqueImports = rowData.keySet();
                    for (UniqueImport u : uniqueImports) {
                        if ("obs".equals(u.getTableName())) {
                            Set<SpreadsheetImportTemplateColumn> obsColumns = rowData.get(u);
                            for (SpreadsheetImportTemplateColumn obsColumn : obsColumns) {
                                if ("obs_datetime".equals(obsColumn.getColumnName())) {
                                    String obsColumnValue = obsColumn.getValue().toString();
                                    obsColumnValue = obsColumnValue.substring(1, obsColumnValue.length() - 1);
                                    Date obsColumnValueDate = java.sql.Date.valueOf(obsColumnValue);
                                    if (obsColumnValueDate.before(encounterDatetime))
                                        encounterDatetime = obsColumnValueDate;
                                }
                            }
                        }
                    }
                    columnNames += ", encounter_datetime";
                    columnValues += ",'" + encounterDatetime.toString() + "'";

                    isFirst = false;
                    break;
                }

                // Check for duplicates
                if (column.getDisallowDuplicateValue()) {
                    sql = "select " + column.getColumnName() + " from " + column.getTableName() + " where "
                            + column.getColumnName() + " = " + column.getValue();
                    if (log.isDebugEnabled()) {
                        log.debug(sql);
                        System.out.println(sql);
                    }
                    ResultSet rs = s.executeQuery(sql);
                    boolean foundDuplicate = rs.next();
                    rs.close();
                    if (foundDuplicate) {
                        throw new SpreadsheetImportDuplicateValueException(column);
                    }
                }

                if (isFirst) {
                    // Should be same for all columns in unique import
                    columnPrespecifiedValueSet = column.getColumnPrespecifiedValues();
                    columnColumnsImportBefore = column.getColumnColumnsImportBefore();
                    isFirst = false;
                } else {
                    columnNames += ",";
                    columnValues += ",";
                }
                columnNames += column.getColumnName();
                columnValues += column.getValue().toString();

            }

            // Data from pre-specified values
            for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) {
                if (isFirst)
                    isFirst = false;
                else {
                    columnNames += ",";
                    columnValues += ",";
                }
                columnNames += columnPrespecifiedValue.getColumnName();
                columnValues += columnPrespecifiedValue.getPrespecifiedValue().getValue();
            }

            // Data from columns import before
            if (!columnColumnsImportBefore.isEmpty()) {

                // Set up
                Map<String, String> mapPrimaryKeyColumnNameToGeneratedKey = new HashMap<String, String>();
                for (SpreadsheetImportTemplateColumnColumn columnColumn : columnColumnsImportBefore) {
                    String primaryKeyColumnName = columnColumn.getColumnName();
                    String columnGeneratedKey = columnColumn.getColumnImportFirst().getGeneratedKey();

                    if (mapPrimaryKeyColumnNameToGeneratedKey.containsKey(primaryKeyColumnName)) {
                        String mapGeneratedKey = mapPrimaryKeyColumnNameToGeneratedKey
                                .get(primaryKeyColumnName);
                        if (!mapGeneratedKey.equals(columnGeneratedKey)) {
                            throw new SpreadsheetImportUnhandledCaseException();
                        }
                    } else {
                        mapPrimaryKeyColumnNameToGeneratedKey.put(primaryKeyColumnName, columnGeneratedKey);
                    }

                    // TODO: I believe patient and person are only tables with this relationship, if not, then this
                    // needs to be generalized
                    if (primaryKeyColumnName.equals("patient_id") && importedTables.contains("person")
                            && !importedTables.contains("patient")) {

                        sql = "insert into patient (patient_id, creator) values (" + columnGeneratedKey + ", "
                                + Context.getAuthenticatedUser().getId() + ")";
                        if (log.isDebugEnabled()) {
                            log.debug(sql);
                        }
                        s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
                        //                     ResultSet rs = s.getGeneratedKeys();
                        //                     rs.next();
                        //                     if (!columnGeneratedKey.equals(rs.getString(1))) {
                        //                        throw new SpreadsheetImportUnhandledCaseException();
                        //                     }
                        importedTables.add("patient");
                    }
                }

                // Add columns
                for (String columnName : mapPrimaryKeyColumnNameToGeneratedKey.keySet()) {
                    if (isFirst)
                        isFirst = false;
                    else {
                        columnNames += ",";
                        columnValues += ",";
                    }
                    columnNames += columnName;
                    columnValues += mapPrimaryKeyColumnNameToGeneratedKey.get(columnName);
                }

            }

            // SPECIAL TREATMENT: if this is observation, then check for column obs_datetime. If not available, then use current time
            if (isObservation) {
                boolean hasDatetime = false;
                for (SpreadsheetImportTemplateColumn column : columnSet) {
                    if ("obs_datetime".equals(column.getColumnName())) {
                        hasDatetime = true;
                        break;
                    }
                }
                if (!hasDatetime) {
                    columnNames += ",obs_datetime";
                    columnValues += ",now()";
                }
                columnNames += ", date_created";
                columnValues += ",now()";
            }

            // SPECIAL TREATMENT: if this is patient identifier, then set location_id to NULL, to avoid CONSTRAINT `patient_identifier_ibfk_2` FOREIGN KEY (`location_id`) REFERENCES `location` (`location_id`))
            if (isPatientIdentifier) {
                columnNames += ", location_id";
                columnValues += ", NULL";
            }

            // creator
            columnNames += ",creator";
            columnValues += "," + Context.getAuthenticatedUser().getId();

            // uuid
            DatabaseMetaData dmd = conn.getMetaData();
            ResultSet rsColumns = dmd.getColumns(null, null, uniqueImport.getTableName(), "uuid");
            if (rsColumns.next()) {
                columnNames += ",uuid";
                columnValues += ",uuid()";
            }
            rsColumns.close();

            // Insert tableName
            sql = "insert into " + uniqueImport.getTableName() + " (" + columnNames + ")" + " values ("
                    + columnValues + ")";
            System.out.println(sql);
            if (log.isDebugEnabled()) {
                log.debug(sql);
            }

            s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
            ResultSet rs = s.getGeneratedKeys();
            rs.next();
            for (SpreadsheetImportTemplateColumn column : columnSet) {
                column.setGeneratedKey(rs.getString(1));
            }
            // SPECIAL TREATMENT: update Encounter ID back to the Excel file by returning it to the caller
            if (isEncounter)
                encounterId = rs.getString(1);
            rs.close();

            importedTables.add(uniqueImport.getTableName());
        }
    } catch (SQLSyntaxErrorException e) {
        throw new SpreadsheetImportSQLSyntaxException(sql, e.getMessage());
    } catch (Exception e) {
        log.debug(e.toString());
        exception = e;
        throw new SpreadsheetImportSQLSyntaxException(sql, e.getMessage()); // TODO: for web debug purpose only, should comment out later
    } finally {
        if (s != null) {
            try {
                s.close();
            } catch (Exception e) {
            }
        }
        if (conn != null) {
            if (rollbackTransaction) {
                conn.rollback();
            } else {
                conn.commit();
            }
            try {
                conn.close();
            } catch (Exception e) {
            }
        }
    }

    if (exception != null) {
        throw exception;
    }

    return encounterId;
}

From source file:pt.fct.di.benchmarks.TPCW_Riak.database.TPCW_Riak_Executor.java

public void BuyComfirm(String customer, String cart) throws Exception {

    Bucket bucket = getBucket("shopping_cart");
    ShoppingCart shop_c = (ShoppingCart) GSON.fromJson(bucket.fetch(cart).execute().getValueAsString(),
            ShoppingCart.class);

    bucket = getBucket("customer");
    Customer customerObj = (Customer) GSON.fromJson(bucket.fetch(customer).execute().getValueAsString(),
            Customer.class);

    double c_discount = (Double) customerObj.getC_DISCOUNT();

    String ship_addr_id = "";
    String cust_addr = (String) customerObj.getAddress();

    float decision = random.nextFloat();
    if (decision < 0.2) {
        ship_addr_id = insertAdress();/*from  w ww. j a va2s . c  o  m*/
    } else {
        ship_addr_id = cust_addr;
    }

    String[] ids = cart.split("\\.");
    int thread_id = Integer.parseInt(ids[1]);

    String shipping = ship_types[random.nextInt(ship_types.length)];

    float total = 0;
    try {
        total = (Float) shop_c.cartInfo.getSC_TOTAL();
    } catch (Exception e) {
        System.out.println("Null pointer on cart:" + cart);
        System.out.println("OPERATIONS: " + operations.toString());
        e.printStackTrace();
        return;
    }

    String order_id = enterOrder(customer, thread_id, shop_c, ship_addr_id, cust_addr, shipping, total,
            c_discount);

    String cc_type = BenchmarkUtil.getRandomAString(10);
    long cc_number = BenchmarkUtil.getRandomNString(16);
    String cc_name = BenchmarkUtil.getRandomAString(30);
    Date cc_expiry = new Date(System.currentTimeMillis() + random.nextInt(644444400));

    enterCCXact(order_id, customer, cc_type, cc_number, cc_name, cc_expiry.toString(), total,
            ship_addr_id.toString());

}

From source file:com.ichi2.anki.SyncClient.java

private JSONObject bundleStats() {
    Log.i(AnkiDroidApp.TAG, "bundleStats");

    JSONObject bundledStats = new JSONObject();

    // Get daily stats since the last day the deck was synchronized
    Date lastDay = new Date(java.lang.Math.max(0, (long) (mDeck.getLastSync() - 60 * 60 * 24) * 1000));
    Log.i(AnkiDroidApp.TAG, "lastDay = " + lastDay.toString());
    ArrayList<Long> ids = AnkiDatabaseManager.getDatabase(mDeck.getDeckPath()).queryColumn(Long.class,
            "SELECT id FROM stats WHERE type = 1 and day >= \"" + lastDay.toString() + "\"", 0);

    try {//w w w  .j a v  a  2 s .c  om
        Stats stat = new Stats(mDeck);
        // Put global stats
        bundledStats.put("global", Stats.globalStats(mDeck).bundleJson());
        // Put daily stats
        JSONArray dailyStats = new JSONArray();
        for (Long id : ids) {
            // Update stat with the values of the stat with id ids.get(i)
            stat.fromDB(id);
            // Bundle this stat and add it to dailyStats
            dailyStats.put(stat.bundleJson());
        }
        bundledStats.put("daily", dailyStats);
    } catch (SQLException e) {
        Log.i(AnkiDroidApp.TAG, "SQLException = " + e.getMessage());
    } catch (JSONException e) {
        Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
    }

    Log.i(AnkiDroidApp.TAG, "Stats =");
    Utils.printJSONObject(bundledStats, false);

    return bundledStats;
}

From source file:org.jboss.bqt.client.xml.XMLQueryVisitationStrategy.java

/**
 * Produce an XML message for an instance of the java.sql.Date.
 * <br>/*w ww. j a  v  a 2s  . c o m*/
 * @param object the instance for which the message is to be produced.
 * @param parent the XML element that is to be the parent of the produced XML message.
 * @return the root element of the XML segment that was produced.
 * @exception JDOMException if there is an error producing the message.
 */
private Element produceMsg(java.sql.Date object, Element parent) throws JDOMException {

    // ----------------------
    // Create the java.sql.Date element ...
    // ----------------------
    Element sqldateElement = new Element(TagNames.Elements.DATE);
    sqldateElement.setText(object.toString());
    if (parent != null) {
        sqldateElement = parent.addContent(sqldateElement);
    }

    return sqldateElement;
}

From source file:com.ichi2.anki.SyncClient.java

/**
 * Anki Desktop -> libanki/anki/sync.py, SyncTools - needFullSync
 * /*from  ww  w . j ava  2s  .  c  o m*/
 * @param sums
 * @return
 */
@SuppressWarnings("unchecked")
public boolean needFullSync(JSONArray sums) {
    Log.i(AnkiDroidApp.TAG, "needFullSync - lastSync = " + mDeck.getLastSync());

    if (mDeck.getLastSync() <= 0) {
        Log.i(AnkiDroidApp.TAG, "deck.lastSync <= 0");
        return true;
    }

    int len = sums.length();
    for (int i = 0; i < len; i++) {
        try {
            JSONObject summary = sums.getJSONObject(i);
            Iterator keys = summary.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                JSONArray l = (JSONArray) summary.get(key);
                Log.i(AnkiDroidApp.TAG, "Key " + key + ", length = " + l.length());
                if (l.length() > 500) {
                    Log.i(AnkiDroidApp.TAG, "Length of key > 500");
                    return true;
                }
            }
        } catch (JSONException e) {
            Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
        }

    }

    AnkiDb ankiDB = AnkiDatabaseManager.getDatabase(mDeck.getDeckPath());

    if (ankiDB.queryScalar("SELECT count() FROM reviewHistory WHERE time > " + mDeck.getLastSync()) > 500) {
        Log.i(AnkiDroidApp.TAG, "reviewHistory since lastSync > 500");
        return true;
    }
    Date lastDay = new Date(java.lang.Math.max(0, (long) (mDeck.getLastSync() - 60 * 60 * 24) * 1000));

    Log.i(AnkiDroidApp.TAG, "lastDay = " + lastDay.toString() + ", lastDayInMillis = " + lastDay.getTime());

    Log.i(AnkiDroidApp.TAG, "Count stats = "
            + ankiDB.queryScalar("SELECT count() FROM stats WHERE day >= \"" + lastDay.toString() + "\""));
    if (ankiDB.queryScalar("SELECT count() FROM stats WHERE day >= \"" + lastDay.toString() + "\"") > 100) {
        Log.i(AnkiDroidApp.TAG, "stats since lastDay > 100");
        return true;
    }

    return false;
}