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:se.technipelago.weather.chart.Generator.java

private XYDataset createHistoryDataset(final Date begin, final Date end, final String column,
        final String label) throws SQLException {
    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    PreparedStatement stmt = null;
    ResultSet result = null;
    long spanDays = (end.getTime() - begin.getTime()) / 1000 / 60 / 60 / 24;
    try {//  ww w .  j a v  a 2  s .  c  o  m
        final java.sql.Timestamp sqlBegin = new java.sql.Timestamp(begin.getTime());
        final java.sql.Timestamp sqlEnd = new java.sql.Timestamp(end.getTime());
        if (spanDays < 100) {
            stmt = conn.prepareStatement("SELECT ts, " + column + " FROM archive WHERE " + column
                    + " IS NOT NULL AND ts BETWEEN ? AND ? ORDER BY ts");
        } else if (spanDays < 1000) {
            stmt = conn.prepareStatement("SELECT date_format(ts, '%Y-%m-%d %H:00:00') AS day, AVG(" + column
                    + ") AS value FROM archive WHERE " + column
                    + " IS NOT NULL AND ts BETWEEN ? AND ? GROUP BY 1");
        } else {
            stmt = conn.prepareStatement("SELECT date_format(ts, '%Y-%m-%d') AS day, AVG(" + column
                    + ") AS value FROM archive WHERE " + column
                    + " IS NOT NULL AND ts BETWEEN ? AND ? GROUP BY 1");
        }
        stmt.setTimestamp(1, sqlBegin);
        stmt.setTimestamp(2, sqlEnd);
        result = stmt.executeQuery();

        final TimeSeries s1 = new TimeSeries(label, FixedMillisecond.class);
        while (result.next()) {
            final java.sql.Timestamp ts = result.getTimestamp(1);
            final long timestamp = ts.getTime();
            s1.add(new FixedMillisecond(timestamp), result.getFloat(2));
        }
        dataset.addSeries(s1);
    } finally {
        if (result != null) {
            try {
                result.close();
            } catch (SQLException e) {
                log.log(Level.SEVERE, "Failed to close ResultSet", e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                log.log(Level.WARNING, "Failed to close select statement", ex);
            }
        }
    }

    return dataset;
}

From source file:com.liferay.portal.upgrade.util.Table.java

public Object getValue(ResultSet rs, String name, Integer type) throws Exception {

    Object value = null;//  ww  w. jav a  2  s .c  o  m

    int t = type.intValue();

    if (t == Types.BIGINT) {
        try {
            value = GetterUtil.getLong(rs.getLong(name));
        } catch (SQLException e) {
            value = GetterUtil.getLong(rs.getString(name));
        }
    } else if (t == Types.BOOLEAN) {
        value = GetterUtil.getBoolean(rs.getBoolean(name));
    } else if (t == Types.CLOB) {
        try {
            Clob clob = rs.getClob(name);

            if (clob == null) {
                value = StringPool.BLANK;
            } else {
                UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(clob.getCharacterStream());

                StringBundler sb = new StringBundler();

                String line = null;

                while ((line = unsyncBufferedReader.readLine()) != null) {
                    if (sb.length() != 0) {
                        sb.append(SAFE_NEWLINE_CHARACTER);
                    }

                    sb.append(line);
                }

                value = sb.toString();
            }
        } catch (Exception e) {

            // If the database doesn't allow CLOB types for the column
            // value, then try retrieving it as a String

            value = GetterUtil.getString(rs.getString(name));
        }
    } else if (t == Types.DOUBLE) {
        value = GetterUtil.getDouble(rs.getDouble(name));
    } else if (t == Types.FLOAT) {
        value = GetterUtil.getFloat(rs.getFloat(name));
    } else if (t == Types.INTEGER) {
        value = GetterUtil.getInteger(rs.getInt(name));
    } else if (t == Types.SMALLINT) {
        value = GetterUtil.getShort(rs.getShort(name));
    } else if (t == Types.TIMESTAMP) {
        try {
            value = rs.getTimestamp(name);
        } catch (Exception e) {
        }

        if (value == null) {
            value = StringPool.NULL;
        }
    } else if (t == Types.VARCHAR) {
        value = GetterUtil.getString(rs.getString(name));
    } else {
        throw new UpgradeException("Upgrade code using unsupported class type " + type);
    }

    return value;
}

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

public int build(Document doc, String id, ResultSet rs, Set<Integer> keyField,
        Map<String, FieldFormatter> fieldNameToFormatter, Map<String, FieldFormatter> fieldIdToFormatter)
        throws Exception {
    if (rs == null) {
        return 0;
    }/* ww w.ja v a2 s.c  om*/
    int rowCounter = 0;
    Element docRoot = doc.getDocumentElement();
    ResultSetMetaData metadata = rs.getMetaData();
    buildFormatterAndNamesArray(metadata, fieldNameToFormatter, fieldIdToFormatter);

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

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

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

            isKeyCol = (!noKey && keyField.contains(new Integer(j)));
            isNull = false;
            col = parser.createElementNS(doc, colName, NS);
            if (isKeyCol) {
                parser.setAttribute(col, AbstractDBO.ID_NAME, String.valueOf(j));
            }
            switch (metadata.getColumnType(j)) {
            case Types.DATE:
            case Types.TIME:
            case Types.TIMESTAMP: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIMESTAMP_TYPE);
                Timestamp dateVal = rs.getTimestamp(j);
                isNull = dateVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, AbstractDBO.DEFAULT_DATE_FORMAT);
                    textVal = "";
                } else {
                    if (fF != null) {
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getDateFormat());
                        textVal = fF.formatDate(dateVal);
                    } else {
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, AbstractDBO.DEFAULT_DATE_FORMAT);
                        textVal = dateFormatter.format(dateVal);
                    }
                }
            }
                break;
            case Types.DOUBLE:
            case Types.FLOAT:
            case Types.REAL: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                float numVal = rs.getFloat(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                if (fF != null) {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat());
                    parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator());
                    parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator());
                    textVal = fF.formatNumber(numVal);
                } else {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat);
                    parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator);
                    parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator);
                    textVal = numberFormatter.format(numVal);
                }
            }
                break;
            case Types.BIGINT:
            case Types.INTEGER:
            case Types.NUMERIC:
            case Types.SMALLINT:
            case Types.TINYINT: {
                BigDecimal bigdecimal = rs.getBigDecimal(j);
                isNull = bigdecimal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                    }
                    textVal = "";
                } else {
                    if (fF != null) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat());
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator());
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator());
                        textVal = fF.formatNumber(bigdecimal);
                    } else if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat);
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator);
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator);
                        textVal = numberFormatter.format(bigdecimal);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                        textVal = bigdecimal.toString();
                    }
                }
            }
                break;
            case Types.NCHAR:
            case Types.NVARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NSTRING_TYPE);
                textVal = rs.getNString(j);
                isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
                break;
            case Types.CHAR:
            case Types.VARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.STRING_TYPE);
                textVal = rs.getString(j);
                isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
                break;
            case Types.NCLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_NSTRING_TYPE);
                NClob clob = rs.getNClob(j);
                isNull = clob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

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

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

    return rowCounter;
}

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

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

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

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

    try {
        sqlConn = dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);
        StringBuilder sBuilder = new StringBuilder();

        if (StringUtils.split(value, " ").length >= 2) {
            for (String str : StringUtils.split(value, " ")) {
                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", str);
                }

                sBuilder.append("+" + str);
                sBuilder.append(" ");
            }

            if (DEBUG) {
                DEBUGGER.debug("StringBuilder: {}", sBuilder);
            }
        } else {
            sBuilder.append("+" + value);
        }

        stmt = sqlConn.prepareCall("{CALL getMessagesByAttribute(?)}");
        stmt.setString(1, sBuilder.toString().trim());

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

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

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

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

                while (resultSet.next()) {
                    Object[] messageData = 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) {
                        for (Object obj : messageData) {
                            DEBUGGER.debug("Value: {}", obj);
                        }
                    }

                    responseData.add(messageData);
                }

                if (DEBUG) {
                    for (Object[] str : responseData) {
                        for (Object obj : str) {
                            DEBUGGER.debug("Value: {}", obj);
                        }
                    }
                }
            }
        }
    } 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 responseData;
}

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

