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.mycompany.demos.Servlet3b.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww  w .  ja  v a  2 s.c  o 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
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    final String DB_URL = "jdbc:mysql://localhost:3306/garbagecollectionv2";
    final String USER = "root";
    final String PASS = "1234";

    double existingLocationLat = 0, existingLocationLng = 0;
    int existingLocationId, newLocationId;
    //float fullness = 0;

    //System.out.println(request.getParameter("action"));
    Connection conn = null;
    Statement stmt = null;
    Statement stmt2 = null;

    try {
        //STEP 2: Register JDBC driver
        System.out.println("Loading Driver...");
        Class.forName(JDBC_DRIVER);

        //STEP 3: Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);

        //STEP 4: Execute a query
        System.out.println("Creating statement...");
        stmt = conn.createStatement();
        stmt2 = conn.createStatement();
        String sql;

        if (request.getParameter("action").equals("add")) {

            sql = "insert into locations (lat,lng) values (" + request.getParameter("lat") + ","
                    + request.getParameter("lng") + ");";
            //System.out.println(sql);
            stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
            ResultSet rs2 = stmt.getGeneratedKeys();
            rs2.next();
            newLocationId = rs2.getInt(1);
            rs2.close();
            //System.out.println(newBinId);

            GraphHopper graphHopper = new GraphHopper()
                    .setGraphHopperLocation("C:\\Users\\panikas\\Desktop\\diploma") // "gh-car"
                    .setEncodingManager(new EncodingManager("car")) // "car"
                    .setOSMFile("europe_germany_berlin.osm") // "germany-lastest.osm.pbf"
                    .forServer();
            graphHopper.importOrLoad();

            GHRequest Grequest = null;
            GHResponse route = null;

            sql = "SELECT * FROM locations WHERE locationId != " + newLocationId + ";";
            ResultSet rs = stmt.executeQuery(sql);

            while (rs.next()) {
                existingLocationLat = rs.getDouble("lat");
                existingLocationLng = rs.getDouble("lng");
                existingLocationId = rs.getInt("locationId");
                Grequest = new GHRequest(existingLocationLat, existingLocationLng,
                        Double.parseDouble(request.getParameter("lat")),
                        Double.parseDouble(request.getParameter("lng")));
                Grequest.setWeighting("fastest");
                Grequest.setVehicle("car");
                route = graphHopper.route(Grequest);
                try (PrintWriter out = new PrintWriter(
                        "C:\\Users\\panikas\\Desktop\\diploma\\code\\Demos\\target\\Demos-1.0-SNAPSHOT\\locations\\route"
                                + existingLocationId + "_" + newLocationId + ".gpx")) {
                    out.print(route.getBest().getInstructions().createGPX("Graphhopper", new Date().getTime(),
                            false, false, true, false));
                } catch (FileNotFoundException ex) {
                    System.out.println("exception filenotfound");
                }
                sql = "insert into distances (originId,destinationId,distance) values (" + existingLocationId
                        + "," + newLocationId + "," + route.getBest().getTime() + ");";
                stmt2.executeUpdate(sql);

                Grequest = new GHRequest(Double.parseDouble(request.getParameter("lat")),
                        Double.parseDouble(request.getParameter("lng")), existingLocationLat,
                        existingLocationLng);
                Grequest.setWeighting("fastest");
                Grequest.setVehicle("car");
                route = graphHopper.route(Grequest);
                try (PrintWriter out = new PrintWriter(
                        "C:\\Users\\panikas\\Desktop\\diploma\\code\\Demos\\target\\Demos-1.0-SNAPSHOT\\locations\\route"
                                + newLocationId + "_" + existingLocationId + ".gpx")) {
                    out.print(route.getBest().getInstructions().createGPX("Graphhopper", new Date().getTime(),
                            false, false, true, false));
                } catch (FileNotFoundException ex) {
                    System.out.println("exception filenotfound");
                }
                sql = "insert into distances (originId,destinationId,distance) values (" + newLocationId + ","
                        + existingLocationId + "," + route.getBest().getTime() + ");";
                stmt2.executeUpdate(sql);

            }

            if (request.getParameter("type").equals("bin")) {
                sql = "insert into bins (locationId,fullness) values (" + newLocationId + ","
                        + request.getParameter("fullness") + ");";
                stmt.executeUpdate(sql);
            } else if (request.getParameter("type").equals("depot")) {
                sql = "insert into depots (locationId,numOfVehicles) values (" + newLocationId + ","
                        + request.getParameter("numOfVehicles") + ");";
                stmt.executeUpdate(sql);
            }

            rs.close();

        } else if (request.getParameter("action").equals("delete")) {
            //System.out.println(request.getParameter("id"));
            sql = "delete from locations where locationId=" + request.getParameter("locationId") + ";";
            stmt.executeUpdate(sql);

        } else if (request.getParameter("action").equals("update")) {
            //System.out.println(request.getParameter("id"));
            //System.out.println(request.getParameter("fullness"));
            sql = "update bins set fullness=" + request.getParameter("fullness") + " where binId="
                    + request.getParameter("binId") + ";";
            stmt.executeUpdate(sql);
        } else if (request.getParameter("action").equals("optimise")) {

            String[] colours = { "#3333ff", "#ff33cc", "#ff6600", "#cc6600", "#cccc00" };
            Collection<Location> locations = new ArrayList<Location>();

            //new problem builder
            VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
            vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE);

            //add vehicles
            sql = "SELECT * FROM depots;";
            ResultSet rs = stmt.executeQuery(sql);
            VehicleType type = VehicleTypeImpl.Builder.newInstance("garbageCollector")
                    .addCapacityDimension(0, 1000).build();
            VehicleImpl vehicle;
            Location currentLocation;
            int locationId, numOfVehicles, depotId;

            while (rs.next()) {

                locationId = rs.getInt("locationId");
                numOfVehicles = rs.getInt("numOfVehicles");
                depotId = rs.getInt("depotId");
                currentLocation = Location.newInstance(Integer.toString(locationId));
                for (int i = 0; i < numOfVehicles; i++) {
                    vehicle = VehicleImpl.Builder.newInstance(depotId + "_" + i)
                            .setStartLocation(currentLocation).setType(type).setReturnToDepot(true).build();
                    vrpBuilder.addVehicle(vehicle);
                }
                locations.add(currentLocation);

            }

            sql = "SELECT * FROM bins where fullness > 50;";
            rs = stmt.executeQuery(sql);
            Service currentService;
            float fullness;
            while (rs.next()) {

                locationId = rs.getInt("locationId");
                fullness = rs.getFloat("fullness");
                currentLocation = Location.newInstance(Integer.toString(locationId));
                currentService = Service.Builder.newInstance("service" + Integer.toString(locationId))
                        .addSizeDimension(0, (int) fullness).setLocation(currentLocation).build();
                vrpBuilder.addJob(currentService);
                locations.add(currentLocation);
            }

            //distance matrix
            VehicleRoutingTransportCostsMatrix.Builder costMatrixBuilder = VehicleRoutingTransportCostsMatrix.Builder
                    .newInstance(false);

            float distance;
            for (Location origin : locations) {
                //System.out.println(location.getId());
                costMatrixBuilder.addTransportDistance(origin.getId(), origin.getId(), 0);
                for (Location destination : locations) {
                    //System.out.println(origin.getId());
                    // System.out.println(destination.getId());

                    if (origin.getId() != destination.getId()) {
                        sql = "SELECT distance FROM distances where originId = " + origin.getId()
                                + " and destinationId = " + destination.getId() + ";";
                        rs = stmt.executeQuery(sql);
                        rs.next();
                        distance = rs.getFloat("distance");
                        costMatrixBuilder.addTransportDistance(origin.getId(), destination.getId(), distance);
                    }
                }
            }

            VehicleRoutingTransportCosts costMatrix = costMatrixBuilder.build();
            vrpBuilder.setRoutingCost(costMatrix);
            VehicleRoutingProblem vrp = vrpBuilder.build();
            VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp);
            Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
            SolutionPrinter.print(vrp, Solutions.bestOf(solutions), SolutionPrinter.Print.VERBOSE);

            //System.out.println("optimise");
            JSONArray files, routes;
            JSONObject route, bins, bin, solution;
            routes = new JSONArray();
            bins = new JSONObject();
            solution = new JSONObject();

            int routeCounter = 0;
            int position;
            for (VehicleRoute jroute : Solutions.bestOf(solutions).getRoutes()) {
                TourActivity prevAct = jroute.getStart();
                route = new JSONObject();
                files = new JSONArray();
                position = 1;

                for (TourActivity act : jroute.getActivities()) {

                    files.add("locations\\route" + prevAct.getLocation().getId() + "_"
                            + act.getLocation().getId() + ".gpx");
                    bin = new JSONObject();
                    bin.put("colour", colours[routeCounter]);
                    bin.put("position", position);
                    bins.put(act.getLocation().getId(), bin);
                    position++;
                    prevAct = act;
                }
                files.add("locations\\route" + prevAct.getLocation().getId() + "_"
                        + jroute.getEnd().getLocation().getId() + ".gpx");
                route.put("files", files);
                route.put("colour", colours[routeCounter]);
                routes.add(route);
                routeCounter++;
            }

            solution.put("routes", routes);
            solution.put("bins", bins);
            System.out.println(solution.toString());
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(solution.toString());

        }

        stmt.close();
        stmt2.close();
        conn.close();
    } catch (SQLException se) {
        //Handle errors for JDBC
        se.printStackTrace();
    } catch (Exception e) {
        //Handle errors for Class.forName
        e.printStackTrace();
    } finally {

        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException se2) {
        }
        try {
            if (stmt2 != null) {
                stmt2.close();
            }
        } catch (SQLException se3) {
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }

    //        JSONObject name = new JSONObject();
    //        JSONArray names = new JSONArray();
    //
    //        name.put(
    //                "name", "foo1");
    //        name.put(
    //                "surname", "bar1");
    //
    //        names.add(name);
    //        name = new JSONObject();
    //
    //        name.put(
    //                "name", "foo2");
    //        name.put(
    //                "surname", "bar2");
    ////        names.add(name);
    //        response.setContentType(
    //                "application/json");
    //        response.setCharacterEncoding(
    //                "UTF-8");
    //        response.getWriter()
    //                .write(name.toString());
    //        System.out.println("done");
    //System.out.println(names.toString());
    //System.out.println(request.getParameter("action"));
    //System.out.println("blah");
}

