Example usage for java.sql ResultSet getBytes

List of usage examples for java.sql ResultSet getBytes

Introduction

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

Prototype

byte[] getBytes(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 array in the Java programming language.

Usage

From source file:org.apache.james.mailrepository.jdbc.JDBCMailRepository.java

/**
 * @see org.apache.james.mailrepository.api.MailRepository#retrieve(String)
 *//*www . j a  v a  2s .  c om*/
@SuppressWarnings("unchecked")
public Mail retrieve(String key) throws MessagingException {
    if (DEEP_DEBUG) {
        System.err.println("retrieving " + key);
    }
    Connection conn = null;
    PreparedStatement retrieveMessage = null;
    ResultSet rsMessage = null;
    try {
        conn = datasource.getConnection();
        if (DEEP_DEBUG) {
            System.err.println("got a conn " + key);
        }

        retrieveMessage = conn.prepareStatement(sqlQueries.getSqlString("retrieveMessageSQL", true));
        retrieveMessage.setString(1, key);
        retrieveMessage.setString(2, repositoryName);
        rsMessage = retrieveMessage.executeQuery();
        if (DEEP_DEBUG) {
            System.err.println("ran the query " + key);
        }
        if (!rsMessage.next()) {
            if (getLogger().isDebugEnabled()) {
                String debugBuffer = "Did not find a record " + key + " in " + repositoryName;
                getLogger().debug(debugBuffer);
            }
            return null;
        }
        // Determine whether attributes are used and retrieve them
        PreparedStatement retrieveMessageAttr = null;
        HashMap<String, Object> attributes = null;
        if (jdbcMailAttributesReady) {
            String retrieveMessageAttrSql = sqlQueries.getSqlString("retrieveMessageAttributesSQL", false);
            ResultSet rsMessageAttr = null;
            try {
                retrieveMessageAttr = conn.prepareStatement(retrieveMessageAttrSql);

                retrieveMessageAttr.setString(1, key);
                retrieveMessageAttr.setString(2, repositoryName);
                rsMessageAttr = retrieveMessageAttr.executeQuery();

                if (rsMessageAttr.next()) {
                    try {
                        byte[] serialized_attr;
                        String getAttributesOption = sqlQueries.getDbOption("getAttributes");
                        if (getAttributesOption != null && (getAttributesOption.equalsIgnoreCase("useBlob")
                                || getAttributesOption.equalsIgnoreCase("useBinaryStream"))) {
                            Blob b = rsMessageAttr.getBlob(1);
                            serialized_attr = b.getBytes(1, (int) b.length());
                        } else {
                            serialized_attr = rsMessageAttr.getBytes(1);
                        }
                        // this check is for better backwards compatibility
                        if (serialized_attr != null) {
                            ByteArrayInputStream bais = new ByteArrayInputStream(serialized_attr);
                            ObjectInputStream ois = new ObjectInputStream(bais);
                            attributes = (HashMap<String, Object>) ois.readObject();
                            ois.close();
                        }
                    } catch (IOException ioe) {
                        if (getLogger().isDebugEnabled()) {
                            String debugBuffer = "Exception reading attributes " + key + " in "
                                    + repositoryName;
                            getLogger().debug(debugBuffer, ioe);
                        }
                    }
                } else {
                    if (getLogger().isDebugEnabled()) {
                        String debugBuffer = "Did not find a record (attributes) " + key + " in "
                                + repositoryName;
                        getLogger().debug(debugBuffer);
                    }
                }
            } catch (SQLException sqle) {
                String errorBuffer = "Error retrieving message" + sqle.getMessage() + sqle.getErrorCode()
                        + sqle.getSQLState() + sqle.getNextException();
                getLogger().error(errorBuffer);
            } finally {
                theJDBCUtil.closeJDBCResultSet(rsMessageAttr);
                theJDBCUtil.closeJDBCStatement(retrieveMessageAttr);
            }
        }

        MailImpl mc = new MailImpl();
        mc.setAttributesRaw(attributes);
        mc.setName(key);
        mc.setState(rsMessage.getString(1));
        mc.setErrorMessage(rsMessage.getString(2));
        String sender = rsMessage.getString(3);
        if (sender == null) {
            mc.setSender(null);
        } else {
            mc.setSender(new MailAddress(sender));
        }
        StringTokenizer st = new StringTokenizer(rsMessage.getString(4), "\r\n", false);
        Set<MailAddress> recipients = new HashSet<MailAddress>();
        while (st.hasMoreTokens()) {
            recipients.add(new MailAddress(st.nextToken()));
        }
        mc.setRecipients(recipients);
        mc.setRemoteHost(rsMessage.getString(5));
        mc.setRemoteAddr(rsMessage.getString(6));
        mc.setLastUpdated(rsMessage.getTimestamp(7));

        MimeMessageJDBCSource source = new MimeMessageJDBCSource(this, key, sr);
        MimeMessageCopyOnWriteProxy message = new MimeMessageCopyOnWriteProxy(source);
        mc.setMessage(message);
        return mc;
    } catch (SQLException sqle) {
        String errorBuffer = "Error retrieving message" + sqle.getMessage() + sqle.getErrorCode()
                + sqle.getSQLState() + sqle.getNextException();
        getLogger().error(errorBuffer);
        getLogger().debug("Failed to retrieve mail", sqle);
        throw new MessagingException("Exception while retrieving mail: " + sqle.getMessage(), sqle);
    } catch (Exception me) {
        throw new MessagingException("Exception while retrieving mail: " + me.getMessage(), me);
    } finally {
        theJDBCUtil.closeJDBCResultSet(rsMessage);
        theJDBCUtil.closeJDBCStatement(retrieveMessage);
        theJDBCUtil.closeJDBCConnection(conn);
    }
}

From source file:com.pinterest.pinlater.backends.mysql.PinLaterMySQLBackend.java

@Override
protected PinLaterJobInfo lookupJobFromShard(final String queueName, final String shardName, final int priority,
        final long localId, final boolean isIncludeBody) throws Exception {
    final String mySQLQuery = isIncludeBody ? MySQLQueries.LOOKUP_JOB_WITH_BODY : MySQLQueries.LOOKUP_JOB;
    String jobsTableName = MySQLBackendUtils.constructJobsTableName(queueName, shardName, priority);
    Connection conn = null;/*w  w  w.j  a va  2s  .  c  o  m*/
    ImmutableMap<String, MySQLDataSources> shardMap = shardMapRef.get();
    try {
        conn = shardMap.get(shardName).getGeneralDataSource().getConnection();
        PinLaterJobInfo jobInfo = JdbcUtils.selectOne(conn, String.format(mySQLQuery, jobsTableName),
                new RowProcessor<PinLaterJobInfo>() {
                    @Override
                    public PinLaterJobInfo process(ResultSet rs) throws IOException, SQLException {
                        PinLaterJobInfo ji = new PinLaterJobInfo();
                        ji.setJobDescriptor(
                                new PinLaterJobDescriptor(queueName, shardName, priority, rs.getLong(1))
                                        .toString());
                        ji.setJobState(PinLaterJobState.findByValue(rs.getInt(2)));
                        ji.setAttemptsAllowed(rs.getInt(3));
                        ji.setAttemptsRemaining(rs.getInt(4));
                        ji.setCreatedAtTimestampMillis(rs.getTimestamp(5).getTime());
                        ji.setRunAfterTimestampMillis(rs.getTimestamp(6).getTime());
                        ji.setUpdatedAtTimestampMillis(rs.getTimestamp(7).getTime());
                        String claimDescriptor = rs.getString(8);
                        if (claimDescriptor != null) {
                            ji.setClaimDescriptor(claimDescriptor);
                        }
                        ;
                        ji.setCustomStatus(Strings.nullToEmpty(rs.getString(9)));
                        if (isIncludeBody) {
                            ji.setBody(rs.getBytes(10));
                        }
                        return ji;
                    }
                }, localId);
        return jobInfo;
    } finally {
        JdbcUtils.closeConnection(conn);
    }
}

From source file:uk.ac.kcl.rowmappers.DocumentRowMapper.java

private void mapDBFields(Document doc, ResultSet rs) throws SQLException, IOException {
    //add additional query fields for ES export
    ResultSetMetaData meta = rs.getMetaData();

    int colCount = meta.getColumnCount();

    for (int col = 1; col <= colCount; col++) {
        Object value = rs.getObject(col);
        if (value != null) {
            String colLabel = meta.getColumnLabel(col).toLowerCase();
            if (!fieldsToIgnore.contains(colLabel)) {
                DateTime dateTime;//from  w  w  w  . j  a  v a2  s .c o  m
                //map correct SQL time types
                switch (meta.getColumnType(col)) {
                case 91:
                    Date dt = (Date) value;
                    dateTime = new DateTime(dt.getTime());
                    doc.getAssociativeArray().put(meta.getColumnLabel(col).toLowerCase(),
                            eSCompatibleDateTimeFormatter.print(dateTime));
                    break;
                case 93:
                    Timestamp ts = (Timestamp) value;
                    dateTime = new DateTime(ts.getTime());
                    doc.getAssociativeArray().put(meta.getColumnLabel(col).toLowerCase(),
                            eSCompatibleDateTimeFormatter.print(dateTime));
                    break;
                default:
                    doc.getAssociativeArray().put(meta.getColumnLabel(col).toLowerCase(), rs.getString(col));
                    break;
                }
            }
        }

        //map binary content from FS or database if required (as per docman reader)
        if (value != null && meta.getColumnLabel(col).equalsIgnoreCase(binaryContentFieldName)) {
            switch (binaryContentSource) {
            case "database":
                doc.setBinaryContent(rs.getBytes(col));
                break;
            case "fileSystemWithDBPath":
                Resource resource = context.getResource(pathPrefix + rs.getString(col));
                doc.setBinaryContent(IOUtils.toByteArray(resource.getInputStream()));
                break;
            default:
                break;
            }
        }
    }
}

From source file:org.apache.qpid.server.store.derby.DerbyMessageStore.java

private void recoverXids(TransactionLogRecoveryHandler.DtxRecordRecoveryHandler dtxrh) throws SQLException {
    Connection conn = newAutoCommitConnection();
    try {/*  w  w w  .  j  av  a2s  . c om*/
        List<Xid> xids = new ArrayList<Xid>();

        Statement stmt = conn.createStatement();
        try {
            ResultSet rs = stmt.executeQuery(SELECT_ALL_FROM_XIDS);
            try {
                while (rs.next()) {

                    long format = rs.getLong(1);
                    byte[] globalId = rs.getBytes(2);
                    byte[] branchId = rs.getBytes(3);
                    xids.add(new Xid(format, globalId, branchId));
                }
            } finally {
                rs.close();
            }
        } finally {
            stmt.close();
        }

        for (Xid xid : xids) {
            List<RecordImpl> enqueues = new ArrayList<RecordImpl>();
            List<RecordImpl> dequeues = new ArrayList<RecordImpl>();

            PreparedStatement pstmt = conn.prepareStatement(SELECT_ALL_FROM_XID_ACTIONS);

            try {
                pstmt.setLong(1, xid.getFormat());
                pstmt.setBytes(2, xid.getGlobalId());
                pstmt.setBytes(3, xid.getBranchId());

                ResultSet rs = pstmt.executeQuery();
                try {
                    while (rs.next()) {

                        String actionType = rs.getString(1);
                        UUID queueId = UUID.fromString(rs.getString(2));
                        long messageId = rs.getLong(3);

                        RecordImpl record = new RecordImpl(queueId, messageId);
                        List<RecordImpl> records = "E".equals(actionType) ? enqueues : dequeues;
                        records.add(record);
                    }
                } finally {
                    rs.close();
                }
            } finally {
                pstmt.close();
            }

            dtxrh.dtxRecord(xid.getFormat(), xid.getGlobalId(), xid.getBranchId(),
                    enqueues.toArray(new RecordImpl[enqueues.size()]),
                    dequeues.toArray(new RecordImpl[dequeues.size()]));
        }

        dtxrh.completeDtxRecordRecovery();
    } finally {
        conn.close();
    }

}

From source file:chh.utils.db.source.common.JdbcClient.java

public List<List<Column>> select(String sqlQuery, List<Column> queryParams) {
    Connection connection = null;
    try {//from w w  w  .  java 2 s.  c  om
        connection = connectionProvider.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery);
        if (queryTimeoutSecs > 0) {
            preparedStatement.setQueryTimeout(queryTimeoutSecs);
        }
        setPreparedStatementParams(preparedStatement, queryParams);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<List<Column>> rows = Lists.newArrayList();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            List<Column> row = Lists.newArrayList();
            for (int i = 1; i <= columnCount; i++) {
                String columnLabel = metaData.getColumnLabel(i);
                int columnType = metaData.getColumnType(i);
                Class columnJavaType = Util.getJavaType(columnType);
                if (columnJavaType.equals(String.class)) {
                    row.add(new Column<String>(columnLabel, resultSet.getString(columnLabel), columnType));
                } else if (columnJavaType.equals(Integer.class)) {
                    row.add(new Column<Integer>(columnLabel, resultSet.getInt(columnLabel), columnType));
                } else if (columnJavaType.equals(Double.class)) {
                    row.add(new Column<Double>(columnLabel, resultSet.getDouble(columnLabel), columnType));
                } else if (columnJavaType.equals(Float.class)) {
                    row.add(new Column<Float>(columnLabel, resultSet.getFloat(columnLabel), columnType));
                } else if (columnJavaType.equals(Short.class)) {
                    row.add(new Column<Short>(columnLabel, resultSet.getShort(columnLabel), columnType));
                } else if (columnJavaType.equals(Boolean.class)) {
                    row.add(new Column<Boolean>(columnLabel, resultSet.getBoolean(columnLabel), columnType));
                } else if (columnJavaType.equals(byte[].class)) {
                    row.add(new Column<byte[]>(columnLabel, resultSet.getBytes(columnLabel), columnType));
                } else if (columnJavaType.equals(Long.class)) {
                    row.add(new Column<Long>(columnLabel, resultSet.getLong(columnLabel), columnType));
                } else if (columnJavaType.equals(Date.class)) {
                    row.add(new Column<Date>(columnLabel, resultSet.getDate(columnLabel), columnType));
                } else if (columnJavaType.equals(Time.class)) {
                    row.add(new Column<Time>(columnLabel, resultSet.getTime(columnLabel), columnType));
                } else if (columnJavaType.equals(Timestamp.class)) {
                    row.add(new Column<Timestamp>(columnLabel, resultSet.getTimestamp(columnLabel),
                            columnType));
                } else {
                    throw new RuntimeException(
                            "type =  " + columnType + " for column " + columnLabel + " not supported.");
                }
            }
            rows.add(row);
        }
        return rows;
    } catch (SQLException e) {
        throw new RuntimeException("Failed to execute select query " + sqlQuery, e);
    } finally {
        closeConnection(connection);
    }
}