/**
 * @param cntSQL/*from  w w w  .  jav a2 s . co m*/
 * @param sql
 * @param tableName
 * @param mapperName
 */
private void doAddressOfRecord(final String cntSQL, final String sql, final String tableName,
        final String mapperName) {
    IdMapperIFace agentMapper = IdMapperMgr.getInstance().get("agent_AgentID");

    Session session = HibernateUtil.getNewSession();
    Transaction trans = null;
    try {
        conv.setProcess(0, BasicSQLUtils.getCountAsInt(oldDBConn, cntSQL));

        IdMapperIFace loanMapper = IdMapperMgr.getInstance().get(mapperName);

        Statement stmt = oldDBConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        ResultSet rs = stmt.executeQuery(sql);

        int cnt = 0;
        while (rs.next()) {
            int col = 1;
            Integer loanID = rs.getInt(col++);
            Integer agentID = rs.getInt(col++);
            String address = rs.getString(col++);
            String city = rs.getString(col++);
            String state = rs.getString(col++);
            String country = rs.getString(col++);
            String postalCode = rs.getString(col++);
            String remarks = rs.getString(col++);
            Timestamp timestampModified = rs.getTimestamp(col++);
            Timestamp timestampCreated = rs.getTimestamp(col++);

            Integer newAgentId = agentMapper.get(agentID);

            if (newAgentId != null) {
                List<?> list = session.createQuery("FROM Agent WHERE id = " + newAgentId).list();
                if (list != null && list.size() == 1) {
                    Agent agent = (Agent) list.get(0);

                    Integer newLoanId = loanMapper.get(loanID);

                    if (newLoanId != null) {
                        list = session.createQuery("FROM " + tableName + " WHERE id = " + newLoanId).list();
                        if (list != null && list.size() == 1) {
                            trans = session.beginTransaction();
                            AddressOfRecord aor = new AddressOfRecord();
                            aor.initialize();
                            aor.setAddress(address);
                            aor.setAgent(agent);
                            aor.setCity(city);
                            aor.setCountry(country);
                            aor.setPostalCode(postalCode);
                            aor.setRemarks(remarks);
                            aor.setState(state);
                            aor.setTimestampCreated(timestampCreated);
                            aor.setTimestampModified(timestampModified);

                            FormDataObjIFace parentObj = (FormDataObjIFace) list.get(0);
                            DataModelObjBase.setDataMember(parentObj, "addressOfRecord", aor);

                            session.saveOrUpdate(parentObj);
                            //session.saveOrUpdate(aor);
                            trans.commit();
                        }
                    }
                }
            }

            if (cnt % 100 == 0) {
                conv.setProcess(0, cnt);
            }
            cnt++;
        }
        rs.close();
        stmt.close();

    } catch (Exception ex) {
        try {
            if (trans != null)
                trans.rollback();
        } catch (Exception ex1) {
        }
        ex.printStackTrace();
        log.error(ex);

    } finally {
        session.close();
    }
}