From source file:br.bookmark.db.util.ResultSetUtils.java

/**
 * Map JDBC objects to Java equivalents.
 * Used by getBean() and getBeans().//from   w  ww .ja  va2  s.c o m
 * <p>
 * Some types not supported.
 * Many not work with all drivers.
 * <p>
 * Makes binary conversions of BIGINT, DATE, DECIMAL, DOUBLE, FLOAT, INTEGER,
 * REAL, SMALLINT, TIME, TIMESTAMP, TINYINT.
 * Makes Sting conversions of CHAR, CLOB, VARCHAR, LONGVARCHAR, BLOB, LONGVARBINARY,
 * VARBINARY.
 * <p>
 * DECIMAL, INTEGER, SMALLINT, TIMESTAMP, CHAR, VARCHAR tested with MySQL and Poolman.
 * Others not guaranteed.
 * @param classeDestino 
 * @throws NoSuchFieldException 
 * @throws SecurityException 
 */
private static void putEntry(Map properties, ResultSetMetaData metaData, ResultSet resultSet, int i,
        Class classeDestino) throws Exception {

    /*
    In a perfect universe, this would be enough
    properties.put(
        metaData.getColumnName(i),
        resultSet.getObject(i));
    But only String, Timestamp, and Integer seem to get through that way.
    */

    String columnName = metaData.getColumnName(i);

    // Testa se  uma FK
    /*Field[] fields = classeDestino.getDeclaredFields();
    for (int j = 0; j < fields.length; j++) {
    if (fields[j].getAnnotation(DBFK.class) != null) {
        properties.put(columnName, resultSet.getString(i));
    }
    }*/
    //System.out.println(i+"-"+metaData.getColumnType(i));
    switch (metaData.getColumnType(i)) {

    // http://java.sun.com/j2se/1.3.0/docs/api/java/sql/Types.html

    case Types.BIGINT:
        properties.put(columnName, new Long(resultSet.getLong(i)));
        break;

    case Types.DATE:
        properties.put(columnName, resultSet.getDate(i));
        break;

    case Types.DECIMAL:
    case Types.DOUBLE:
        properties.put(columnName, new Double(resultSet.getDouble(i)));
        break;

    case Types.FLOAT:
        properties.put(columnName, new Float(resultSet.getFloat(i)));
        break;

    case Types.INTEGER:
        int valor = 0;
        try { // Se o campo esta vazio d erro
            valor = resultSet.getInt(i);
        } catch (SQLException e) {
        }
        properties.put(columnName, new Integer(valor));
        break;

    case Types.REAL:
        properties.put(columnName, new Double(resultSet.getString(i)));
        break;

    case Types.SMALLINT:
        properties.put(columnName, new Short(resultSet.getShort(i)));
        break;

    case Types.TIME:
        properties.put(columnName, resultSet.getTime(i));
        break;

    case Types.TIMESTAMP:
        properties.put(columnName, resultSet.getTimestamp(i));
        break;

    // :FIXME: Throws java.lang.ClassCastException: java.lang.Integer
    // :FIXME: with Poolman and MySQL unless use getString.
    case Types.TINYINT:
        properties.put(columnName, new Byte(resultSet.getString(i)));
        break;

    case Types.CHAR:
    case Types.CLOB:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        // :FIXME: Handle binaries differently?
    case Types.BLOB:
    case Types.LONGVARBINARY:
    case Types.VARBINARY:
        properties.put(columnName, resultSet.getString(i));
        break;

    /*
        :FIXME: Add handlers for
        ARRAY
        BINARY
        BIT
        DISTINCT
        JAVA_OBJECT
        NULL
        NUMERIC
        OTHER
        REF
        STRUCT
    */

    // Otherwise, pass as *String property to be converted
    default:
        properties.put(columnName + "String", resultSet.getString(i));
        break;
    } // end switch

}

