Example usage for java.sql ResultSet getTimestamp

List of usage examples for java.sql ResultSet getTimestamp

Introduction

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

Prototype

java.sql.Timestamp getTimestamp(String columnLabel) throws SQLException;

Source Link

Document

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

Usage

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

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

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

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

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

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

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

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

    return rowCounter;
}

From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java

private EventRecurrence eventRecurrenceFromCursor(Calendar cal, ResultSet evrs) throws SQLException {
    EventRecurrence er = new EventRecurrence();
    er.setKind(RecurrenceKind.valueOf(evrs.getString("event_repeatkind")));
    er.setDays(new RecurrenceDaysParser().parse(evrs.getString("event_repeatdays")));
    er.setFrequence(evrs.getInt("event_repeatfrequence"));
    Timestamp endRepeat = evrs.getTimestamp("event_endrepeat");
    if (endRepeat != null) {
        cal.setTimeInMillis(endRepeat.getTime());
        er.setEnd(cal.getTime());/* w  w  w . j ava 2  s .  c om*/
    }
    return er;
}

From source file:dk.netarkivet.harvester.datamodel.RunningJobsInfoDBDAO.java

/**
 * Returns the most recent record for every job, partitioned by harvest
 * definition name./*from w  w w.j  av  a  2 s  . c  o m*/
 * @return the full listing of started job information, partitioned by
 *         harvest definition name.
 */
@Override
public Map<String, List<StartedJobInfo>> getMostRecentByHarvestName() {

    Connection c = HarvestDBConnection.get();

    Map<String, List<StartedJobInfo>> infoMap = new TreeMap<String, List<StartedJobInfo>>();
    Statement stm = null;
    try {
        stm = c.createStatement();
        ResultSet rs = stm.executeQuery("SELECT " + HM_COLUMN.getColumnsInOrder() + " FROM runningJobsMonitor");

        while (rs.next()) {

            long jobId = rs.getLong(HM_COLUMN.jobId.rank());
            String harvestName = rs.getString(HM_COLUMN.harvestName.rank());

            List<StartedJobInfo> infosForHarvest = infoMap.get(harvestName);
            if (infosForHarvest == null) {
                infosForHarvest = new LinkedList<StartedJobInfo>();
                infoMap.put(harvestName, infosForHarvest);
            }

            StartedJobInfo sji = new StartedJobInfo(harvestName, jobId);

            sji.setElapsedSeconds(rs.getLong(HM_COLUMN.elapsedSeconds.rank()));
            sji.setHostUrl(rs.getString(HM_COLUMN.hostUrl.rank()));
            sji.setProgress(rs.getDouble(HM_COLUMN.progress.rank()));
            sji.setQueuedFilesCount(rs.getLong(HM_COLUMN.queuedFilesCount.rank()));
            sji.setTotalQueuesCount(rs.getLong(HM_COLUMN.totalQueuesCount.rank()));
            sji.setActiveQueuesCount(rs.getLong(HM_COLUMN.activeQueuesCount.rank()));
            sji.setRetiredQueuesCount(rs.getLong(HM_COLUMN.retiredQueuesCount.rank()));
            sji.setExhaustedQueuesCount(rs.getLong(HM_COLUMN.exhaustedQueuesCount.rank()));
            sji.setAlertsCount(rs.getLong(HM_COLUMN.alertsCount.rank()));
            sji.setDownloadedFilesCount(rs.getLong(HM_COLUMN.downloadedFilesCount.rank()));
            sji.setCurrentProcessedKBPerSec(rs.getLong(HM_COLUMN.currentProcessedKBPerSec.rank()));
            sji.setProcessedKBPerSec(rs.getLong(HM_COLUMN.processedKBPerSec.rank()));
            sji.setCurrentProcessedDocsPerSec(rs.getDouble(HM_COLUMN.currentProcessedDocsPerSec.rank()));
            sji.setProcessedDocsPerSec(rs.getDouble(HM_COLUMN.processedDocsPerSec.rank()));
            sji.setActiveToeCount(rs.getInt(HM_COLUMN.activeToeCount.rank()));
            sji.setStatus(CrawlStatus.values()[rs.getInt(HM_COLUMN.status.rank())]);
            sji.setTimestamp(new Date(rs.getTimestamp(HM_COLUMN.tstamp.rank()).getTime()));

            infosForHarvest.add(sji);
        }

        return infoMap;

    } catch (SQLException e) {
        String message = "SQL error querying runningJobsMonitor" + "\n"
                + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(message, e);
        throw new IOFailure(message, e);
    } finally {
        DBUtils.closeStatementIfOpen(stm);
        HarvestDBConnection.release(c);
    }

}

