Example usage for java.sql ResultSet getByte

List of usage examples for java.sql ResultSet getByte

Introduction

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

Prototype

byte getByte(String columnLabel) throws SQLException;

Source Link

Document

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

Usage

From source file:com.zimbra.cs.db.DbMailItem.java

public static TypedIdList readTombstones(Mailbox mbox, long lastSync, boolean equalModSeq)
        throws ServiceException {
    TypedIdList tombstones = new TypedIdList();

    DbConnection conn = mbox.getOperationConnection();
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {//from w w w  .  j  av  a2s  .c  o  m
        if (equalModSeq) {
            stmt = conn.prepareStatement(
                    "SELECT type, ids, sequence FROM " + getTombstoneTableName(mbox) + " WHERE "
                            + IN_THIS_MAILBOX_AND + "sequence >= ? AND ids IS NOT NULL" + " ORDER BY sequence");
        } else {
            stmt = conn.prepareStatement(
                    "SELECT type, ids, sequence FROM " + getTombstoneTableName(mbox) + " WHERE "
                            + IN_THIS_MAILBOX_AND + "sequence > ? AND ids IS NOT NULL" + " ORDER BY sequence");
        }

        Db.getInstance().enableStreaming(stmt);
        int pos = 1;
        pos = setMailboxId(stmt, mbox, pos);
        stmt.setLong(pos++, lastSync);
        rs = stmt.executeQuery();

        while (rs.next()) {
            MailItem.Type type = MailItem.Type.of(rs.getByte(1));
            String row = rs.getString(2);
            int modSeq = rs.getInt(3);
            if (row == null || row.equals("")) {
                continue;
            }

            // the list of tombstones is comma-delimited
            for (String stone : row.split(",")) {
                try {
                    // a tombstone may either be ID or ID:UUID, so parse accordingly
                    int delimiter = stone.indexOf(':');
                    if (delimiter == -1) {
                        tombstones.add(type, Integer.parseInt(stone), null, modSeq);
                    } else {
                        tombstones.add(type, Integer.parseInt(stone.substring(0, delimiter)),
                                Strings.emptyToNull(stone.substring(delimiter + 1)), modSeq);
                    }
                } catch (NumberFormatException nfe) {
                    ZimbraLog.sync.warn("unparseable TOMBSTONE entry: " + stone);
                }
            }
        }
        return tombstones;
    } catch (SQLException e) {
        throw ServiceException.FAILURE("reading tombstones since change: " + lastSync, e);
    } finally {
        DbPool.closeResults(rs);
        DbPool.closeStatement(stmt);
    }
}

From source file:com.zimbra.cs.db.DbMailItem.java

/**
 * Accumulates <tt>PendingDelete</tt> info for the given <tt>ResultSet</tt>.
 * @return a <tt>List</tt> of all versioned items, to be used in a subsequent call to
 * {@link DbMailItem#accumulateLeafRevisions}, or an empty list.
 *//*from www . j av a 2  s.c  om*/