From source file:edu.uga.cs.fluxbuster.features.FeatureCalculator.java

/**
 * Retrieves the number of dns queries per domain for each cluster
 * generated on a specific run date.// w  w w  .ja  v  a2  s . co  m
 *
 * @param log_date the run date
 * @return a table of values where the keys are cluster ids and the values 
 *       are the queries per domain value
 * @throws SQLException if there is an error retrieving the queries
 *       per domain values
 */
private Hashtable<Integer, Double> getQueriesPerDomain(Date log_date) throws SQLException {
    Hashtable<Integer, Double> retval = new Hashtable<Integer, Double>();
    StringBuffer querybuf = new StringBuffer();
    Formatter formatter = new Formatter(querybuf);
    formatter.format(properties.getProperty(PREVCLUSTER_QUERY3KEY), df.format(log_date));
    ResultSet rs = null;
    try {
        rs = dbi.executeQueryWithResult(querybuf.toString());
        while (rs.next()) {
            retval.put(rs.getInt(1), rs.getDouble(2));
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(e);
        }
    } finally {
        if (rs != null && !rs.isClosed()) {
            rs.close();
        }
        formatter.close();
    }
    return retval;
}

From source file:fuel.gui.stats.MotorStatsPanel.java

private void refreshGraphs(Motorcycle motor) {
    graphContainer.removeAll();/* w  w  w. jav a 2s.c  o m*/
    if (motor != null) {
        DefaultPieDataset usageDataset = new DefaultPieDataset();
        try {
            ResultSet thisMotor = database
                    .Query("SELECT SUM(distance) FROM fuelrecords WHERE motorcycleId = " + motor.getId(), true);
            ResultSet otherMotors = database.Query(
                    "SELECT SUM(distance) FROM fuelrecords WHERE NOT motorcycleId = " + motor.getId(), true);
            thisMotor.next();
            otherMotors.next();

            usageDataset.setValue(motor.toString(), thisMotor.getInt("1"));
            usageDataset.setValue("Andere motoren", otherMotors.getInt("1"));

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage() + ex.getCause());
        }
        JFreeChart usagePiechart = ChartFactory.createPieChart3D("", usageDataset, true, true, false);
        PiePlot3D plot3 = (PiePlot3D) usagePiechart.getPlot();
        plot3.setForegroundAlpha(0.6f);
        //plot3.setCircular(true);

        JPanel usagePiechartPanel = new ChartPanel(usagePiechart);
        usagePiechartPanel
                .setBorder(BorderFactory.createTitledBorder(BorderFactory.createTitledBorder("Motorgebruik")));
        usagePiechartPanel.setPreferredSize(new java.awt.Dimension(240, 240));
        usagePiechartPanel.setLayout(new BorderLayout());

        DefaultPieDataset stationDataset = new DefaultPieDataset();
        try {
            for (Station station : database.getStations()) {
                ResultSet numberStations = database.Query(
                        "SELECT DISTINCT stationId FROM fuelrecords WHERE stationId = " + station.getId(),
                        true);
                if (numberStations.next()) {
                    ResultSet otherMotors = database.Query("SELECT COUNT(*) FROM fuelrecords WHERE stationId = "
                            + station.getId() + " AND motorcycleId = " + motor.getId(), true);
                    otherMotors.next();
                    if (otherMotors.getInt("1") > 0) {
                        stationDataset.setValue(station.toString(), otherMotors.getInt("1"));
                    }
                }
            }

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage() + ex.getCause());
        }
        JFreeChart stationPiechart = ChartFactory.createPieChart3D("", stationDataset, true, true, false);
        PiePlot3D plot2 = (PiePlot3D) stationPiechart.getPlot();
        plot2.setForegroundAlpha(0.6f);
        //plot3.setCircular(true);

        JPanel stationPiechartPanel = new ChartPanel(stationPiechart);
        stationPiechartPanel.setBorder(
                BorderFactory.createTitledBorder(BorderFactory.createTitledBorder("Tankstation verhouding")));
        stationPiechartPanel.setPreferredSize(new java.awt.Dimension(240, 240));
        stationPiechartPanel.setLayout(new BorderLayout());

        DefaultPieDataset fuelDataset = new DefaultPieDataset();
        try {
            ResultSet numberResults = database.Query("SELECT DISTINCT typeOfGas FROM fuelrecords", true);
            while (numberResults.next()) {
                ResultSet thisStation = database.Query(
                        "SELECT SUM(liter) FROM fuelrecords WHERE typeOfGas = '"
                                + numberResults.getString("typeOfGas") + "'AND motorcycleId = " + motor.getId(),
                        true);
                thisStation.next();
                if (thisStation.getDouble("1") > 0) {
                    fuelDataset.setValue(numberResults.getString("TYPEOFGAS"), thisStation.getDouble("1"));
                }
            }

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage() + ex.getCause());
        }
        JFreeChart fuelPieChart = ChartFactory.createPieChart3D("", fuelDataset, true, true, false);
        PiePlot3D plot1 = (PiePlot3D) fuelPieChart.getPlot();
        plot1.setForegroundAlpha(0.6f);
        //plot3.setCircular(true);

        JPanel fuelPieChartPanel = new ChartPanel(fuelPieChart);
        fuelPieChartPanel.setBorder(
                BorderFactory.createTitledBorder(BorderFactory.createTitledBorder("Brandstof verhouding")));
        fuelPieChartPanel.setPreferredSize(new java.awt.Dimension(240, 240));

        DefaultCategoryDataset barDataset = new DefaultCategoryDataset();
        try {
            ResultSet motorThing = database
                    .Query("SELECT distance/liter,date FROM fuelrecords WHERE motorcycleId = " + motor.getId()
                            + " ORDER BY date ASC", true);
            while (motorThing.next()) {
                barDataset.addValue(motorThing.getDouble("1"), motorThing.getString("DATE"), "Verbruik");
            }

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage() + ex.getCause());
        }

        JFreeChart barChart = ChartFactory.createBarChart3D("", // chart title
                "", // domain axis label
                "Aantal", // range axis label
                barDataset, // data
                PlotOrientation.VERTICAL, false, // include legend
                true, // tooltips?
                false // URLs?
        );
        CategoryPlot plot = barChart.getCategoryPlot();
        BarRenderer3D renderer = (BarRenderer3D) plot.getRenderer();
        renderer.setDrawBarOutline(false);

        ChartPanel barChartPanel = new ChartPanel(barChart);
        barChartPanel.getChartRenderingInfo().setEntityCollection(null);
        barChartPanel.setBorder(BorderFactory.createTitledBorder("Verbruik"));
        barChartPanel.setPreferredSize(new java.awt.Dimension(320, 240));
        barChartPanel.setLayout(new BorderLayout());

        JPanel piePanel = new JPanel(new GridLayout(0, 3));
        piePanel.add(usagePiechartPanel);
        piePanel.add(stationPiechartPanel);
        piePanel.add(fuelPieChartPanel);

        //uitgaven
        DefaultPieDataset expensesDataset = new DefaultPieDataset();
        try {
            Map<String, ResultSet> allCosts = new HashMap<String, ResultSet>();
            ResultSet fuelCosts = database
                    .Query("SELECT SUM(cost) FROM fuelrecords WHERE motorcycleId = " + motor.getId(), true);
            allCosts.put("Brandstof", fuelCosts);
            ResultSet expenses = database.Query("SELECT DISTINCT categoryid FROM expenses", true);
            while (expenses.next()) {
                ResultSet set = database.Query("SELECT SUM(costs) FROM expenses WHERE categoryid = "
                        + expenses.getInt("categoryid") + " AND motorcycleid = " + motor.getId(), true);
                ResultSet set2 = database
                        .Query("SELECT name FROM categories WHERE id = " + expenses.getInt("categoryid"), true);
                set2.next();
                allCosts.put(set2.getString("name"), set);
            }

            for (Map.Entry<String, ResultSet> element : allCosts.entrySet()) {
                element.getValue().next();
                if (element.getValue().getInt("1") > 0) {
                    expensesDataset.setValue(element.getKey(), element.getValue().getInt("1"));
                }
            }

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage() + ex.getCause());
        }
        JFreeChart expensesPiechart = ChartFactory.createPieChart3D("", expensesDataset, true, true, false);
        PiePlot3D plot4 = (PiePlot3D) expensesPiechart.getPlot();
        plot4.setForegroundAlpha(0.6f);

        JPanel expensesPiePanel = new ChartPanel(expensesPiechart);
        expensesPiePanel
                .setBorder(BorderFactory.createTitledBorder(BorderFactory.createTitledBorder("Uitgaven")));
        expensesPiePanel.setPreferredSize(new java.awt.Dimension(240, 240));
        expensesPiePanel.setLayout(new BorderLayout());

        graphContainer.add(piePanel);
        graphContainer.add(barChartPanel);
        graphContainer.add(expensesPiePanel);
    }
    revalidate();
    repaint();
}