From source file:org.infoglue.cms.util.workflow.InfoGlueJDBCPropertySet.java

public Collection getKeys(String prefix, int type) throws PropertyException {
    //logger.info("isRecacheCall:" + isRecacheCall);
    Map currentTypeMap = typeMap;
    Map currentValueMap = valueMap;

    if (prefix == null) {
        prefix = "";
    }// w w  w  .  j  av  a2  s.  co  m

    Connection conn = null;

    try {
        logger.info("Getting keys with prefix:" + prefix + " and type: " + type);
        conn = getConnection();

        PreparedStatement ps = null;
        String sql = "SELECT " + colItemKey + "," + colItemType + ", " + colString + ", " + colDate + ", "
                + colData + ", " + colFloat + ", " + colNumber + " FROM " + tableName + " WHERE " + colItemKey
                + " LIKE ? AND " + colGlobalKey + " = ?";

        if (logger.isInfoEnabled()) {
            logger.info("app:" + CmsPropertyHandler.getApplicationName());
            logger.info("operating mode:" + CmsPropertyHandler.getOperatingMode());
        }

        if (CmsPropertyHandler.getApplicationName().equalsIgnoreCase("deliver")
                && CmsPropertyHandler.getOperatingMode().equalsIgnoreCase("3")) {
            sql = "SELECT " + colItemKey + "," + colItemType + ", " + colString + ", " + colDate + ", "
                    + colData + ", " + colFloat + ", " + colNumber + " FROM " + tableName;
            sql += " WHERE ";
            sql += "" + colItemKey + " LIKE ? AND ";
            sql += "" + colItemKey + " NOT LIKE 'principal_%_languageCode' AND ";
            sql += "" + colItemKey + " NOT LIKE 'principal_%_defaultToolName' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'principal_%_defaultGUI' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'principal_%_theme' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'content_%_allowedContentTypeNames' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'content_%_defaultContentTypeName' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'content_%_initialLanguageId' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'repository_%_defaultFolderContentTypeName' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'repository_%_defaultTemplateRepository' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'repository_%_parentRepository' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'repository_%_WYSIWYGConfig' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'repository_%_StylesXML' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'repository_%_extraProperties' AND  ";
            sql += "" + colGlobalKey + " = ? ";
        }

        if (logger.isInfoEnabled())
            logger.info("sql:" + sql);

        if (type == 0) {
            ps = conn.prepareStatement(sql);
            ps.setString(1, prefix + "%");
            ps.setString(2, globalKey);
        } else {
            sql = sql + " AND " + colItemType + " = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, prefix + "%");
            ps.setString(2, globalKey);
            ps.setInt(3, type);
        }

        Timer t = new Timer();

        ArrayList list = new ArrayList();
        ResultSet rs = ps.executeQuery();

        int rows = 0;
        while (rs.next()) {
            rows++;
            String key = rs.getString(colItemKey);
            int typeId = rs.getInt(colItemType);

            if (logger.isInfoEnabled())
                logger.info("key[" + typeId + "]:" + key);

            list.add(key);

            if (typeMap == null)
                typeMap = new HashMap();
            if (typeMapFallback == null)
                typeMapFallback = new HashMap();

            currentTypeMap = typeMap;
            if (isRecacheCall)
                currentTypeMap = typeMapFallback;

            synchronized (currentTypeMap) {
                currentTypeMap.put(key, new Integer(typeId));
            }

            Object o = null;

            switch (typeId) {
            case PropertySet.BOOLEAN:

                int boolVal = rs.getInt(colNumber);
                o = new Boolean(boolVal == 1);

                break;

            case PropertySet.DATA:
                o = rs.getBytes(colData);

                break;

            case PropertySet.DATE:
                o = rs.getTimestamp(colDate);

                break;

            case PropertySet.DOUBLE:
                o = new Double(rs.getDouble(colFloat));

                break;

            case PropertySet.INT:
                o = new Integer(rs.getInt(colNumber));

                break;

            case PropertySet.LONG:
                o = new Long(rs.getLong(colNumber));

                break;

            case PropertySet.STRING:
                o = rs.getString(colString);

                break;

            default:
                logger.error("JDBCPropertySet doesn't support this type yet:" + key + ":" + typeId);
                //throw new InvalidPropertyTypeException("JDBCPropertySet doesn't support this type yet:" + typeId);
            }

            if (valueMap == null)
                valueMap = new HashMap();
            if (valueMapFallback == null)
                valueMapFallback = new HashMap();

            currentValueMap = valueMap;
            if (isRecacheCall)
                currentValueMap = valueMapFallback;

            synchronized (currentValueMap) {
                currentValueMap.put(key, o);
            }
        }
        if (logger.isInfoEnabled())
            t.printElapsedTime("All rows in InfoGlueJDBCPropertySet [" + rows + "] took");

        allKeysCached = true;
        if (isRecacheCall) {
            //logger.info("Switching valueMap from:" + valueMap.hashCode() + " --> " + currentValueMap.hashCode());
            typeMap = currentTypeMap;
            valueMap = currentValueMap;
            typeMapFallback = new HashMap();
            valueMapFallback = new HashMap();
        }

        rs.close();
        ps.close();

        return list;
    } catch (SQLException e) {
        logger.error("Problem getting keys due to an SQL exception:" + e.getCause().getMessage(), e);
        throw new PropertyException(e.getMessage());
    } finally {
        closeConnection(conn);
        isRecacheCall = false;
    }
}