static List<Integer> accumulateLeafNodes(PendingDelete info, Mailbox mbox, ResultSet rs)
        throws SQLException, ServiceException {
    boolean dumpsterEnabled = mbox.dumpsterEnabled();
    boolean useDumpsterForSpam = mbox.useDumpsterForSpam();
    StoreManager sm = StoreManager.getInstance();
    List<Integer> versioned = new ArrayList<Integer>();

    while (rs.next()) {
        // first check to make sure we don't have a modify conflict
        int revision = rs.getInt(LEAF_CI_MOD_CONTENT);
        int modMetadata = rs.getInt(LEAF_CI_MOD_METADATA);
        if (!mbox.checkItemChangeID(modMetadata, revision)) {
            info.incomplete = true;
            continue;
        }

        int id = rs.getInt(LEAF_CI_ID);
        String uuid = rs.getString(LEAF_CI_UUID);
        long size = rs.getLong(LEAF_CI_SIZE);
        MailItem.Type type = MailItem.Type.of(rs.getByte(LEAF_CI_TYPE));

        Integer itemId = Integer.valueOf(id);
        info.itemIds.add(type, itemId, uuid);
        info.size += size;

        if (rs.getBoolean(LEAF_CI_IS_UNREAD)) {
            info.unreadIds.add(itemId);
        }
        boolean isMessage = false;
        switch (type) {
        case CONTACT:
            info.contacts++;
            break;
        case CHAT:
        case MESSAGE:
            isMessage = true;
            break;
        }

        // record deleted virtual conversations and modified-or-deleted real conversations
        if (isMessage) {
            int parentId = rs.getInt(LEAF_CI_PARENT_ID);
            if (rs.wasNull() || parentId <= 0) {
                // conversations don't have UUIDs, so this is safe
                info.itemIds.add(MailItem.Type.VIRTUAL_CONVERSATION, -id, null);
            } else {
                info.modifiedIds.add(parentId);
            }
        }

        int flags = rs.getInt(LEAF_CI_FLAGS);
        if ((flags & Flag.BITMASK_VERSIONED) != 0) {
            versioned.add(id);
        }

        Integer folderId = rs.getInt(LEAF_CI_FOLDER_ID);
        boolean isDeleted = (flags & Flag.BITMASK_DELETED) != 0;
        LocationCount fcount = info.folderCounts.get(folderId);
        if (fcount == null) {
            info.folderCounts.put(folderId, new LocationCount(1, isDeleted ? 1 : 0, size));
        } else {
            fcount.increment(1, isDeleted ? 1 : 0, size);
        }

        String[] tags = DbTag.deserializeTags(rs.getString(LEAF_CI_TAGS));
        if (tags != null) {
            for (String tag : tags) {
                LocationCount tcount = info.tagCounts.get(tag);
                if (tcount == null) {
                    info.tagCounts.put(tag, new LocationCount(1, isDeleted ? 1 : 0, size));
                } else {
                    tcount.increment(1, isDeleted ? 1 : 0, size);
                }
            }
        }

        int fid = folderId != null ? folderId.intValue() : -1;
        if (!dumpsterEnabled || fid == Mailbox.ID_FOLDER_DRAFTS
                || (fid == Mailbox.ID_FOLDER_SPAM && !useDumpsterForSpam)) {
            String blobDigest = rs.getString(LEAF_CI_BLOB_DIGEST);
            if (blobDigest != null) {
                info.blobDigests.add(blobDigest);
                String locator = rs.getString(LEAF_CI_LOCATOR);
                try {
                    MailboxBlob mblob = sm.getMailboxBlob(mbox, id, revision, locator, false);
                    if (mblob == null) {
                        ZimbraLog.mailbox.warn("missing blob for id: %d, change: %d", id, revision);
                    } else {
                        info.blobs.add(mblob);
                    }
                } catch (Exception e1) {
                    ZimbraLog.mailbox.warn("Exception while getting mailbox blob", e1);
                }
            }

            int indexId = rs.getInt(LEAF_CI_INDEX_ID);
            boolean indexed = !rs.wasNull();
            if (indexed) {
                if (info.sharedIndex == null) {
                    info.sharedIndex = new HashSet<Integer>();
                }
                boolean shared = (flags & Flag.BITMASK_COPIED) != 0;
                if (shared) {
                    info.sharedIndex.add(indexId);
                } else {
                    info.indexIds.add(indexId > MailItem.IndexStatus.STALE.id() ? indexId : id);
                }
            }
        }
    }

    return versioned;
}

From source file:com.zimbra.cs.db.DbMailItem.java