From source file:org.waarp.common.database.data.AbstractDbData.java

/**
 * Get one value into DbValue from ResultSet
 * /*from   ww w  .j  av a  2 s.c o  m*/
 * @param rs
 * @param value
 * @throws WaarpDatabaseSqlException
 */
static public void getTrueValue(ResultSet rs, DbValue value) throws WaarpDatabaseSqlException {
    try {
        switch (value.type) {
        case Types.VARCHAR:
            value.value = rs.getString(value.column);
            break;
        case Types.LONGVARCHAR:
            value.value = rs.getString(value.column);
            break;
        case Types.BIT:
            value.value = rs.getBoolean(value.column);
            break;
        case Types.TINYINT:
            value.value = rs.getByte(value.column);
            break;
        case Types.SMALLINT:
            value.value = rs.getShort(value.column);
            break;
        case Types.INTEGER:
            value.value = rs.getInt(value.column);
            break;
        case Types.BIGINT:
            value.value = rs.getLong(value.column);
            break;
        case Types.REAL:
            value.value = rs.getFloat(value.column);
            break;
        case Types.DOUBLE:
            value.value = rs.getDouble(value.column);
            break;
        case Types.VARBINARY:
            value.value = rs.getBytes(value.column);
            break;
        case Types.DATE:
            value.value = rs.getDate(value.column);
            break;
        case Types.TIMESTAMP:
            value.value = rs.getTimestamp(value.column);
            break;
        case Types.CLOB:
            value.value = rs.getClob(value.column).getCharacterStream();
            break;
        case Types.BLOB:
            value.value = rs.getBlob(value.column).getBinaryStream();
            break;
        default:
            throw new WaarpDatabaseSqlException("Type not supported: " + value.type + " for " + value.column);
        }
    } catch (SQLException e) {
        DbSession.error(e);
        throw new WaarpDatabaseSqlException("Getting values in error: " + value.type + " for " + value.column,
                e);
    }
}

