Example usage for java.sql Date Date

List of usage examples for java.sql Date Date

Introduction

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

Prototype

public Date(long date) 

Source Link

Document

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Usage

From source file:org.apache.phoenix.end2end.index.IndexMaintenanceIT.java

private void verifyResult(ResultSet rs, int i) throws SQLException {
    assertTrue(rs.next());//  www .  j a v a  2s .  c  om
    assertEquals("VARCHAR" + String.valueOf(i) + "_" + StringUtils.rightPad("CHAR" + String.valueOf(i), 10, ' ')
            + "_A.VARCHAR" + String.valueOf(i) + "_"
            + StringUtils.rightPad("B.CHAR" + String.valueOf(i), 10, ' '), rs.getString(1));
    assertEquals(i * 3, rs.getInt(2));
    Date date = new Date(DateUtil.parseDate("2015-01-01 00:00:00").getTime() + (i) * MILLIS_IN_DAY);
    assertEquals(date, rs.getDate(3));
    assertEquals(date, rs.getDate(4));
    assertEquals(date, rs.getDate(5));
    assertEquals("varchar" + String.valueOf(i), rs.getString(6));
    assertEquals("char" + String.valueOf(i), rs.getString(7));
    assertEquals(i, rs.getInt(8));
    assertEquals(i, rs.getLong(9));
    assertEquals(i * 0.5d, rs.getDouble(10), 0.000001);
    assertEquals(i, rs.getLong(11));
    assertEquals(i, rs.getLong(12));
}

From source file:tdunnick.phinmsx.model.Charts.java

/**
 * Adds data for one interval in the bar chart.  The date is set to MMM-yy
 * format./* w  w  w. j  a  v a 2s. c om*/
 * 
 * @param data to add interval to
 * @param constraints for that data
 * @param d time (date) for that interval
 * @param values for each constraint
 */
private void addBarData(DefaultCategoryDataset data, ArrayList constraints, long d, int[] values) {
    SimpleDateFormat f = new SimpleDateFormat("MMM-yy");
    String date = f.format(new Date(d));
    for (int i = 0; i < values.length; i++) {
        data.addValue(values[i], (String) constraints.get(i), date);
        values[i] = 0;
    }
}

From source file:org.apache.nifi.csv.TestWriteCSVResult.java

@Test
public void testDataTypes() throws IOException {
    final CSVFormat csvFormat = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL).withRecordSeparator("\n");

    final StringBuilder headerBuilder = new StringBuilder();
    final List<RecordField> fields = new ArrayList<>();
    for (final RecordFieldType fieldType : RecordFieldType.values()) {
        if (fieldType == RecordFieldType.CHOICE) {
            final List<DataType> possibleTypes = new ArrayList<>();
            possibleTypes.add(RecordFieldType.INT.getDataType());
            possibleTypes.add(RecordFieldType.LONG.getDataType());

            fields.add(new RecordField(fieldType.name().toLowerCase(),
                    fieldType.getChoiceDataType(possibleTypes)));
        } else {/*from ww  w.j av a 2s .  co  m*/
            fields.add(new RecordField(fieldType.name().toLowerCase(), fieldType.getDataType()));
        }

        headerBuilder.append('"').append(fieldType.name().toLowerCase()).append('"').append(",");
    }
    final RecordSchema schema = new SimpleRecordSchema(fields);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final long now = System.currentTimeMillis();

    try (final WriteCSVResult result = new WriteCSVResult(csvFormat, schema, new SchemaNameAsAttribute(), baos,
            RecordFieldType.DATE.getDefaultFormat(), RecordFieldType.TIME.getDefaultFormat(),
            RecordFieldType.TIMESTAMP.getDefaultFormat(), true, "UTF-8")) {

        final Map<String, Object> valueMap = new HashMap<>();
        valueMap.put("string", "abc?123");
        valueMap.put("boolean", true);
        valueMap.put("byte", (byte) 1);
        valueMap.put("char", 'c');
        valueMap.put("short", (short) 8);
        valueMap.put("int", 9);
        valueMap.put("bigint", BigInteger.valueOf(8L));
        valueMap.put("long", 8L);
        valueMap.put("float", 8.0F);
        valueMap.put("double", 8.0D);
        valueMap.put("date", new Date(now));
        valueMap.put("time", new Time(now));
        valueMap.put("timestamp", new Timestamp(now));
        valueMap.put("record", null);
        valueMap.put("choice", 48L);
        valueMap.put("array", null);

        final Record record = new MapRecord(schema, valueMap);
        final RecordSet rs = RecordSet.of(schema, record);

        result.write(rs);
    }

    final String output = new String(baos.toByteArray(), StandardCharsets.UTF_8);

    headerBuilder.deleteCharAt(headerBuilder.length() - 1);
    final String headerLine = headerBuilder.toString();

    final String[] splits = output.split("\n");
    assertEquals(2, splits.length);
    assertEquals(headerLine, splits[0]);

    final String values = splits[1];
    final StringBuilder expectedBuilder = new StringBuilder();
    expectedBuilder.append("\"abc?123\",\"true\",\"1\",\"c\",\"8\",\"9\",\"8\",\"8\",\"8.0\",\"8.0\",");

    final String dateValue = getDateFormat(RecordFieldType.DATE.getDefaultFormat()).format(now);
    final String timeValue = getDateFormat(RecordFieldType.TIME.getDefaultFormat()).format(now);
    final String timestampValue = getDateFormat(RecordFieldType.TIMESTAMP.getDefaultFormat()).format(now);

    expectedBuilder.append('"').append(dateValue).append('"').append(',');
    expectedBuilder.append('"').append(timeValue).append('"').append(',');
    expectedBuilder.append('"').append(timestampValue).append('"').append(',');
    expectedBuilder.append(",\"48\",,");
    final String expectedValues = expectedBuilder.toString();

    assertEquals(expectedValues, values);
}

