Example usage for java.sql ResultSet getDouble

List of usage examples for java.sql ResultSet getDouble

Introduction

In this page you can find the example usage for java.sql ResultSet getDouble.

Prototype

double getDouble(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a double in the Java programming language.

Usage

From source file:com.engine.QuoteServletData.java

/**
 *
 * @param id - zTblOpp4.ID/*from   w w  w  .ja  v a 2  s  . c  om*/
 */
public QuoteServletData(String id) {
    items = new ArrayList<>();
    java.sql.Connection con = null;
    java.sql.PreparedStatement stmt = null;
    java.sql.ResultSet rs = null;
    try {
        con = ControlPanelPool.getInstance().getConnection();
        /*
        stmt = con.prepareStatement("SELECT * FROM zTblOpp4 WHERE z3ID = ?");
        stmt.setString(1, id);
        rs = stmt.executeQuery();
        originZip = "";
        country = "";
        while (rs.next()) {
        originZip = rs.getString("ZIP");
        country = rs.getString("COUNTRY");
        }
        productClass = "";
         */
        System.out.println("tblOppMngr4.z4ID = " + id);
        String z3Id = "";
        String z1Id = "";
        stmt = con.prepareStatement("SELECT * FROM tblOppMngr4 WHERE z4ID = ?");
        stmt.setString(1, id);
        rs = stmt.executeQuery();
        while (rs.next()) {
            z3Id = rs.getString("z3ID");
            z1Id = rs.getString("z1ID");
            originZip = rs.getString("SFZIP");
        }
        stmt = con.prepareStatement("SELECT * FROM tblOppMngr1 WHERE z1ID = ?");
        stmt.setString(1, z1Id);
        rs = stmt.executeQuery();
        while (rs.next()) {
            destinationZip = rs.getString("STZIP");
        }
        //https://www.zipcodeapi.com/rest/NGaSQLHFvsGMP1rbcB7RJbb67rX5JAqxgAq6m7LSAsEpt5BFGIxqUIw29u7S4xqk/distance.json/10801/08854/mile
        //get the warehouse and compare the zip codes and find out which one is the closest and use that 
        //for generating the quote that is crossdock
        //while the regular quote should be generated as well
        //the warehouse should also be checked to be able to handle the hazmat material if the matrial is hazmat 
        //when it is a crossdock the notify prior to delivery fee should be added
        //if it is a direct order do not notify prior to delivery
        stmt = con.prepareStatement("SELECT * FROM tblOppMngr3 WHERE z1ID = ?");
        stmt.setString(1, z1Id);
        rs = stmt.executeQuery();
        while (rs.next()) {
            if (rs.getString("HZMT") != null && !rs.getString("HZMT").isEmpty()) {
                if (rs.getString("HZMT").startsWith("Haz")) {
                    productClass = "85";
                }
                if (rs.getString("HZMT").startsWith("Non")) {
                    productClass = "65";
                }
            } else {
                productClass = "65";
            }
            productUm = rs.getString("UNITMEASURE") == null ? "LB" : rs.getString("UNITMEASURE");
            productWeight = (rs.getDouble("QUANT") == 0 ? 1 : rs.getDouble("QUANT"))
                    * (rs.getDouble("MEASURE") == 0 ? 1 : rs.getDouble("MEASURE"));
            Item it = new Item(rs.getString("ID"), productClass, String.valueOf(productWeight));
            items.add(it);
        }
        stmt = con.prepareStatement("SELECT * FROM tblUMMultiplier WHERE UM = ?");
        stmt.setString(1, productUm);
        rs = stmt.executeQuery();
        while (rs.next()) {
            productWeight = productWeight * rs.getFloat("LBmultplier");
        }
        stmt = con.prepareStatement("SELECT * FROM tblWarehouse WHERE Active = 1");
        ConcurrentMap<String, String> warehouseZip = new ConcurrentHashMap<>();
        rs = stmt.executeQuery();

        while (rs.next()) {
            if (rs.getString("WHZIP") != null) {
                warehouseZip.put(rs.getString("WHZIP"), "");
            }
        }
        for (String key : warehouseZip.keySet()) {
            if (key.matches("[0-9]+")) {
                URL url = new URL("http://10.1.1.58:8080/zip/distance?zip1=" + originZip + "&zip2=" + key);
                URLConnection conn = url.openConnection();
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                while ((inputLine = br.readLine()) != null) {
                    warehouseZip.put(key, inputLine.substring(1, inputLine.length() - 1));
                }
                br.close();
            }
        }
        double min = 10000.0;
        for (String key : warehouseZip.keySet()) {
            if (!warehouseZip.get(key).isEmpty() && warehouseZip.get(key) != null) {
                if (Double.valueOf(warehouseZip.get(key)) < min) {
                    min = Double.valueOf(warehouseZip.get(key));
                    whZip = key;
                }
            }
        }
        con.close();
    } catch (IOException | SQLException | PropertyVetoException ex) {
        Logger.getLogger(QuoteServletData.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        DbUtils.closeQuietly(con, stmt, rs);
    }
}

From source file:neg.JRViewerComercial.java

private static void crearFilaHojaExcel(HSSFWorkbook libro, HSSFSheet hoja, int num_fila, ResultSet rs,
        HSSFCellStyle cs2, HSSFCellStyle cs3) throws SQLException, UnknownHostException {
    HSSFRow fila = null;//from www .  j av  a  2s .  c o m
    HSSFCell celda = null;
    HSSFRichTextString texto = null;
    int num_fila_aux = 2;
    while (rs.next()) {
        // Se crea una fila dentro de la hoja
        fila = hoja.createRow(num_fila);

        //Celda del Tarifa Cliente
        HSSFDataFormat format = libro.createDataFormat();

        HSSFCellStyle style = libro.createCellStyle();
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setRightBorderColor(HSSFColor.BLACK.index);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setTopBorderColor(HSSFColor.BLACK.index);

        style.setDataFormat(format.getFormat("#,##0"));

        //Celda de cliente
        celda = fila.createCell((short) 0);
        celda.setCellStyle(cs2);
        String cliente = rs.getString("cl_nombre");
        texto = new HSSFRichTextString(cliente);
        celda.setCellStyle(cs3);
        celda.setCellValue(texto);

        celda.setCellStyle(style);

        //Celda de enero
        celda = fila.createCell((short) 1);
        celda.setCellStyle(cs3);
        double enero = rs.getDouble("enero");
        celda.setCellStyle(cs3);
        celda.setCellValue(enero);
        style.setDataFormat(format.getFormat("00"));

        //Celda de febrero
        celda = fila.createCell((short) 2);
        double febrero = rs.getDouble("febrero");
        celda.setCellStyle(cs3);
        celda.setCellValue(febrero);
        style.setDataFormat(format.getFormat("00"));

        //Celda de marzo
        celda = fila.createCell((short) 3);
        celda.setCellStyle(cs2);
        double marzo = rs.getDouble("marzo");
        celda.setCellStyle(cs3);
        celda.setCellValue(marzo);
        style.setDataFormat(format.getFormat("00"));

        //Celda de abril
        celda = fila.createCell((short) 4);
        double abril = rs.getDouble("abril");
        celda.setCellStyle(cs3);
        celda.setCellValue(abril);
        style.setDataFormat(format.getFormat("00"));

        //Celda de mayo
        celda = fila.createCell((short) 5);
        double mayo = rs.getDouble("mayo");
        celda.setCellStyle(cs3);
        celda.setCellValue(mayo);
        style.setDataFormat(format.getFormat("00"));

        //Celda de junio
        celda = fila.createCell((short) 6);
        double junio = rs.getDouble("junio");
        celda.setCellStyle(cs3);
        celda.setCellValue(junio);

        //Celda del julio
        celda = fila.createCell((short) 7);
        double julio = rs.getDouble("julio");
        celda.setCellStyle(cs3);
        celda.setCellValue(julio);
        style.setDataFormat(format.getFormat("00"));

        //Celda de agosto
        celda = fila.createCell((short) 8);
        celda.setCellStyle(cs2);
        double agosto = rs.getDouble("agosto");
        celda.setCellStyle(cs3);
        celda.setCellValue(agosto);
        style.setDataFormat(format.getFormat("00"));

        //Celda de septiembre
        celda = fila.createCell((short) 9);
        double septiembre = rs.getDouble("septiembre");
        celda.setCellStyle(cs3);
        celda.setCellValue(septiembre);
        style.setDataFormat(format.getFormat("00"));

        //Celda de octubre
        celda = fila.createCell((short) 10);
        celda.setCellStyle(cs2);
        double octubre = rs.getDouble("octubre");
        celda.setCellStyle(cs3);
        celda.setCellValue(octubre);
        style.setDataFormat(format.getFormat("00"));

        //Celda de noviembre
        celda = fila.createCell((short) 11);
        double noviembre = rs.getDouble("noviembre");
        celda.setCellStyle(cs3);
        celda.setCellValue(noviembre);
        style.setDataFormat(format.getFormat("00"));

        //Celda de diciembre
        celda = fila.createCell((short) 12);
        celda.setCellStyle(cs2);
        double diciembre = rs.getDouble("diciembre");
        celda.setCellStyle(cs3);
        celda.setCellValue(diciembre);
        style.setDataFormat(format.getFormat("00"));

        //Celda de la tarifa de cliente
        celda = fila.createCell((short) 13);
        celda.setCellValue(rs.getDouble("ta_cliente"));

        //Celda de margen
        celda = fila.createCell((short) 14);
        double t_cliente = Double.parseDouble(rs.getString("ta_cliente"));
        double t_proveedor = Double.parseDouble(rs.getString("ta_proveedor"));
        double margen = t_cliente - t_proveedor;
        style.setDataFormat(format.getFormat("00.00"));
        celda.setCellValue(margen);

        //Celda de MG %
        celda = fila.createCell((short) 15);
        String porCientoPedido = (!rs.getString("ta_cliente").equals("0"))
                ? new java.text.DecimalFormat("#,##0").format(((t_cliente - t_proveedor) / t_cliente) * 100)
                        .concat("% ")
                : "0% ";
        texto = new HSSFRichTextString(porCientoPedido);
        celda.setCellStyle(cs3);
        celda.setCellValue(texto);

        //Celda de mg pedido
        celda = fila.createCell((short) 16);
        double num_pedidos = Double.parseDouble(rs.getString("num_pedido"));
        style.setDataFormat(format.getFormat("00"));
        double mg_pedido = ((t_cliente - t_proveedor) / num_pedidos);
        celda.setCellStyle(cs3);
        celda.setCellValue(mg_pedido);

        //Celda del num. pedido
        celda = fila.createCell((short) 17);
        int num_pedido = rs.getInt("num_pedido");
        celda.setCellStyle(cs3);
        celda.setCellValue(num_pedido);

        //Se incrementa el numero de fila
        num_fila++;
        num_fila_aux++;
    }
}

From source file:neg.JRViewerComercialProveedor.java

private static void crearFilaHojaExcel(HSSFWorkbook libro, HSSFSheet hoja, int num_fila, ResultSet rs,
        HSSFCellStyle cs2, HSSFCellStyle cs3) throws SQLException, UnknownHostException {
    HSSFRow fila = null;//ww w.  j a va  2s.  com
    HSSFCell celda = null;
    HSSFRichTextString texto = null;
    int num_fila_aux = 2;
    while (rs.next()) {
        // Se crea una fila dentro de la hoja
        fila = hoja.createRow(num_fila);

        //Celda del Tarifa Cliente
        HSSFDataFormat format = libro.createDataFormat();

        HSSFCellStyle style = libro.createCellStyle();
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setRightBorderColor(HSSFColor.BLACK.index);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setTopBorderColor(HSSFColor.BLACK.index);

        style.setDataFormat(format.getFormat("#,##0"));

        //Celda de Proveedor
        celda = fila.createCell((short) 0);
        celda.setCellStyle(cs2);
        String proveedor = rs.getString("pr_nombre_fiscal");
        texto = new HSSFRichTextString(proveedor);
        celda.setCellStyle(cs3);
        celda.setCellValue(texto);

        celda.setCellStyle(style);

        //Celda de enero
        celda = fila.createCell((short) 1);
        celda.setCellStyle(cs3);
        double enero = rs.getDouble("enero_pr");
        celda.setCellStyle(cs3);
        celda.setCellValue(enero);
        style.setDataFormat(format.getFormat("00"));

        //Celda de febrero
        celda = fila.createCell((short) 2);
        double febrero = rs.getDouble("febrero_pr");
        celda.setCellStyle(cs3);
        celda.setCellValue(febrero);
        style.setDataFormat(format.getFormat("00"));

        //Celda de marzo
        celda = fila.createCell((short) 3);
        celda.setCellStyle(cs2);
        double marzo = rs.getDouble("marzo_pr");
        celda.setCellStyle(cs3);
        celda.setCellValue(marzo);
        style.setDataFormat(format.getFormat("00"));

        //Celda de abril
        celda = fila.createCell((short) 4);
        double abril = rs.getDouble("abril_pr");
        celda.setCellStyle(cs3);
        celda.setCellValue(abril);
        style.setDataFormat(format.getFormat("00"));

        //Celda de mayo
        celda = fila.createCell((short) 5);
        double mayo = rs.getDouble("mayo_pr");
        celda.setCellStyle(cs3);
        celda.setCellValue(mayo);
        style.setDataFormat(format.getFormat("00"));

        //Celda de junio
        celda = fila.createCell((short) 6);
        double junio = rs.getDouble("junio_pr");
        celda.setCellStyle(cs3);
        celda.setCellValue(junio);

        //Celda del julio
        celda = fila.createCell((short) 7);
        double julio = rs.getDouble("julio_pr");
        celda.setCellStyle(cs3);
        celda.setCellValue(julio);
        style.setDataFormat(format.getFormat("00"));

        //Celda de agosto
        celda = fila.createCell((short) 8);
        celda.setCellStyle(cs2);
        double agosto = rs.getDouble("agosto_pr");
        celda.setCellStyle(cs3);
        celda.setCellValue(agosto);
        style.setDataFormat(format.getFormat("00"));

        //Celda de septiembre
        celda = fila.createCell((short) 9);
        double septiembre = rs.getDouble("septiembre_pr");
        celda.setCellStyle(cs3);
        celda.setCellValue(septiembre);
        style.setDataFormat(format.getFormat("00"));

        //Celda de octubre
        celda = fila.createCell((short) 10);
        celda.setCellStyle(cs2);
        double octubre = rs.getDouble("octubre_pr");
        celda.setCellStyle(cs3);
        celda.setCellValue(octubre);
        style.setDataFormat(format.getFormat("00"));

        //Celda de noviembre
        celda = fila.createCell((short) 11);
        double noviembre = rs.getDouble("noviembre_pr");
        celda.setCellStyle(cs3);
        celda.setCellValue(noviembre);
        style.setDataFormat(format.getFormat("00"));

        //Celda de diciembre
        celda = fila.createCell((short) 12);
        celda.setCellStyle(cs2);
        double diciembre = rs.getDouble("diciembre_pr");
        celda.setCellStyle(cs3);
        celda.setCellValue(diciembre);
        style.setDataFormat(format.getFormat("00"));

        //Celda de la tarifa de Proveedor
        celda = fila.createCell((short) 13);
        celda.setCellValue(rs.getDouble("ta_proveedor"));

        //Celda de % turismo
        celda = fila.createCell((short) 14);
        celda.setCellStyle(cs3);
        double t_proveedor = Double.parseDouble(rs.getString("ta_proveedor"));
        double factor = Integer.parseInt(rs.getString("factor"));

        int num_pedido = Integer.parseInt(rs.getString("num_pedido"));
        String turismo = (!rs.getString("factor").equals("0"))
                ? new java.text.DecimalFormat("#,##0").format((factor / num_pedido) * 100).concat(" % ")
                : "0 % ";
        style.setDataFormat(format.getFormat("00.00"));
        celda.setCellValue(turismo);

        //Celda de % funciona
        celda = fila.createCell((short) 15);
        celda.setCellStyle(cs3);
        double funciona = Integer.parseInt(rs.getString("estado_ve"));

        String estado_ve = (!rs.getString("estado_ve").equals("0"))
                ? new java.text.DecimalFormat("#,##0").format((funciona / num_pedido) * 100).concat(" % ")
                : "0 % ";
        celda.setCellStyle(cs3);
        celda.setCellValue(estado_ve);

        //Celda % Gra Unitaria
        celda = fila.createCell((short) 16);
        celda.setCellStyle(cs3);
        double soporte = Integer.parseInt(rs.getString("soporte"));

        String grua = (!rs.getString("soporte").equals("0"))
                ? new java.text.DecimalFormat("#,##0").format((soporte / num_pedido) * 100).concat(" % ")
                : "0 % ";

        celda.setCellStyle(cs3);
        celda.setCellValue(grua);

        //Celda del num. pedido
        celda = fila.createCell((short) 17);
        celda.setCellStyle(cs3);
        celda.setCellValue(num_pedido);

        //Se incrementa el numero de fila
        num_fila++;
        num_fila_aux++;
    }
}

From source file:de.hybris.platform.test.TransactionTest.java

@Test
public void testLocking() throws Exception {

    if (Config.isHSQLDBUsed()) {
        LOG.warn("HDSQLDB doesnt seem to support SELECT FOR UPDATE properly so we don't test it any more");
        return;/*from   ww w .  j a va 2  s .  c  o  m*/
    }

    final ProductManager productManager = ProductManager.getInstance();

    final Currency curr = C2LManager.getInstance().createCurrency("TestCurr");

    /** Verify that we can begin a transaction, lock an entity, then commit without an exception occurring. */
    {
        final Transaction transaction = Transaction.current();
        try {
            assertNotNull("Transaction object is null", transaction);
            assertFalse("A previous transaction is already running.", transaction.isRunning());
            transaction.begin();
            final Product productForTest1 = productManager.createProduct("transactionLockingTest1");
            transaction.commit();
            transaction.begin();
            transaction.lock(productForTest1);
            transaction.commit();
        } catch (final Exception e) {
            transaction.rollback();
            throw e;
        }
    }

    {
        /** Verify that an IllegalStateException is thrown if we attempt to lock outside of a transaction. */
        final Transaction transaction = Transaction.current();
        try {
            assertNotNull("Transaction object is null", transaction);
            assertFalse("A previous transaction is already running.", transaction.isRunning());
            final Product productForTest2 = productManager.createProduct("transactionLockingTest2");
            transaction.lock(productForTest2);
            fail("Expected IllegalStateException to occur when attempting to lock an item outside of a transaction.");
        }
        // An IllegalStateException is expected for this test to pass.
        catch (final IllegalStateException e) {
            //
        }
    }

    /**
     * Verify that if we attempt to acquire a lock on the same entity multiple times from the same transaction, that
     * no errors occur.
     */
    {
        final Transaction transaction = Transaction.current();
        try {
            assertNotNull("Transaction object is null", transaction);
            assertFalse("A previous transaction is already running.", transaction.isRunning());
            final Product productForTest3 = productManager.createProduct("transactionLockingTest3");
            transaction.begin();
            for (int i = 0; i < 10; i++) {
                transaction.lock(productForTest3);
            }
            transaction.commit();
        } catch (final Exception e) {
            transaction.rollback();
            throw e;
        }
    }

    /**
     * Verify that if we begin a transaction, lock an entity, then commit multiple times that a lock can be acquired
     * each time.
     */
    {
        final Transaction transaction = Transaction.current();
        try {
            final Product productForTest4 = productManager.createProduct("transactionLockingTest4");
            for (int i = 0; i < 10; i++) {
                assertNotNull("Transaction object is null", transaction);
                assertFalse("A previous transaction is already running.", transaction.isRunning());
                transaction.begin();
                transaction.lock(productForTest4);
                transaction.commit();
            }
        } catch (final Exception e) {
            transaction.rollback();
            throw e;
        }
    }

    /**
     * Verify that if we begin a transaction, lock an entity, then rollback multiple times that a lock can be acquired
     * each time.
     */
    {
        final Transaction transaction = Transaction.current();
        try {
            final Product productForTest5 = productManager.createProduct("transactionLockingTest5");
            for (int i = 0; i < 10; i++) {
                assertNotNull("Transaction object is null", transaction);
                assertFalse("A previous transaction is already running.", transaction.isRunning());
                transaction.begin();
                transaction.lock(productForTest5);
                transaction.rollback();
            }
        } catch (final Exception e) {
            transaction.rollback();
            throw e;
        }
    }

    /**
     * Verify that we can not lock after a transaction has been committed.
     */
    {
        final Transaction transaction = Transaction.current();
        try {
            final Product productForTest6 = productManager.createProduct("transactionLockingTest6");
            assertNotNull("Transaction object is null", transaction);
            assertFalse("A previous transaction is already running.", transaction.isRunning());
            transaction.begin();
            transaction.commit();
            transaction.lock(productForTest6);
            fail("A lock was acquired after the transaction has been committed.");
        }
        // An IllegalStateException is expected for the test to pass
        catch (final IllegalStateException e) {
            //
        }
    }

    /**
     * Verify that we can not lock after a transaction has been rolled back.
     */
    {
        final Transaction transaction = Transaction.current();
        try {
            final Product productForTest7 = productManager.createProduct("transactionLockingTest7");
            assertNotNull("Transaction object is null", transaction);
            assertFalse("A previous transaction is already running.", transaction.isRunning());
            transaction.begin();
            transaction.rollback();
            transaction.lock(productForTest7);
            fail("A lock was acquired after the transaction has been rolled back.");
        }
        // An IllegalStateException is expected for the test to pass
        catch (final IllegalStateException e) {
            //
        }
    }

    /**
     * Verify multiple threads attempting to lock the same object and the behavior that occurs.
     */
    try {
        final Order lockedOrder = OrderManager.getInstance().createOrder(//
                "lockedOrder", //
                JaloSession.getCurrentSession().getUser(), //
                curr, //
                Calendar.getInstance().getTime(), //
                true);
        lockedOrder.setTotal(0.0d);

        final ComposedType composedType = lockedOrder.getComposedType();

        final String checkQuery = "SELECT "
                + composedType.getAttributeDescriptorIncludingPrivate(Order.TOTAL).getDatabaseColumn()
                + " FROM " + composedType.getTable() + " WHERE PK = ?";

        final int THREADS = 16;

        // Create an executor service that uses 16 threads to test
        // the transaction locking
        final ExecutorService executor = Executors.newFixedThreadPool(//
                THREADS, //
                new ThreadFactory() {
                    final Tenant threadFactoryTenant = Registry.getCurrentTenant();

                    @Override
                    public Thread newThread(final Runnable runnable) {
                        return new Thread() {
                            protected void prepareThread() {
                                Registry.setCurrentTenant(threadFactoryTenant);
                            }

                            protected void unprepareThread() {
                                JaloSession.deactivate();
                                Registry.unsetCurrentTenant();
                            }

                            @Override
                            public void run() {
                                try {
                                    prepareThread();
                                    runnable.run();
                                } finally {
                                    unprepareThread();
                                }
                            }
                        };
                    }
                });

        // Create 8 callables that will concurrently
        // attempt to lock the same object.
        final AtomicInteger stackCounter = new AtomicInteger();
        final List<Callable<Object>> callables = new ArrayList<Callable<Object>>();
        for (int j = 0; j < THREADS; j++) {
            callables.add(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    final PK pk = lockedOrder.getPK();
                    if (pk == null) {
                        throw new IllegalStateException();
                    }

                    for (int k = 0; k < 100; k++) {
                        final Transaction transaction = Transaction.current();

                        assertNotNull("Transaction object is null", transaction);

                        PreparedStatement statement = null;
                        ResultSet resultSet = null;
                        try {
                            transaction.begin();
                            transaction.setTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED);
                            transaction.lock(lockedOrder);
                            final int stack = stackCounter.incrementAndGet();
                            if (stack > 1) {
                                stackCounter.decrementAndGet();
                                throw new IllegalStateException("Got " + stack + " threads in protected area!");
                            }

                            statement = transaction.getTXBoundConnection().prepareStatement(checkQuery);
                            statement.setLong(1, lockedOrder.getPK().getLongValue());
                            resultSet = statement.executeQuery();
                            if (!resultSet.next()) {
                                throw new IllegalStateException("Expected result set");
                            }
                            final double dbValue = resultSet.getDouble(1);
                            final double jaloValue = lockedOrder.getTotal();
                            if (Math.abs(dbValue - jaloValue) >= 1d) {
                                throw new IllegalStateException(
                                        "Jalo value differs from db value : " + jaloValue + "<>" + dbValue);
                            }

                            lockedOrder.setTotal(jaloValue + 1.0d);

                            stackCounter.decrementAndGet();
                            transaction.commit();
                        } catch (final Exception e) {
                            e.printStackTrace();
                            transaction.rollback();
                            throw e;
                        } finally {
                            Utilities.tryToCloseJDBC(null, statement, resultSet, true);
                        }
                    }
                    return null;
                }
            });
        }
        // Get the value of each future to determine if an exception was thrown.
        for (final Future<Object> future : executor.invokeAll(callables)) {
            future.get();
        }
        final double expected = THREADS * 100;
        assertEquals(//
                "Total value of order after all transaction differs", //
                expected, //
                ((Order) JaloSession.getCurrentSession().getItem(lockedOrder.getPK())).getTotal(), 0.000001);
    } catch (final IllegalStateException e) {
        e.printStackTrace();
        throw e;
    }

    /**
     * Verify changes to a value on a lock
     */

    // TODO:

    /**
     * Tests related to caching
     */

    // TODO:
}