From source file:com.linkage.community.schedule.dbutils.CustomScalarHandler.java

/**
 * Returns one <code>ResultSet</code> column as an object via the
 * <code>ResultSet.getObject()</code> method that performs type
 * conversions.//from  w w w .  ja va2 s  . c  o m
 * @param rs <code>ResultSet</code> to process.
 * @return The column or <code>null</code> if there are no rows in
 * the <code>ResultSet</code>.
 *
 * @throws SQLException if a database access error occurs
 * @throws ClassCastException if the class datatype does not match the column type
 *
 * @see org.apache.commons.dbutils.ResultSetHandler#handle(java.sql.ResultSet)
 */
// We assume that the user has picked the correct type to match the column
// so getObject will return the appropriate type and the cast will succeed.

@SuppressWarnings("unchecked")
//@Override
public T handle(ResultSet rs) throws SQLException {
    Object obj = null;
    if (rs.next()) {
        if (this.columnName == null) {
            obj = rs.getObject(this.columnIndex);
            if (obj instanceof Integer)
                return (T) (obj = rs.getInt(columnIndex));
            else if (obj instanceof Long)
                return (T) (obj = (new Long(rs.getLong(columnIndex)).intValue()));
            else if (obj instanceof Boolean)
                return (T) (obj = rs.getBoolean(columnIndex));
            else if (obj instanceof Double)
                return (T) (obj = rs.getDouble(columnIndex));
            else if (obj instanceof Float)
                return (T) (obj = rs.getFloat(columnIndex));
            else if (obj instanceof Short)
                return (T) (obj = rs.getShort(columnIndex));
            else if (obj instanceof Byte)
                return (T) (obj = rs.getByte(columnIndex));
            else
                return (T) obj;
        } else {
            obj = rs.getObject(this.columnName);
            if (obj instanceof Integer)
                return (T) (obj = rs.getInt(columnName));
            else if (obj instanceof Long)
                return (T) (obj = rs.getLong(columnName));
            else if (obj instanceof Boolean)
                return (T) (obj = rs.getBoolean(columnName));
            else if (obj instanceof Double)
                return (T) (obj = rs.getDouble(columnName));
            else if (obj instanceof Float)
                return (T) (obj = rs.getFloat(columnName));
            else if (obj instanceof Short)
                return (T) (obj = rs.getShort(columnName));
            else if (obj instanceof Byte)
                return (T) (obj = rs.getByte(columnName));
            else
                return (T) obj;
        }
    }
    return null;
}