From source file:nl.strohalm.cyclos.setup.migrations.version3_6.ClosedAccountBalancesMigration.java

@Override
public int execute(final JDBCWrapper jdbc) throws SQLException {

    // First, ensure the account status still exists, ie, not already migrated
    ResultSet accountStatusExists = null;
    try {//from   w ww .java2s.  c o m
        accountStatusExists = jdbc.query("select 1 from account_status limit 1");
    } catch (final SQLException e) {
        // The already does not exists. Exit.
        return 0;
    } finally {
        JDBCWrapper.closeQuietly(accountStatusExists);
    }

    // Populate the account limit logs from both the account status and the pending account status tables
    jdbc.execute(
            "insert into account_limit_logs " + " (account_id, date, by_id, credit_limit, upper_credit_limit) "
                    + " select account_id, date, credit_limit_by_id, credit_limit, upper_credit_limit"
                    + " from account_status" + " where credit_limit_by_id is not null");

    jdbc.execute(
            "insert into account_limit_logs " + " (account_id, date, by_id, credit_limit, upper_credit_limit) "
                    + " select account_id, date, by_id, lower_limit, upper_limit"
                    + " from pending_account_status" + " where type = 'lim'");

    // Populate the amount_reservations table from pending transfers, scheduled payments which reserves the total amount and their installments
    jdbc.execute("insert into amount_reservations" + " (subclass, account_id, date, amount, transfer_id)"
            + " select 'P', from_account_id, date, amount, id " + " from transfers t " + " where t.status = ? ",
            Payment.Status.PENDING.getValue());
    jdbc.execute(
            "insert into amount_reservations" + " (subclass, account_id, date, amount, scheduled_payment_id)"
                    + " select 'S', from_account_id, date, amount, id " + " from scheduled_payments "
                    + " where reserve_amount = true ");
    jdbc.execute(
            "insert into amount_reservations" + " (subclass, account_id, date, amount, transfer_id)"
                    + " select 'I', t.from_account_id, ifnull(t.process_date, t.date), -t.amount, t.id "
                    + " from transfers t inner join scheduled_payments sp on t.scheduled_payment_id = sp.id"
                    + " where sp.reserve_amount = true and t.status <> ? ",
            Payment.Status.SCHEDULED.getValue());

    // Iterate each account
    int results = 0;
    final ResultSet accounts = jdbc.query("select id, creation_date from accounts");
    try {
        while (accounts.next()) {
            final long accountId = accounts.getLong("id");
            final Date creationDate = new Date(DateUtils
                    .truncate(accounts.getTimestamp("creation_date"), Calendar.DAY_OF_MONTH).getTime());
            // Get, by day, each diff, either for balance or reserved amount
            ResultSet diffs = jdbc.query(" select * from ( "
                    + "     select 'B' as type, b.date, b.balance as diff" + "     from ( "
                    + "         select date(date) as date, sum(amount) as balance " + "         from ( "
                    + "             select t.process_date as date, "
                    + "             case when t.chargeback_of_id is null then "
                    + "                 case when t.from_account_id = ? then -t.amount else t.amount end "
                    + "             else "
                    + "                 case when t.to_account_id = ? then t.amount else -t.amount end "
                    + "             end as amount " + "             from transfers t "
                    + "             where (t.from_account_id = ? or t.to_account_id = ?) "
                    + "               and t.process_date is not null " + "         ) t "
                    + "         group by date(date) " + "     ) b " + "     union "
                    + "     select 'R', date(r.date), sum(r.amount) " + "     from amount_reservations r "
                    + "     where r.account_id = ? " + "     group by date(r.date) " + " ) t "
                    + " where date < current_date() " + " order by date", accountId, accountId, accountId,
                    accountId, accountId);
            Date lastDate = creationDate;
            double balance = 0;
            double reserved = 0;
            try {
                boolean hasData = false;
                while (diffs.next()) {
                    hasData = true;
                    boolean isBalance = "B".equals(diffs.getString("type"));
                    Date date = diffs.getDate("date");
                    double diff = diffs.getDouble("diff");
                    if (!lastDate.equals(date)) {
                        // Insert a closed balance when the date changes
                        results += jdbc.execute(
                                "insert into closed_account_balances (date, account_id, balance, reserved) values (?, ?, ?, ?)",
                                nextDay(lastDate), accountId, balance, reserved);
                    }
                    if (isBalance) {
                        balance += diff;
                    } else {
                        reserved += diff;
                    }
                    lastDate = date;
                }
                if (hasData) {
                    // There is a last closed balance to insert
                    results += jdbc.execute(
                            "insert into closed_account_balances (date, account_id, balance, reserved) values (?, ?, ?, ?)",
                            nextDay(lastDate), accountId, balance, reserved);
                }
            } finally {
                JDBCWrapper.closeQuietly(diffs);
            }
            // Set the last closing date
            jdbc.execute("update accounts set last_closing_date = ? where id = ?", lastDate, accountId);
        }
    } finally {
        JDBCWrapper.closeQuietly(accounts);
    }

    // Now it is safe to drop the account_status table
    jdbc.execute("drop table account_status");
    jdbc.execute("drop table pending_account_status");

    return results;
}