public static TypedIdList listItems(Folder folder, long messageSyncStart, MailItem.Type type,
        boolean descending, boolean older) throws ServiceException {
    Mailbox mbox = folder.getMailbox();/*w  ww.  ja v a2 s. c  o  m*/
    assert Db.supports(Db.Capability.ROW_LEVEL_LOCKING) || Thread.holdsLock(mbox);

    TypedIdList result = new TypedIdList();
    DbConnection conn = mbox.getOperationConnection();
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        if (older) {
            stmt = conn.prepareStatement("SELECT id, type, uuid FROM " + getMailItemTableName(folder)
                    + " WHERE " + IN_THIS_MAILBOX_AND + " type = ? AND folder_id = ? AND date < ?"
                    + " ORDER BY date" + (descending ? " DESC" : ""));
        } else {
            stmt = conn.prepareStatement("SELECT id, type, uuid FROM " + getMailItemTableName(folder)
                    + " WHERE " + IN_THIS_MAILBOX_AND + " type = ? AND folder_id = ? AND date >= ?"
                    + " ORDER BY date" + (descending ? " DESC" : ""));
        }
        int pos = 1;
        pos = setMailboxId(stmt, mbox, pos);
        stmt.setByte(pos++, type.toByte());
        stmt.setInt(pos++, folder.getId());
        stmt.setLong(pos++, messageSyncStart);
        rs = stmt.executeQuery();

        while (rs.next()) {
            MailItem.Type dataType = MailItem.Type.of(rs.getByte(2));
            result.add(dataType, rs.getInt(1), rs.getString(3));
        }
        return result;
    } catch (SQLException e) {
        throw ServiceException.FAILURE("fetching item list for folder " + folder.getId(), e);
    } finally {
        DbPool.closeResults(rs);
        DbPool.closeStatement(stmt);
    }
}

From source file:com.nway.spring.jdbc.bean.JavassistBeanProcessor.java

private Object processColumn(ResultSet rs, int index, Class<?> propType, String writer, StringBuilder handler)
        throws SQLException {
    if (propType.equals(String.class)) {
        handler.append("bean.").append(writer).append("(").append("$1.getString(").append(index).append("));");
        return rs.getString(index);
    } else if (propType.equals(Integer.TYPE)) {
        handler.append("bean.").append(writer).append("(").append("$1.getInt(").append(index).append("));");
        return rs.getInt(index);
    } else if (propType.equals(Integer.class)) {
        handler.append("bean.").append(writer).append("(").append("integerValue($1.getInt(").append(index)
                .append("),$1.wasNull()));");
        return JdbcUtils.getResultSetValue(rs, index, Integer.class);
    } else if (propType.equals(Long.TYPE)) {
        handler.append("bean.").append(writer).append("(").append("$1.getLong(").append(index).append("));");
        return rs.getLong(index);
    } else if (propType.equals(Long.class)) {
        handler.append("bean.").append(writer).append("(").append("longValue($1.getLong(").append(index)
                .append("),$1.wasNull()));");
        return JdbcUtils.getResultSetValue(rs, index, Long.class);
    } else if (propType.equals(java.sql.Date.class)) {
        handler.append("bean.").append(writer).append("(").append("$1.getDate(").append(index).append("));");
        return rs.getDate(index);
    } else if (propType.equals(java.util.Date.class) || propType.equals(Timestamp.class)) {
        handler.append("bean.").append(writer).append("(").append("$1.getTimestamp(").append(index)
                .append("));");
        return rs.getTimestamp(index);
    } else if (propType.equals(Double.TYPE)) {
        handler.append("bean.").append(writer).append("(").append("$1.getDouble(").append(index).append("));");
        return rs.getDouble(index);
    } else if (propType.equals(Double.class)) {
        handler.append("bean.").append(writer).append("(").append("doubleValue($1.getDouble(").append(index)
                .append("),$1.wasNull()));");
        return JdbcUtils.getResultSetValue(rs, index, Double.class);
    } else if (propType.equals(Float.TYPE)) {
        handler.append("bean.").append(writer).append("(").append("$1.getFloat(").append(index).append("));");
        return rs.getFloat(index);
    } else if (propType.equals(Float.class)) {
        handler.append("bean.").append(writer).append("(").append("floatValue($1.getFloat(").append(index)
                .append("),$1.wasNull()));");
        return JdbcUtils.getResultSetValue(rs, index, Float.class);
    } else if (propType.equals(Time.class)) {
        handler.append("bean.").append(writer).append("(").append("$1.getTime(").append(index).append("));");
        return rs.getTime(index);
    } else if (propType.equals(Boolean.TYPE)) {
        handler.append("bean.").append(writer).append("(").append("$1.getBoolean(").append(index).append("));");
        return rs.getBoolean(index);
    } else if (propType.equals(Boolean.class)) {
        handler.append("bean.").append(writer).append("(").append("booleanValue($1.getBoolean(").append(index)
                .append("),$1.wasNull()));");
        return JdbcUtils.getResultSetValue(rs, index, Boolean.class);
    } else if (propType.equals(byte[].class)) {
        handler.append("bean.").append(writer).append("(").append("$1.getBytes(").append(index).append("));");
        return rs.getBytes(index);
    } else if (BigDecimal.class.equals(propType)) {
        handler.append("bean.").append(writer).append("(").append("$1.getBigDecimal(").append(index)
                .append("));");
        return rs.getBigDecimal(index);
    } else if (Blob.class.equals(propType)) {
        handler.append("bean.").append(writer).append("(").append("$1.getBlob(").append(index).append("));");
        return rs.getBlob(index);
    } else if (Clob.class.equals(propType)) {
        handler.append("bean.").append(writer).append("(").append("$1.getClob(").append(index).append("));");
        return rs.getClob(index);
    } else if (propType.equals(Short.TYPE)) {
        handler.append("bean.").append(writer).append("(").append("$1.getShort(").append(index).append("));");
        return rs.getShort(index);
    } else if (propType.equals(Short.class)) {
        handler.append("bean.").append(writer).append("(").append("shortValue($1.getShort(").append(index)
                .append("),$1.wasNull()));");
        return JdbcUtils.getResultSetValue(rs, index, Short.class);
    } else if (propType.equals(Byte.TYPE)) {
        handler.append("bean.").append(writer).append("(").append("$1.getByte(").append(index).append("));");
        return rs.getByte(index);
    } else if (propType.equals(Byte.class)) {
        handler.append("bean.").append(writer).append("(").append("byteValue($1.getByte(").append(index)
                .append("),$1.wasNull()));");
        return JdbcUtils.getResultSetValue(rs, index, Byte.class);
    } else {//from ww w  .j ava  2 s .com
        handler.append("bean.").append(writer).append("(").append("(").append(propType.getName()).append(")")
                .append("$1.getObject(").append(index).append("));");
        return rs.getObject(index);
    }
}