From source file:org.photovault.common.SchemaUpdateAction.java

private void convertPhotos() throws SQLException {
    SchemaUpdateOperation oper = new SchemaUpdateOperation("Converting photos");
    Session s = HibernateUtil.getSessionFactory().openSession();
    HibernateDAOFactory daoFactory = (HibernateDAOFactory) DAOFactory.instance(HibernateDAOFactory.class);
    daoFactory.setSession(s);// w  w w.  j  av a  2  s.  c om
    DTOResolverFactory rf = daoFactory.getDTOResolverFactory();
    PhotoInfoDAO photoDao = daoFactory.getPhotoInfoDAO();
    ImageDescriptorDAO imgDao = daoFactory.getImageDescriptorDAO();
    ImageFileDAO ifDao = daoFactory.getImageFileDAO();
    VolumeDAO volDao = daoFactory.getVolumeDAO();

    /*
    We need a second session for reading old data so that Hibernate can 
    commit its changes
     */
    Session sqlSess = HibernateUtil.getSessionFactory().openSession();
    Connection conn = sqlSess.connection();
    Statement stmt = conn.createStatement();
    ResultSet countRs = stmt.executeQuery("select count(*) from photos");
    int photoCount = -1;
    if (countRs.next()) {
        photoCount = countRs.getInt(1);
    }
    countRs.close();
    ResultSet rs = stmt.executeQuery(oldPhotoQuerySql);
    int currentPhotoId = -1;
    OriginalImageDescriptor currentOriginal = null;
    long photoStartTime = -1;
    int convertedCount = -1;

    while (rs.next()) {
        int photoId = rs.getInt("p_photo_id");
        boolean isNewPhoto = false;
        if (photoId != currentPhotoId) {
            isNewPhoto = true;
            currentPhotoId = photoId;
            convertedCount++;
            fireStatusChangeEvent(new SchemaUpdateEvent(oper, convertedCount * 100 / photoCount));
            /*
            Photos are not dependent from each other, so clear the session 
            cache to improve performance and memory usage.
             */
            s.clear();
            log.debug("finished photo " + currentPhotoId + " in "
                    + (System.currentTimeMillis() - photoStartTime) + " ms");
            log.debug("Starting photo " + photoId);
            photoStartTime = System.currentTimeMillis();
        }
        // Create the image file corresponding to this row

        ImageFile imgf = ifDao.findImageFileWithHash(rs.getBytes("i_hash"));
        if (imgf == null) {
            // The file was not previously known, create
            imgf = new ImageFile();

            imgf.setFileSize(rs.getInt("i_file_size"));
            imgf.setHash(rs.getBytes("i_hash"));
            String instUuid = rs.getString("i_instance_uuid");
            if (instUuid != null) {
                imgf.setId(UUID.fromString(instUuid));
            } else {
                imgf.setId(UUID.randomUUID());
            }
            if (rs.getInt("i_is_original") == 1) {
                currentOriginal = new OriginalImageDescriptor(imgf, "image#0");
                currentOriginal.setHeight(rs.getInt("i_height"));
                currentOriginal.setWidth(rs.getInt("i_width"));
            } else {
                CopyImageDescriptor cimg = new CopyImageDescriptor(imgf, "image#0", currentOriginal);
                ChannelMapOperation cm = ChannelMapOperationFactory
                        .createFromXmlData(rs.getBytes("i_channel_map"));
                cimg.setColorChannelMapping(cm);
                Rectangle2D crop = readCropArea(rs, "i_crop_");
                cimg.setCropArea(crop);
                cimg.setHeight(rs.getInt("i_height"));
                cimg.setWidth(rs.getInt("i_width"));
                cimg.setRotation(rs.getDouble("i_rotated"));
                // Does this instance have raw conversion applied?
                rs.getDouble("i_whitepoint");
                if (!rs.wasNull()) {
                    RawConversionSettings r = readRawSettings(rs, "i_");
                    cimg.setRawSettings(r);
                }
                // imgDao.makePersistent( cimg );
            }

            ifDao.makePersistent(imgf);
        } else {
            log.debug("Found existing file with id " + imgf.getId());
            // TODO: verify that the file matches
            ImageDescriptorBase img = imgf.getImage("image#0");
            if (img instanceof OriginalImageDescriptor) {
                /*
                 The existing image is original. Use it for this photo as well
                 */
                if (isNewPhoto) {
                    currentOriginal = (OriginalImageDescriptor) img;
                }
                /*
                 TODO: If we have already different original for this photo,
                 then the previous judgment that this file is an original
                 is wrong. Delete it and modify connected photos to use original
                 of this photo as theri original!!!
                 */
            } else {
                /*
                 The existing image is a copy.
                 */
                if (rs.getInt("i_is_original") == 1) {
                    /*
                     The old database image instance is marked as original 
                     but we already know that this is a copy of another image.
                             
                     TODO: calculate all parameters by combining the 
                     transformations made for these two!!!
                     */
                    log.warn("Resetting original to another image");
                } else if (((CopyImageDescriptor) img).getOriginal() != currentOriginal) {
                    /*
                     Not much we can do. This is a known copy of some other image,
                     so for now we just add information of the location to 
                     database. We cannot associate the copy with two originals.                         
                     */
                    log.warn("Existing copy has different original!!!");
                }
            }
        }

        String volName = rs.getString("i_volume_id");
        UUID volUuid = volIds.get(volName);
        if (volUuid != null) {
            FileLocation fl = new FileLocation(volDao.findById(volUuid, false), rs.getString("i_fname"));
            imgf.addLocation(fl);
        }

        if (isNewPhoto) {
            convertPhotoInfo(rs, rf, currentOriginal, photoDao);
        }
        s.flush();
    }
    s.close();
    try {
        rs.close();
        stmt.close();
        sqlSess.close();
    } catch (SQLException e) {
        log.error(e);
        throw e;
    }

}