From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java

public static Date readDate(ByteBuf in) {
    Timestamp ts = readTimestamp(in);
    return new Date(ts.getTime());
}

From source file:gov.nih.nci.integration.dao.ServiceInvocationMessagesDaoTest.java

private IHubMessage createIHubMessage() {
    final IHubMessage iHubMessage = new IHubMessage();
    iHubMessage.setRequest("request string");
    iHubMessage.setStartTime(new Date(new java.util.Date().getTime()));
    iHubMessage.setStatus(Status.PROCESS);
    iHubMessage.setReferenceMessageId(refMsgId);

    return iHubMessage;
}

From source file:gov.nih.nci.integration.invoker.CaTissueConsentStrategyTest.java

/**
 * Tests registerConsents using the ServiceInvocationStrategy class for the failure scenario
 * /* w  w  w .j ava2 s .  c om*/
 * @throws IntegrationException - IntegrationException
 * @throws JAXBException - JAXBException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void registerConsentsSpecimenNotExist() throws IntegrationException, JAXBException {
    final Date stTime = new Date(new java.util.Date().getTime());

    xsltTransformer.transform(null, null, null);
    EasyMock.expectLastCall().andAnswer(new IAnswer() {

        public Object answer() {
            return getRegisterConsentXMLStr();
        }
    }).anyTimes();

    final ServiceInvocationResult clientResult = new ServiceInvocationResult();
    clientResult.setDataChanged(false);

    final IntegrationException ie = new IntegrationException(IntegrationError._1090, new Throwable( //NOPMD
            "Specimen for given LABEL doesn't exist"), "Specimen for given LABEL doesn't exist");
    clientResult.setInvocationException(ie);

    EasyMock.expect(caTissueConsentClient.registerConsents((String) EasyMock.anyObject()))
            .andReturn(clientResult);
    EasyMock.replay(caTissueConsentClient);
    final ServiceInvocationMessage serviceInvocationMessage = prepareServiceInvocationMessage(REFMSGID,
            getRegisterConsentXMLStr(), stTime, caTissueConsentStrategy.getStrategyIdentifier());
    final ServiceInvocationResult strategyResult = caTissueConsentStrategy.invoke(serviceInvocationMessage);
    Assert.assertNotNull(strategyResult);
}