From source file:com.ibm.bluemix.samples.PostgreSQLClient.java

/**
 * Grab text from PostgreSQL//from  ww  w .  jav  a2 s  .c om
 * 
 * @return List of Strings of text from PostgreSQL
 * @throws Exception
 */
public EntityTrack getTrack(String notesID, String liquidID) throws Exception {
    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("SELECT * FROM track");
    String str = String.format(" where NotesID='%s' and LiquidID='%s'", notesID, liquidID);
    sqlBuilder.append(str);

    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet results = null;
    EntityTrack track = null;

    try {
        connection = getConnection();
        statement = connection.prepareStatement(sqlBuilder.toString());
        results = statement.executeQuery();

        while (results.next()) {
            track = new EntityTrack();
            if (results.getString("NotesID") != null) {
                track.setNotesID(results.getString("NotesID"));
            }
            if (results.getString("LiquidID") != null) {
                track.setLiquidID(results.getString("LiquidID"));
            }
            if (results.getString("Name") != null) {
                track.setName(results.getString("Name"));
            }
            if (results.getString("TechDomain") != null) {
                track.setTechDomain(results.getString("TechDomain"));
            }
            if (results.getString("TechOther") != null) {
                track.setTechOther(results.getString("TechOther"));
            }
            if (results.getString("EventType") != null) {
                track.setEventType(results.getString("EventType"));
            }
            if (results.getString("EventOther") != null) {
                track.setEventOther(results.getString("EventOther"));
            }
            if (results.getString("RegisterDate") != null) {
                track.setRegisterDate(results.getString("RegisterDate"));
            }
            if (results.getString("CompleteDate") != null) {
                track.setCompleteDate(results.getString("CompleteDate"));
            }
            if (results.getString("Status") != null) {
                track.setStatus(results.getString("Status"));
            }
            if (results.getString("IsFirst") != null) {
                track.setIsFirst(results.getString("IsFirst"));
            }
            if (results.getString("IsSecond") != null) {
                track.setIsSecond(results.getString("IsSecond"));
            }

            track.setWinDollar(results.getDouble("WinDollar"));
            track.setWinHour(results.getDouble("WinHour"));
            track.setWinPoint(results.getDouble("WinPoint"));
        }

        return track;
    } catch (SQLException e) {
        throw e;
    } finally {
        if (results != null) {
            results.close();
        }

        if (statement != null) {
            statement.close();
        }

        if (connection != null) {
            connection.close();
        }
    }
}