From source file:net.pms.dlna.DLNAMediaDatabase.java

public ArrayList<DLNAMediaInfo> getData(String name, long modified) {
    ArrayList<DLNAMediaInfo> list = new ArrayList<DLNAMediaInfo>();
    Connection conn = null;/*from  ww  w . j av  a2 s. c om*/
    ResultSet rs = null;
    PreparedStatement stmt = null;
    try {
        conn = getConnection();
        stmt = conn.prepareStatement("SELECT * FROM FILES WHERE FILENAME = ? AND MODIFIED = ?");
        stmt.setString(1, name);
        stmt.setTimestamp(2, new Timestamp(modified));
        rs = stmt.executeQuery();
        while (rs.next()) {
            DLNAMediaInfo media = new DLNAMediaInfo();
            int id = rs.getInt("ID");
            media.setDuration(toDouble(rs, "DURATION"));
            media.setBitrate(rs.getInt("BITRATE"));
            media.setWidth(rs.getInt("WIDTH"));
            media.setHeight(rs.getInt("HEIGHT"));
            media.setSize(rs.getLong("SIZE"));
            media.setCodecV(rs.getString("CODECV"));
            media.setFrameRate(rs.getString("FRAMERATE"));
            media.setAspect(rs.getString("ASPECT"));
            media.setAspectRatioContainer(rs.getString("ASPECTRATIOCONTAINER"));
            media.setAspectRatioVideoTrack(rs.getString("ASPECTRATIOVIDEOTRACK"));
            media.setReferenceFrameCount(rs.getByte("REFRAMES"));
            media.setAvcLevel(rs.getString("AVCLEVEL"));
            media.setBitsPerPixel(rs.getInt("BITSPERPIXEL"));
            media.setThumb(rs.getBytes("THUMB"));
            media.setContainer(rs.getString("CONTAINER"));
            media.setModel(rs.getString("MODEL"));
            if (media.getModel() != null && !FormatConfiguration.JPG.equals(media.getContainer())) {
                media.setExtrasAsString(media.getModel());
            }
            media.setExposure(rs.getInt("EXPOSURE"));
            media.setOrientation(rs.getInt("ORIENTATION"));
            media.setIso(rs.getInt("ISO"));
            media.setMuxingMode(rs.getString("MUXINGMODE"));
            media.setFrameRateMode(rs.getString("FRAMERATEMODE"));
            media.setMediaparsed(true);
            PreparedStatement audios = conn.prepareStatement("SELECT * FROM AUDIOTRACKS WHERE FILEID = ?");
            audios.setInt(1, id);
            ResultSet subrs = audios.executeQuery();
            while (subrs.next()) {
                DLNAMediaAudio audio = new DLNAMediaAudio();
                audio.setId(subrs.getInt("ID"));
                audio.setLang(subrs.getString("LANG"));
                audio.setFlavor(subrs.getString("FLAVOR"));
                audio.getAudioProperties().setNumberOfChannels(subrs.getInt("NRAUDIOCHANNELS"));
                audio.setSampleFrequency(subrs.getString("SAMPLEFREQ"));
                audio.setCodecA(subrs.getString("CODECA"));
                audio.setBitsperSample(subrs.getInt("BITSPERSAMPLE"));
                audio.setAlbum(subrs.getString("ALBUM"));
                audio.setArtist(subrs.getString("ARTIST"));
                audio.setSongname(subrs.getString("SONGNAME"));
                audio.setGenre(subrs.getString("GENRE"));
                audio.setYear(subrs.getInt("YEAR"));
                audio.setTrack(subrs.getInt("TRACK"));
                audio.getAudioProperties().setAudioDelay(subrs.getInt("DELAY"));
                audio.setMuxingModeAudio(subrs.getString("MUXINGMODE"));
                audio.setBitRate(subrs.getInt("BITRATE"));
                media.getAudioTracksList().add(audio);
            }
            subrs.close();
            audios.close();

            PreparedStatement subs = conn.prepareStatement("SELECT * FROM SUBTRACKS WHERE FILEID = ?");
            subs.setInt(1, id);
            subrs = subs.executeQuery();
            while (subrs.next()) {
                DLNAMediaSubtitle sub = new DLNAMediaSubtitle();
                sub.setId(subrs.getInt("ID"));
                sub.setLang(subrs.getString("LANG"));
                sub.setFlavor(subrs.getString("FLAVOR"));
                sub.setType(SubtitleType.valueOfStableIndex(subrs.getInt("TYPE")));
                media.getSubtitleTracksList().add(sub);
            }
            subrs.close();
            subs.close();

            list.add(media);
        }
    } catch (SQLException se) {
        logger.error(null, se);
        return null;
    } finally {
        close(rs);
        close(stmt);
        close(conn);
    }
    return list;
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

public Field resultToField(ResultSetMetaData md, ResultSet rs, int columnIndex, int maxClobSize,
        int maxBlobSize, DataType userSpecifiedType, UnknownTypeAction unknownTypeAction,
        boolean timestampToString) throws SQLException, IOException, StageException {
    Field field;//from w w w. jav a 2  s .c o  m
    if (userSpecifiedType != DataType.USE_COLUMN_TYPE) {
        // If user specifies the data type, overwrite the column type returned by database.
        field = Field.create(Field.Type.valueOf(userSpecifiedType.getLabel()), rs.getObject(columnIndex));
    } else {
        // All types as of JDBC 2.0 are here:
        // https://docs.oracle.com/javase/8/docs/api/constant-values.html#java.sql.Types.ARRAY
        // Good source of recommended mappings is here:
        // http://www.cs.mun.ca/java-api-1.5/guide/jdbc/getstart/mapping.html
        switch (md.getColumnType(columnIndex)) {
        case Types.BIGINT:
            field = Field.create(Field.Type.LONG, rs.getObject(columnIndex));
            break;
        case Types.BINARY:
        case Types.LONGVARBINARY:
        case Types.VARBINARY:
            field = Field.create(Field.Type.BYTE_ARRAY, rs.getBytes(columnIndex));
            break;
        case Types.BIT:
        case Types.BOOLEAN:
            field = Field.create(Field.Type.BOOLEAN, rs.getObject(columnIndex));
            break;
        case Types.CHAR:
        case Types.LONGNVARCHAR:
        case Types.LONGVARCHAR:
        case Types.NCHAR:
        case Types.NVARCHAR:
        case Types.VARCHAR:
            field = Field.create(Field.Type.STRING, rs.getObject(columnIndex));
            break;
        case Types.CLOB:
        case Types.NCLOB:
            field = Field.create(Field.Type.STRING, getClobString(rs.getClob(columnIndex), maxClobSize));
            break;
        case Types.BLOB:
            field = Field.create(Field.Type.BYTE_ARRAY, getBlobBytes(rs.getBlob(columnIndex), maxBlobSize));
            break;
        case Types.DATE:
            field = Field.create(Field.Type.DATE, rs.getDate(columnIndex));
            break;
        case Types.DECIMAL:
        case Types.NUMERIC:
            field = Field.create(Field.Type.DECIMAL, rs.getBigDecimal(columnIndex));
            field.setAttribute(HeaderAttributeConstants.ATTR_SCALE,
                    String.valueOf(rs.getMetaData().getScale(columnIndex)));
            field.setAttribute(HeaderAttributeConstants.ATTR_PRECISION,
                    String.valueOf(rs.getMetaData().getPrecision(columnIndex)));
            break;
        case Types.DOUBLE:
            field = Field.create(Field.Type.DOUBLE, rs.getObject(columnIndex));
            break;
        case Types.FLOAT:
        case Types.REAL:
            field = Field.create(Field.Type.FLOAT, rs.getObject(columnIndex));
            break;
        case Types.INTEGER:
            field = Field.create(Field.Type.INTEGER, rs.getObject(columnIndex));
            break;
        case Types.ROWID:
            field = Field.create(Field.Type.STRING, rs.getRowId(columnIndex).toString());
            break;
        case Types.SMALLINT:
        case Types.TINYINT:
            field = Field.create(Field.Type.SHORT, rs.getObject(columnIndex));
            break;
        case Types.TIME:
            field = Field.create(Field.Type.TIME, rs.getObject(columnIndex));
            break;
        case Types.TIMESTAMP:
            final Timestamp timestamp = rs.getTimestamp(columnIndex);
            if (timestampToString) {
                field = Field.create(Field.Type.STRING, timestamp == null ? null : timestamp.toString());
            } else {
                field = Field.create(Field.Type.DATETIME, timestamp);
                if (timestamp != null) {
                    final long actualNanos = timestamp.getNanos() % NANOS_TO_MILLIS_ADJUSTMENT;
                    if (actualNanos > 0) {
                        field.setAttribute(FIELD_ATTRIBUTE_NANOSECONDS, String.valueOf(actualNanos));
                    }
                }
            }
            break;
        // Ugly hack until we can support LocalTime, LocalDate, LocalDateTime, etc.
        case Types.TIME_WITH_TIMEZONE:
            OffsetTime offsetTime = rs.getObject(columnIndex, OffsetTime.class);
            field = Field.create(Field.Type.TIME, Date.from(offsetTime.atDate(LocalDate.MIN).toInstant()));
            break;
        case Types.TIMESTAMP_WITH_TIMEZONE:
            OffsetDateTime offsetDateTime = rs.getObject(columnIndex, OffsetDateTime.class);
            field = Field.create(Field.Type.ZONED_DATETIME, offsetDateTime.toZonedDateTime());
            break;
        //case Types.REF_CURSOR: // JDK8 only
        case Types.SQLXML:
        case Types.STRUCT:
        case Types.ARRAY:
        case Types.DATALINK:
        case Types.DISTINCT:
        case Types.JAVA_OBJECT:
        case Types.NULL:
        case Types.OTHER:
        case Types.REF:
        default:
            if (unknownTypeAction == null) {
                return null;
            }
            switch (unknownTypeAction) {
            case STOP_PIPELINE:
                throw new StageException(JdbcErrors.JDBC_37, md.getColumnType(columnIndex),
                        md.getColumnLabel(columnIndex));
            case CONVERT_TO_STRING:
                Object value = rs.getObject(columnIndex);
                if (value != null) {
                    field = Field.create(Field.Type.STRING, rs.getObject(columnIndex).toString());
                } else {
                    field = Field.create(Field.Type.STRING, null);
                }
                break;
            default:
                throw new IllegalStateException("Unknown action: " + unknownTypeAction);
            }
        }
    }

    return field;
}

From source file:org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager.java

/**
 * Performs a consistency check.//  w ww .j a v a 2 s. co  m
 */
private void checkConsistency() {
    int count = 0;
    int total = 0;
    log.info("{}: checking workspace consistency...", name);

    Collection modifications = new ArrayList();
    ResultSet rs = null;
    DataInputStream din = null;
    try {
        String sql;
        if (getStorageModel() == SM_BINARY_KEYS) {
            sql = "select NODE_ID, BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE";
        } else {
            sql = "select NODE_ID_HI, NODE_ID_LO, BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE";
        }
        Statement stmt = connectionManager.executeStmt(sql, new Object[0]);
        rs = stmt.getResultSet();
        while (rs.next()) {
            NodeId id;
            Blob blob;
            if (getStorageModel() == SM_BINARY_KEYS) {
                id = new NodeId(new UUID(rs.getBytes(1)));
                blob = rs.getBlob(2);
            } else {
                id = new NodeId(new UUID(rs.getLong(1), rs.getLong(2)));
                blob = rs.getBlob(3);
            }
            din = new DataInputStream(blob.getBinaryStream());
            try {
                NodePropBundle bundle = binding.readBundle(din, id);
                Collection missingChildren = new ArrayList();
                Iterator iter = bundle.getChildNodeEntries().iterator();
                while (iter.hasNext()) {
                    NodePropBundle.ChildNodeEntry entry = (NodePropBundle.ChildNodeEntry) iter.next();
                    if (entry.getId().toString().endsWith("babecafebabe")) {
                        continue;
                    }
                    if (id.toString().endsWith("babecafebabe")) {
                        continue;
                    }
                    try {
                        NodePropBundle child = loadBundle(entry.getId());
                        if (child == null) {
                            log.error("NodeState " + id.getUUID() + " references inexistent child "
                                    + entry.getName() + " with id " + entry.getId().getUUID());
                            missingChildren.add(entry);
                        } else {
                            NodeId cp = child.getParentId();
                            if (cp == null) {
                                log.error("ChildNode has invalid parent uuid: null");
                            } else if (!cp.equals(id)) {
                                log.error("ChildNode has invalid parent uuid: " + cp + " (instead of "
                                        + id.getUUID() + ")");
                            }
                        }
                    } catch (ItemStateException e) {
                        log.error("Error while loading child node: " + e);
                    }
                }
                if (consistencyFix && !missingChildren.isEmpty()) {
                    Iterator iterator = missingChildren.iterator();
                    while (iterator.hasNext()) {
                        bundle.getChildNodeEntries().remove(iterator.next());
                    }
                    modifications.add(bundle);
                }

                NodeId parentId = bundle.getParentId();
                if (parentId != null) {
                    if (!exists(parentId)) {
                        log.error("NodeState " + id + " references inexistent parent id " + parentId);
                    }
                }
            } catch (IOException e) {
                log.error("Error in bundle " + id + ": " + e);
                din = new DataInputStream(blob.getBinaryStream());
                binding.checkBundle(din);
            }
            count++;
            if (count % 1000 == 0) {
                log.info(name + ": checked " + count + "/" + total + " bundles...");
            }
        }
    } catch (Exception e) {
        log.error("Error in bundle", e);
    } finally {
        IOUtils.closeQuietly(din);
        closeResultSet(rs);
    }

    if (consistencyFix && !modifications.isEmpty()) {
        log.info(name + ": Fixing " + modifications.size() + " inconsistent bundle(s)...");
        Iterator iterator = modifications.iterator();
        while (iterator.hasNext()) {
            NodePropBundle bundle = (NodePropBundle) iterator.next();
            try {
                log.info(name + ": Fixing bundle " + bundle.getId());
                bundle.markOld(); // use UPDATE instead of INSERT
                storeBundle(bundle);
            } catch (ItemStateException e) {
                log.error(name + ": Error storing fixed bundle: " + e);
            }
        }
    }

    log.info(name + ": checked " + count + "/" + total + " bundles.");
}