From source file:org.efs.openreports.engine.ChartReportEngine.java

/**
 * Executes the Chart query and builds an array of ChartValues from the results.
 *///from w w  w .j  a v a2  s  . c  o m
public ChartValue[] getChartValues(ReportChart reportChart, Map parameters) throws ProviderException {
    Connection conn = null;
    PreparedStatement pStmt = null;
    ResultSet rs = null;

    try {
        ReportDataSource dataSource = reportChart.getDataSource();
        conn = dataSourceProvider.getConnection(dataSource.getId());

        // Use JasperReports Query logic to parse parameters in chart
        // queries

        JRDesignQuery query = new JRDesignQuery();
        query.setText(reportChart.getQuery());

        // convert parameters to JRDesignParameters so they can be parsed
        Map jrParameters = ORUtil.buildJRDesignParameters(parameters);

        pStmt = JRQueryExecuter.getStatement(query, jrParameters, parameters, conn);

        rs = pStmt.executeQuery();

        Vector v = new Vector();

        int chartType = reportChart.getChartType();
        if (chartType == ReportChart.BAR_CHART) {
            while (rs.next()) {
                CategoryChartValue catValue = new CategoryChartValue();

                catValue.setValue(rs.getDouble(1));
                catValue.setSeries(rs.getString(2));
                catValue.setCategory(rs.getString(3));

                v.add(catValue);
            }
        } else if (chartType == ReportChart.PIE_CHART || chartType == ReportChart.RING_CHART) {
            while (rs.next()) {
                PieChartValue pieValue = new PieChartValue();

                pieValue.setValue(rs.getDouble(1));
                pieValue.setKey(rs.getString(2));

                v.add(pieValue);
            }
        } else if (chartType == ReportChart.XY_CHART) {
            while (rs.next()) {
                XYChartValue xyValue = new XYChartValue();

                xyValue.setSeries(rs.getString(1));
                xyValue.setValue(rs.getDouble(2));
                xyValue.setSecondValue(rs.getDouble(3));

                v.add(xyValue);
            }
        } else if (chartType == ReportChart.TIME_CHART) {
            while (rs.next()) {
                TimeChartValue timeValue = new TimeChartValue();

                timeValue.setSeries(rs.getString(1));
                timeValue.setValue(rs.getDouble(2));
                timeValue.setTime(rs.getTimestamp(3));

                v.add(timeValue);
            }
        }

        ChartValue[] values = new ChartValue[v.size()];
        v.copyInto(values);

        return values;
    } catch (Exception e) {
        e.printStackTrace();
        throw new ProviderException(
                LocalStrings.getString(LocalStrings.ERROR_CHARTQUERY_INVALID) + ": " + e.toString());
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (pStmt != null)
                pStmt.close();
            if (conn != null)
                conn.close();
        } catch (Exception c) {
            log.error("Error closing");
        }
    }
}