From source file:edu.ku.brc.specify.conversion.SpecifyDBConverter.java

/**
 * @param oldDBConn//from  w  ww .  ja  v a  2  s. c o m
 * @param newDBConn
 */
protected void fixLoanPreps(final Connection oldDBConn, final Connection newDBConn) {
    // Category == 0 -> Is a Loan, 1 is a Gift

    System.out.println("------------------------ Loans ----------------------------");

    int fixCnt = 0;
    int totalCnt = 0;
    int skippedCnt = 0;
    int notFndCnt = 0;
    int noMatch = 0;

    IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
    IdTableMapper loanPrepsMapper = IdMapperMgr.getInstance().addTableMapper("loanphysicalobject",
            "LoanPhysicalObjectID", false);
    IdTableMapper loansMapper = IdMapperMgr.getInstance().addTableMapper("loan", "LoanID", false);
    IdTableMapper prepMapper = IdMapperMgr.getInstance().addTableMapper("collectionobject",
            "CollectionObjectID", false);

    Statement stmt = null;
    PreparedStatement newStmt = null;
    PreparedStatement pStmt = null;
    try {
        pStmt = newDBConn.prepareStatement(
                "UPDATE loanpreparation SET Quantity=?, QuantityResolved=?, QuantityReturned=?, IsResolved=?, TimestampModified=?, TimestampCreated=?, "
                        + "LoanID=?, DescriptionOfMaterial=?, OutComments=?, InComments=?, PreparationID=?, Version=? "
                        + "WHERE LoanPreparationID = ?");

        newStmt = newDBConn.prepareStatement(
                "SELECT LoanPreparationID, TimestampModified, Version FROM loanpreparation WHERE LoanPreparationID = ?");

        String sql = "SELECT lp.LoanPhysicalObjectID, lp.PhysicalObjectID, lp.LoanID, lp.Quantity, lp.DescriptionOfMaterial, lp.OutComments, lp.InComments, "
                + "lp.QuantityResolved, lp.QuantityReturned, lp.TimestampCreated, lp.TimestampModified, lp.LastEditedBy, l.Closed "
                + "FROM loanphysicalobject lp INNER JOIN loan l ON l.LoanID = lp.LoanID WHERE l.Category = 0";

        stmt = oldDBConn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            int id = rs.getInt(1);
            Timestamp oldCreatedTS = rs.getTimestamp(10);

            //System.out.println(id);
            Integer newID = loanPrepsMapper.get(id);
            if (newID != null) {
                newStmt.setInt(1, newID);

                ResultSet rs2 = newStmt.executeQuery();
                if (rs2.next()) {
                    Timestamp oldModifiedTS = rs.getTimestamp(11);
                    if (rs2.getInt(3) == 0) // version
                    {
                        Integer prepId = rs.getInt(2);
                        Integer loanId = rs.getInt(3);
                        Integer newLoanId = loansMapper.get(loanId);
                        Integer qty = rs.getInt(4);
                        String descOfMat = rs.getString(5);
                        String outComments = rs.getString(6);
                        String inComments = rs.getString(7);
                        Integer qtyRes = rs.getInt(8);
                        Integer qtyRet = rs.getInt(9);
                        String lasteditedBy = rs.getString(12);
                        Boolean isLoanClosed = rs.getBoolean(13);

                        isLoanClosed = isLoanClosed == null ? false : isLoanClosed;

                        pStmt.setInt(1, qty);
                        pStmt.setInt(2, qtyRes);
                        pStmt.setInt(3, qtyRet);

                        boolean isResolved = isLoanClosed;

                        if (!isLoanClosed) // if Loan is Closed then all are resolved by definition
                        {
                            if (qty != null) {
                                if (qtyRes != null && qty.equals(qtyRes)) {
                                    isResolved = true;

                                } else if (qtyRet != null && qty.equals(qtyRet)) {
                                    isResolved = true;
                                }
                            }
                        }
                        pStmt.setBoolean(4, isResolved);
                        pStmt.setTimestamp(5, oldModifiedTS);
                        pStmt.setTimestamp(6, oldCreatedTS);

                        pStmt.setInt(7, newLoanId);
                        pStmt.setString(8, descOfMat);
                        pStmt.setString(9, outComments);
                        pStmt.setString(10, inComments);
                        pStmt.setInt(11, prepId != null ? prepMapper.get(prepId) : null);
                        pStmt.setInt(12, 1); // Version

                        pStmt.setInt(13, newID);

                        if (pStmt.executeUpdate() != 1) {
                            log.error(String.format("*** Error updating OldID %d  newID %d", rs.getInt(1),
                                    newID));
                        } else {
                            fixCnt++;
                        }
                    } else {
                        noMatch++;
                    }
                } else {
                    notFndCnt++;
                }
                rs2.close();
            } else {
                //log.error(String.format("*** Error not new Id for OldID %d", rs.getInt(1)));
                skippedCnt++;
            }
            totalCnt++;
        }
        rs.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (stmt != null)
                stmt.close();
            if (newStmt != null)
                newStmt.close();
            if (pStmt != null)
                pStmt.close();

        } catch (Exception ex) {
        }
    }

    System.out.println(String.format("Total: %d  Fixed: %d  Skipped: %d  NotFnd: %d  noMatch: %d", totalCnt,
            fixCnt, skippedCnt, notFndCnt, noMatch));
}

