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:com.adito.jdbc.JDBCPolicyDatabase.java

Policy buildPolicy(ResultSet rs) throws Exception {
    Timestamp cd = rs.getTimestamp("date_created");
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(cd == null ? System.currentTimeMillis() : cd.getTime());
    Timestamp ad = rs.getTimestamp("date_amended");
    Calendar a = Calendar.getInstance();
    a.setTimeInMillis(ad == null ? System.currentTimeMillis() : ad.getTime());
    return new DefaultPolicy(rs.getInt("id"), rs.getString("policy_name"), rs.getString("policy_description"),
            rs.getInt("policy_type_id"), c, a, rs.getInt("realm_id"));
}

From source file:com.cws.esolutions.core.dao.impl.WebMessagingDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IWebMessagingDAO#retrieveAlertMessages()
 *///from ww  w . j  a v a  2  s. co m
public synchronized List<Object[]> retrieveAlertMessages() throws SQLException {
    final String methodName = IWebMessagingDAO.CNAME + "#retrieveAlertMessages() throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<Object[]> response = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);
        stmt = sqlConn.prepareCall("{CALL retrAlertMessages()}");

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (DEBUG) {
                DEBUGGER.debug("ResultSet: {}", resultSet);
            }

            if (resultSet.next()) {
                resultSet.beforeFirst();
                response = new ArrayList<Object[]>();

                while (resultSet.next()) {
                    Object[] data = new Object[] { resultSet.getString(1), // svc_message_id
                            resultSet.getString(2), // svc_message_title
                            resultSet.getString(3), // svc_message_txt
                            resultSet.getString(4), // svc_message_author
                            resultSet.getTimestamp(5), // svc_message_submitdate
                            resultSet.getBoolean(6), // svc_message_active
                            resultSet.getBoolean(7), // svc_message_alert
                            resultSet.getBoolean(8), // svc_message_expires
                            resultSet.getTimestamp(9), // svc_message_expirydate
                            resultSet.getTimestamp(10), // svc_message_modifiedon
                            resultSet.getString(11) // svc_message_modifiedby
                    };

                    if (DEBUG) {
                        DEBUGGER.debug("data: {}", data);
                    }

                    response.add(data);
                }
            }
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

        if (stmt != null) {
            stmt.close();
        }

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

    return response;
}

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  . j a  v  a2  s .  c  om*/
    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.funambol.foundation.items.dao.DataBaseFileDataObjectMetadataDAO.java

/**
 * Creates a <code>FileDataObjectMetadata</code> object and fills metadata
 * from a database row (content is still null).
 *
 * @param wrapperId the file data object identifier
 * @param rs the ResultSet//  w  w  w.j  a  v a  2 s  . c o m
 * @return a FileDataObjectWrapper set with the results of the query
 * @throws java.sql.SQLException if an error occurs
 * @throws com.funambol.framework.server.store.NotFoundException if no file
 *         data object has been found with the given id
 */