From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java

/**
 * Convert the specified column of the SQL ResultSet to the proper
 * java type./*from w  w  w .  j  av  a 2s.  c  o  m*/
 */
public byte getByte(ResultSet rs, int column) throws SQLException {
    return rs.getByte(column);
}

From source file:com.zimbra.cs.db.DbMailItem.java

public static Pair<List<Map<String, String>>, TypedIdList> getItemsChangedSinceDate(Mailbox mbox,
        MailItem.Type type, int changeDate, Set<Integer> visible) throws ServiceException {
    int lastDeleteSync = -1;
    if (Mailbox.isCachedType(type)) {
        throw ServiceException.INVALID_REQUEST("folders and tags must be retrieved from cache", null);
    }//  w w w  . ja v a 2 s . co  m
    List<Map<String, String>> idList = new ArrayList<Map<String, String>>();
    TypedIdList missed = new TypedIdList();
    DbConnection conn = mbox.getOperationConnection();
    PreparedStatement stmt = null;
    try {
        String typeConstraint = type == MailItem.Type.UNKNOWN ? "type NOT IN " + NON_SYNCABLE_TYPES
                : typeIn(type);
        String dateConstraint = changeDate > 0 ? "change_date > ? AND " : "";
        stmt = conn.prepareStatement(
                "SELECT id, type, parent_id, folder_id, prev_folders, date, mod_metadata, change_date, uuid"
                        + " FROM " + getMailItemTableName(mbox) + " WHERE " + IN_THIS_MAILBOX_AND
                        + dateConstraint + typeConstraint + " ORDER BY mod_metadata, id");
        if (type == MailItem.Type.MESSAGE) {
            Db.getInstance().enableStreaming(stmt);
        }
        int pos = 1;
        pos = setMailboxId(stmt, mbox, pos);
        if (changeDate > 0) {
            stmt.setInt(pos++, changeDate);
        }
        ResultSet rs = null;
        try {
            rs = stmt.executeQuery();
            while (rs.next()) {

                Map<String, String> resultData = new HashMap<String, String>();
                resultData.put("id", Integer.toString(rs.getInt(1)));
                resultData.put("type", Integer.toString(rs.getInt(2)));
                resultData.put("parent_id", Integer.toString(rs.getInt(3)));
                resultData.put("folder_id", Integer.toString(rs.getInt(4)));
                resultData.put("prev_folders", rs.getString(5));
                long temp = rs.getInt(6) * 1000L;
                resultData.put("date", Long.toString(temp));
                resultData.put("mod_metadata", Integer.toString(rs.getInt(7)));
                temp = rs.getInt(8) * 1000L;
                resultData.put("change_date", Long.toString(temp));
                if (visible == null || visible.contains(rs.getInt(3))) {
                    idList.add(resultData);
                } else {
                    int modSeq = rs.getInt(7);
                    if (modSeq > lastDeleteSync) {
                        missed.add(MailItem.Type.of(rs.getByte(2)), rs.getInt(1), rs.getString(9), modSeq,
                                rs.getString(5));
                    }
                }
            }
        } finally {
            DbPool.closeResults(rs);
        }
    } catch (SQLException e) {
        throw ServiceException.FAILURE("Getting items modified since " + changeDate, e);
    } finally {
        DbPool.closeStatement(stmt);
    }

    return new Pair<List<Map<String, String>>, TypedIdList>(idList, missed);
}

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 {/*from  w w w  .j a v  a2  s. com*/
            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.zimbra.cs.db.DbMailItem.java

public static Mailbox.MailboxData getFoldersAndTags(Mailbox mbox, FolderTagMap folderData, FolderTagMap tagData,
        boolean forceReload) throws ServiceException {
    boolean reload = forceReload;

    DbConnection conn = mbox.getOperationConnection();
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {/* w w w. ja  v  a 2 s . c om*/
        String table = getMailItemTableName(mbox, "mi");

        // folder data is loaded from the MAIL_ITEM table...
        stmt = conn.prepareStatement("SELECT " + DB_FIELDS + " FROM " + table + " WHERE " + IN_THIS_MAILBOX_AND
                + "type IN " + FOLDER_TYPES);
        setMailboxId(stmt, mbox, 1);
        rs = stmt.executeQuery();
        while (rs.next()) {
            UnderlyingData data = constructItem(rs);
            MailItem.Type type = MailItem.Type.of(data.type);
            if (MailItem.isAcceptableType(MailItem.Type.FOLDER, type)) {
                folderData.put(data, null);
            } else if (MailItem.isAcceptableType(MailItem.Type.TAG, type)) {
                tagData.put(data, null);
            }

            rs.getInt(CI_UNREAD);
            reload |= rs.wasNull();
        }
        rs.close();

        // tag data is loaded from a different table...
        reload |= DbTag.getAllTags(mbox, tagData);

        for (UnderlyingData data : folderData.keySet()) {
            if (data.parentId != data.folderId) {
                // we had a small folder data inconsistency issue, so resolve it here
                //   rather than returning it up to the caller
                stmt.close();
                stmt = conn.prepareStatement("UPDATE " + table + " SET parent_id = folder_id" + " WHERE "
                        + IN_THIS_MAILBOX_AND + "id = ?");
                int pos = 1;
                pos = setMailboxId(stmt, mbox, pos);
                stmt.setInt(pos++, data.id);
                stmt.executeUpdate();

                data.parentId = data.folderId;
                ZimbraLog.mailbox.info("correcting PARENT_ID column for %s %d", MailItem.Type.of(data.type),
                        data.id);
            }
        }

        if (!reload) {
            return null;
        }

        Map<Integer, UnderlyingData> lookup = new HashMap<Integer, UnderlyingData>(
                folderData.size() + tagData.size());

        // going to recalculate counts, so discard any existing counts...
        for (FolderTagMap itemData : new FolderTagMap[] { folderData, tagData }) {
            for (Map.Entry<UnderlyingData, FolderTagCounts> entry : itemData.entrySet()) {
                UnderlyingData data = entry.getKey();
                lookup.put(data.id, data);
                data.size = data.unreadCount = 0;
                entry.setValue(new FolderTagCounts());
            }
        }

        rs.close();
        stmt.close();

        // recalculate the counts for all folders and the overall mailbox size...
        Mailbox.MailboxData mbd = new Mailbox.MailboxData();
        stmt = conn.prepareStatement("SELECT folder_id, type, flags, COUNT(*), SUM(unread), SUM(size)"
                + " FROM " + table + " WHERE " + IN_THIS_MAILBOX_AND + "type NOT IN " + NON_SEARCHABLE_TYPES
                + " GROUP BY folder_id, type, flags");
        setMailboxId(stmt, mbox, 1);
        rs = stmt.executeQuery();

        while (rs.next()) {
            int folderId = rs.getInt(1);
            byte type = rs.getByte(2);
            boolean deleted = (rs.getInt(3) & Flag.BITMASK_DELETED) != 0;
            int count = rs.getInt(4);
            int unread = rs.getInt(5);
            long size = rs.getLong(6);

            if (type == MailItem.Type.CONTACT.toByte()) {
                mbd.contacts += count;
            }
            mbd.size += size;

            UnderlyingData data = lookup.get(folderId);
            if (data != null) {
                data.unreadCount += unread;
                data.size += count;

                FolderTagCounts fcounts = folderData.get(data);
                fcounts.totalSize += size;
                if (deleted) {
                    fcounts.deletedCount += count;
                    fcounts.deletedUnreadCount += unread;
                }
            } else {
                ZimbraLog.mailbox.warn(
                        "inconsistent DB state: items with no corresponding folder (folder id %d)", folderId);
            }
        }

        // recalculate the counts for all tags...
        DbTag.recalculateTagCounts(mbox, lookup);

        rs.close();
        stmt.close();

        stmt = conn.prepareStatement("SELECT mi.folder_id, SUM(rev.size)" + " FROM " + table + ", "
                + getRevisionTableName(mbox, "rev") + " WHERE mi.id = rev.item_id"
                + (DebugConfig.disableMailboxGroups ? ""
                        : " AND rev.mailbox_id = ? AND mi.mailbox_id = rev.mailbox_id")
                + " GROUP BY folder_id");
        setMailboxId(stmt, mbox, 1);
        rs = stmt.executeQuery();

        while (rs.next()) {
            int folderId = rs.getInt(1);
            long size = rs.getLong(2);

            mbd.size += size;

            UnderlyingData data = lookup.get(folderId);
            if (data != null) {
                folderData.get(data).totalSize += size;
            } else {
                ZimbraLog.mailbox
                        .warn("inconsistent DB state: revisions with no corresponding folder (folder ID "
                                + folderId + ")");
            }
        }

        return mbd;
    } catch (SQLException e) {
        throw ServiceException.FAILURE("fetching folder data for mailbox " + mbox.getId(), e);
    } finally {
        DbPool.closeResults(rs);
        DbPool.closeStatement(stmt);
    }
}

From source file:com.l2jfree.gameserver.gameobjects.L2Player.java

/**
 * Restores sub-class data for the L2Player, used to check the current
 * class index for the character./*from w  w w .  jav a  2s.  c o  m*/
 */
private static boolean restoreSubClassData(L2Player player) {
    Connection con = null;

    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement(RESTORE_CHAR_SUBCLASSES);
        statement.setInt(1, player.getObjectId());

        ResultSet rset = statement.executeQuery();

        while (rset.next()) {
            SubClass subClass = new SubClass();
            subClass.setClassId(rset.getInt("class_id"));
            subClass.setLevel(rset.getByte("level"));
            subClass.setExp(rset.getLong("exp"));
            subClass.setSp(rset.getInt("sp"));
            subClass.setClassIndex(rset.getInt("class_index"));

            // Enforce the correct indexing of _subClasses against their class indexes.
            player.getSubClasses().put(subClass.getClassIndex(), subClass);
        }

        statement.close();
    } catch (Exception e) {
        _log.error("Could not restore classes for " + player.getName() + ": ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }

    return true;
}

From source file:com.l2jfree.gameserver.gameobjects.L2Player.java

/**
 * Retrieve a L2Player from the characters table of the database and add it in _allObjects of the L2world.<BR><BR>
 *
 * <B><U> Actions</U> :</B><BR><BR>
 * <li>Retrieve the L2Player from the characters table of the database </li>
 * <li>Add the L2Player object in _allObjects </li>
 * <li>Set the x,y,z position of the L2Player and make it invisible</li>
 * <li>Update the overloaded status of the L2Player</li><BR><BR>
 *
 * @param objectId Identifier of the object to initialized
 *
 * @return The L2Player loaded from the database
 *
 *//*from ww w. ja va2 s.  c  o  m*/
public static L2Player load(int objectId) {
    disconnectIfOnline(objectId);

    L2Player player = null;
    Connection con = null;

    try {
        // Retrieve the L2Player from the characters table of the database
        con = L2DatabaseFactory.getInstance().getConnection(con);

        PreparedStatement statement = con.prepareStatement(RESTORE_CHARACTER);
        statement.setInt(1, objectId);
        ResultSet rset = statement.executeQuery();

        double currentHp = 1, currentMp = 1, currentCp = 1;
        if (rset.next()) {
            final int activeClassId = rset.getInt("classid");
            final boolean female = rset.getInt("sex") != 0;
            final L2PlayerTemplate template = CharTemplateTable.getInstance().getTemplate(activeClassId);
            PlayerAppearance app = new PlayerAppearance(rset.getByte("face"), rset.getByte("hairColor"),
                    rset.getByte("hairStyle"), female);

            player = new L2Player(objectId, template, rset.getString("account_name"), app);
            player.setName(rset.getString("char_name"));
            player._lastAccess = rset.getLong("lastAccess");

            player.getStat().setExp(rset.getLong("exp"));
            player.setExpBeforeDeath(rset.getLong("expBeforeDeath"));
            player.getStat().setLevel(rset.getByte("level"));
            player.getStat().setSp(rset.getInt("sp"));

            player.setWantsPeace(rset.getInt("wantspeace"));

            player.setHeading(rset.getInt("heading"));

            player.setKarma(rset.getInt("karma"));
            player.setFame(rset.getInt("fame"));
            player.setPvpKills(rset.getInt("pvpkills"));
            player.setPkKills(rset.getInt("pkkills"));

            player.setClanJoinExpiryTime(rset.getLong("clan_join_expiry_time"));
            if (player.getClanJoinExpiryTime() < System.currentTimeMillis()) {
                player.setClanJoinExpiryTime(0);
            }
            player.setClanCreateExpiryTime(rset.getLong("clan_create_expiry_time"));
            if (player.getClanCreateExpiryTime() < System.currentTimeMillis()) {
                player.setClanCreateExpiryTime(0);
            }

            int clanId = rset.getInt("clanid");

            if (clanId > 0) {
                player.setClan(ClanTable.getInstance().getClan(clanId));
            }

            player.setDeleteTimer(rset.getLong("deletetime"));
            player.setOnlineTime(rset.getLong("onlinetime"));
            player.setNewbie(rset.getInt("newbie"));
            player.setNoble(rset.getInt("nobless") == 1);

            player.setTitle(rset.getString("title"));
            player.setAccessLevel(rset.getInt("accesslevel"));
            player.setFistsWeaponItem(player.findFistsWeaponItem(activeClassId));
            player.setUptime(System.currentTimeMillis());

            // Only 1 line needed for each and their values only have to be set once as long as you don't die before it's set.
            currentHp = rset.getDouble("curHp");
            currentMp = rset.getDouble("curMp");
            currentCp = rset.getDouble("curCp");

            player._classIndex = 0;
            try {
                player.setBaseClass(rset.getInt("base_class"));
            } catch (Exception e) {
                player.setBaseClass(activeClassId);
            }

            // Restore Subclass Data (cannot be done earlier in function)
            if (restoreSubClassData(player)) {
                if (activeClassId != player.getBaseClass()) {
                    for (SubClass subClass : player.getSubClasses().values())
                        if (subClass.getClassId() == activeClassId)
                            player._classIndex = subClass.getClassIndex();
                }
            }
            if (player.getClassIndex() == 0 && activeClassId != player.getBaseClass()) {
                // Subclass in use but doesn't exist in DB -
                // a possible restart-while-modifysubclass cheat has been attempted.
                // Switching to use base class
                player.setClassId(player.getBaseClass());
                _log.warn("Player " + player.getName()
                        + " reverted to base class. Possibly has tried a relogin exploit while subclassing.");
            } else
                player._activeClass = activeClassId;

            player.setIsIn7sDungeon(rset.getInt("isin7sdungeon") == 1);
            player.setInJail(rset.getInt("in_jail") == 1);
            player.setJailTimer(rset.getLong("jail_timer"));
            player.setBanChatTimer(rset.getLong("banchat_timer"));
            if (player.isInJail())
                player.setJailTimer(rset.getLong("jail_timer"));
            else
                player.setJailTimer(0);

            CursedWeaponsManager.getInstance().onEnter(player);

            player.setNoble(rset.getBoolean("nobless"));
            player.setCharViP((rset.getInt("charViP") == 1));
            player.setSubPledgeType(rset.getInt("subpledge"));
            player.setPledgeRank(rset.getInt("pledge_rank"));
            player.setApprentice(rset.getInt("apprentice"));
            player.setSponsor(rset.getInt("sponsor"));
            if (player.getClan() != null) {
                if (player.getClan().getLeaderId() != player.getObjectId()) {
                    if (player.getPledgeRank() == 0) {
                        player.setPledgeRank(5);
                    }
                    player.setClanPrivileges(player.getClan().getRankPrivs(player.getPledgeRank()));
                } else {
                    player.setClanPrivileges(L2Clan.CP_ALL);
                    player.setPledgeRank(1);
                }
            } else {
                player.setClanPrivileges(L2Clan.CP_NOTHING);
            }
            player.setLvlJoinedAcademy(rset.getInt("lvl_joined_academy"));
            player.setAllianceWithVarkaKetra(rset.getInt("varka_ketra_ally"));
            player.setDeathPenaltyBuffLevel(rset.getInt("death_penalty_level"));
            player.setVitalityPoints(rset.getInt("vitality_points"), true);

            // Add the L2Player object in _allObjects
            // L2World.getInstance().storeObject(player);

            // Set the x,y,z position of the L2Player and make it invisible
            player.getPosition().setXYZInvisible(rset.getInt("x"), rset.getInt("y"), rset.getInt("z"));

            // Set Teleport Bookmark Slot
            player.setBookMarkSlot(rset.getInt("BookmarkSlot"));
        }

        rset.close();
        statement.close();

        if (player == null)
            return null;

        // Retrieve from the database all secondary data of this L2Player
        // and reward expertise/lucky skills if necessary.
        player.restoreCharData();
        player.rewardSkills();

        // Buff and status icons
        player.getEffects().restoreEffects();
        player.restoreSkillReuses();

        player.stopEffects(L2EffectType.HEAL_OVER_TIME);
        player.stopEffects(L2EffectType.COMBAT_POINT_HEAL_OVER_TIME);

        // Restore current Cp, HP and MP values
        player.getStatus().setCurrentCp(currentCp);
        player.getStatus().setCurrentHp(currentHp);
        player.getStatus().setCurrentMp(currentMp);

        if (currentHp < 0.5) {
            player.setIsDead(true);
            player.getStatus().stopHpMpRegeneration();
        }

        // Restore pet if exists in the world
        player.setPet(L2World.getInstance().getPet(player.getObjectId()));
        if (player.getPet() != null)
            player.getPet().setOwner(player);

        // refresh overloaded already done when loading inventory
        // Update the expertise status of the L2Player
        player.refreshExpertisePenalty();
    } catch (Exception e) {
        _log.error("Failed loading character.", e);
    } finally {
        L2DatabaseFactory.close(con);
    }

    return player;
}