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:gov.nih.nci.integration.invoker.CaTissueParticipantStrategyTest.java

/**
 * Tests updateRegistrationParticipant using the ServiceInvocationStrategy class for the failure scenario
 * //from  w ww .j av  a2s . c o m
 * @throws IntegrationException - IntegrationException
 * @throws JAXBException - JAXBException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void updateParticipantRegistrationFailure() 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 getSpecimenXMLStr();
        }
    }).anyTimes();

    final ServiceInvocationResult clientResult = new ServiceInvocationResult();
    clientResult.setDataChanged(false);
    clientResult.setOriginalData(getSpecimenXMLStr());
    final IntegrationException ie = new IntegrationException(IntegrationError._1034, new Throwable( // NOPMD
            "Participant does not contain the unique identifier SSN"),
            "Participant does not contain the unique identifier SSN");
    clientResult.setInvocationException(ie);

    EasyMock.expect(caTissueParticipantClient.updateRegistrationParticipant((String) EasyMock.anyObject()))
            .andReturn(clientResult);
    EasyMock.replay(caTissueParticipantClient);
    final ServiceInvocationMessage serviceInvocationMessage = prepareServiceInvocationMessage(REFMSGID,
            getSpecimenXMLStr(), stTime, caTissueUpdateRegistrationStrategy.getStrategyIdentifier());
    final ServiceInvocationResult strategyResult = caTissueUpdateRegistrationStrategy
            .invoke(serviceInvocationMessage);
    Assert.assertNotNull(strategyResult);
}

From source file:org.eclipse.smila.connectivity.framework.crawler.jdbc.test.AbstractDataEnabledJdbcCrawlerTestCase.java

/**
 * {@inheritDoc} Called by the JUnit-Runner before execution of a testMethod of inheriting classes. Sets up a Database
 * fixture by performing the following steps:
 * <ol>/*from  ww  w. ja v  a2  s. c  o  m*/
 * <li>Shutdown a (potentially) running Derby engine by calling {@link DriverManager#getConnection(String)} with the
 * Shutdown-URL (see {@link #SHUTDOWN_URL}).</li>
 * <li>Delete all database files (potentially) remaining from prior test cases.</li>
 * <li>Configure Derby engine to log all executed SQL in the log file and to rather append to an existing logfile than
 * to overwrite it.</li>
 * <li>Get a {@link Connection} to the Derby DB and insert 100 rows of data (see source code for details). This
 * includes BLOB (from image file) and CLOB (from text file) fields.</li>
 * <li>Release allocated JDBC-resources (Statement, Connection).</li>
 * <li>Shutdown Derby Engine via Shutdown-URL (so the Crawler can start it up as it would normally)</li>
 * <li>Instantiates a {@link JdbcCrawler}.</li>
 * </ol>
 * 
 * @see junit.framework.TestCase#setUp()
 */
@Override
protected void setUp() throws Exception {

    super.setUp();

    Class.forName(DRIVER_NAME).newInstance();
    // shutdown embedded Derby engine (if running)
    // using SHUTDOWN_URL *always* results in SQLException, so we catch and ignore ...
    try {
        DriverManager.getConnection(SHUTDOWN_URL);
    } catch (final SQLException e) {
        _log.info("Testcase Setup: Shutting down Derby Engine");

    }

    // delete existing db files
    final File dbDirectory = new File(DB_NAME);
    if (FileUtils.deleteQuietly(dbDirectory)) {
        _log.info("Deleted DB files of [" + DB_NAME + "] database");
    } else {
        _log.warn("Could not delete DB files of [" + DB_NAME + "] database");
    }

    Class.forName(DRIVER_NAME).newInstance();
    final Properties p = System.getProperties();

    // we want to see all sql in the db log file
    p.put("derby.language.logStatementText", "true");
    // we don't want the logfile to be recreated each time the engine starts ...
    p.put("derby.infolog.append", "true");
    Connection connection = DriverManager.getConnection(CONNECTION_URL);

    final ArrayList<Statement> statements = new ArrayList<Statement>(); // list of Statements,
    // PreparedStatements
    PreparedStatement psInsert = null;
    Statement createStatement = null;

    createStatement = connection.createStatement();
    statements.add(createStatement);

    // create a person table...
    createStatement
            .execute("CREATE TABLE person(id int, vorname varchar(40), name varchar(40), strasse varchar(40), "
                    + "plz varchar(5), ort varchar(40), festnetz varchar(20), body_mass_index double, vacationdays "
                    + "integer, birthday date, scheduled_for_downsizing smallint, downsized timestamp, photo blob, cv clob)");
    _log.info("Created TABLE [person]");

    // insert 100 records ...
    psInsert = connection
            .prepareStatement("INSERT INTO person VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)");
    statements.add(psInsert);

    // prepare resource files for blob / clob insertion...
    final File resDir = new File(RES_FOLDER_PATH);
    final File photoFile = new File(resDir, PHOTO_FILE_NAME);
    final File cvFile = new File(resDir, CV_FILE_NAME);

    for (int i = 1; i <= RECORDS_TO_INSERT; i++) {

        psInsert.setInt(COLUMN_ID, i);
        psInsert.setString(COLUMN_FIRSTNAME, "Mustervorname" + i);
        psInsert.setString(COLUMN_SURNAME, "Mustername" + i);
        psInsert.setString(COLUMN_STREET, "Musterstrasse " + i);
        psInsert.setString(COLUMN_PLZ, String.valueOf(getRandomInteger(DIGITS_IN_PLZ)));
        psInsert.setString(COLUMN_CITY, "Musterstadt" + i);
        psInsert.setString(COLUMN_PHONE,
                "0" + getRandomInteger(DIGITS_IN_AREA_CODE) + "-" + getRandomInteger(DIGITS_IN_EXTENSION));
        psInsert.setDouble(COLUMN_BMI, (Math.random() / Math.random()));
        psInsert.setLong(COLUMN_VACATIONDAYS, getRandomInteger(MAX_VACATIONDAYS));
        psInsert.setDate(COLUMN_BIRTHDAY, new Date(new java.util.Date().getTime()));
        psInsert.setBoolean(COLUMN_SCHEDULED_FOR_DOWNSIZING, ((getRandomInteger(1) % 2) == 0));
        psInsert.setDate(COLUMN_DOWNSIZED, new Date(new java.util.Date().getTime()));

        psInsert.setBytes(COLUMN_PHOTO, FileUtils.readFileToByteArray(photoFile));

        psInsert.setString(COLUMN_CV, FileUtils.readFileToString(cvFile));

        psInsert.execute();

    }

    // release all open resources to avoid unnecessary memory usage

    for (final Statement st : statements) {
        try {
            st.close();
        } catch (final SQLException sqle) {
            _log.error("Could not release Statement", sqle);
        }
    }
    statements.clear();

    // Connection
    try {
        if (connection != null) {
            connection.close();
            connection = null;
        }
    } catch (final SQLException sqle) {
        _log.error("Could not release Connection", sqle);
    }

    // shutdown Derby engine AGAIN, so the Crawler can start it up as it would normally
    try {
        DriverManager.getConnection(SHUTDOWN_URL);
    } catch (final SQLException e) {
        _log.info("Testcase Setup: Shutting down Derby Engine");
    }

    _crawler = new JdbcCrawler();

}

From source file:org.kuali.coeus.common.committee.impl.bo.CommitteeMembershipBase.java

/**
 * This method determines if the current committee member is active as of the current date.
 * @return true if member is active, false otherwise
 *///from  w  w  w .  j av a  2  s  .  c  om
public boolean isActive() {
    Date currentDate = DateUtils.clearTimeFields(new Date(System.currentTimeMillis()));
    return isActive(currentDate);
}

From source file:com.asakusafw.operation.tools.hadoop.fs.Clean.java

private boolean remove(FileSystem fs, FileStatus file, Context context) {
    LOG.debug("Attempt to remove {}", file.getPath()); //$NON-NLS-1$
    boolean isSymlink = context.isSymlink(fs, file);
    if (isSymlink) {
        LOG.error(MessageFormat.format("[OT-CLEAN-W01001] Symlink is currenty not supported: {0}",
                file.getPath()));/*www  . j  av a  2 s. com*/
        context.setError();
        return false;
    }
    if (file.isDirectory()) {
        if (context.isRecursive()) {
            List<FileStatus> children;
            try {
                children = asList(fs.listStatus(file.getPath()));
            } catch (IOException e) {
                LOG.error(
                        MessageFormat.format("[OT-CLEAN-E01003] Failed to list directory: {0}", file.getPath()),
                        e);
                context.setError();
                return false;
            }
            boolean deleteChildren = true;
            for (FileStatus child : children) {
                deleteChildren &= remove(fs, child, context);
            }
            if (deleteChildren == false) {
                LOG.info(MessageFormat.format("[OT-CLEAN-I01004] Skipped: {0} (is no-empty directory)",
                        file.getPath(), new Date(file.getModificationTime())));
                return false;
            }
        } else {
            LOG.info(MessageFormat.format("[OT-CLEAN-I01003] Skipped: {0} (is directory)", file.getPath(),
                    new Date(file.getModificationTime())));
            return false;
        }
    }
    if (context.canDelete(file)) {
        LOG.debug("Removing {}", file.getPath()); //$NON-NLS-1$
        if (context.isDryRun() == false) {
            try {
                boolean removed = fs.delete(file.getPath(), false);
                if (removed == false) {
                    LOG.error(MessageFormat.format("[OT-CLEAN-E01004] Failed to remove: {0}", file.getPath()));
                    context.setError();
                    return false;
                }
            } catch (IOException e) {
                LOG.warn(MessageFormat.format("[OT-CLEAN-E01004] Failed to remove: {0}", file.getPath()), e);
                context.setError();
                return false;
            }
        }
        LOG.info(MessageFormat.format("[OT-CLEAN-I01001] Removed: {0} (timestamp={1})", file.getPath(),
                new Date(file.getModificationTime())));
    } else {
        LOG.info(MessageFormat.format("[OT-CLEAN-I01002] Kept: {0} (timestamp={1})", file.getPath(),
                new Date(file.getModificationTime())));
        return false;
    }
    return true;
}

From source file:ips1ap101.lib.base.util.TimeUtils.java

public static Date newDate(java.util.Date date) {
    if (date == null) {
        return null;
    } else {/*from ww  w .  j a  va  2 s .c o m*/
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(date.getTime());
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return new Date(c.getTimeInMillis());
    }
}

From source file:org.kuali.coeus.common.committee.impl.bo.CommitteeBase.java

private boolean isChairPerson(CommitteeMembershipBase committeeMembership) {

    boolean isChairRoleFound = false;
    Date currentDate = DateUtils.clearTimeFields(new Date(System.currentTimeMillis()));

    for (CommitteeMembershipRole committeeMembershipRole : committeeMembership.getMembershipRoles()) {
        if (committeeMembershipRole.getMembershipRoleCode().equals(CHAIR_MEMBERSHIP_ROLE_CODE)
                && committeeMembershipRole.getStartDate() != null
                && committeeMembershipRole.getEndDate() != null
                && !currentDate.before(committeeMembershipRole.getStartDate())
                && !currentDate.after(committeeMembershipRole.getEndDate())) {
            isChairRoleFound = true;// w  ww .  j  av a  2 s.c  o m
            break;
        }
    }
    return isChairRoleFound;
}

From source file:org.apache.phoenix.end2end.DateTimeIT.java

public DateTimeIT() throws Exception {
    super();
    date = new Date(System.currentTimeMillis());
}

From source file:com.mobiaware.auction.data.impl.MySqlDataServiceImpl.java

@Override
public int editAuction(final Auction auction) {
    int uid = -1;

    Connection conn = null;/*w  ww.ja va2s.  c om*/
    CallableStatement stmt = null;
    ResultSet rs = null;

    try {
        conn = _dataSource.getConnection();

        stmt = conn.prepareCall("{call SP_EDITAUCTION (?,?,?,?,?,?)}");
        stmt.registerOutParameter(1, Types.INTEGER);
        stmt.setString(2, auction.getName());
        stmt.setDate(3, new Date(auction.getStartDate()));
        stmt.setDate(4, new Date(auction.getEndDate()));
        stmt.setString(5, auction.getLogoUrl());
        stmt.setString(6, auction.getColor());
        stmt.execute();

        uid = stmt.getInt(1);
    } catch (SQLException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    } finally {
        DbUtils.closeQuietly(conn, stmt, rs);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("AUCTION [method:{} result:{}]", new Object[] { "edit", uid });
    }

    return uid;
}

From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java

private void massUpdateMilestoneGanttItems(final List<MilestoneGanttItem> milestoneGanttItems,
        Integer sAccountId) {/*w  ww  .  j a  va  2 s. c o m*/
    if (CollectionUtils.isNotEmpty(milestoneGanttItems)) {
        Lock lock = DistributionLockUtil.getLock("gantt-milestone-service" + sAccountId);
        try {
            final long now = new GregorianCalendar().getTimeInMillis();
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                try (Connection connection = dataSource.getConnection()) {
                    connection.setAutoCommit(false);
                    PreparedStatement preparedStatement = connection.prepareStatement(
                            "UPDATE `m_prj_milestone` SET " + "name = ?, `startdate` = ?, `enddate` = ?, "
                                    + "`lastUpdatedTime`=?, `owner`=?, `ganttIndex`=? WHERE `id` = ?");
                    for (int i = 0; i < milestoneGanttItems.size(); i++) {
                        preparedStatement.setString(1, milestoneGanttItems.get(i).getName());
                        preparedStatement.setDate(2,
                                getDateWithNullValue(milestoneGanttItems.get(i).getStartDate()));
                        preparedStatement.setDate(3,
                                getDateWithNullValue(milestoneGanttItems.get(i).getEndDate()));
                        preparedStatement.setDate(4, new Date(now));
                        preparedStatement.setString(5, milestoneGanttItems.get(i).getAssignUser());
                        preparedStatement.setInt(6, milestoneGanttItems.get(i).getGanttIndex());
                        preparedStatement.setInt(7, milestoneGanttItems.get(i).getId());
                        preparedStatement.addBatch();

                    }
                    preparedStatement.executeBatch();
                    connection.commit();
                }
            }
        } catch (Exception e) {
            throw new MyCollabException(e);
        } finally {
            DistributionLockUtil.removeLock("gantt-milestone-service" + sAccountId);
            lock.unlock();
        }
    }
}

From source file:com.xumpy.thuisadmin.dao.BedragenDaoTest.java

@Test
@Transactional(value = "jpaTransactionManager")
public void testBedragenInPeriode() throws ParseException {
    userInfo.setPersoon(personenDao.findOne(1));
    startDate = new Date(dt.parse("2015-02-18").getTime());
    endDate = new Date(dt.parse("2015-02-23").getTime());

    List<Bedragen> checkBedragen = fetchTestBedragen();

    List<? extends Bedragen> bedragInPeriode = bedragenDao.BedragInPeriode(startDate, endDate,
            rekening.getPk_id(), 0, userInfo.getPersoon().getPk_id());

    for (int i = 0; i < checkBedragen.size(); i++) {
        assertEquals(checkBedragen.get(i).getPk_id(), bedragInPeriode.get(i).getPk_id());
    }/*w  w  w. jav  a 2 s  .c o  m*/
}