private FileDataObjectWrapper createFileDataObjectWrapper(String wrapperId, ResultSet rs)
        throws SQLException, NotFoundException {

    FileDataObjectWrapper fdow = null;
    FileDataObject fdo = new FileDataObject();
    Map<String, String> properties = new LinkedHashMap<String, String>();

    boolean isFirstTime = true;
    while (rs.next()) {

        if (isFirstTime) {

            FileDataObjectMetadata metadata = new FileDataObjectMetadata(rs.getString(SQL_FIELD_TRUE_NAME));

            metadata.setCreated(utcDateTime(rs.getTimestamp(SQL_FIELD_CREATED)));
            metadata.setModified(utcDateTime(rs.getTimestamp(SQL_FIELD_MODIFIED)));
            metadata.setAccessed(utcDateTime(rs.getTimestamp(SQL_FIELD_ACCESSED)));

            metadata.setHidden(ONE.equals(rs.getString(SQL_FIELD_H)));
            metadata.setSystem(ONE.equals(rs.getString(SQL_FIELD_S)));
            metadata.setArchived(ONE.equals(rs.getString(SQL_FIELD_A)));
            metadata.setDeleted(ONE.equals(rs.getString(SQL_FIELD_D)));
            metadata.setWritable(ONE.equals(rs.getString(SQL_FIELD_W)));
            metadata.setReadable(ONE.equals(rs.getString(SQL_FIELD_R)));
            metadata.setExecutable(ONE.equals(rs.getString(SQL_FIELD_X)));

            metadata.setUploadStatus(rs.getString(SQL_FIELD_UPLOAD_STATUS));

            metadata.setContentType(rs.getString(SQL_FIELD_CTTYPE));

            long size = rs.getLong(SQL_FIELD_SIZE);
            if (rs.wasNull()) {
                metadata.setSize(null);
            } else {
                metadata.setSize(size);
            }
            fdo.setMetadata(metadata);

            fdow = new FileDataObjectWrapper(wrapperId, rs.getString(SQL_FIELD_USERID), fdo);

            fdow.setLocalName(rs.getString(SQL_FIELD_LOCAL_NAME));

            long sizeOnStorage = rs.getLong(SQL_FIELD_SIZE_ON_STORAGE);
            if (rs.wasNull()) {
                fdow.setSizeOnStorage(null);
            } else {
                fdow.setSizeOnStorage(sizeOnStorage);
            }

            fdow.setStatus(rs.getString(SQL_FIELD_STATUS).charAt(0));
            fdow.setLastUpdate(new Timestamp(rs.getLong(SQL_FIELD_LAST_UPDATE)));

            isFirstTime = false;
        }

        long fdoId = rs.getLong(SQL_FIELD_FDO_ID);
        if (!rs.wasNull()) {
            properties.put(rs.getString(SQL_FIELD_NAME), rs.getString(SQL_FIELD_VALUE));
        }
    }
    fdo.setProperties(properties);

    if (fdow == null) {
        throw new NotFoundException("No file data object found for '" + wrapperId + "'.");
    }
    return fdow;
}

From source file:com.cws.esolutions.core.dao.impl.WebMessagingDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IWebMessagingDAO#retrieveMessages()
 *///from w w w.  j  a  va 2s  .  c o m
public synchronized List<Object[]> retrieveMessages() throws SQLException {
    final String methodName = IWebMessagingDAO.CNAME + "#retrieveMessages() throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<Object[]> response = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);
        stmt = sqlConn.prepareCall("{CALL retrServiceMessages()}");

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (DEBUG) {
                DEBUGGER.debug("ResultSet: {}", resultSet);
            }

            if (resultSet.next()) {
                resultSet.beforeFirst();
                response = new ArrayList<Object[]>();

                while (resultSet.next()) {
                    Object[] data = new Object[] { resultSet.getString(1), // svc_message_id
                            resultSet.getString(2), // svc_message_title
                            resultSet.getString(3), // svc_message_txt
                            resultSet.getString(4), // svc_message_author
                            resultSet.getTimestamp(5), // svc_message_submitdate
                            resultSet.getBoolean(6), // svc_message_active
                            resultSet.getBoolean(7), // svc_message_alert
                            resultSet.getBoolean(8), // svc_message_expires
                            resultSet.getTimestamp(9), // svc_message_expirydate
                            resultSet.getTimestamp(10), // svc_message_modifiedon
                            resultSet.getString(11) // svc_message_modifiedby
                    };

                    if (DEBUG) {
                        DEBUGGER.debug("data: {}", data);
                    }

                    response.add(data);
                }
            }
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

        if (stmt != null) {
            stmt.close();
        }

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

    return response;
}

From source file:com.splicemachine.derby.impl.load.HdfsImportIT.java