From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java

private int printResultSet(final ResultSet rs) throws Exception {
    int count = 0;
    long empno, empno2;
    String ename, ename2;/*from   w ww  .java 2s .co  m*/
    String[] nicknames;
    String[] nicknames2;
    double salary, salary2;
    Date hireDate, hireDate2;

    System.out.println();
    System.out.println("===================================================================");
    System.out.println("   empno        ename      salary       hire_date       nicknames");
    System.out.println("===================================================================");

    while (rs.next()) {
        ++count;

        if (count == 1) {
            assertTrue(rs.isFirst());
        } else {
            assertFalse(rs.isFirst());
        }

        assertEquals(count, rs.getRow());

        empno = rs.getLong(1);
        assertFalse(rs.wasNull());
        empno2 = rs.getLong("empno");
        assertEquals(empno, empno2);
        ename = rs.getString(2);
        ename2 = rs.getString("ename");
        assertEquals(ename, ename2);
        salary = rs.getDouble(3);
        salary2 = rs.getDouble("salary");
        assertEquals(salary, salary2, 0.001);
        hireDate = rs.getDate(4);
        hireDate2 = rs.getDate("hiredate");
        assertEquals(hireDate, hireDate2);
        nicknames = (String[]) rs.getArray(5).getArray();
        nicknames2 = (String[]) rs.getArray("nicknames").getArray();
        assertArrayEquals(nicknames, nicknames2);

        String nodeName = rs.getString(Constants.COLUMN_JCR_NAME);
        assertEquals("testdata-" + count, nodeName);
        assertEquals("/testdatafolder/" + nodeName, rs.getString(Constants.COLUMN_JCR_PATH));
        String nodeId = rs.getString(Constants.COLUMN_JCR_UUID);
        assertTrue(nodeId != null && !nodeId.isEmpty());
        assertTrue(rs.getDouble(Constants.COLUMN_JCR_SCORE) > 0.0);

        assertWrongValueFormatColumn(rs);
        assertNonExistingColumn(rs);

        System.out.println(String.format(REC_OUT_FORMAT, empno, ename, salary,
                new SimpleDateFormat("yyyy-MM-dd").format(hireDate), join(nicknames, ",")));
        System.out.println(String.format(NODE_INFO_OUT_FORMAT, rs.getString("jcr:uuid"),
                rs.getString("jcr:name"), rs.getString("jcr:path"), rs.getDouble("jcr:score")));

        assertEquals(count, empno);
        assertEquals("Name' " + count, ename);
        assertEquals(100000.0 + count, salary, .1);
        assertEquals(getEmpHireDate().getTimeInMillis(), hireDate.getTime());

        assertFalse(rs.rowUpdated());
        assertFalse(rs.rowInserted());
        assertFalse(rs.rowDeleted());
    }

    System.out.println("==================================================");
    System.out.println();

    return count;
}

