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:ProcessRequest.java

public void parseQueryResults(ResultSet rs, String table, OutputStream os, boolean append)
        throws SQLException, JSONException, IOException {
    //JSONArray resultJSONArray = new JSONArray();
    ResultSetMetaData rsmd = rs.getMetaData();
    int columns = rsmd.getColumnCount();
    rs.last();//from w  w w .j  av a 2 s . co m
    int rows = rs.getRow();
    os.write(new String("total rows: " + rows).getBytes());
    rs.first();
    int rowCount = 0;
    while (rs.next()) {
        if (!rs.isFirst() || append) {
            os.write(new String(",\n").getBytes());
            os.write(new String("" + rowCount).getBytes());
        }
        if (rowCount >= 69)
            System.out.println("break point");
        rowCount++;
        JSONObject result = new JSONObject();
        JSONObject resultMeta = new JSONObject();
        resultMeta.put("table", table);
        result.put("metadata", resultMeta);
        for (int i = 1; i <= columns; i++) {
            //out.println("<td>"+rs.getString(i)+"</td>");
            int type = rsmd.getColumnType(i);
            //result.put(rsmd.getColumnName(i), rs.get)
            switch (type) {
            case Types.BIT:
                result.put(rsmd.getColumnName(i), rs.getBoolean(i));
                break;
            case Types.TINYINT:
                result.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case Types.SMALLINT:
                result.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case Types.INTEGER:
                //System.out.println(rsmd.getColumnName(i) + "  type: "+type);
                result.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case Types.BIGINT:
                result.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case Types.FLOAT:
                result.put(rsmd.getColumnName(i), rs.getFloat(i));
                break;
            case Types.REAL:
                result.put(rsmd.getColumnName(i), rs.getDouble(i));
                break;
            case Types.DOUBLE:
                result.put(rsmd.getColumnName(i), rs.getDouble(i));
                break;
            case Types.NUMERIC:
                result.put(rsmd.getColumnName(i), rs.getDouble(i));
                break;
            case Types.DECIMAL:
                result.put(rsmd.getColumnName(i), rs.getDouble(i));
                break;
            case Types.CHAR:
                result.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case Types.VARCHAR:
                result.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case Types.LONGVARCHAR:
                result.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case Types.DATE: {
                java.util.Date date = rs.getDate(i);
                result.put(rsmd.getColumnName(i), date.getTime());
                break;
            }
            case Types.TIME: {
                java.util.Date date = rs.getDate(i);
                result.put(rsmd.getColumnName(i), date.getTime());
                break;
            }
            case Types.TIMESTAMP: {
                java.util.Date date = rs.getDate(i);
                result.put(rsmd.getColumnName(i), date.getTime());
                break;
            }
            case Types.BINARY:
                result.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case Types.VARBINARY:
                result.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case Types.LONGVARBINARY:
                result.put(rsmd.getColumnName(i), rs.getLong(i));
                break;
            case Types.NULL:
                result.put(rsmd.getColumnName(i), "");
                break;
            case Types.BOOLEAN:
                result.put(rsmd.getColumnName(i), rs.getBoolean(i));
                break;
            case Types.ROWID:
                result.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case Types.NCHAR:
                result.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case Types.NVARCHAR:
                result.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case Types.LONGNVARCHAR:
                result.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case Types.SQLXML:
            case Types.NCLOB:
            case Types.DATALINK:
            case Types.REF:
            case Types.OTHER:
            case Types.JAVA_OBJECT:
            case Types.DISTINCT:
            case Types.STRUCT:
            case Types.ARRAY:
            case Types.BLOB:
            case Types.CLOB:
            default:
                result.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            }
        }
        //if(table.equals("Ticket"))
        //System.out.println(result.toString(5));
        //if(result.getInt("TicketNumber")==126868)
        //   System.out.println("break point");
        //resultJSONArray.put(result);
        os.write(result.toString(5).getBytes());
    }
    //return resultJSONArray;
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 *  Create a new Node from a ResultSet./*from  w  ww. j av  a2 s .c o m*/
 */
public Node createNode(DbMapping dbm, ResultSet rs, DbColumn[] columns, int offset)
        throws SQLException, IOException, ClassNotFoundException {
    HashMap propBuffer = new HashMap();
    String id = null;
    String name = null;
    String protoName = dbm.getTypeName();
    DbMapping dbmap = dbm;

    Node node = new Node();

    for (int i = 0; i < columns.length; i++) {
        // set prototype?
        if (columns[i].isPrototypeField()) {
            protoName = rs.getString(i + 1 + offset);

            if (protoName != null) {
                dbmap = getDbMapping(protoName);

                if (dbmap == null) {
                    // invalid prototype name!
                    app.logError(ErrorReporter.errorMsg(this.getClass(), "createNode")
                            + "Invalid prototype name: " + protoName + " - using default");
                    dbmap = dbm;
                    protoName = dbmap.getTypeName();
                }
            }
        }

        // set id?
        if (columns[i].isIdField()) {
            id = rs.getString(i + 1 + offset);
            // if id == null, the object doesn't actually exist - return null
            if (id == null) {
                return null;
            }
        }

        // set name?
        if (columns[i].isNameField()) {
            name = rs.getString(i + 1 + offset);
        }

        Property newprop = new Property(node);

        switch (columns[i].getType()) {
        case Types.BIT:
            newprop.setBooleanValue(rs.getBoolean(i + 1 + offset));

            break;

        case Types.TINYINT:
        case Types.BIGINT:
        case Types.SMALLINT:
        case Types.INTEGER:
            newprop.setIntegerValue(rs.getLong(i + 1 + offset));

            break;

        case Types.REAL:
        case Types.FLOAT:
        case Types.DOUBLE:
            newprop.setFloatValue(rs.getDouble(i + 1 + offset));

            break;

        case Types.DECIMAL:
        case Types.NUMERIC:

            BigDecimal num = rs.getBigDecimal(i + 1 + offset);

            if (num == null) {
                break;
            }

            if (num.scale() > 0) {
                newprop.setFloatValue(num.doubleValue());
            } else {
                newprop.setIntegerValue(num.longValue());
            }

            break;

        case Types.VARBINARY:
        case Types.BINARY:
            //                    newprop.setStringValue(rs.getString(i+1+offset));
            newprop.setJavaObjectValue(rs.getBytes(i + 1 + offset));

            break;

        case Types.LONGVARBINARY: {
            InputStream in = rs.getBinaryStream(i + 1 + offset);
            if (in == null) {
                break;
            }
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int read;
            while ((read = in.read(buffer)) > -1) {
                bout.write(buffer, 0, read);
            }
            newprop.setJavaObjectValue(bout.toByteArray());
        }

            break;
        case Types.LONGVARCHAR:
            try {
                newprop.setStringValue(rs.getString(i + 1 + offset));
            } catch (SQLException x) {
                Reader in = rs.getCharacterStream(i + 1 + offset);
                char[] buffer = new char[2048];
                int read = 0;
                int r;

                while ((r = in.read(buffer, read, buffer.length - read)) > -1) {
                    read += r;

                    if (read == buffer.length) {
                        // grow input buffer
                        char[] newBuffer = new char[buffer.length * 2];

                        System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
                        buffer = newBuffer;
                    }
                }

                newprop.setStringValue(new String(buffer, 0, read));
            }

            break;

        case Types.CHAR:
        case Types.VARCHAR:
        case Types.OTHER:
            newprop.setStringValue(rs.getString(i + 1 + offset));

            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            newprop.setDateValue(rs.getTimestamp(i + 1 + offset));

            break;

        case Types.NULL:
            newprop.setStringValue(null);

            break;

        case Types.CLOB:
            Clob cl = rs.getClob(i + 1 + offset);
            if (cl == null) {
                newprop.setStringValue(null);
                break;
            }
            char[] c = new char[(int) cl.length()];
            Reader isr = cl.getCharacterStream();
            isr.read(c);
            newprop.setStringValue(String.copyValueOf(c));
            break;

        default:
            newprop.setStringValue(rs.getString(i + 1 + offset));

            break;
        }

        if (rs.wasNull()) {
            newprop.setStringValue(null);
        }

        propBuffer.put(columns[i].getName(), newprop);

        // mark property as clean, since it's fresh from the db
        newprop.dirty = false;
    }

    if (id == null) {
        return null;
    }

    Hashtable propMap = new Hashtable();
    DbColumn[] columns2 = dbmap.getColumns();
    for (int i = 0; i < columns2.length; i++) {
        Relation rel = columns2[i].getRelation();

        if (rel != null && (rel.reftype == Relation.PRIMITIVE || rel.reftype == Relation.REFERENCE)) {

            Property prop = (Property) propBuffer.get(columns2[i].getName());

            if (prop == null) {
                continue;
            }
            prop.setName(rel.propName);
            // if the property is a pointer to another node, change the property type to NODE
            if ((rel.reftype == Relation.REFERENCE) && rel.usesPrimaryKey()) {
                // FIXME: References to anything other than the primary key are not supported
                prop.convertToNodeReference(rel.otherType, this.app.getCurrentRequestEvaluator().getLayer());
            }
            propMap.put(rel.propName.toLowerCase(), prop);
        }
    }

    node.init(dbmap, id, name, protoName, propMap, safe);

    return node;
}

From source file:com.flexive.core.search.PropertyEntry.java

/**
 * Return the result value of this property entry in a given result set.
 *
 * @param rs       the SQL result set//w ww.j  a  v  a  2s  .co  m
 * @param languageId id of the requested language
 * @param xpathAvailable if the XPath was selected as an additional column for content table entries
 * @param typeId    the result row type ID (if available, otherwise -1)
 * @return the value of this property (column) in the result set
 * @throws FxSqlSearchException if the database cannot read the value
 */
public Object getResultValue(ResultSet rs, long languageId, boolean xpathAvailable, long typeId)
        throws FxSqlSearchException {
    final FxValue result;
    final int pos = positionInResultSet;
    // Handle by type
    try {
        switch (overrideDataType == null ? property.getDataType() : overrideDataType) {
        case DateTime:
            switch (rs.getMetaData().getColumnType(pos)) {
            case java.sql.Types.BIGINT:
            case java.sql.Types.DECIMAL:
            case java.sql.Types.NUMERIC:
            case java.sql.Types.INTEGER:
                result = new FxDateTime(multilanguage, FxLanguage.SYSTEM_ID, new Date(rs.getLong(pos)));
                break;
            default:
                Timestamp dttstp = rs.getTimestamp(pos);
                Date _dtdate = dttstp != null ? new Date(dttstp.getTime()) : null;
                result = new FxDateTime(multilanguage, FxLanguage.SYSTEM_ID, _dtdate);
                if (dttstp == null)
                    result.setEmpty(FxLanguage.SYSTEM_ID);
            }
            break;
        case Date:
            Timestamp tstp = rs.getTimestamp(pos);
            result = new FxDate(multilanguage, FxLanguage.SYSTEM_ID,
                    tstp != null ? new Date(tstp.getTime()) : null);
            if (tstp == null) {
                result.setEmpty();
            }
            break;
        case DateRange:
            final Pair<Date, Date> pair = decodeDateRange(rs, pos, 1);
            if (pair.getFirst() == null || pair.getSecond() == null) {
                result = new FxDateRange(multilanguage, FxLanguage.SYSTEM_ID, FxDateRange.EMPTY);
                result.setEmpty(FxLanguage.SYSTEM_ID);
            } else {
                result = new FxDateRange(multilanguage, FxLanguage.SYSTEM_ID,
                        new DateRange(pair.getFirst(), pair.getSecond()));
            }
            break;
        case DateTimeRange:
            final Pair<Date, Date> pair2 = decodeDateRange(rs, pos, 1);
            if (pair2.getFirst() == null || pair2.getSecond() == null) {
                result = new FxDateTimeRange(multilanguage, FxLanguage.SYSTEM_ID, FxDateRange.EMPTY);
                result.setEmpty(FxLanguage.SYSTEM_ID);
            } else {
                result = new FxDateTimeRange(new DateRange(pair2.getFirst(), pair2.getSecond()));
            }
            break;
        case HTML:
            result = new FxHTML(multilanguage, FxLanguage.SYSTEM_ID, rs.getString(pos));
            break;
        case String1024:
        case Text:
            result = new FxString(multilanguage, FxLanguage.SYSTEM_ID, rs.getString(pos));
            break;
        case LargeNumber:
            result = new FxLargeNumber(multilanguage, FxLanguage.SYSTEM_ID, rs.getLong(pos));
            break;
        case Number:
            result = new FxNumber(multilanguage, FxLanguage.SYSTEM_ID, rs.getInt(pos));
            break;
        case Float:
            result = new FxFloat(multilanguage, FxLanguage.SYSTEM_ID, rs.getFloat(pos));
            break;
        case Boolean:
            result = new FxBoolean(multilanguage, FxLanguage.SYSTEM_ID, rs.getBoolean(pos));
            break;
        case Double:
            result = new FxDouble(multilanguage, FxLanguage.SYSTEM_ID, rs.getDouble(pos));
            break;
        case Reference:
            result = new FxReference(new ReferencedContent(new FxPK(rs.getLong(pos), FxPK.MAX))); // TODO!!
            break;
        case SelectOne:
            FxSelectListItem oneItem = getEnvironment().getSelectListItem(rs.getLong(pos));
            result = new FxSelectOne(multilanguage, FxLanguage.SYSTEM_ID, oneItem);
            break;
        case SelectMany:
            FxSelectListItem manyItem = getEnvironment().getSelectListItem(rs.getLong(pos));
            SelectMany valueMany = new SelectMany(manyItem.getList());
            valueMany.selectFromList(rs.getString(pos + 1));
            result = new FxSelectMany(multilanguage, FxLanguage.SYSTEM_ID, valueMany);
            break;
        case Binary:
            result = new FxBinary(multilanguage, FxLanguage.SYSTEM_ID, DataSelector.decodeBinary(rs, pos));
            break;
        default:
            throw new FxSqlSearchException(LOG, "ex.sqlSearch.reader.UnknownColumnType",
                    String.valueOf(getProperty().getDataType()));
        }

        if (rs.wasNull()) {
            result.setEmpty(languageId);
        }

        int currentPosition = positionInResultSet + getReadColumns().length;

        // process XPath
        if (isProcessXPath()) {
            if (xpathAvailable && getTableType() == PropertyResolver.Table.T_CONTENT_DATA) {
                // Get the XPATH if we are reading from the content data table
                result.setXPath(rebuildXPath(rs.getString(currentPosition++)));
            } else if (xpathAvailable && getTableType() == PropertyResolver.Table.T_CONTENT
                    && property != null) {
                // set XPath for system-internal properties
                result.setXPath("ROOT/" + property.getName());
            } else if (getTableType() == PropertyResolver.Table.T_CONTENT_DATA_FLAT) {
                // fill in XPath from assignment, create XPath with full type information
                if (typeId != -1) {
                    result.setXPath(getEnvironment().getType(typeId).getName() + "/" + assignment.getAlias());
                }
            }
        } else {
            result.setXPath(null);
        }

        // process data
        if (isProcessData() && getTableType() != null) {
            final Integer valueData;
            switch (getTableType()) {
            case T_CONTENT_DATA:
                final int data = rs.getInt(currentPosition++);
                valueData = rs.wasNull() ? null : data;
                break;
            case T_CONTENT_DATA_FLAT:
                // comma-separated string with the data entries of all columns
                final String csvData = rs.getString(currentPosition++);
                valueData = FxArrayUtils.getHexIntElementAt(csvData, ',', flatColumnIndex);
                break;
            default:
                // no value data in other tables
                valueData = null;
            }
            result.setValueData(languageId, valueData);
        }

        return result;
    } catch (SQLException e) {
        throw new FxSqlSearchException(e);
    }
}

From source file:dbservlet.Servlet.java

public void update(HttpServletRequest request, HttpServletResponse response)
        throws ClassNotFoundException, SQLException, ServletException, IOException {
    Connection conn = null;/*from   w ww  .j a  v a  2 s .com*/
    Statement stat = null;
    ResultSet rs = null;
    ResultSet rs0 = null;
    ResultSet rs1 = null;
    ResultSet rs2 = null;
    String data = request.getParameter("data");
    StringBuilder html = new StringBuilder();
    JSONArray datalist = null;
    JSONObject input = null;
    try {
        input = new JSONObject(data);
    } catch (JSONException ex) {
        Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        datalist = input.getJSONArray("data");
    } catch (JSONException ex) {
        Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    Date now = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
    String BuyDate = dateFormat.format(now);
    System.out.println(BuyDate);
    for (int i = 0; i < datalist.length(); i++) {
        String product_ID = "";
        String quantity = "";
        String customer_ID = "";
        //String BuyDate="";
        String salesperson_id = "";
        try {
            product_ID = (String) datalist.getJSONObject(i).get("id");
            quantity = (String) datalist.getJSONObject(i).get("amount");
            customer_ID = (String) datalist.getJSONObject(i).get("customer_ID");
            //BuyDate = (String) datalist.getJSONObject(i).get("BuyDate");
            salesperson_id = (String) datalist.getJSONObject(i).get("salesperson_id");
            if (salesperson_id.length() != 7) {
                response.getWriter().print("0");
                return;
            }
            //System.out.println(salesperson_id);
        } catch (JSONException ex) {
            Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        conn = connect();
        stat = conn.createStatement();
        rs = stat.executeQuery(
                "select salesperson_id,customer_ID from Salespersons,Customers_Info where salesperson_id="
                        + salesperson_id + " and customer_ID=" + customer_ID + "");
        //System.out.print(rs.getString(salesperson_id));
        if (!rs.first()) {

            response.getWriter().print("0");
            System.out.print(rs);

        } else {
            try {
                int intage = Integer.parseInt(quantity);
                rs1 = stat.executeQuery(
                        "select inventory_amount from Products where product_ID=" + product_ID + "");
                if (rs1.next()) {
                    int initage = rs1.getInt("inventory_amount");
                    int quantityresult = initage - intage;
                    String s = String.valueOf(quantityresult);
                    stat.execute("update Products set inventory_amount=" + s + " where product_ID=" + product_ID
                            + "");
                    response.getWriter().print("1");
                    request.setAttribute("result", select(product_ID, ""));
                } else {
                    response.getWriter().print("0");
                }
            } catch (Exception e) {
                //                     System.out.println("fuck1");
                //                     request.getRequestDispatcher("productwrong.jsp").forward(request, response);
            }

            try {
                rs1 = stat.executeQuery("select MAX(order_number) from Transactions");
                int orderNumber;
                if (rs1.next()) {
                    orderNumber = 1 + rs1.getInt(1);
                } else {
                    orderNumber = 1;
                }

                String ran = String.valueOf(orderNumber);
                while (ran.length() < 7) {
                    ran = 0 + ran;
                }
                stat.execute(
                        "INSERT INTO `Transactions`(`order_number`, `BuyDate`, `salesperson_id`, `customer_ID`, `product_ID`, `quantity`) VALUES ('"
                                + ran + "','" + BuyDate + "','" + salesperson_id + "','" + customer_ID + "','"
                                + product_ID + "','" + quantity + "')");

            } catch (Exception e) {

                request.getRequestDispatcher("tranwrong.jsp").forward(request, response);
            }

            try {
                int initquan = Integer.parseInt(quantity);
                rs1 = stat.executeQuery("select * from Products where product_ID=" + product_ID + "");
                rs1.next();

                double initprice = rs1.getDouble("price");

                rs2 = stat
                        .executeQuery("select * from Salespersons where salesperson_id=" + salesperson_id + "");
                rs2.next();
                double salesvolume = rs2.getDouble("sales_volume");

                double finalresult = salesvolume + initprice * initquan;

                stat.execute("update Salespersons set sales_volume=" + finalresult + " where salesperson_id="
                        + salesperson_id + "");
                //request.getRequestDispatcher("update.jsp").forward(request, response);
            } catch (Exception e) {
                System.out.println("hello");
                request.getRequestDispatcher("salewrong.jsp").forward(request, response);
            }
        }

        //            html.append("");
        //            String result=html.toString();
        //response.getWriter().print("sucess");
        //request.getRequestDispatcher("salewrong.jsp").forward(request, response);
    }
}

From source file:com.sundevils.web.controller.TopController.java

@RequestMapping(value = "/AccountView", method = { RequestMethod.POST, RequestMethod.GET })
public ModelAndView viewAccount(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws IOException {
    ModelAndView model = null;/*  ww  w  .j a va  2s.c o  m*/
    ResultSet rs = null;
    ResultSet rs_details = null;
    ResultSet rs_details_personal = null;
    String ViewDetails = "";
    String ViewUserSelect = null;
    String role = (String) session.getAttribute("Role");
    try {
        if (role == null) {
            model = new ModelAndView();
            model.setViewName("index");
            return model;
        } else if (role.equals("EMPLOYEE")) {
            try {

                model = new ModelAndView();
                ViewAccounts handler = new ViewAccounts();
                List<AccountDetails> accountReqstdetails = new ArrayList<AccountDetails>();
                rs = handler.requestAccountHandler();
                try {
                    while (rs.next()) {
                        AccountDetails view = new AccountDetails();
                        view.setUserName(rs.getString("requestfrom"));
                        accountReqstdetails.add(view);
                    }

                    model.addObject("accountView", accountReqstdetails);
                    //request.setAttribute(", o);
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    LoginHandler handler_logout;
                    handler_logout = new LoginHandler();
                    String userSessionName = (String) session.getAttribute("USERNAME");
                    handler_logout.updateLoggedInFlag(userSessionName, 0);
                    model.setViewName("index");
                    LOG.error("Issue while viewing the account" + e.getMessage());
                }
                if (request.getParameter("submit") != null) {
                    ViewDetails = request.getParameter("Type");
                    ViewUserSelect = request.getParameter("radio");
                    if (ViewUserSelect == null) {
                        model.addObject("Select", "No User selected");
                        model.setViewName("AccountDetails");
                        return model;
                    }
                    List<AccountDetails> accountDetailsView = new ArrayList<AccountDetails>();
                    if (ViewDetails.equals("Account")) {
                        rs_details = handler.requestAccountDetailsHandler(ViewUserSelect);
                        try {
                            while (rs_details.next()) {
                                AccountDetails view = new AccountDetails();
                                view.setUserNameAccount(rs_details.getString("username"));
                                view.setAccountNumber(rs_details.getString("accountnumber"));
                                view.setAccountType(rs_details.getString("accounttype"));
                                view.setBalance(rs_details.getDouble("balance"));
                                accountDetailsView.add(view);
                            }
                            model.addObject("AccountDetails", "1");
                            model.addObject("accountDetailsView", accountDetailsView);
                            //request.setAttribute(", o);
                        } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            LoginHandler handler_logout;
                            handler_logout = new LoginHandler();
                            String userSessionName = (String) session.getAttribute("USERNAME");
                            handler_logout.updateLoggedInFlag(userSessionName, 0);
                            model.setViewName("index");
                            LOG.error("Issue while getting the account details " + e.getMessage());
                        }
                    }
                    if (ViewDetails.equals("Personal")) {
                        rs_details_personal = handler.requestPersonalDetailsHandler(ViewUserSelect);
                        List<PersonalDetails> personalDetailsView = new ArrayList<PersonalDetails>();
                        try {
                            while (rs_details_personal.next()) {
                                PersonalDetails view = new PersonalDetails();
                                view.setFirstName(rs_details_personal.getString("firstname"));
                                view.setLastName(rs_details_personal.getString("lastname"));
                                view.setAddress(rs_details_personal.getString("address"));
                                view.setGender(rs_details_personal.getString("gender"));
                                view.setState(rs_details_personal.getString("state"));
                                view.setZip(rs_details_personal.getString("zip"));
                                view.setPhonenumber(rs_details_personal.getString("phonenumber"));
                                view.setDob(rs_details_personal.getString("dateofbirth"));
                                view.setEmail(rs_details_personal.getString("email"));
                                personalDetailsView.add(view);
                            }
                            model.addObject("PersonalDetails", "1");
                            model.addObject("personalDetailsView", personalDetailsView);
                            //request.setAttribute(", o);
                        } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            LoginHandler handler_logout;
                            handler_logout = new LoginHandler();
                            String userSessionName = (String) session.getAttribute("USERNAME");
                            handler_logout.updateLoggedInFlag(userSessionName, 0);
                            model.setViewName("index");
                            LOG.error("Issue while getting the personal details " + e.getMessage());
                        }
                    }
                }
            } catch (Exception e) {
                LoginHandler handler_logout;
                handler_logout = new LoginHandler();
                String userSessionName = (String) session.getAttribute("USERNAME");
                handler_logout.updateLoggedInFlag(userSessionName, 0);
                model.setViewName("index");
                LOG.error("Issue while getting the personal details " + e.getMessage());
                LOG.error("Issue while viewing the account" + e.getMessage());
            }

            model.setViewName("AccountDetails");
        } else {
            model = new ModelAndView();
            LoginHandler handler = new LoginHandler();
            String userName = (String) session.getAttribute("USERNAME");
            handler.updateLoggedInFlag(userName, 0);
            session.invalidate();
            model.setViewName("index");
        }
    } catch (Exception e) {
        LoginHandler handler_logout;
        handler_logout = new LoginHandler();
        String userSessionName = (String) session.getAttribute("USERNAME");
        handler_logout.updateLoggedInFlag(userSessionName, 0);
        model.setViewName("index");
        LOG.error("Issue while viewing the account" + e.getMessage());
    } finally {
        try {
            if (rs_details != null) {
                rs_details.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            if (rs_details_personal != null) {
                rs_details_personal.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return model;
}

From source file:interfazGrafica.loginInterface.java

private void aceptarConsultarCotActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptarConsultarCotActionPerformed
    // TODO add your handling code here:
    try {//from   w  w w  .  java 2 s  .  com
        Cotizaciones cot = new Cotizaciones();
        int codCot = Integer.parseInt(codCotConsultarCot.getText());
        String codCotS = "" + codCot;
        ResultSet tabla = cot.consultarCotizacion(codCotS);
        while (tabla.next()) {
            codVendedorConsultarCot.setText(tabla.getString("nombre_usuario"));
            codCompradorConsultarCot.setText(tabla.getString("nombre_comprador"));
            codVehiculoConsultarCot.setText(tabla.getString("marca_vehiculo"));
            double valor = tabla.getDouble("valor_vehiculo");
            valor = valor + valor * 0.16;
            valorTotalConsultarCot.setText("" + valor);
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
    } catch (NumberFormatException ex) {
        JOptionPane.showMessageDialog(null, "El codigo de la cotizacion debe ser un numero", "Error",
                JOptionPane.ERROR_MESSAGE);
    }

}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncDAO.java

public void exportChildDB(String uuidForChild, OutputStream os) throws DAOException {
    PrintStream out = new PrintStream(os);
    Set<String> tablesToSkip = new HashSet<String>();
    {/*from   w  ww.j  a va 2  s . c om*/
        tablesToSkip.add("hl7_in_archive");
        tablesToSkip.add("hl7_in_queue");
        tablesToSkip.add("hl7_in_error");
        tablesToSkip.add("formentry_archive");
        tablesToSkip.add("formentry_queue");
        tablesToSkip.add("formentry_error");
        tablesToSkip.add("sync_class");
        tablesToSkip.add("sync_import");
        tablesToSkip.add("sync_record");
        tablesToSkip.add("sync_server");
        tablesToSkip.add("sync_server_class");
        tablesToSkip.add("sync_server_record");
        // TODO: figure out which other tables to skip
        // tablesToSkip.add("obs");
        // tablesToSkip.add("concept");
        // tablesToSkip.add("patient");
    }
    List<String> tablesToDump = new ArrayList<String>();
    Session session = sessionFactory.getCurrentSession();
    String schema = (String) session.createSQLQuery("SELECT schema()").uniqueResult();
    log.warn("schema: " + schema);
    // Get all tables that we'll need to dump
    {
        Query query = session.createSQLQuery(
                "SELECT tabs.table_name FROM INFORMATION_SCHEMA.TABLES tabs WHERE tabs.table_schema = '"
                        + schema + "'");
        for (Object tn : query.list()) {
            String tableName = (String) tn;
            if (!tablesToSkip.contains(tableName.toLowerCase()))
                tablesToDump.add(tableName);
        }
    }
    log.warn("tables to dump: " + tablesToDump);

    String thisServerGuid = getGlobalProperty(SyncConstants.PROPERTY_SERVER_UUID);

    // Write the DDL Header as mysqldump does
    {
        out.println("-- ------------------------------------------------------");
        out.println("-- Database dump to create an openmrs child server");
        out.println("-- Schema: " + schema);
        out.println("-- Parent GUID: " + thisServerGuid);
        out.println("-- Parent version: " + OpenmrsConstants.OPENMRS_VERSION);
        out.println("-- ------------------------------------------------------");
        out.println("");
        out.println("/*!40101 SET CHARACTER_SET_CLIENT=utf8 */;");
        out.println("/*!40101 SET NAMES utf8 */;");
        out.println("/*!40103 SET TIME_ZONE='+00:00' */;");
        out.println("/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;");
        out.println("/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;");
        out.println("/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;");
        out.println("/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;");
        out.println("/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;");
        out.println("/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;");
        out.println("/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;");
        out.println("/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;");
        out.println("");
    }
    try {
        // JDBC way of doing this
        // Connection conn =
        // DriverManager.getConnection("jdbc:mysql://localhost/" + schema,
        // "test", "test");
        Connection conn = sessionFactory.getCurrentSession().connection();
        try {
            Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

            // Get the create database statement
            ResultSet rs = st.executeQuery("SHOW CREATE DATABASE " + schema);
            for (String tableName : tablesToDump) {
                out.println();
                out.println("--");
                out.println("-- Table structure for table `" + tableName + "`");
                out.println("--");
                out.println("DROP TABLE IF EXISTS `" + tableName + "`;");
                out.println("SET @saved_cs_client     = @@character_set_client;");
                out.println("SET character_set_client = utf8;");
                rs = st.executeQuery("SHOW CREATE TABLE " + tableName);
                while (rs.next()) {
                    out.println(rs.getString("Create Table") + ";");
                }
                out.println("SET character_set_client = @saved_cs_client;");
                out.println();

                {
                    out.println("-- Dumping data for table `" + tableName + "`");
                    out.println("LOCK TABLES `" + tableName + "` WRITE;");
                    out.println("/*!40000 ALTER TABLE `" + tableName + "` DISABLE KEYS */;");
                    boolean first = true;

                    rs = st.executeQuery("select * from " + tableName);
                    ResultSetMetaData md = rs.getMetaData();
                    int numColumns = md.getColumnCount();
                    int rowNum = 0;
                    boolean insert = false;

                    while (rs.next()) {
                        if (rowNum == 0) {
                            insert = true;
                            out.print("INSERT INTO `" + tableName + "` VALUES ");
                        }
                        ++rowNum;
                        if (first) {
                            first = false;
                        } else {
                            out.print(", ");
                        }
                        if (rowNum % 20 == 0) {
                            out.println();
                        }
                        out.print("(");
                        for (int i = 1; i <= numColumns; ++i) {
                            if (i != 1) {
                                out.print(",");
                            }
                            if (rs.getObject(i) == null) {
                                out.print("NULL");
                            } else {
                                switch (md.getColumnType(i)) {
                                case Types.VARCHAR:
                                case Types.CHAR:
                                case Types.LONGVARCHAR:
                                    out.print("'");
                                    out.print(
                                            rs.getString(i).replaceAll("\n", "\\\\n").replaceAll("'", "\\\\'"));
                                    out.print("'");
                                    break;
                                case Types.BIGINT:
                                case Types.DECIMAL:
                                case Types.NUMERIC:
                                    out.print(rs.getBigDecimal(i));
                                    break;
                                case Types.BIT:
                                    out.print(rs.getBoolean(i));
                                    break;
                                case Types.INTEGER:
                                case Types.SMALLINT:
                                case Types.TINYINT:
                                    out.print(rs.getInt(i));
                                    break;
                                case Types.REAL:
                                case Types.FLOAT:
                                case Types.DOUBLE:
                                    out.print(rs.getDouble(i));
                                    break;
                                case Types.BLOB:
                                case Types.VARBINARY:
                                case Types.LONGVARBINARY:
                                    Blob blob = rs.getBlob(i);
                                    out.print("'");
                                    InputStream in = blob.getBinaryStream();
                                    while (true) {
                                        int b = in.read();
                                        if (b < 0) {
                                            break;
                                        }
                                        char c = (char) b;
                                        if (c == '\'') {
                                            out.print("\'");
                                        } else {
                                            out.print(c);
                                        }
                                    }
                                    out.print("'");
                                    break;
                                case Types.CLOB:
                                    out.print("'");
                                    out.print(
                                            rs.getString(i).replaceAll("\n", "\\\\n").replaceAll("'", "\\\\'"));
                                    out.print("'");
                                    break;
                                case Types.DATE:
                                    out.print("'" + rs.getDate(i) + "'");
                                    break;
                                case Types.TIMESTAMP:
                                    out.print("'" + rs.getTimestamp(i) + "'");
                                    break;
                                default:
                                    throw new RuntimeException("TODO: handle type code " + md.getColumnType(i)
                                            + " (name " + md.getColumnTypeName(i) + ")");
                                }
                            }
                        }
                        out.print(")");
                    }
                    if (insert) {
                        out.println(";");
                        insert = false;
                    }

                    out.println("/*!40000 ALTER TABLE `" + tableName + "` ENABLE KEYS */;");
                    out.println("UNLOCK TABLES;");
                    out.println();
                }
            }
        } finally {
            conn.close();
        }

        // Now we mark this as a child
        out.println("-- Now mark this as a child database");
        if (uuidForChild == null)
            uuidForChild = SyncUtil.generateUuid();
        out.println("update global_property set property_value = '" + uuidForChild + "' where property = '"
                + SyncConstants.PROPERTY_SERVER_UUID + "';");

        // Write the footer of the DDL script
        {
            out.println("/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;");
            out.println("/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;");
            out.println("/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;");
            out.println("/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;");
            out.println("/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;");
            out.println("/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;");
            out.println("/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;");
            out.println("/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;");
        }
        out.flush();
        out.close();
    } catch (IOException ex) {
        log.error("IOException", ex);

    } catch (SQLException ex) {
        log.error("SQLException", ex);
    }
}

From source file:com.sdcs.courierbooking.service.UserServiceImpl.java

@Override
public String authenticateAdminDetails(String strAdminDate) {
    JSONObject sdcsAdminDetailsJson = new JSONObject();
    ResultSet resultsetAdmin = userDao.authenticateAdminDetails(strAdminDate);
    if (resultsetAdmin != null) {
        double oneDayCourier = 0;
        double oneDayCourierAmount = 0;
        double HtoHCourier = 0;
        double HtoHCourierAmount = 0;
        double fourHourCourier = 0;
        double fourHourCourierAmount = 0;
        double ConfidentialCourier = 0;
        double ConfidentialCourierAmount = 0;
        double airportCourier = 0;
        double airportCourierAmount = 0;
        double totalAmount = 0;
        double totalCourier = 0;
        double undispatchedoneDayCourier = 0;
        double undispatchedoneDayCourierAmount = 0;
        double undispatchedHtoHCourier = 0;
        double undispatchedHtoHCourierAmount = 0;
        double undispatchedfourHourCourier = 0;
        double undispatchedfourHourCourierAmount = 0;
        double undispatchedConfidentialCourier = 0;
        double undispatchedConfidentialCourierAmount = 0;
        double undispatchedairportCourier = 0;
        double undispatchedairportCourierAmount = 0;
        double undispatchedtotalAmount = 0;
        double undispatchedtotalCourier = 0;
        double dispatchedoneDayCourier = 0;
        double dispatchedoneDayCourierAmount = 0;
        double dispatchedHtoHCourier = 0;
        double dispatchedHtoHCourierAmount = 0;
        double dispatchedfourHourCourier = 0;
        double dispatchedfourHourCourierAmount = 0;
        double dispatchedConfidentialCourier = 0;
        double dispatchedConfidentialCourierAmount = 0;
        double dispatchedairportCourier = 0;
        double dispatchedairportCourierAmount = 0;
        double dispatchedtotalAmount = 0;
        double dispatchedtotalCourier = 0;
        double deliveredoneDayCourier = 0;
        double deliveredoneDayCourierAmount = 0;
        double deliveredHtoHCourier = 0;
        double deliveredHtoHCourierAmount = 0;
        double deliveredfourHourCourier = 0;
        double deliveredfourHourCourierAmount = 0;
        double deliveredConfidentialCourier = 0;
        double deliveredConfidentialCourierAmount = 0;
        double deliveredairportCourier = 0;
        double deliveredairportCourierAmount = 0;
        double deliveredtotalAmount = 0;
        double deliveredtotalCourier = 0;

        try {//w w  w.  j  a v a  2  s  .c o m
            while (resultsetAdmin.next()) {
                if (resultsetAdmin.getByte("deliver_in_one_day") == 1) {
                    oneDayCourier += 1;
                    oneDayCourierAmount += resultsetAdmin.getDouble("total_amount");
                    if (resultsetAdmin.getInt("delivery_taken") == 1) {
                        dispatchedoneDayCourier += 1;
                        dispatchedoneDayCourierAmount += resultsetAdmin.getDouble("total_amount");
                    } else if (resultsetAdmin.getInt("delivery_taken") == 0) {
                        undispatchedoneDayCourier += 1;
                        undispatchedoneDayCourierAmount += resultsetAdmin.getDouble("total_amount");
                    } else {
                        deliveredoneDayCourier += 1;
                        deliveredoneDayCourierAmount += resultsetAdmin.getDouble("total_amount");
                    }
                } else if (resultsetAdmin.getByte("deliver_in_four_hour") == 1) {
                    fourHourCourier += 1;
                    fourHourCourierAmount += resultsetAdmin.getDouble("total_amount");
                    if (resultsetAdmin.getInt("delivery_taken") == 1) {
                        dispatchedfourHourCourier += 1;
                        dispatchedfourHourCourierAmount += resultsetAdmin.getDouble("total_amount");
                    } else if (resultsetAdmin.getInt("delivery_taken") == 0) {
                        undispatchedfourHourCourier += 1;
                        undispatchedfourHourCourierAmount += resultsetAdmin.getDouble("total_amount");
                    } else {
                        deliveredfourHourCourier += 1;
                        deliveredfourHourCourierAmount += resultsetAdmin.getDouble("total_amount");
                    }

                } else if (resultsetAdmin.getByte("confidential_delivery") == 1) {
                    ConfidentialCourier += 1;
                    ConfidentialCourierAmount += resultsetAdmin.getDouble("total_amount");
                    if (resultsetAdmin.getInt("delivery_taken") == 1) {
                        dispatchedConfidentialCourier += 1;
                        dispatchedConfidentialCourierAmount += resultsetAdmin.getDouble("total_amount");
                    } else if (resultsetAdmin.getInt("delivery_taken") == 0) {
                        undispatchedConfidentialCourier += 1;
                        undispatchedConfidentialCourierAmount += resultsetAdmin.getDouble("total_amount");
                    } else {
                        deliveredConfidentialCourier += 1;
                        deliveredConfidentialCourierAmount += resultsetAdmin.getDouble("total_amount");
                    }

                } else if (resultsetAdmin.getByte("price_for_Airport_delivery") == 1) {
                    airportCourier += 1;
                    airportCourierAmount += resultsetAdmin.getDouble("total_amount");
                    if (resultsetAdmin.getInt("delivery_taken") == 1) {
                        dispatchedairportCourier += 1;
                        dispatchedairportCourierAmount += resultsetAdmin.getDouble("total_amount");
                    } else if (resultsetAdmin.getInt("delivery_taken") == 0) {
                        undispatchedairportCourier += 1;
                        undispatchedairportCourierAmount += resultsetAdmin.getDouble("total_amount");
                    } else {
                        deliveredairportCourier += 1;
                        deliveredairportCourierAmount += resultsetAdmin.getDouble("total_amount");
                    }

                } else if (resultsetAdmin.getByte("deliver_hand_to_hand") == 1) {
                    HtoHCourier += 1;
                    HtoHCourierAmount += resultsetAdmin.getDouble("total_amount");
                    if (resultsetAdmin.getInt("delivery_taken") == 1) {
                        dispatchedHtoHCourier += 1;
                        dispatchedHtoHCourierAmount += resultsetAdmin.getDouble("total_amount");
                    } else if (resultsetAdmin.getInt("delivery_taken") == 0) {
                        undispatchedHtoHCourier += 1;
                        undispatchedHtoHCourierAmount += resultsetAdmin.getDouble("total_amount");
                    } else {
                        deliveredHtoHCourier += 1;
                        deliveredHtoHCourierAmount += resultsetAdmin.getDouble("total_amount");
                    }

                }
                totalCourier += 1;
                totalAmount += resultsetAdmin.getDouble("total_amount");
                if (resultsetAdmin.getInt("delivery_taken") == 1) {
                    dispatchedtotalCourier += 1;
                    dispatchedtotalAmount += resultsetAdmin.getDouble("total_amount");
                } else if (resultsetAdmin.getInt("delivery_taken") == 0) {
                    undispatchedtotalCourier += 1;
                    undispatchedtotalAmount += resultsetAdmin.getDouble("total_amount");
                } else {
                    deliveredtotalCourier += 1;
                    deliveredtotalAmount += resultsetAdmin.getDouble("total_amount");
                }

            }
            resultsetAdmin.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JSONArray bookedhistories = new JSONArray();

        JSONObject history = new JSONObject();
        history.put("deliver_in_one_day", Double.valueOf(oneDayCourier).toString());
        history.put("deliver_in_four_hour", Double.valueOf(fourHourCourier).toString());
        history.put("confidential_delivery", Double.valueOf(ConfidentialCourier).toString());
        history.put("price_for_Airport_delivery", Double.valueOf(airportCourier).toString());
        history.put("deliver_hand_to_hand", Double.valueOf(HtoHCourier).toString());
        history.put("oneDayCourierAmount", Double.valueOf(oneDayCourierAmount).toString());
        history.put("HtoHCourierAmount", Double.valueOf(HtoHCourierAmount).toString());
        history.put("fourHourCourierAmount", Double.valueOf(fourHourCourierAmount).toString());
        history.put("ConfidentialCourierAmount", Double.valueOf(ConfidentialCourierAmount).toString());
        history.put("airportCourierAmount", Double.valueOf(airportCourierAmount).toString());
        history.put("totalAmount", Double.valueOf(totalAmount).toString());
        history.put("totalCourier", Double.valueOf(totalCourier).toString());
        history.put("discription", "Booked Couriers");
        history.put("discriptiona", "4");
        bookedhistories.put(history);

        JSONObject historya = new JSONObject();
        historya.put("deliver_in_one_day", Double.valueOf(dispatchedoneDayCourier).toString());
        historya.put("deliver_in_four_hour", Double.valueOf(dispatchedfourHourCourier).toString());
        historya.put("confidential_delivery", Double.valueOf(dispatchedConfidentialCourier).toString());
        historya.put("price_for_Airport_delivery", Double.valueOf(dispatchedairportCourier).toString());
        historya.put("deliver_hand_to_hand", Double.valueOf(dispatchedHtoHCourier).toString());
        historya.put("oneDayCourierAmount", Double.valueOf(dispatchedoneDayCourierAmount).toString());
        historya.put("HtoHCourierAmount", Double.valueOf(dispatchedHtoHCourierAmount).toString());
        historya.put("fourHourCourierAmount", Double.valueOf(dispatchedfourHourCourierAmount).toString());
        historya.put("ConfidentialCourierAmount",
                Double.valueOf(dispatchedConfidentialCourierAmount).toString());
        historya.put("airportCourierAmount", Double.valueOf(dispatchedairportCourierAmount).toString());
        historya.put("totalAmount", Double.valueOf(dispatchedtotalAmount).toString());
        historya.put("totalCourier", Double.valueOf(dispatchedtotalCourier).toString());
        historya.put("discription", "Inprogress Couriers");
        historya.put("discriptiona", "0");
        bookedhistories.put(historya);

        JSONObject historyb = new JSONObject();
        historyb.put("deliver_in_one_day", Double.valueOf(undispatchedoneDayCourier).toString());
        historyb.put("deliver_in_four_hour", Double.valueOf(undispatchedfourHourCourier).toString());
        historyb.put("confidential_delivery", Double.valueOf(undispatchedConfidentialCourier).toString());
        historyb.put("price_for_Airport_delivery", Double.valueOf(undispatchedairportCourier).toString());
        historyb.put("deliver_hand_to_hand", Double.valueOf(undispatchedHtoHCourier).toString());
        historyb.put("oneDayCourierAmount", Double.valueOf(undispatchedoneDayCourierAmount).toString());
        historyb.put("HtoHCourierAmount", Double.valueOf(undispatchedHtoHCourierAmount).toString());
        historyb.put("fourHourCourierAmount", Double.valueOf(undispatchedfourHourCourierAmount).toString());
        historyb.put("ConfidentialCourierAmount",
                Double.valueOf(undispatchedConfidentialCourierAmount).toString());
        historyb.put("airportCourierAmount", Double.valueOf(undispatchedairportCourierAmount).toString());
        historyb.put("totalAmount", Double.valueOf(undispatchedtotalAmount).toString());
        historyb.put("totalCourier", Double.valueOf(undispatchedtotalCourier).toString());
        historyb.put("discription", "Undispatched Couriers");
        historyb.put("discriptiona", "1");
        bookedhistories.put(historyb);

        JSONObject historyc = new JSONObject();
        historyc.put("deliver_in_one_day", Double.valueOf(deliveredoneDayCourier).toString());
        historyc.put("deliver_in_four_hour", Double.valueOf(deliveredfourHourCourier).toString());
        historyc.put("confidential_delivery", Double.valueOf(deliveredConfidentialCourier).toString());
        historyc.put("price_for_Airport_delivery", Double.valueOf(deliveredairportCourier).toString());
        historyc.put("deliver_hand_to_hand", Double.valueOf(deliveredHtoHCourier).toString());
        historyc.put("oneDayCourierAmount", Double.valueOf(deliveredoneDayCourierAmount).toString());
        historyc.put("HtoHCourierAmount", Double.valueOf(deliveredHtoHCourierAmount).toString());
        historyc.put("fourHourCourierAmount", Double.valueOf(deliveredfourHourCourierAmount).toString());
        historyc.put("ConfidentialCourierAmount",
                Double.valueOf(deliveredConfidentialCourierAmount).toString());
        historyc.put("airportCourierAmount", Double.valueOf(deliveredairportCourierAmount).toString());
        historyc.put("totalAmount", Double.valueOf(deliveredtotalAmount).toString());
        historyc.put("totalCourier", Double.valueOf(deliveredtotalCourier).toString());
        historyc.put("discription", "Delivered Couriers");
        historyc.put("discriptiona", "2");
        bookedhistories.put(historyc);

        sdcsAdminDetailsJson.put("couriersCalculations", bookedhistories);
        sdcsAdminDetailsJson.put("status", true);

        // TODO Auto-generated method stub

    } else {
        sdcsAdminDetailsJson.put("status", false);
    }
    return sdcsAdminDetailsJson.toString();
}

From source file:com.cmart.DB.CassandraDBQuery.java

@Override
public ArrayList<Item> getItemsByID(ArrayList<Long> itemIDs, int sortCol, Boolean sortDec, Boolean getimages,
        int numImages) throws Exception {
    ArrayList<Item> items = new ArrayList<Item>();

    if (sortDec == null || sortCol < 0)
        return items;

    Connection conn = this.getConnection();
    if (conn != null) {
        try {//from w  w w .ja v a2  s .c  o  m
            PreparedStatement statement;

            /*switch(sortCol){
               case 0: orderBy = "endDate"; break;
               case 1: orderBy = "currentBid"; break;
               case 2: orderBy = "endDate"; break;
               default: orderBy = "endDate"; break;
            }*/

            StringBuilder ids = new StringBuilder();
            ids.append("('0'");

            for (Long itemid : itemIDs) {
                ids.append(",'");
                ids.append(itemid);
                ids.append("'");
            }
            ids.append(");");

            statement = conn.prepareStatement("SELECT * FROM items WHERE KEY IN " + ids.toString());

            ResultSet rs = statement.executeQuery();

            while (rs.next()) {
                try {

                    // Cassandra can fail because items don't have all the info required
                    Item currentItem = null;
                    try {
                        ArrayList<Image> images = this.getItemImages(rs.getLong("KEY"));

                        currentItem = new Item(rs.getLong("KEY"), rs.getString("name"),
                                rs.getString("description"), rs.getInt("quantity"), rs.getDouble("startprice"),
                                rs.getDouble("reserveprice"), rs.getDouble("buynowprice"),
                                rs.getDouble("curbid"), rs.getDouble("maxbid"), rs.getInt("noofbids"),
                                new Date(rs.getLong("startdate")), new Date(rs.getLong("enddate")),
                                rs.getLong("sellerid"), rs.getLong("categoryid"), rs.getString("thumbnail"),
                                images);
                    } catch (Exception e) {
                    }

                    if (currentItem != null) {
                        items.add(currentItem);
                    }
                } catch (NullPointerException e) {
                }
            }

            // We now need to sort the items
            switch (sortCol) {
            case 1: {
                // lowest price first
                if (!sortDec) {
                    Collections.sort(items, new Comparator<Item>() {
                        public int compare(Item i1, Item i2) {
                            return i1.getCurrentBid() < i2.getCurrentBid() ? -1 : 1;
                        }
                    });
                }
                // highest price first, we have reversed the comparator operator
                else {
                    Collections.sort(items, new Comparator<Item>() {
                        public int compare(Item i1, Item i2) {
                            return i1.getCurrentBid() < i2.getCurrentBid() ? 1 : -1;
                        }
                    });
                }

                break;
            }
            default: {
                // Earliest expiration first
                if (!sortDec) {
                    Collections.sort(items, new Comparator<Item>() {
                        public int compare(Item i1, Item i2) {
                            return i1.getEndDate().before(i2.getEndDate()) ? -1 : 1;
                        }
                    });
                }
                // Latest expiration first
                else {
                    Collections.sort(items, new Comparator<Item>() {
                        public int compare(Item i1, Item i2) {
                            return i1.getEndDate().before(i2.getEndDate()) ? 1 : -1;
                        }
                    });
                }

                break;
            }
            }

            rs.close();
            statement.close();
        } catch (Exception e) {
            System.err.println("CassandraQuery (getItemsByID): Could not get the items");
            e.printStackTrace();
            throw e;
        }

        this.closeConnection(conn);
    }

    return items;
}

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

@SuppressWarnings("deprecation")
@Test// w w  w  .j  a  v a 2s  .  co m
public void testResultSetWhenClosed() throws Exception {
    Statement statement = getConnection().createStatement();
    ResultSet rs = statement.executeQuery(SQL_EMPS);

    rs.close();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    try {
        rs.getString(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getString("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBoolean(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBoolean("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getByte(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getByte("col1");
        fail();
    } catch (SQLException ignore) {
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    try {
        rs.getDate(1, null);
        fail();
    } catch (SQLException ignore) {
    }

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

    try {
        rs.getDate("col1", null);
        fail();
    } catch (SQLException ignore) {
    }

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

    try {
        rs.getTime(1, null);
        fail();
    } catch (SQLException ignore) {
    }

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

    try {
        rs.getTime("col1", null);
        fail();
    } catch (SQLException ignore) {
    }

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

    try {
        rs.getTimestamp(1, null);
        fail();
    } catch (SQLException ignore) {
    }

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

    try {
        rs.getTimestamp("col1", null);
        fail();
    } catch (SQLException ignore) {
    }

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

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

    try {
        rs.getUnicodeStream(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getUnicodeStream("col1");
        fail();
    } catch (SQLException ignore) {
    }

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

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

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

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

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

    try {
        rs.setFetchDirection(1);
        fail();
    } catch (SQLException ignore) {
    }

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

    try {
        rs.setFetchSize(100);
        fail();
    } catch (SQLException ignore) {
    }

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

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

    statement.close();
}