@Test
public void testImportFromSQL() throws Exception {

    PreparedStatement ps = methodWatcher.prepareStatement(format("call SYSCS_UTIL.IMPORT_DATA(" + "'%s'," + // schema name
            "'%s'," + // table name
            "null," + // insert column list
            "'%s'," + // file path
            "','," + // column delimiter
            "null," + // character delimiter
            "null," + // timestamp format
            "'MM/dd/yyyy'," + // date format
            "'HH.mm.ss'," + // time format
            "%d," + // max bad records
            "'%s'," + // bad record dir
            "null," + // has one line records
            "null)", // char set
            spliceSchemaWatcher.schemaName, TABLE_3, getResourceDirectory() + "order_detail_small.csv", 0,
            BADDIR.getCanonicalPath()));

    ps.execute();/*  www. ja v a 2s.  co m*/

    ResultSet rs = methodWatcher
            .executeQuery(format("select * from %s.%s", spliceSchemaWatcher.schemaName, TABLE_3));
    List<String> results = Lists.newArrayList();
    while (rs.next()) {
        String orderId = rs.getString(1);
        int item_id = rs.getInt(2);
        int order_amt = rs.getInt(3);
        Timestamp order_date = rs.getTimestamp(4);
        int emp_id = rs.getInt(5);
        int prom_id = rs.getInt(6);
        int qty_sold = rs.getInt(7);
        float unit_price = rs.getInt(8);
        float unit_cost = rs.getFloat(9);
        float discount = rs.getFloat(10);
        int cust_id = rs.getInt(11);
        assertNotNull("No Order Id returned!", orderId);
        Assert.assertTrue("ItemId incorrect!", item_id > 0);
        Assert.assertTrue("Order amt incorrect!", order_amt > 0);
        assertNotNull("order_date incorrect", order_date);
        Assert.assertTrue("EmpId incorrect", emp_id > 0);
        Assert.assertEquals("prom_id incorrect", 0, prom_id);
        Assert.assertTrue("qty_sold incorrect", qty_sold > 0);
        Assert.assertTrue("unit price incorrect!", unit_price > 0);
        Assert.assertTrue("unit cost incorrect", unit_cost > 0);
        Assert.assertEquals("discount incorrect", 0.0f, discount, 1 / 100f);
        Assert.assertTrue("cust_id incorrect", cust_id != 0);
        results.add(String.format(
                "orderId:%s,item_id:%d,order_amt:%d,order_date:%s,emp_id:%d,prom_id:%d," + "qty_sold:%d,"
                        + "unit_price:%f,unit_cost:%f,discount:%f,cust_id:%d",
                orderId, item_id, order_amt, order_date, emp_id, prom_id, qty_sold, unit_price, unit_cost,
                discount, cust_id));
    }
    Assert.assertTrue("import failed!", results.size() > 0);
}

From source file:librec.data.DataDAO.java

/**
 * Read data from the database. Note that we don't take care of duplicate lines.
 * /*from  w  w w . j av  a 2  s . c om*/
 * @return a sparse matrix storing all the relevant data
 */