From source file:Query6Servlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w w  w  .j  a va 2 s . co m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Connection connection = null;
    Statement stmt = null;

    String patientswithAllSqlStat = null;
    String patientswithAmlSqlStat = null;

    ResultSet rsetForALL = null;
    ResultSet rsetForAML = null;

    String patientID = null;
    double expValue = 0;
    List<Double> exprValuesForPatientID = null;

    Map<String, List<Double>> patientToExpValueALL = new HashMap<String, List<Double>>();
    Map<String, List<Double>> patientToExpValueAML = new HashMap<String, List<Double>>();

    //Variables for average correlation
    int i, j;
    double correlation = 0;
    double totalCorrelationALL = 0;
    double avgCorrelationAll = 0;
    double numComForAll = 0;
    Set<String> patientsForALLSet = null;
    String[] patientsForALL = null;

    double totalCorrelationAML = 0;
    double avgCorrelationAllAml = 0;
    double numComForAml = 0;
    Set<String> patientsForAMLSet = null;
    String[] patientsForAML = null;

    List<Double> patientOneExprValues = null;
    Double[] patientOneExprValuesArr = null;
    List<Double> patientTwoExprValues = null;
    Double[] patientTwoExprValuesArr = null;

    response.setContentType("application/json");

    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        Class.forName("oracle.jdbc.driver.OracleDriver");

        connection = DriverManager.getConnection("jdbc:oracle:thin:@aos.acsu.buffalo.edu:1521/aos.buffalo.edu",
                "vvelrath", "cse601");

        stmt = connection.createStatement();

        patientswithAllSqlStat = "SELECT C.P_ID, EXPRESSION FROM MICROARRAY_FACT M, CLINICAL_FACT C "
                + "WHERE M.S_ID = C.S_ID AND M.PB_ID IN (SELECT PB_ID FROM PROBE, GENE_FACT "
                + "WHERE PROBE.USER_ID = GENE_FACT.GENE_UID AND "
                + "GO_ID = 0007154) AND M.S_ID IN (SELECT S_ID FROM CLINICAL_FACT "
                + "WHERE P_ID IN (SELECT P_ID FROM CLINICAL_FACT, DISEASE "
                + "WHERE CLINICAL_FACT.DS_ID = DISEASE.DS_ID AND NAME = 'ALL'))";

        patientswithAmlSqlStat = "SELECT C.P_ID, EXPRESSION FROM MICROARRAY_FACT M, CLINICAL_FACT C "
                + "WHERE M.S_ID = C.S_ID AND M.PB_ID IN (SELECT PB_ID FROM PROBE, GENE_FACT "
                + "WHERE PROBE.USER_ID = GENE_FACT.GENE_UID AND "
                + "GO_ID = 0007154) AND M.S_ID IN (SELECT S_ID FROM CLINICAL_FACT "
                + "WHERE P_ID IN (SELECT P_ID FROM CLINICAL_FACT, DISEASE "
                + "WHERE CLINICAL_FACT.DS_ID = DISEASE.DS_ID AND NAME = 'AML'))";

        //Executing the query for ALL
        rsetForALL = stmt.executeQuery(patientswithAllSqlStat);

        //Converting the result set for "ALL" to the map
        while (rsetForALL.next()) {
            patientID = rsetForALL.getString(1);
            expValue = rsetForALL.getDouble(2);

            if (patientToExpValueALL.get(patientID) != null) {
                exprValuesForPatientID = patientToExpValueALL.get(patientID);
            } else {
                exprValuesForPatientID = new ArrayList<Double>();
            }

            exprValuesForPatientID.add(expValue);
            patientToExpValueALL.put(patientID, exprValuesForPatientID);
        }

        //Executing the query for AML
        rsetForAML = stmt.executeQuery(patientswithAmlSqlStat);

        //Converting the result set for "AML" to the map
        while (rsetForAML.next()) {
            patientID = rsetForAML.getString(1);
            expValue = rsetForAML.getDouble(2);

            if (patientToExpValueAML.get(patientID) != null) {
                exprValuesForPatientID = patientToExpValueAML.get(patientID);
            } else {
                exprValuesForPatientID = new ArrayList<Double>();
            }

            exprValuesForPatientID.add(expValue);
            patientToExpValueAML.put(patientID, exprValuesForPatientID);
        }

        //Finding average correlation for two patients with ALL and for between ALL and AML
        patientsForALLSet = patientToExpValueALL.keySet();
        patientsForALL = new String[patientsForALLSet.size()];
        patientsForALLSet.toArray(patientsForALL);

        patientsForAMLSet = patientToExpValueAML.keySet();
        patientsForAML = new String[patientsForAMLSet.size()];
        patientsForAMLSet.toArray(patientsForAML);

        for (i = 0; i < patientsForALL.length; i++) {

            patientOneExprValues = patientToExpValueALL.get(patientsForALL[i]);
            patientOneExprValuesArr = new Double[patientOneExprValues.size()];
            patientOneExprValues.toArray(patientOneExprValuesArr);

            //Calculating the correlation for between ALL
            for (j = i + 1; j < patientsForALL.length; j++) {

                patientTwoExprValues = patientToExpValueALL.get(patientsForALL[j]);
                patientTwoExprValuesArr = new Double[patientTwoExprValues.size()];
                ;
                patientTwoExprValues.toArray(patientTwoExprValuesArr);

                correlation = new PearsonsCorrelation().correlation(
                        ArrayUtils.toPrimitive(patientOneExprValuesArr),
                        ArrayUtils.toPrimitive(patientTwoExprValuesArr));
                totalCorrelationALL += correlation;
                numComForAll++;
            }

            //Calculating the correlation for between ALL and AML
            for (j = 0; j < patientsForAML.length; j++) {
                patientTwoExprValues = patientToExpValueAML.get(patientsForAML[j]);
                patientTwoExprValuesArr = new Double[patientTwoExprValues.size()];
                ;
                patientTwoExprValues.toArray(patientTwoExprValuesArr);
                correlation = new PearsonsCorrelation().correlation(
                        ArrayUtils.toPrimitive(patientOneExprValuesArr),
                        ArrayUtils.toPrimitive(patientTwoExprValuesArr));
                totalCorrelationAML += correlation;
                numComForAml++;
            }
        }

        avgCorrelationAll = totalCorrelationALL / numComForAll;
        avgCorrelationAllAml = totalCorrelationAML / numComForAml;

        //Populating the JSON Object
        JSONObject avgCorr = new JSONObject();

        avgCorr.put("avgcorrall", avgCorrelationAll);
        avgCorr.put("avgcorrallaml", avgCorrelationAllAml);

        out.print(avgCorr);

        //Closing the statement and connection
        stmt.close();
        connection.close();
    } catch (SQLException e) {
        System.out.println("Connection Failed! Check output console");
    } catch (ClassNotFoundException e) {
        System.out.println("Where is your Oracle JDBC Driver?");
    } catch (JSONException ex) {
        Logger.getLogger(Query4Servlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:ProcessRequest.java

public void calculateTicketDetail(Integer ticketID, JSONObject recordObject)
        throws SQLException, JSONException {
    //first, make sure we have a valid product
    String productQuery = "SELECT * FROM " + DbSingleton.PRODUCT_TABLE_NAME + " WHERE "
            + DbSingleton.ProductSchema.COLUMN_ID + "='"
            + recordObject.getString(DbSingleton.ProductSchema.COLUMN_ID) + "'";
    ResultSet productResultSet = executeQuery(productQuery);
    productResultSet.last();//from   w w w  .  ja va2 s  .  co  m
    int rowCount = productResultSet.getRow();
    productResultSet.first();
    String productID = null;
    Double factor = null;
    if (rowCount < 1) {
        throw new SQLException("no products defined!");
    } else {
        do {
            if (recordObject.getString(DbSingleton.TicketDetailSchema.COLUMN_PRODUCT_ID)
                    .equals(productResultSet.getString(DbSingleton.ProductSchema.COLUMN_ID))) {
                productID = productResultSet.getString(DbSingleton.ProductSchema.COLUMN_ID);
                factor = productResultSet.getDouble(DbSingleton.ProductSchema.COLUMN_FACTOR);
                break;
            }
        } while (productResultSet.next());
        if (productID == null) {
            throw new SQLException("no such product id");
        } else {
            recordObject.remove(DbSingleton.TicketDetailSchema.COLUMN_PRODUCT_NAME);
            recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_PRODUCT_NAME,
                    productResultSet.getString(DbSingleton.ProductSchema.COLUMN_NAME));
            recordObject.remove(DbSingleton.TicketDetailSchema.COLUMN_INVENTORY_NAME);
            recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_INVENTORY_NAME,
                    productResultSet.getString(DbSingleton.ProductSchema.COLUMN_INVENTORY_NAME));
            recordObject.remove(DbSingleton.TicketDetailSchema.COLUMN_PRICE_PER_UOM);
            recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_PRICE_PER_UOM,
                    productResultSet.getString(DbSingleton.ProductSchema.COLUMN_T1_PRICE));
            recordObject.remove(DbSingleton.TicketDetailSchema.COLUMN_UOM);
            recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_UOM,
                    productResultSet.getString(DbSingleton.ProductSchema.COLUMN_UOM));
            recordObject.remove(DbSingleton.TicketDetailSchema.COLUMN_FACTOR);
            recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_FACTOR,
                    productResultSet.getString(DbSingleton.ProductSchema.COLUMN_FACTOR));
            recordObject.remove(DbSingleton.TicketDetailSchema.COLUMN_PRODUCT_TAXABLE);
            recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_PRODUCT_TAXABLE,
                    (productResultSet.getBoolean(DbSingleton.ProductSchema.COLUMN_PRODUCT_TAXABLE)) ? 1 : 0);
        }
    }

    String uom = recordObject.getString(DbSingleton.TicketDetailSchema.COLUMN_UOM);
    if (uom.equals("CUYD") || uom.equals("EACH")) {
        //grab units
        recordObject.remove(DbSingleton.TicketDetailSchema.COLUMN_NET_LBS);
        recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_NET_LBS,
                recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_UNITS));
    } else {
        //grab net weight
        if (recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_GROSS_LBS) < recordObject
                .getDouble(DbSingleton.TicketDetailSchema.COLUMN_TARE_LBS)) {
            recordObject.remove(DbSingleton.TicketDetailSchema.COLUMN_NET_LBS);
            Double net = recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_TARE_LBS)
                    - recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_GROSS_LBS)
                    - recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_DEDUCT_LBS);
            recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_NET_LBS, net);
        }
        recordObject.remove(DbSingleton.TicketDetailSchema.COLUMN_UNITS);
        if (factor != 0) {
            recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_UNITS,
                    recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_NET_LBS) / factor);
        } else {
            recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_UNITS, 0);
        }
    }

    recordObject.remove(DbSingleton.TicketDetailSchema.COLUMN_UNIT_TOTAL);
    recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_UNIT_TOTAL,
            recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_UNITS)
                    * recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_PRICE_PER_UOM));

    if (productResultSet.getDouble(DbSingleton.ProductSchema.COLUMN_MIN_COST) > 0) {
        if (recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_UNITS) < productResultSet
                .getDouble(DbSingleton.ProductSchema.COLUMN_MIN_COST)
                && recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_UNITS) > 0) {
            recordObject.remove(DbSingleton.TicketDetailSchema.COLUMN_UNIT_TOTAL);
            recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_UNIT_TOTAL,
                    recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_MIN_COST));
            recordObject.remove(DbSingleton.TicketDetailSchema.COLUMN_PRICE_PER_UOM);
            recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_PRICE_PER_UOM,
                    recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_UNIT_TOTAL)
                            / recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_UNITS));
        }
    }

    //String ticketQuery = "SELECT * FROM "+DbSingleton.TICKET_TABLE_NAME+" WHERE "+DbSingleton.TicketSchema.COLUMN_TICKET_ID+"="+recordObject.getInt(DbSingleton.TicketDetailSchema.COLUMN_TICKET_ID);
    String ticketQuery = "SELECT * FROM " + DbSingleton.TICKET_TABLE_NAME + " WHERE "
            + DbSingleton.TicketSchema.COLUMN_TICKET_ID + "=" + ticketID;
    ResultSet ticketResultSet = executeQuery(ticketQuery);
    ticketResultSet.first();

    String query = "SELECT * FROM " + DbSingleton.CUSTOMER_TABLE_NAME + " WHERE "
            + DbSingleton.CustomerSchema.COLUMN_ID + "='"
            + ticketResultSet.getString(DbSingleton.TicketSchema.COLUMN_CUSTOMER_ID) + "'";
    ResultSet customerResultSet = executeQuery(query);
    customerResultSet.last();
    rowCount = customerResultSet.getRow();
    customerResultSet.first();
    if (customerResultSet.getBoolean(DbSingleton.CustomerSchema.COLUMN_TAXABLE)) {
        if (productResultSet.getBoolean(DbSingleton.ProductSchema.COLUMN_PRODUCT_TAXABLE)) {
            String iniQuery = "SELECT * FROM INISetting WHERE INIKey=TaxRate";
            ResultSet iniResultSet = executeQuery(iniQuery);
            iniResultSet.last();
            rowCount = iniResultSet.getRow();
            iniResultSet.first();
            if (rowCount < 1) {
                throw new SQLException("could not get tax info for a taxable item!");
            } else {
                Double taxRate = iniResultSet.getDouble("INIValue");
                recordObject.remove(DbSingleton.TicketDetailSchema.COLUMN_UNIT_TAX);
                recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_UNIT_TAX,
                        recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_NET_LBS) * taxRate);
            }
        }
    }

    recordObject.remove(DbSingleton.TicketDetailSchema.COLUMN_TOTAL);
    recordObject.put(DbSingleton.TicketDetailSchema.COLUMN_TOTAL,
            recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_UNIT_TOTAL)
                    + recordObject.getDouble(DbSingleton.TicketDetailSchema.COLUMN_UNIT_TAX));
}