From source file:database.DataLoader.java

private void moveAdminMessages() throws SQLException, ClassNotFoundException, Exception {
    try {// w  w  w. j a v a 2  s . co  m
        final String tableName = ADMIN_DISCUSS;
        final ResultSet resSet = getFromOldBase(getSelectAll(tableName));
        while (resSet.next()) {

            TransactionTemplate temp = new TransactionTemplate(transactionManager);
            temp.execute(new TransactionCallbackWithoutResult() {

                @Override
                protected void doInTransactionWithoutResult(TransactionStatus ts) {
                    Long oldId = 0L;
                    try {
                        oldId = resSet.getLong("id");
                        Long oldOrderId = resSet.getLong("order_id");
                        Long oldAdminId = resSet.getLong("admin_id");
                        Long newOrderId = getNewId(oldOrderId, ORDER);
                        Long newAdminId = getNewId(oldAdminId, USERS);
                        Timestamp date = resSet.getTimestamp("timestamp");
                        Order order = orderDao.find(newOrderId);
                        User admin = userDao.find(newAdminId);
                        String message = resSet.getString("message");
                        AdminMessage ent = new AdminMessage();
                        ent.setAdmin(admin);
                        ent.setMessageDate(date);
                        ent.setOrder(order);
                        ent.setText(message);

                        saveObjectAndLink(ent, oldId, tableName);
                    } catch (Throwable e) {
                        ts.setRollbackOnly();
                        addErrorMessage("admin: " + oldId + " "
                                + StringAdapter.transliterate(StringAdapter.getStackExeption(e)));
                    }
                }
            });

        }
    } catch (Throwable e) {
        log.warn("admin:  " + StringAdapter.transliterate(StringAdapter.getStackExeption(e)));
    }
}

From source file:com.concursive.connect.web.modules.login.dao.User.java

/**
 * Set the properties of the User object from the ResultSet
 *
 * @param rs Description of the Parameter
 * @throws SQLException Description of the Exception
 *///w  ww .ja va  2  s.  c o  m