From source file:com.flexive.core.storage.GenericDivisionExporter.java

/**
 * Dump a generic table to XML//w ww.  java2 s .  co m
 *
 * @param tableName     name of the table
 * @param stmt          an open statement
 * @param out           output stream
 * @param sb            an available and valid StringBuilder
 * @param xmlTag        name of the xml tag to write per row
 * @param idColumn      (optional) id column to sort results
 * @param onlyBinaries  process binary fields (else these will be ignored)
 * @throws SQLException on errors
 * @throws IOException  on errors
 */
private void dumpTable(String tableName, Statement stmt, OutputStream out, StringBuilder sb, String xmlTag,
        String idColumn, boolean onlyBinaries) throws SQLException, IOException {
    ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName
            + (StringUtils.isEmpty(idColumn) ? "" : " ORDER BY " + idColumn + " ASC"));
    final ResultSetMetaData md = rs.getMetaData();
    String value, att;
    boolean hasSubTags;
    while (rs.next()) {
        hasSubTags = false;
        if (!onlyBinaries) {
            sb.setLength(0);
            sb.append("  <").append(xmlTag);
        }
        for (int i = 1; i <= md.getColumnCount(); i++) {
            value = null;
            att = md.getColumnName(i).toLowerCase();
            switch (md.getColumnType(i)) {
            case java.sql.Types.DECIMAL:
            case java.sql.Types.NUMERIC:
            case java.sql.Types.BIGINT:
                if (!onlyBinaries) {
                    value = String.valueOf(rs.getBigDecimal(i));
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.INTEGER:
            case java.sql.Types.SMALLINT:
            case java.sql.Types.TINYINT:
                if (!onlyBinaries) {
                    value = String.valueOf(rs.getLong(i));
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.DOUBLE:
            case java.sql.Types.FLOAT:
            case java.sql.Types.REAL:
                if (!onlyBinaries) {
                    value = String.valueOf(rs.getDouble(i));
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.TIMESTAMP:
            case java.sql.Types.DATE:
                if (!onlyBinaries) {
                    final Timestamp ts = rs.getTimestamp(i);
                    if (rs.wasNull())
                        value = null;
                    else
                        value = FxFormatUtils.getDateTimeFormat().format(ts);
                }
                break;
            case java.sql.Types.BIT:
            case java.sql.Types.CHAR:
            case java.sql.Types.BOOLEAN:
                if (!onlyBinaries) {
                    value = rs.getBoolean(i) ? "1" : "0";
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.CLOB:
            case java.sql.Types.BLOB:
            case java.sql.Types.LONGVARBINARY:
            case java.sql.Types.LONGVARCHAR:
            case java.sql.Types.VARBINARY:
            case java.sql.Types.VARCHAR:
            case java.sql.Types.BINARY:
            case SQL_LONGNVARCHAR:
            case SQL_NCHAR:
            case SQL_NCLOB:
            case SQL_NVARCHAR:

                hasSubTags = true;
                break;
            default:
                LOG.warn("Unhandled type [" + md.getColumnType(i) + "] for [" + tableName + "." + att + "]");
            }
            if (value != null && !onlyBinaries)
                sb.append(' ').append(att).append("=\"").append(value).append("\"");
        }
        if (hasSubTags) {
            if (!onlyBinaries)
                sb.append(">\n");
            for (int i = 1; i <= md.getColumnCount(); i++) {
                switch (md.getColumnType(i)) {
                case java.sql.Types.VARBINARY:
                case java.sql.Types.LONGVARBINARY:
                case java.sql.Types.BLOB:
                case java.sql.Types.BINARY:
                    if (idColumn == null)
                        throw new IllegalArgumentException("Id column required to process binaries!");
                    String binFile = FOLDER_BINARY + "/BIN_" + String.valueOf(rs.getLong(idColumn)) + "_" + i
                            + ".blob";
                    att = md.getColumnName(i).toLowerCase();
                    if (onlyBinaries) {
                        if (!(out instanceof ZipOutputStream))
                            throw new IllegalArgumentException(
                                    "out has to be a ZipOutputStream to store binaries!");
                        ZipOutputStream zip = (ZipOutputStream) out;
                        InputStream in = rs.getBinaryStream(i);
                        if (rs.wasNull())
                            break;

                        ZipEntry ze = new ZipEntry(binFile);
                        zip.putNextEntry(ze);

                        byte[] buffer = new byte[4096];
                        int read;
                        while ((read = in.read(buffer)) != -1)
                            zip.write(buffer, 0, read);
                        in.close();
                        zip.closeEntry();
                        zip.flush();
                    } else {
                        InputStream in = rs.getBinaryStream(i); //need to fetch to see if it is empty
                        if (rs.wasNull())
                            break;
                        in.close();
                        sb.append("    <").append(att).append(">").append(binFile).append("</").append(att)
                                .append(">\n");
                    }
                    break;
                case java.sql.Types.CLOB:
                case SQL_LONGNVARCHAR:
                case SQL_NCHAR:
                case SQL_NCLOB:
                case SQL_NVARCHAR:
                case java.sql.Types.LONGVARCHAR:
                case java.sql.Types.VARCHAR:
                    if (!onlyBinaries) {
                        value = rs.getString(i);
                        if (rs.wasNull())
                            break;
                        att = md.getColumnName(i).toLowerCase();
                        sb.append("    <").append(att).append('>');
                        escape(sb, value);
                        sb.append("</").append(att).append(">\n");
                    }
                    break;
                }
            }
            if (!onlyBinaries)
                sb.append("  </").append(xmlTag).append(">\n");
        } else {
            if (!onlyBinaries)
                sb.append("/>\n");
        }
        if (!onlyBinaries)
            write(out, sb);
    }
}

From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java

private void loadExceptions(Connection con, Calendar cal, Map<EventObmId, Event> eventById,
        AbstractSQLCollectionHelper<?> eventIds) throws SQLException {
    if (eventById.isEmpty()) {
        return;//www. java 2s  .  c  o m
    }
    String exceps = "SELECT " + EXCEPS_FIELDS
            + " FROM Event e LEFT JOIN EventException on event_id=eventexception_parent_id "
            + "WHERE event_id IN (" + eventIds.asPlaceHolders() + ") AND eventexception_child_id IS NULL";
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        ps = con.prepareStatement(exceps);
        eventIds.insertValues(ps, 1);
        rs = ps.executeQuery();
        while (rs.next()) {
            EventObmId eventId = new EventObmId(rs.getInt(1));
            Event e = eventById.get(eventId);
            EventRecurrence er = e.getRecurrence();
            Timestamp t = rs.getTimestamp(2);
            if (t != null) {
                cal.setTimeInMillis(t.getTime());
                er.addException(cal.getTime());
            }
        }
    } finally {
        obmHelper.cleanup(null, ps, rs);
    }
}

From source file:com.mirth.connect.donkey.server.data.jdbc.JdbcDao.java

private Message getMessageFromResultSet(String channelId, ResultSet resultSet) {
    try {/*from www. j  ava2 s.  c  om*/
        Message message = new Message();
        long messageId = resultSet.getLong("id");
        Calendar receivedDate = Calendar.getInstance();
        receivedDate.setTimeInMillis(resultSet.getTimestamp("received_date").getTime());

        message.setMessageId(messageId);
        message.setChannelId(channelId);
        message.setReceivedDate(receivedDate);
        message.setProcessed(resultSet.getBoolean("processed"));
        message.setServerId(resultSet.getString("server_id"));
        message.setImportChannelId(resultSet.getString("import_channel_id"));

        long importId = resultSet.getLong("import_id");
        if (!resultSet.wasNull()) {
            message.setImportId(importId);
        }

        long originalId = resultSet.getLong("original_id");
        if (!resultSet.wasNull()) {
            message.setOriginalId(originalId);
        }

        return message;
    } catch (SQLException e) {
        throw new DonkeyDaoException(e);
    }
}

From source file:edu.emory.cci.aiw.i2b2etl.ksb.I2b2KnowledgeSourceBackend.java

private TemporalPropositionDefinition newTemporalPropositionDefinition(ResultSet rs, Date accessed,
        ValueMetadataParser valueMetadataParser)
        throws SAXParseException, KnowledgeSourceReadException, SQLException {
    if (Arrays.contains(VALUE_TYPE_CDS, rs.getString(3))) {
        valueMetadataParser.init();/*  w w  w  . ja v a2  s .  c  om*/
        String clob = rs.getString(4);
        valueMetadataParser.parse(clob);
        ValueType valueType = valueMetadataParser.getValueType();
        PrimitiveParameterDefinition result = new PrimitiveParameterDefinition(rs.getString(7));
        result.setDisplayName(rs.getString(1));
        result.setDescription(rs.getString(4));
        result.setInDataSource(rs.getBoolean(6));
        result.setValueType(valueType);
        result.setAccessed(accessed);
        result.setCreated(rs.getTimestamp(8));
        result.setUpdated(rs.getTimestamp(9));
        result.setDownloaded(rs.getTimestamp(10));
        result.setSourceId(this.sourceIdFactory.getInstance());
        return result;
    } else {
        EventDefinition result = new EventDefinition(rs.getString(7));
        result.setDisplayName(rs.getString(1));
        result.setDescription(rs.getString(4));
        result.setInDataSource(rs.getBoolean(6));
        result.setAccessed(accessed);
        result.setCreated(rs.getTimestamp(8));
        result.setUpdated(rs.getTimestamp(9));
        result.setDownloaded(rs.getTimestamp(10));
        result.setSourceId(this.sourceIdFactory.getInstance());
        return result;
    }
}

From source file:ece356.UserDBAO.java

public static ArrayList<PatientData> queryPatients(String username, String state, String city,
        String loggedInUser) throws ClassNotFoundException, SQLException {
    Connection con = null;/*from  w w  w  .  j a v  a  2  s . com*/
    PreparedStatement pstmt = null;
    ArrayList<PatientData> ret;
    try {
        con = getConnection();
        ResultSet resultSet;

        // Query who is already friends with the person logged in            
        String friendShipQuery = "select friend.recieved_username as friend from friend where sent_username = ? and friend.isAccepted=1"
                + " union"
                + " select friend.sent_username as friend from friend where recieved_username = ? and friend.isAccepted=1";

        pstmt = con.prepareStatement(friendShipQuery);
        pstmt.setString(1, loggedInUser);
        pstmt.setString(2, loggedInUser);

        resultSet = pstmt.executeQuery();
        ArrayList<String> alreadyFriends = new ArrayList();
        while (resultSet.next()) {
            alreadyFriends.add(resultSet.getString("friend"));
        }

        // Query if a request has already been sent to this person
        friendShipQuery = "select friend.recieved_username as friend from friend where sent_username = ? and friend.isAccepted=0";

        pstmt = con.prepareStatement(friendShipQuery);
        pstmt.setString(1, loggedInUser);

        resultSet = pstmt.executeQuery();
        ArrayList<String> waitingForRequest = new ArrayList();
        while (resultSet.next()) {
            waitingForRequest.add(resultSet.getString("friend"));
        }

        ArrayList<String> keys = new ArrayList();
        ArrayList<String> values = new ArrayList();
        if (username != null && !username.equals("")) {
            keys.add("patient_username");
            values.add(username);
        }

        if (state != null && !state.equals("")) {
            keys.add("home_address_state");
            values.add(state);
        }

        if (city != null && !city.equals("")) {
            keys.add("home_address_city");
            values.add(city);
        }

        // Query for general doctor information
        String query = "SELECT * FROM patientSearchView";
        if (!keys.isEmpty()) {
            query = query + " where";
            for (String key : keys) {
                query = query + " " + key + " LIKE ?";
                query += " AND";
            }
            query = query.substring(0, query.length() - 4);
            System.out.println(query);
        }
        pstmt = con.prepareStatement(query);

        if (!values.isEmpty()) {
            int count = 1;
            for (String value : values) {
                pstmt.setString(count, "%" + value + "%");
                count++;
            }
        }

        resultSet = pstmt.executeQuery();

        ret = new ArrayList();
        while (resultSet.next()) {
            PatientData patient = new PatientData();
            patient.userName = resultSet.getString("patient_username");
            patient.city = resultSet.getString("home_address_city");
            patient.state = resultSet.getString("home_address_state");
            patient.numberOfReviews = resultSet.getInt("numberOfReviews");
            patient.lastReviewDate = resultSet.getTimestamp("lastReviewDate");
            ret.add(patient);

            if (alreadyFriends.contains(patient.getUserName())) {
                patient.setFriendShipStatusWithLoggedInUser(FriendShipStatus.ALREADY_FRIENDS);
            } else if (waitingForRequest.contains(patient.getUserName())) {
                patient.setFriendShipStatusWithLoggedInUser(FriendShipStatus.WAITING_FOR_ACCEPT);
            } else {
                patient.setFriendShipStatusWithLoggedInUser(FriendShipStatus.NOT_FRIENDS);
            }
        }

        // Add friendship status for each patient
        /*select friend.sent_username, friend.isAccepted as friend
        from friend where friend.recieved_username = 'pat_bob'
        union
        select friend.recieved_username, friend.isAccepted as friend 
        from friend where friend.sent_username = 'pat_bob'*/

        return ret;
    } catch (Exception e) {
        System.out.println("EXCEPTION:%% " + e);
    } finally {
        if (pstmt != null) {
            pstmt.close();
        }
        if (con != null) {
            con.close();
        }
    }
    return null;
}

From source file:com.draagon.meta.manager.db.driver.GenericSQLDriver.java

protected void parseField(Object o, MetaField f, ResultSet rs, int j) throws SQLException {
    switch (f.getType()) {
    case MetaField.BOOLEAN: {
        boolean bv = rs.getBoolean(j);
        if (rs.wasNull()) {
            f.setBoolean(o, null);/*from   w  w w.  j  av  a  2s  .co  m*/
        } else {
            f.setBoolean(o, new Boolean(bv));
        }
    }
        break;

    case MetaField.BYTE: {
        byte bv = rs.getByte(j);
        if (rs.wasNull()) {
            f.setByte(o, null);
        } else {
            f.setByte(o, new Byte(bv));
        }
    }
        break;

    case MetaField.SHORT: {
        short sv = rs.getShort(j);
        if (rs.wasNull()) {
            f.setShort(o, null);
        } else {
            f.setShort(o, new Short(sv));
        }
    }
        break;

    case MetaField.INT: {
        int iv = rs.getInt(j);
        if (rs.wasNull()) {
            f.setInt(o, null);
        } else {
            f.setInt(o, new Integer(iv));
        }
    }
        break;

    case MetaField.DATE: {
        Timestamp tv = rs.getTimestamp(j);
        if (rs.wasNull()) {
            f.setDate(o, null);
        } else {
            f.setDate(o, new java.util.Date(tv.getTime()));
        }
    }
        break;

    case MetaField.LONG: {
        long lv = rs.getLong(j);
        if (rs.wasNull()) {
            f.setLong(o, null);
        } else {
            f.setLong(o, new Long(lv));
        }
    }
        break;

    case MetaField.FLOAT: {
        float fv = rs.getFloat(j);
        if (rs.wasNull()) {
            f.setFloat(o, null);
        } else {
            f.setFloat(o, new Float(fv));
        }
    }
        break;

    case MetaField.DOUBLE: {
        double dv = rs.getDouble(j);
        if (rs.wasNull()) {
            f.setDouble(o, null);
        } else {
            f.setDouble(o, new Double(dv));
        }
    }
        break;

    case MetaField.STRING:
        f.setString(o, rs.getString(j));
        break;

    case MetaField.OBJECT:
        f.setObject(o, rs.getObject(j));
        break;
    }
}