Example usage for java.sql ResultSet getBoolean

List of usage examples for java.sql ResultSet getBoolean

Introduction

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

Prototype

boolean getBoolean(String columnLabel) throws SQLException;

Source Link

Document

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

Usage

From source file:com.mirth.connect.server.migration.Migrate3_0_0.java

private void migrateChannelTable() {
    PreparedStatement preparedStatement = null;
    ResultSet results = null;

    try {/*from w  w  w  .  j a  v  a 2  s . c om*/
        /*
         * MIRTH-1667: Derby fails if autoCommit is set to true and there are a large number of
         * results. The following error occurs: "ERROR 40XD0: Container has been closed"
         */
        Connection connection = getConnection();
        connection.setAutoCommit(false);

        preparedStatement = connection.prepareStatement(
                "SELECT ID, NAME, DESCRIPTION, IS_ENABLED, VERSION, REVISION, LAST_MODIFIED, SOURCE_CONNECTOR, DESTINATION_CONNECTORS, PROPERTIES, PREPROCESSING_SCRIPT, POSTPROCESSING_SCRIPT, DEPLOY_SCRIPT, SHUTDOWN_SCRIPT FROM OLD_CHANNEL");
        results = preparedStatement.executeQuery();

        while (results.next()) {
            String channelId = "";

            try {
                channelId = results.getString(1);
                String name = results.getString(2);
                String description = results.getString(3);
                Boolean isEnabled = results.getBoolean(4);
                String version = results.getString(5);
                Integer revision = results.getInt(6);

                Calendar lastModified = Calendar.getInstance();
                lastModified.setTimeInMillis(results.getTimestamp(7).getTime());

                String sourceConnector = results.getString(8);
                String destinationConnectors = results.getString(9);
                String properties = results.getString(10);
                String preprocessingScript = results.getString(11);
                String postprocessingScript = results.getString(12);
                String deployScript = results.getString(13);
                String shutdownScript = results.getString(14);

                Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                Element element = document.createElement("channel");
                document.appendChild(element);
                DonkeyElement channel = new DonkeyElement(element);

                channel.addChildElement("id", channelId);
                channel.addChildElement("name", name);
                channel.addChildElement("description", description);
                channel.addChildElement("enabled", Boolean.toString(isEnabled));
                channel.addChildElement("version", version);

                DonkeyElement lastModifiedElement = channel.addChildElement("lastModified");
                lastModifiedElement.addChildElement("time", String.valueOf(lastModified.getTimeInMillis()));
                lastModifiedElement.addChildElement("timezone", lastModified.getTimeZone().getDisplayName());

                channel.addChildElement("revision", String.valueOf(revision));

                channel.addChildElementFromXml(sourceConnector).setNodeName("sourceConnector");
                channel.addChildElementFromXml(destinationConnectors).setNodeName("destinationConnectors");
                channel.addChildElementFromXml(properties);

                channel.addChildElement("preprocessingScript", preprocessingScript);
                channel.addChildElement("postprocessingScript", postprocessingScript);
                channel.addChildElement("deployScript", deployScript);
                channel.addChildElement("shutdownScript", shutdownScript);

                String serializedChannel = channel.toXml();

                PreparedStatement updateStatement = null;

                try {
                    updateStatement = connection.prepareStatement(
                            "INSERT INTO CHANNEL (ID, NAME, REVISION, CHANNEL) VALUES (?, ?, ?, ?)");
                    updateStatement.setString(1, channelId);
                    updateStatement.setString(2, name);
                    updateStatement.setInt(3, revision);
                    updateStatement.setString(4, serializedChannel);
                    updateStatement.executeUpdate();
                    updateStatement.close();
                } finally {
                    DbUtils.closeQuietly(updateStatement);
                }
            } catch (Exception e) {
                logger.error("Error migrating channel " + channelId + ".", e);
            }
        }

        connection.commit();
    } catch (SQLException e) {
        logger.error("Error migrating channels.", e);
    } finally {
        DbUtils.closeQuietly(results);
        DbUtils.closeQuietly(preparedStatement);
    }
}

From source file:com.flexive.core.storage.genericSQL.GenericEnvironmentLoader.java

/**
 * {@inheritDoc}/*w  w  w. j av a  2 s .  c  o  m*/
 */