private void build(ResultSet rs) throws SQLException {
    //user table
    id = rs.getInt("user_id");
    groupId = rs.getInt("group_id");
    departmentId = rs.getInt("department_id");
    firstName = rs.getString("first_name");
    lastName = rs.getString("last_name");
    username = rs.getString("username");
    password = rs.getString("password");
    temporaryPassword = rs.getString("temporary_password");
    company = rs.getString("company");
    email = rs.getString("email");
    entered = rs.getTimestamp("entered");
    enteredBy = rs.getInt("enteredby");
    enabled = rs.getBoolean("enabled");
    startPage = rs.getInt("start_page");
    accessAdmin = rs.getBoolean("access_admin");
    accessInvite = rs.getBoolean("access_invite");
    accessUserSettings = rs.getBoolean("access_settings");
    accessGuestProjects = rs.getBoolean("access_guest");
    lastLogin = rs.getTimestamp("last_login");
    expiration = rs.getTimestamp("expiration");
    registered = rs.getBoolean("registered");
    accountSize = DatabaseUtils.getInt(rs, "account_size");
    terms = rs.getBoolean("terms");
    timeZone = rs.getString("timezone");
    currency = rs.getString("currency");
    this.setLanguage(rs.getString("language"));
    modified = rs.getTimestamp("modified");
    modifiedBy = rs.getInt("modifiedby");
    try {
        // new fields not in original (in order of the user table)
        accessAddProjects = rs.getBoolean("access_add_projects");
        accessViewAllContacts = rs.getBoolean("access_contacts_view_all");
        accessEditAllContacts = rs.getBoolean("access_contacts_edit_all");
        watchForums = rs.getBoolean("watch_forums");
        nickname = rs.getString("nickname");
        salutationId = rs.getInt("salutation");
        profileProjectId = DatabaseUtils.getInt(rs, "profile_project_id");
        showProfileTo = DatabaseUtils.getInt(rs, "show_profile_to", Constants.WITH_ANYONE);
        showFullNameTo = DatabaseUtils.getInt(rs, "show_fullname_to", Constants.WITH_FRIENDS);
        showEmailTo = DatabaseUtils.getInt(rs, "show_email_to", Constants.WITH_NO_ONE);
        showGenderTo = DatabaseUtils.getInt(rs, "show_gender_to", Constants.WITH_ANYONE);
        showLocationTo = DatabaseUtils.getInt(rs, "show_location_to", Constants.WITH_ANYONE);
        showCompanyTo = DatabaseUtils.getInt(rs, "show_company_to", Constants.WITH_ANYONE);
        points = rs.getInt("points");
        instanceId = DatabaseUtils.getInt(rs, "instance_id", -1);
        connectCRMAdmin = rs.getBoolean("connect_crm_admin");
        connectCRMManager = rs.getBoolean("connect_crm_manager");
        // department table
        department = rs.getString("department");
        // project table
        profileUniqueId = rs.getString("projecttextid");
    } catch (Exception e) {
        // since these field may not exist in an upgraded system,
        // do not throw an error
    }
    //cleanup
    idRange = String.valueOf(id);
}

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

/**
 * Returns the most recent progress record for the given job ID.
 * @param jobId the job id./*from  ww w  . jav a  2  s  .c o  m*/
 * @return the most recent progress record for the given job ID.
 */