From source file:gov.nih.nci.cadsr.persist.de.Data_Elements_Mgr.java

/**
 * Returns the version of a DE based on deIDSEQ
 * // ww w. j  a  v  a  2  s  .  c o  m
 * @param deIDSEQ
 * @param conn
 * @return
 * @throws DBException
 */
public double getDeVersionByIdseq(String deIDSEQ, Connection conn) throws DBException {

    PreparedStatement stmt = null;
    ResultSet rs = null;
    double version = 0;
    try {
        String sql = "select version from data_elements_view where de_idseq = ?";
        stmt = conn.prepareStatement(sql.toString());
        stmt.setString(1, deIDSEQ);
        rs = stmt.executeQuery();
        while (rs.next()) {
            version = rs.getDouble(1);
        }
    } catch (SQLException e) {
        logger.error(
                DBException.DEFAULT_ERROR_MSG + " in getDeVersionByIdseq() method in Data_Elements_Mgr " + e);
        errorList.add(DeErrorCodes.API_DE_000);
        throw new DBException(errorList);
    } finally {
        rs = SQLHelper.closeResultSet(rs);
        stmt = SQLHelper.closePreparedStatement(stmt);
    }
    return version;

}

From source file:uta.ak.usttmp.common.dao.mapper.EvolutionRelaRowMapper.java