@Override
public List<FxGroup> loadGroups(Connection con) throws FxLoadException {
    Statement stmt = null;
    ArrayList<FxGroup> alRet = new ArrayList<FxGroup>(50);
    try {
        final Map<Long, List<FxStructureOption>> groupOptions = loadAllGroupOptions(con);
        final Map<Long, FxString[]> mlText = Database.loadFxStrings(con, TBL_STRUCT_GROUPS, "DESCRIPTION",
                "HINT");

        //                         1   2     3           4           5
        final String sql = "SELECT ID, NAME, DEFMINMULT, DEFMAXMULT, MAYOVERRIDEMULT FROM " + TBL_STRUCT_GROUPS
                + " ORDER BY ID ASC";
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        long id;
        while (rs != null && rs.next()) {
            id = rs.getLong(1);
            FxString label;
            FxString hint;
            if (mlText.containsKey(id)) {
                label = mlText.get(id)[0];
                hint = mlText.get(id)[1];
            } else {
                label = new FxString("");
                hint = new FxString("");
            }
            alRet.add(new FxGroup(id, rs.getString(2), label, hint, rs.getBoolean(5),
                    FxMultiplicity.of(rs.getInt(3), rs.getInt(4)),
                    FxSharedUtils.get(groupOptions, id, new ArrayList<FxStructureOption>(0))));
        }
        return alRet;
    } catch (SQLException e) {
        throw new FxLoadException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(GenericEnvironmentLoader.class, null, stmt);
    }
}

From source file:info.raack.appliancelabeler.data.JDBCDatabase.java

public List<ApplianceStateTransition> getPredictedApplianceStateTransitionsForMonitor(
        EnergyMonitor energyMonitor, final int algorithmId, Date start, Date end, boolean anonymousAppliances) {
    final List<UserAppliance> userAppliances = getUserAppliancesForAlgorithmForEnergyMonitor(energyMonitor,
            algorithmId);// w ww  . j ava 2  s  .  co  m

    String query = null;
    Object[] args = null;

    if (algorithmId != 0) {
        if (!anonymousAppliances) {
            query = "select ast.* from appliance_state_transitions ast, user_appliances ua where ast.detection_algorithm = ? and ua.energy_monitor_id = ? and ua.id = ast.user_appliance_id and ua.algorithm_generated = 0 and ast.time >= ? and ast.time < ? order by ast.time";
            args = new Object[] { algorithmId, energyMonitor.getId(), start.getTime(), end.getTime() };
        } else {
            query = "select ast.* from appliance_state_transitions ast, user_appliances ua where ast.detection_algorithm = ? and ua.energy_monitor_id = ? and ua.id = ast.user_appliance_id and ua.algorithm_generated = 1 and ast.time >= ? and ast.time < ? order by ast.time";
            args = new Object[] { algorithmId, energyMonitor.getId(), start.getTime(), end.getTime() };
        }
    } else {
        query = "select ast.* from appliance_state_transitions ast, user_appliances ua where ast.detection_algorithm is null and ua.energy_monitor_id = ? and ua.id = ast.user_appliance_id order by ast.time";
        args = new Object[] { energyMonitor.getId() };
    }

    List<ApplianceStateTransition> applianceStateTransitions = jdbcTemplate.query(query, args,
            new RowMapper<ApplianceStateTransition>() {

                public ApplianceStateTransition mapRow(ResultSet rs, int arg1) throws SQLException {

                    int userApplianceId = rs.getInt("user_appliance_id");

                    UserAppliance userAppliance = null;

                    for (UserAppliance app : userAppliances) {
                        if (app.getId() == userApplianceId) {
                            userAppliance = app;
                        }
                    }

                    return new GenericStateTransition(rs.getInt("ast.id"), userAppliance, algorithmId,
                            rs.getBoolean("start_on"), rs.getLong("time"));
                }
            });

    return applianceStateTransitions;
}

From source file:org.meerkat.services.WebApp.java

/**
 * getCustomEventsList//from w w  w . ja  v a2s  .  c om
 * @param appName
 * @param rows
 * @param rowBegin
 * @param rowEnd
 * @param orderBy
 * @param asdDSC
 * @return customEvents
 */