From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.StandardRowSetBuilder.java

public int build(Document doc, String id, ResultSet rs, Set<Integer> keyField,
        Map<String, FieldFormatter> fieldNameToFormatter, Map<String, FieldFormatter> fieldIdToFormatter)
        throws Exception {
    if (rs == null) {
        return 0;
    }/*from   ww w .j ava2 s  .c  o  m*/
    int rowCounter = 0;
    Element docRoot = doc.getDocumentElement();
    ResultSetMetaData metadata = rs.getMetaData();
    FieldFormatter[] fFormatters = buildFormatterArray(metadata, fieldNameToFormatter, fieldIdToFormatter);

    boolean noKey = ((keyField == null) || keyField.isEmpty());

    //boolean isNull = false;
    Element data = null;
    Element row = null;
    Element col = null;
    Text text = null;
    String textVal = null;
    String precKey = null;
    String colKey = null;
    Map<String, String> keyAttr = new HashMap<String, String>();
    while (rs.next()) {
        if (rowCounter % 10 == 0) {
            ThreadUtils.checkInterrupted(getClass().getSimpleName(), name, logger);
        }
        row = parser.createElement(doc, AbstractDBO.ROW_NAME);

        parser.setAttribute(row, AbstractDBO.ID_NAME, id);
        for (int j = 1; j <= metadata.getColumnCount(); j++) {
            FieldFormatter fF = fFormatters[j];

            //isNull = false;
            col = parser.createElement(doc, AbstractDBO.COL_NAME);
            switch (metadata.getColumnType(j)) {
            case Types.DATE: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DATE_TYPE);
                java.sql.Date dateVal = rs.getDate(j);
                textVal = processDateTime(col, fF, dateVal, AbstractDBO.DEFAULT_DATE_FORMAT);
            }
                break;
            case Types.TIME: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIME_TYPE);
                java.sql.Time dateVal = rs.getTime(j);
                textVal = processDateTime(col, fF, dateVal, AbstractDBO.DEFAULT_TIME_FORMAT);
            }
                break;
            case Types.TIMESTAMP: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIMESTAMP_TYPE);
                Timestamp dateVal = rs.getTimestamp(j);
                textVal = processDateTime(col, fF, dateVal, AbstractDBO.DEFAULT_DATE_FORMAT);
            }
                break;
            case Types.DOUBLE: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                double numVal = rs.getDouble(j);
                textVal = processDouble(col, fF, numVal);
            }
                break;
            case Types.FLOAT:
            case Types.REAL: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                float numVal = rs.getFloat(j);
                textVal = processDouble(col, fF, numVal);
            }
                break;
            case Types.BIGINT: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BIGINT_TYPE);
                long numVal = rs.getLong(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                textVal = String.valueOf(numVal);
            }
                break;
            case Types.INTEGER: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.INTEGER_TYPE);
                int numVal = rs.getInt(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                textVal = String.valueOf(numVal);
            }
                break;
            case Types.SMALLINT:
            case Types.TINYINT: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.SMALLINT_TYPE);
                short numVal = rs.getShort(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                textVal = String.valueOf(numVal);
            }
                break;
            case Types.NUMERIC:
            case Types.DECIMAL: {
                BigDecimal bigdecimal = rs.getBigDecimal(j);
                boolean isNull = bigdecimal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DECIMAL_TYPE);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                    }
                    textVal = "";
                } else {
                    if (fF != null) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DECIMAL_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat());
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator());
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator());
                        textVal = fF.formatNumber(bigdecimal);
                    } else if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DECIMAL_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat);
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator);
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator);
                        textVal = numberFormatter.format(bigdecimal);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                        textVal = bigdecimal.toString();
                    }
                }
            }
                break;
            case Types.BOOLEAN: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BOOLEAN_TYPE);
                boolean bVal = rs.getBoolean(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                textVal = String.valueOf(bVal);
            }
                break;
            case Types.SQLXML: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.XML_TYPE);
                SQLXML xml = rs.getSQLXML(j);
                boolean isNull = xml == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    textVal = xml.getString();
                }
            }
                break;
            case Types.NCHAR:
            case Types.NVARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NSTRING_TYPE);
                textVal = rs.getNString(j);
                if (textVal == null) {
                    textVal = "";
                }
            }
                break;
            case Types.CHAR:
            case Types.VARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.STRING_TYPE);
                textVal = rs.getString(j);
                boolean isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
                break;
            case Types.NCLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_NSTRING_TYPE);
                NClob clob = rs.getNClob(j);
                if (clob != null) {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

                    IOUtils.copy(is, str);
                    is.close();
                    textVal = str.toString();
                } else {
                    textVal = "";
                }
            }
                break;
            case Types.CLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_STRING_TYPE);
                Clob clob = rs.getClob(j);
                if (clob != null) {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

                    IOUtils.copy(is, str);
                    is.close();
                    textVal = str.toString();
                } else {
                    textVal = "";
                }
            }
                break;
            case Types.BLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BASE64_TYPE);
                Blob blob = rs.getBlob(j);
                boolean isNull = blob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    InputStream is = blob.getBinaryStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    IOUtils.copy(is, baos);
                    is.close();
                    try {
                        byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length());
                        textVal = Base64.getEncoder().encodeToString(buffer);
                    } catch (SQLFeatureNotSupportedException exc) {
                        textVal = Base64.getEncoder().encodeToString(baos.toByteArray());
                    }
                }
            }
                break;
            default: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DEFAULT_TYPE);
                textVal = rs.getString(j);
                boolean isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
            }
            if (textVal != null) {
                text = doc.createTextNode(textVal);
                col.appendChild(text);
            }
            if (!noKey && keyField.contains(new Integer(j))) {
                if (textVal != null) {
                    if (colKey == null) {
                        colKey = textVal;
                    } else {
                        colKey += "##" + textVal;
                    }
                    keyAttr.put("key_" + j, textVal);
                }
            } else {
                row.appendChild(col);
            }
        }
        if (noKey) {
            if (data == null) {
                data = parser.createElement(doc, AbstractDBO.DATA_NAME);
                parser.setAttribute(data, AbstractDBO.ID_NAME, id);
            }
        } else if ((colKey != null) && !colKey.equals(precKey)) {
            if (data != null) {
                docRoot.appendChild(data);
            }
            data = parser.createElement(doc, AbstractDBO.DATA_NAME);
            parser.setAttribute(data, AbstractDBO.ID_NAME, id);
            for (Entry<String, String> keyAttrEntry : keyAttr.entrySet()) {
                parser.setAttribute(data, keyAttrEntry.getKey(), keyAttrEntry.getValue());
            }
            keyAttr.clear();
            precKey = colKey;
        }
        colKey = null;
        data.appendChild(row);
        rowCounter++;
    }
    if (data != null) {
        docRoot.appendChild(data);
    }

    return rowCounter;
}

From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java

private void assertWrongValueFormatColumn(final ResultSet rs) throws Exception {
    assertFalse(rs.getBoolean(2));//from  ww  w .  j a v  a 2  s .c om
    assertFalse(rs.getBoolean("ename"));

    try {
        rs.getShort(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getShort("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getInt(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getInt("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getLong(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getLong("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getFloat(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getFloat("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDouble(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDouble("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBigDecimal(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBigDecimal("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBytes(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBytes("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate(2, Calendar.getInstance());
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate("ename", Calendar.getInstance());
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime(2, Calendar.getInstance());
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime("ename", Calendar.getInstance());
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp(2, Calendar.getInstance());
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp("ename", Calendar.getInstance());
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getAsciiStream(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getAsciiStream("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBinaryStream(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBinaryStream("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getCharacterStream(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getCharacterStream("ename");
        fail();
    } catch (SQLException ignore) {
    }

}