@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {

    EvolutionRelationship er = new EvolutionRelationship();

    String queryTp = "select * from c_topic where mme_eid=?";
    Topic preTopic = (Topic) this.jdbcTemplate.queryForObject(queryTp, new TopicRowMapper(),
            rs.getLong("pre_topic_id"));
    Topic nextTopic = (Topic) this.jdbcTemplate.queryForObject(queryTp, new TopicRowMapper(),
            rs.getLong("next_topic_id"));

    er.setNextTopic(nextTopic);/*from  w  ww  . j  a v a 2s  .c  o m*/
    er.setPreTopic(preTopic);
    er.setRankAgainstNextTopicInPreGroup(rs.getInt("rank_against_next_topic_in_pre_group"));
    er.setRankAgainstPreTopicInNextGroup(rs.getInt("rank_against_pre_topic_in_next_group"));
    er.setSimilarity(rs.getDouble("similarity"));
    er.setMiningTaskId(rs.getLong("miningtask_id"));
    er.setPreTopicSeq(rs.getInt("pre_topic_seq"));
    er.setNextTopicSeq(rs.getInt("next_topic_seq"));

    return er;
}

From source file:edu.uga.cs.fluxbuster.features.FeatureCalculator.java

/**
 * Calculates the domains per network feature for each cluster generated
 * on a specific run date./*  w ww  .  j a va2 s  .c o  m*/
 * 
 * @param log_date the run date
 * @param window the number of days previous to use in feature calculation
 * @return a table of values where the keys are cluster ids and the values 
 *       are the feature values
 * @throws SQLException if there is an error calculating the feature values
 */