@Override
public StartedJobInfo getMostRecentByJobId(long jobId) {
    Connection c = HarvestDBConnection.get();
    Statement stm = null;
    try {
        stm = c.createStatement();
        ResultSet rs = stm.executeQuery("SELECT " + HM_COLUMN.getColumnsInOrder() + " FROM runningJobsMonitor"
                + " WHERE jobId=" + jobId);

        if (rs.next()) {
            String harvestName = rs.getString(HM_COLUMN.harvestName.rank());
            StartedJobInfo sji = new StartedJobInfo(harvestName, jobId);

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

            return sji;
        }

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

    throw new UnknownID("No running job with ID " + jobId);
}

From source file:net.agmodel.metbroker.driver.impl.JmaGsmJp.java

/**
 * get database connection and execute SQL command.
 * And put the result to Sequence Object
 * @param seqMap Sequence Map//  www. j av a2 s .co m
 * @param stationId station id
 * @param query SQL statement
 * @param start start date
 * @param end end date
 * @param hourly if true, use SIX_HOURS, else ONE_DAY
 * @throws DriverException something fail.
 */
private void queryTable(StationDataSetProxy seqMap, String stationId, String query, Date start, Date end,
        boolean hourly) throws DriverException {
    Connection con = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    java.sql.Timestamp startDate = new java.sql.Timestamp(start.getTime());
    java.sql.Timestamp endDate = new java.sql.Timestamp(end.getTime());
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

    try {
        con = dataSource.getConnection();

        logger.debug("Connection: " + con.toString());

        /*         stmt = con.prepareStatement(query);
                 stmt.setInt(1, new Integer(stationId).intValue());
                 stmt.setTimestamp(2, startDate, cal);
                 stmt.setTimestamp(3, endDate, cal);
                 stmt.setInt(4, new Integer(stationId).intValue());
                 stmt.setTimestamp(5, startDate, cal);
                 stmt.setTimestamp(6, endDate, cal);
        */
        stmt = con.prepareStatement(query);
        stmt.setInt(1, new Integer(stationId).intValue());
        stmt.setTimestamp(2, startDate);
        stmt.setTimestamp(3, endDate);
        stmt.setInt(4, new Integer(stationId).intValue());
        stmt.setTimestamp(5, startDate);
        stmt.setTimestamp(6, endDate);
        rs = stmt.executeQuery();

        logger.debug("ResultSet: " + rs.toString());

        AirTemperature tempSequence = null;
        if (seqMap.containsKey(MetElement.AIRTEMPERATURE)) {
            tempSequence = (AirTemperature) seqMap.getSequence(MetElement.AIRTEMPERATURE);
        }
        Rain rainSequence = null;
        if (seqMap.containsKey(MetElement.RAIN)) {
            rainSequence = (Rain) seqMap.getSequence(MetElement.RAIN);
        }
        Humidity humiditySequence = null;
        if (seqMap.containsKey(MetElement.HUMIDITY)) {
            humiditySequence = (Humidity) seqMap.getSequence(MetElement.HUMIDITY);
        }
        Wind windSequence = null;
        if (seqMap.containsKey(MetElement.WIND)) {
            windSequence = (Wind) seqMap.getSequence(MetElement.WIND);
        }

        while (rs.next()) {
            java.util.Date recordTime = null;
            MutableInterval dataInterval = new MutableInterval();
            recordTime = rs.getTimestamp("end_date");

            if (hourly) {
                dataInterval.set(Duration.SIX_HOURS, recordTime);
            } else {
                dataInterval.set(Duration.ONE_DAY, recordTime);
            }

            if (seqMap.containsKey(MetElement.AIRTEMPERATURE)) {
                float dummy = (float) (rs.getFloat("temperature") - 273.15);
                if (!rs.wasNull()) {
                    ((AirTempMaxMinMeanImpl) tempSequence).putMeanOverInterval(dataInterval, dummy);
                }
            }
            if (seqMap.containsKey(MetElement.RAIN)) {
                float dummy = rs.getFloat("total_preciptasion");
                if (!rs.wasNull()) {
                    ((RainImpl) rainSequence).putRainfallOverInterval(dataInterval, dummy);
                }
            }
            if (seqMap.containsKey(MetElement.HUMIDITY)) {
                float dummy = rs.getFloat("relative_humidity");
                if (!rs.wasNull()) {
                    ((RHImpl) humiditySequence).putRHOverInterval(dataInterval, dummy);
                }
            }
            if (seqMap.containsKey(MetElement.WIND)) {
                float u = rs.getFloat("u_wind");
                if (!rs.wasNull()) {
                    float v = rs.getFloat("v_wind");
                    if (!rs.wasNull()) {
                        ((Wind2DImpl) windSequence).putSpeedOverInterval(dataInterval, v, u);
                    }
                }
            }
        }
    } catch (SQLException s) {
        s.printStackTrace();
    } finally {
        try {
            rs.close();
        } catch (Exception s) {
        }
        try {
            stmt.close();
        } catch (Exception s) {
        }
        try {
            con.close();
        } catch (Exception e) {
        }

    }

}