public final ArrayList<WebAppEvent> getCustomEventsList(String rowBegin, String rowEnd, String orderBy,
        String asdDSC) {
    ArrayList<WebAppEvent> customEvents = new ArrayList<WebAppEvent>();
    Connection conn = embDB.getConnForQueries();
    String orderByStr = "";

    // Prevent null values if called direct link (outside Datatables)
    if (rowBegin == null || rowEnd == null) {
        rowBegin = "0";
        rowEnd = "10";
    }

    // Process order
    if (orderBy == null) {
        orderBy = "0";
    }
    if (orderBy.equals("0")) {
        orderByStr = "ID";
    } else if (orderBy.equals("1")) {
        orderByStr = "DATEEV";
    } else if (orderBy.equals("2")) {
        orderByStr = "ONLINE";
    } else if (orderBy.equals("3")) {
        orderByStr = "AVAILABILITY";
    } else if (orderBy.equals("4")) {
        orderByStr = "LOADTIME";
    } else if (orderBy.equals("5")) {
        orderByStr = "LATENCY";
    } else if (orderBy.equals("6")) {
        orderByStr = "HTTPSTATUSCODE";
    } else if (orderBy.equals("7")) {
        orderByStr = "DESCRIPTION";
    }

    int nRows = Integer.valueOf(rowEnd) - Integer.valueOf(rowBegin);

    String fields = "SELECT ID, CRITICAL, DATEEV, ONLINE, AVAILABILITY, \n"
            + "LOADTIME, LATENCY, HTTPSTATUSCODE, DESCRIPTION \n";

    log.debug(" ");
    log.debug("||-- APP: " + this.name);
    log.debug("||-- Results: " + rowBegin + " to: " + rowBegin + nRows);
    log.debug("||-- Order by: " + orderByStr + " " + asdDSC);

    String eventsQuery = fields + "FROM MEERKAT.EVENTS \n" + "WHERE APPNAME LIKE '" + this.name + "' \n"
            + "ORDER BY " + orderByStr + " " + asdDSC + " \n" + "OFFSET " + rowBegin + " ROWS FETCH NEXT "
            + nRows + " ROWS ONLY ";

    int id;
    boolean critical;
    String date;
    boolean online;
    String availability;
    String loadTime;
    String latency;
    int httStatusCode = 0;
    String description;

    PreparedStatement ps;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(eventsQuery);
        rs = ps.executeQuery();

        while (rs.next()) {
            id = rs.getInt(1);
            critical = rs.getBoolean(2);
            date = rs.getTimestamp(3).toString();
            online = rs.getBoolean(4);
            availability = String.valueOf(rs.getDouble(5));
            loadTime = String.valueOf(rs.getDouble(6));
            latency = String.valueOf(rs.getDouble(7));
            httStatusCode = rs.getInt(8);
            description = rs.getString(9);

            WebAppEvent currEv = new WebAppEvent(critical, date, online, availability, httStatusCode,
                    description);
            currEv.setID(id);
            currEv.setPageLoadTime(loadTime);
            currEv.setLatency(latency);
            customEvents.add(currEv);
        }

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

    } catch (SQLException e) {
        log.error("Failed query events from application " + this.getName());
        log.error("", e);
        log.error("QUERY IS: " + eventsQuery);
    }

    return customEvents;
}

From source file:com.flexive.ejb.beans.structure.TypeEngineBean.java

/**
 * Load the structure options for a given type
 *
 * @param con an open and valid connection
 * @param typeId the type's id/* w ww.  ja  v a 2 s  .  c  om*/
 * @param idColumn the name of the id column
 * @param table the table name
 * @return structure options
 * @throws SQLException on errors
 */
private List<FxStructureOption> loadTypeOptions(Connection con, long typeId, String idColumn, String table)
        throws SQLException {
    PreparedStatement ps = null;
    List<FxStructureOption> result = new ArrayList<FxStructureOption>(4);
    try {
        //                                1      2           3        4
        ps = con.prepareStatement(
                "SELECT OPTKEY,MAYOVERRIDE,ISINHERITED,OPTVALUE FROM " + table + " WHERE " + idColumn + "=?");
        ps.setLong(1, typeId);
        final ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            FxStructureOption.setOption(result, rs.getString(1), rs.getBoolean(2), rs.getBoolean(3),
                    rs.getString(4));
        }
        ps.close();
        return result;
    } finally {
        if (ps != null)
            ps.close();
    }
}