public SparseMatrix[] loadData(double binThold, int maxIds) throws Exception {

    Logs.info("Dataset: From database");

    // Table {row-id, col-id, rate}
    Table<Integer, Integer, Double> dataTable = HashBasedTable.create();
    // Table {row-id, col-id, timestamp}
    Table<Integer, Integer, Long> timeTable = null;
    // Map {col-id, multiple row-id}: used to fast build a rating matrix
    Multimap<Integer, Integer> colMap = HashMultimap.create();

    DatabaseManager dbm = new DatabaseManager();
    Connection conn = null;
    PreparedStatement stmnt = null;
    ResultSet rs = null;

    minTimestamp = Long.MAX_VALUE;
    maxTimestamp = Long.MIN_VALUE;

    try {
        conn = dbm.getConnection();

        if (maxIds > 0) {
            stmnt = conn.prepareStatement(
                    "SELECT UserId, ItemId, Time, Rating FROM Rating WHERE ItemId < ? AND UserId < ?;");
            stmnt.setInt(1, maxIds);
            stmnt.setInt(2, maxIds);
        } else {
            stmnt = conn.prepareStatement("SELECT UserId, ItemId, Time, Rating FROM Rating;");
        }
        //         Logs.info("Executing statement: {}", stmnt);
        rs = stmnt.executeQuery();
        while (rs.next()) {

            int user = rs.getInt("UserId");
            int item = rs.getInt("ItemId");

            // convert time to milliseconds
            long mms = rs.getTimestamp("Time").getTime();
            long timestamp = timeUnit.toMillis(mms);

            Double rate = rs.getDouble("Rating");

            // binarize the rating for item recommendation task
            if (binThold >= 0)
                rate = rate > binThold ? 1.0 : 0.0;

            scaleDist.add(rate);

            // inner id starting from 0
            int row = userIds.containsKey(user) ? userIds.get(user) : userIds.size();
            userIds.put(user, row);

            int col = itemIds.containsKey(item) ? itemIds.get(item) : itemIds.size();
            itemIds.put(item, col);

            dataTable.put(row, col, rate);
            colMap.put(col, row);

            // record rating's issuing time
            if (timeTable == null)
                timeTable = HashBasedTable.create();

            if (minTimestamp > timestamp)
                minTimestamp = timestamp;

            if (maxTimestamp < timestamp)
                maxTimestamp = timestamp;

            timeTable.put(row, col, timestamp);
            //            if(dataTable.size() % 100000 == 0)
            //               Logs.info("Ratings loaded into dataTable: {}", dataTable.size());
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DbUtils.closeQuietly(stmnt);
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(rs);
    }

    //      Logs.info("All ratings loaded into dataTable");

    numRatings = scaleDist.size();
    ratingScale = new ArrayList<>(scaleDist.elementSet());
    Collections.sort(ratingScale);

    int numRows = numUsers(), numCols = numItems();

    // if min-rate = 0.0, shift upper a scale
    double minRate = ratingScale.get(0).doubleValue();
    double epsilon = minRate == 0.0 ? ratingScale.get(1).doubleValue() - minRate : 0;
    if (epsilon > 0) {
        // shift upper a scale
        for (int i = 0, im = ratingScale.size(); i < im; i++) {
            double val = ratingScale.get(i);
            ratingScale.set(i, val + epsilon);
        }
        // update data table
        for (int row = 0; row < numRows; row++) {
            for (int col = 0; col < numCols; col++) {
                if (dataTable.contains(row, col))
                    dataTable.put(row, col, dataTable.get(row, col) + epsilon);
            }
        }
    }

    String dateRange = "";
    dateRange = String.format(", Timestamps = {%s, %s}", Dates.toString(minTimestamp),
            Dates.toString(maxTimestamp));

    Logs.debug("With Specs: {Users, {}} = {{}, {}, {}}, Scale = {{}}{}",
            (isItemAsUser ? "Users, Links" : "Items, Ratings"), numRows, numCols, numRatings,
            Strings.toString(ratingScale), dateRange);

    // build rating matrix
    rateMatrix = new SparseMatrix(numRows, numCols, dataTable, colMap);

    if (timeTable != null)
        timeMatrix = new SparseMatrix(numRows, numCols, timeTable, colMap);

    // release memory of data table
    dataTable = null;
    timeTable = null;

    return new SparseMatrix[] { rateMatrix, timeMatrix };

}

From source file:ManagerQuery.java

private double executeQueryJVFreePark() {
    double percent = -1;
    int free_total = 0;
    int total_capacity = 0;

    try {//from w w  w  .  j  a  v a 2 s  . c  o  m
        Repository repo = buildSparqlRepository();
        repo.initialize();
        RepositoryConnection con = repo.getConnection();
        TupleQuery tupleQueryParkFree = con.prepareTupleQuery(QueryLanguage.SPARQL, this.query);
        TupleQueryResult resultEvent = tupleQueryParkFree.evaluate();

        if (resultEvent != null) {
            while (resultEvent.hasNext()) {
                BindingSet bindingSetEvent = resultEvent.next();
                String free = bindingSetEvent.getValue("free").stringValue();
                String capacity = bindingSetEvent.getValue("capacity").stringValue();
                free_total = free_total + Integer.parseInt(free);
                total_capacity = total_capacity + Integer.parseInt(capacity);
            }

            if (total_capacity != 0) {
                percent = (free_total * 100.0) / total_capacity;
                DBAccess mysql_access = new DBAccess(this.map_dbAcc.get("AlarmEmail"));
                mysql_access.setConnection(this.map_dbAcc.get("Dashboard"));
                System.out.println("Posti liberi parcheggi di : " + free_total);
                System.out.println("Capacit parcheggi di : " + total_capacity);
                System.out.println("Precentuale posti liberi parcheggi di : " + percent);
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date data_attuale = new Date();
                String data_attuale_fixed = df.format(data_attuale);
                String query_insert = "INSERT INTO Dashboard.Data"
                        + "(IdMetric_data, computationDate, value_num, value_perc1, value_perc2, value_perc3, value_text, quant_perc1, quant_perc2, quant_perc3, tot_perc1, tot_perc2, tot_perc3) VALUES"
                        + "(\"" + this.idProc + "\",\"" + data_attuale_fixed + "\",null,\"" + percent
                        + "\" ,null,null, \"\",\"" + free_total + "\",null,null,\"" + total_capacity
                        + "\",null,null)";
                mysql_access.writeDataBaseData(query_insert);
                mysql_access.close();
            } else {
                DBAccess mysql_access2 = new DBAccess(this.map_dbAcc.get("AlarmEmail"));
                mysql_access2.setConnection(this.map_dbAcc.get("Dashboard"));
                String LastCompDateQuery = "SELECT MAX(computationDate) as lastCompDate, value_num, value_perc1, value_perc2, value_perc3, value_text FROM Dashboard.Data WHERE IdMetric_data=\""
                        + this.idProc + "\" ORDER BY computationDate DESC";
                ResultSet resultSet = mysql_access2.readDataBase(LastCompDateQuery, this);
                Timestamp lastTimestamp = null;
                Double[] lastValues = new Double[(resultSet.getMetaData().getColumnCount()) - 1];
                while (resultSet.next()) {
                    lastTimestamp = resultSet.getTimestamp("lastCompDate");
                    lastValues[0] = Double.parseDouble((resultSet.getString("value_perc1").trim()));
                }
                mysql_access2.close();
                //this.almMng.updateStatusOnComputingDate(lastTimestamp, lastValues);
            }
        }
    } catch (Exception exp) {
        Utility.WriteExcepLog(this.logger, exp);
        String msgBody = Utility.exceptionMessage(exp, this.getClass().getName(),
                this.idProc + " - " + this.descrip);
        this.notifyEvent("Import data error", msgBody);
    }

    return percent;
}

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

/**
 * Load group./*from   www .  j  av  a 2  s . co  m*/
 *
 * @param rs the rs
 * @param loadDetails the load details
 *
 * @return the group bean
 *
 * @throws SQLException the SQL exception
 */
private GroupBean loadGroup(final ResultSet rs, final BuilderBean loadDetails) throws SQLException {

    GroupBean group = new GroupBean();

    group.setId(rs.getInt("GroupId"));
    group.setGUID(rs.getInt("GUID"));
    group.setObjectType(rs.getString("ObjectType"));
    group.setType(rs.getString("Type"));
    group.setYear(rs.getInt("Year"));
    group.setColour(rs.getString("Colour"));
    group.setWeighting(rs.getInt("Weighting"));
    group.setPermission(rs.getString("Permission"));
    group.setName(rs.getString("Name"));
    group.setDescription(rs.getString("Description"));
    group.setGroupDN(rs.getString("GroupDN"));
    group.setItemCount(rs.getInt("ItemCount"));

    if (loadDetails.getBoolean("TAGS")) {
        try {
            group.setTags(this.getTagDAO().load(group.getGUID(), loadDetails.getString("USERDN"), true));
        } catch (Exception e) {
            dataLogger.error("Error loading tags for group: " + e.getMessage());
        }
    }

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

    if (loadDetails.getBoolean("ITEMS")) {
        int referenceId = 0;
        try {
            referenceId = Integer.parseInt(loadDetails.getString("REFERENCEID"));
        } catch (Exception e) {
            dataLogger.debug("Error parsing ReferenceId: " + e.getMessage());
        }
        try {
            group.setItems(
                    this.getItemDAO().load(group.getGUID(), true, "Group", group.getObjectType(), referenceId,
                            loadDetails.getString("ITEMS_STARTDATE"), loadDetails.getString("ITEMS_ENDDATE")));
        } catch (Exception e) {
            dataLogger.error("Error loading items: " + e.getMessage());
        }
    }

    if (StringUtils.equalsIgnoreCase(group.getType(), "Election") && loadDetails.getBoolean("VOTES")) {
        /* Load the votes for this election group */
        try {
            TreeMap<Integer, VoteBean> votesCast = this.voteDAO.load(group.getGUID());
            group.setVotesCast(votesCast);
            group.setCastVoteCount(votesCast.keySet().size());
        } catch (Exception e) {
            dataLogger.error("Error loading votes cast: " + e.getMessage());
        }
        try {
            TreeMap<Integer, Integer> eligibleVotes = this.voteDAO.loadEligible(group.getGUID());
            group.setEligibleVoteCount(eligibleVotes.keySet().size());
        } catch (Exception e) {
            dataLogger.error("Error loading eligible vote count: " + e.getMessage());
        }
    }
    if (StringUtils.equalsIgnoreCase(group.getType(), "Election") && loadDetails.getBoolean("CANDIDATES")) {
        // * Load the candidates for this election group */
        try {
            Collection<CandidateBean> candidates = this.candidateDAO.load(group.getGUID(), loadDetails);
            group.setCandidates(candidates);
        } catch (Exception e) {
            dataLogger.error("Error loading votes cast: " + e.getMessage());
        }
    }

    if (loadDetails.getBoolean("IDENTITIES")) {

        boolean loadIdentities = false;
        if (StringUtils.equalsIgnoreCase(group.getObjectType(), "Organisations")
                || StringUtils.equalsIgnoreCase(group.getObjectType(), "Members")) {
            loadIdentities = true;
        }
        if (loadIdentities && group.getItems() != null) {
            group.setItems(loadIdentities(group.getItems()));
        }
    }

    if (loadDetails.getBoolean("MEMO")) {
        try {
            group.setMemo(this.getMemoDAO().load(group.getGUID(), loadDetails.getBoolean("MEMO_FULL")));
        } catch (Exception e) {
            dataLogger.error("Error loading memos: " + e.getMessage());
        }
    }

    if (loadDetails.getBoolean("CREATED")) {
        UserBean user = new UserBean();
        user.setDN(rs.getString("CreatedBy"));
        user.setPreferredName(rs.getString("CreatedFirstName"));
        user.setLastName(rs.getString("CreatedLastName"));
        group.setCreatedUser(user);
    }
    if (loadDetails.getBoolean("MODIFIED")) {
        UserBean user = new UserBean();
        user.setDN(rs.getString("ModifiedBy"));
        user.setPreferredName(rs.getString("ModifiedFirstName"));
        user.setLastName(rs.getString("ModifiedLastName"));
        group.setModifiedUser(user);
    }
    return group;
}

From source file:com.alfaariss.oa.authentication.remote.saml2.idp.storage.jdbc.IDPJDBCStorage.java

private SAML2IDP retrieveByID(String id) throws OAException {
    Connection connection = null;
    PreparedStatement pSelect = null;
    ResultSet resultSet = null;
    SAML2IDP saml2IDP = null;/*from ww  w  . j  a v a2  s.  c o  m*/

    IMetadataProviderManager oMPM = MdMgrManager.getInstance().getMetadataProviderManager(_sId);

    try {
        connection = _dataSource.getConnection();

        pSelect = connection.prepareStatement(_sQuerySelectOnID);
        pSelect.setBoolean(1, true);
        pSelect.setString(2, id);
        resultSet = pSelect.executeQuery();
        if (resultSet.next()) {
            boolean bACSIndex = resultSet.getBoolean(COLUMN_ACS_INDEX);

            Boolean boolAllowCreate = null;
            String sAllowCreate = resultSet.getString(COLUMN_ALLOW_CREATE);
            if (sAllowCreate != null) {
                boolean bAllowCreate = resultSet.getBoolean(COLUMN_ALLOW_CREATE);
                boolAllowCreate = new Boolean(bAllowCreate);
            }

            boolean bScoping = resultSet.getBoolean(COLUMN_SCOPING);
            boolean bNameIDPolicy = resultSet.getBoolean(COLUMN_NAMEIDPOLICY);
            boolean bAvoidSubjectConfirmation = resultSet.getBoolean(COLUMN_AVOID_SUBJCONF);
            boolean bDisableSSOForIDP = resultSet.getBoolean(COLUMN_DISABLE_SSO);

            Date dLastModified = null;
            try {
                dLastModified = resultSet.getTimestamp(COLUMN_DATELASTMODIFIED);
            } catch (Exception e) {
                _oLogger.info(
                        "No " + COLUMN_DATELASTMODIFIED + " column found for SAML2IDP '" + id + "'; ignoring.");
            }

            saml2IDP = new SAML2IDP(id, resultSet.getBytes(COLUMN_SOURCEID),
                    resultSet.getString(COLUMN_FRIENDLYNAME), resultSet.getString(COLUMN_METADATA_FILE),
                    resultSet.getString(COLUMN_METADATA_URL), resultSet.getInt(COLUMN_METADATA_TIMEOUT),
                    bACSIndex, boolAllowCreate, bScoping, bNameIDPolicy,
                    resultSet.getString(COLUMN_NAMEIDFORMAT), bAvoidSubjectConfirmation, bDisableSSOForIDP,
                    dLastModified, oMPM.getId());
        }
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _oLogger.fatal("Internal error during retrieval of organization with ID: " + id, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        try {
            if (pSelect != null)
                pSelect.close();
        } catch (Exception e) {
            _oLogger.error("Could not close select statement", e);
        }

        try {
            if (connection != null)
                connection.close();
        } catch (Exception e) {
            _oLogger.error("Could not close connection", e);
        }
    }
    return saml2IDP;
}