From source file:org.forumj.dbextreme.db.service.test.user.tests.UpdateUserTest.java

private static void prepareUser3(Long id) {
    testUser3.setId(id);/*from   w  w  w .j  ava  2s.c o  m*/
    testUser3.setNick("nick");
    testUser3.setPass("pass1");
    testUser3.setEmail("mail");
    testUser3.setName("name");
    testUser3.setFam("fam");
    testUser3.setSex("M");
    testUser3.setBith(new Date(new java.util.Date().getTime()));
    testUser3.setPass2("pass2");
    testUser3.setShowMail(true);
    testUser3.setShowName(true);
    testUser3.setCity("city");
    testUser3.setShowCity(true);
    testUser3.setCountry("country");
    testUser3.setShowCountry(true);
    testUser3.setShowSex(true);
    testUser3.setIcq("icq");
    testUser3.setShowIcq(true);
    testUser3.setShowBithday(true);
    testUser3.setLanguge(Locale.UA);
    testUser3.setHideIp(true);
    testUser3.setView(7);
    testUser3.setPp(66);
    testUser3.setPt(77);
    testUser3.setAvatar("avatar");
    testUser3.setShowAvatar(true);
    testUser3.setAvatarApproved(true);
    testUser3.setWantSeeAvatars(true);
    testUser3.setTimeZone(7);
    testUser3.setFooter("footer");
    testUser3.setBan(1);
    testUser3.setActivateCode(45567678);
    testUser3.setIsActive(true);
}

From source file:org.envirocar.aggregation.AggregatedTracksServlet.java

private String createAggregatedTracksList() throws SQLException {
    ResultSet rs = this.connection.executeQueryStatement(query);

    ArrayNode array = om.createArrayNode();
    ObjectNode object;//  w w w.j a v a2  s . c o m
    String id;
    Timestamp ts;
    while (rs.next()) {
        object = om.createObjectNode();
        id = rs.getString("id");
        ts = rs.getTimestamp(AGGREGATION_DATE);

        object.put(id, df.format(new Date(ts.getTime())));

        array.add(object);
    }

    rs.close();

    ObjectNode node = om.createObjectNode();

    node.put("tracks", array);
    return node.toString();
}

From source file:org.apache.phoenix.end2end.index.IndexExpressionIT.java

/**
 * Adds a row to the index data table/*w w w  .ja v  a 2  s.  c o m*/
 * 
 * @param i
 *            row number
 */
private void insertRow(PreparedStatement stmt, int i) throws SQLException {
    // insert row
    stmt.setString(1, "varchar" + String.valueOf(i));
    stmt.setString(2, "char" + String.valueOf(i));
    stmt.setInt(3, i);
    stmt.setLong(4, i);
    stmt.setBigDecimal(5, new BigDecimal(i * 0.5d));
    Date date = new Date(DateUtil.parseDate("2015-01-01 00:00:00").getTime() + (i - 1) * NUM_MILLIS_IN_DAY);
    stmt.setDate(6, date);
    stmt.setString(7, "a.varchar" + String.valueOf(i));
    stmt.setString(8, "a.char" + String.valueOf(i));
    stmt.setInt(9, i);
    stmt.setLong(10, i);
    stmt.setBigDecimal(11, new BigDecimal(i * 0.5d));
    stmt.setDate(12, date);
    stmt.setString(13, "b.varchar" + String.valueOf(i));
    stmt.setString(14, "b.char" + String.valueOf(i));
    stmt.setInt(15, i);
    stmt.setLong(16, i);
    stmt.setBigDecimal(17, new BigDecimal(i * 0.5d));
    stmt.setDate(18, date);
    stmt.executeUpdate();
}