public Map<Integer, Double> calculateDomainsPerNetwork(Date log_date, int window) throws SQLException {
    HashMap<Integer, Double> retval = new HashMap<Integer, Double>();
    ArrayList<Date> prevDates = getPrevDates(log_date, window);
    if (prevDates.size() > 0) {
        String logDateStr = df.format(log_date);
        StringBuffer add_query = new StringBuffer();
        Formatter formatter = new Formatter(add_query);

        for (Date prevDate : prevDates) {
            String prevDateStr = df.format(prevDate);
            formatter.format(" " + properties.getProperty(DOMAINSPERNETWORK_QUERY1KEY) + " ", logDateStr,
                    prevDateStr, prevDateStr);
        }
        formatter.close();

        StringBuffer querybuf = new StringBuffer();
        formatter = new Formatter(querybuf);
        formatter.format(properties.getProperty(DOMAINSPERNETWORK_QUERY2KEY), logDateStr, logDateStr,
                logDateStr, add_query.toString());
        ResultSet rs = null;
        try {
            rs = dbi.executeQueryWithResult(querybuf.toString());
            while (rs.next()) {
                retval.put(rs.getInt(1), rs.getDouble(2));
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error(e);
            }
        } finally {
            if (rs != null && !rs.isClosed()) {
                rs.close();
            }
            formatter.close();
        }
    }
    return retval;
}

From source file:com.sfs.whichdoctor.analysis.RevenueAnalysisDAOImpl.java

/**
 * Load stream revenue.//from   w  w w.j a va2 s.c  om
 *
 * @param rs the rs
 * @return the revenue bean
 * @throws SQLException the sQL exception
 */
private RevenueBean loadStreamRevenue(final ResultSet rs) throws SQLException {

    final RevenueBean revenue = new RevenueBean();

    revenue.setRevenueType(rs.getString("RevenueType"));
    revenue.setRevenueClass(rs.getString("RevenueClass"));

    revenue.setValue(rs.getDouble("RevenueValue"));
    revenue.setNetValue(rs.getDouble("RevenueNetValue"));

    final double gstRate = rs.getDouble("InvoiceGSTRate");
    revenue.setGSTValue(gstRate, revenue.getGSTValue());

    /** Temporary placeholder for Receipt details */
    final ReceiptBean receipt = loadReceipt(rs);

    PaymentBean payment = new PaymentBean();
    payment.setIncomeStream(rs.getString("RevenueType"));
    payment.setValue(rs.getDouble("RevenueValue"));
    payment.setNetValue(rs.getDouble("RevenueNetValue"));
    /* Load invoice details */
    if (rs.getInt("InvoiceGUID") > 0) {
        payment.setDebit(loadDebit(rs));
    }

    final Collection<PaymentBean> payments = new ArrayList<PaymentBean>();
    payments.add(payment);
    receipt.setPayments(payments);
    TreeMap<Integer, ReceiptBean> receipts = new TreeMap<Integer, ReceiptBean>();
    receipts.put(new Integer(receipt.getId()), receipt);
    revenue.setReceipts(receipts);

    return revenue;
}