From source file:gobblin.source.extractor.extract.jdbc.JdbcExtractor.java

private String parseColumnAsString(final ResultSet resultset, final ResultSetMetaData resultsetMetadata, int i)
        throws SQLException {

    if (isBlob(resultsetMetadata.getColumnType(i))) {
        return readBlobAsString(resultset.getBlob(i));
    }// w  w w  .  j  a v a  2  s.c  o  m
    if ((resultsetMetadata.getColumnType(i) == Types.BIT || resultsetMetadata.getColumnType(i) == Types.BOOLEAN)
            && convertBitToBoolean()) {
        return Boolean.toString(resultset.getBoolean(i));
    }
    return resultset.getString(i);
}

From source file:com.sfs.whichdoctor.dao.ItemDAOImpl.java

/**
 * Load item./*from   w  w w .j a  va 2s.co m*/
 *
 * @param rs the rs
 *
 * @return the item bean
 *
 * @throws SQLException the SQL exception
 */
private ItemBean loadItem(final ResultSet rs) throws SQLException {

    ItemBean item = new ItemBean();

    item.setId(rs.getInt("ItemId"));
    item.setGUID(rs.getInt("GUID"));
    item.setObject1GUID(rs.getInt("Object1GUID"));
    item.setObject2GUID(rs.getInt("Object2GUID"));
    item.setReferenceGUID(rs.getInt("ReferenceGUID"));
    item.setName(rs.getString("Name"));
    item.setTitle(rs.getString("Title"));
    item.setComment(rs.getString("Comment"));
    item.setItemType(rs.getString("ItemType"));
    item.setWeighting(rs.getInt("Weighting"));
    try {
        item.setStartDate(rs.getDate("StartDate"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error parsing StartDate: " + sqe.getMessage());
    }
    try {
        item.setEndDate(rs.getDate("EndDate"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error parsing EndDate: " + sqe.getMessage());
    }
    item.setPermission(rs.getString("Permission"));

    item.setActive(rs.getBoolean("Active"));
    item.setCreatedBy(rs.getString("CreatedBy"));
    try {
        item.setCreatedDate(rs.getDate("Created"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error parsing CreatedDate: " + sqe.getMessage());
    }

    if (StringUtils.equalsIgnoreCase(item.getItemType(), "Employment")) {
        // Order by employment date
        String start = "";
        if (item.getStartDate() != null) {
            Long time = BASE_TIME - item.getStartDate().getTime();
            start = String.valueOf(time);
        }
        item.setOrderIndex(start + rs.getString("OrderIndex"), rs.getRow());
    } else {
        item.setOrderIndex(rs.getString("OrderIndex"), rs.getRow());
    }

    return item;
}

From source file:com.mirth.connect.donkey.test.util.TestUtils.java

public static Map<String, Object> getCustomMetaData(String channelId, long messageId, int metaDataId)
        throws SQLException {
    Map<String, Object> map = new HashMap<String, Object>();
    List<MetaDataColumn> columns = getExistingMetaDataColumns(channelId);

    if (columns.size() > 0) {
        long localChannelId = ChannelController.getInstance().getLocalChannelId(channelId);
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet result = null;

        try {//from   ww  w . j  a va 2s  . c o  m
            connection = getConnection();
            statement = connection.prepareStatement(
                    "SELECT * FROM d_mcm" + localChannelId + " WHERE message_id = ? AND metadata_id = ?");
            statement.setLong(1, messageId);
            statement.setInt(2, metaDataId);
            result = statement.executeQuery();

            if (result.next()) {
                for (MetaDataColumn column : columns) {
                    result.getObject(column.getName());

                    if (!result.wasNull()) {
                        // @formatter:off
                        switch (column.getType()) {
                        case BOOLEAN:
                            map.put(column.getName(), result.getBoolean(column.getName()));
                            break;
                        case NUMBER:
                            map.put(column.getName(), result.getBigDecimal(column.getName()));
                            break;
                        case STRING:
                            map.put(column.getName(), result.getString(column.getName()));
                            break;
                        case TIMESTAMP:
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTimeInMillis(result.getTimestamp(column.getName()).getTime());
                            map.put(column.getName(), calendar);
                            break;
                        }
                        // @formatter:on
                    }
                }
            }
        } finally {
            close(result);
            close(statement);
            close(connection);
        }
    }

    return map;
}

From source file:org.opendatakit.persistence.engine.pgres.RelationRowMapper.java

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

    CommonFieldsBase row;//  w  w w  . ja va2  s .  com
    try {
        row = relation.getEmptyRow(user);
        row.setFromDatabase(true);
    } catch (Exception e) {
        throw new IllegalStateException("failed to create empty row", e);
    }

    /**
     * Correct for the funky handling of nulls by the various accessors...
     */
    for (DataField f : relation.getFieldList()) {
        switch (f.getDataType()) {
        case BINARY:
            byte[] blobBytes = rs.getBytes(f.getName());
            row.setBlobField(f, blobBytes);
            break;
        case LONG_STRING:
        case URI:
        case STRING:
            row.setStringField(f, rs.getString(f.getName()));
            break;
        case INTEGER:
            long l = rs.getLong(f.getName());
            if (rs.wasNull()) {
                row.setLongField(f, null);
            } else {
                row.setLongField(f, Long.valueOf(l));
            }
            break;
        case DECIMAL: {
            String value = rs.getString(f.getName());
            if (value == null) {
                row.setNumericField(f, null);
            } else {
                row.setNumericField(f, new WrappedBigDecimal(value));
            }
        }
            break;
        case BOOLEAN:
            Boolean b = rs.getBoolean(f.getName());
            if (rs.wasNull()) {
                row.setBooleanField(f, null);
            } else {
                row.setBooleanField(f, b);
            }
            break;
        case DATETIME:
            Date d = rs.getTimestamp(f.getName());
            if (d == null) {
                row.setDateField(f, null);
            } else {
                row.setDateField(f, (Date) d.clone());
            }
            break;
        default:
            throw new IllegalStateException("Did not expect non-primitive type in column fetch");
        }
    }
    return row;
}

From source file:com.sfs.whichdoctor.dao.SupervisorDAOImpl.java

/**
 * Load supervisor.//from  w ww.  j  a v  a2  s.c o  m
 *
 * @param rs the rs
 * @param loadDetails the load details
 *
 * @return the supervisor bean
 *
 * @throws SQLException the SQL exception
 */
private SupervisorBean loadSupervisor(final ResultSet rs, final BuilderBean loadDetails) throws SQLException {
    SupervisorBean supervisor = new SupervisorBean();

    supervisor.setId(rs.getInt("SupervisorId"));
    supervisor.setGUID(rs.getInt("GUID"));
    supervisor.setReferenceGUID(rs.getInt("ReferenceGUID"));
    supervisor.setOrderId(rs.getInt("OrderId"));
    supervisor.setRelationshipClass(rs.getString("RelationshipClass"));
    supervisor.setRelationshipType(rs.getString("RelationshipType"));
    supervisor.setRelationshipAbbreviation(rs.getString("RelationshipAbbreviation"));
    supervisor.setSupervisorClass(rs.getString("SupervisorClass"));
    supervisor.setPersonGUID(rs.getInt("PersonGUID"));

    if (loadDetails.getBoolean("SUPERVISOR_PERSONOBJ")) {
        try {
            PersonBean person = this.personDAO.loadGUID(supervisor.getPersonGUID(), loadDetails);
            supervisor.setPerson(person);
        } catch (Exception e) {
            dataLogger.error("Error loading person for supervisor: " + e.getMessage());
        }
    }

    supervisor.setActive(rs.getBoolean("Active"));
    try {
        supervisor.setCreatedDate(rs.getTimestamp("CreatedDate"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error setting CreatedDate: " + sqe.getMessage());
    }
    supervisor.setCreatedBy(rs.getString("CreatedBy"));
    try {
        supervisor.setModifiedDate(rs.getTimestamp("ModifiedDate"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error setting ModifiedDate: " + sqe.getMessage());
    }
    supervisor.setModifiedBy(rs.getString("ModifiedBy"));

    return supervisor;
}