Example usage for java.util Date setTime

List of usage examples for java.util Date setTime

Introduction

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

Prototype

public void setTime(long time) 

Source Link

Document

Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.

Usage

From source file:org.openmeetings.test.AbstractOpenmeetingsSpringTest.java

public Appointment createAppointment() throws Exception {
    assertNotNull("Can't access to appointment dao implimentation", appointmentDao);

    // add new appointment
    Appointment ap = new Appointment();

    ap.setAppointmentName("appointmentName");
    ap.setAppointmentLocation("appointmentLocation");

    Date appointmentstart = new Date();
    Date appointmentend = new Date();
    appointmentend.setTime(appointmentstart.getTime() + 3600);

    ap.setAppointmentStarttime(appointmentstart);
    ap.setAppointmentEndtime(appointmentend);
    ap.setAppointmentDescription("appointmentDescription");
    ap.setStarttime(new Date());
    ap.setDeleted("false");
    ap.setIsDaily(false);//  w w w.java 2  s.  c om
    ap.setIsWeekly(false);
    ap.setIsMonthly(false);
    ap.setIsYearly(false);
    ap.setIsPasswordProtected(false);

    ap.setUserId(usersDao.getUser(1L));
    ap.setIsConnectedEvent(false);
    Long id = appointmentDao.addAppointmentObj(ap);
    assertNotNull("Cann't add appointment", id);
    return ap;
}

From source file:Main.java

/**
 * <p>Internal calculation method.</p>
 * /*  ww  w  . j  a  v  a  2  s  . c  om*/
 * @param val  the calendar
 * @param field  the field constant
 * @param round  true to round, false to truncate
 * @throws ArithmeticException if the year is over 280 million
 */
private static void modify(Calendar val, int field, boolean round) {
    if (val.get(Calendar.YEAR) > 280000000) {
        throw new ArithmeticException("Calendar value too large for accurate calculations");
    }

    if (field == Calendar.MILLISECOND) {
        return;
    }

    // ----------------- Fix for LANG-59 ---------------------- START ---------------
    // see http://issues.apache.org/jira/browse/LANG-59
    //
    // Manually truncate milliseconds, seconds and minutes, rather than using
    // Calendar methods.

    Date date = val.getTime();
    long time = date.getTime();
    boolean done = false;

    // truncate milliseconds
    int millisecs = val.get(Calendar.MILLISECOND);
    if (!round || millisecs < 500) {
        time = time - millisecs;
    }
    if (field == Calendar.SECOND) {
        done = true;
    }

    // truncate seconds
    int seconds = val.get(Calendar.SECOND);
    if (!done && (!round || seconds < 30)) {
        time = time - (seconds * 1000L);
    }
    if (field == Calendar.MINUTE) {
        done = true;
    }

    // truncate minutes
    int minutes = val.get(Calendar.MINUTE);
    if (!done && (!round || minutes < 30)) {
        time = time - (minutes * 60000L);
    }

    // reset time
    if (date.getTime() != time) {
        date.setTime(time);
        val.setTime(date);
    }
    // ----------------- Fix for LANG-59 ----------------------- END ----------------

    boolean roundUp = false;
    for (int i = 0; i < fields.length; i++) {
        for (int j = 0; j < fields[i].length; j++) {
            if (fields[i][j] == field) {
                //This is our field... we stop looping
                if (round && roundUp) {
                    if (field == DateUtils.SEMI_MONTH) {
                        //This is a special case that's hard to generalize
                        //If the date is 1, we round up to 16, otherwise
                        //  we subtract 15 days and add 1 month
                        if (val.get(Calendar.DATE) == 1) {
                            val.add(Calendar.DATE, 15);
                        } else {
                            val.add(Calendar.DATE, -15);
                            val.add(Calendar.MONTH, 1);
                        }
                    } else {
                        //We need at add one to this field since the
                        //  last number causes us to round up
                        val.add(fields[i][0], 1);
                    }
                }
                return;
            }
        }
        //We have various fields that are not easy roundings
        int offset = 0;
        boolean offsetSet = false;
        //These are special types of fields that require different rounding rules
        switch (field) {
        case DateUtils.SEMI_MONTH:
            if (fields[i][0] == Calendar.DATE) {
                //If we're going to drop the DATE field's value,
                //  we want to do this our own way.
                //We need to subtrace 1 since the date has a minimum of 1
                offset = val.get(Calendar.DATE) - 1;
                //If we're above 15 days adjustment, that means we're in the
                //  bottom half of the month and should stay accordingly.
                if (offset >= 15) {
                    offset -= 15;
                }
                //Record whether we're in the top or bottom half of that range
                roundUp = offset > 7;
                offsetSet = true;
            }
            break;
        case Calendar.AM_PM:
            if (fields[i][0] == Calendar.HOUR_OF_DAY) {
                //If we're going to drop the HOUR field's value,
                //  we want to do this our own way.
                offset = val.get(Calendar.HOUR_OF_DAY);
                if (offset >= 12) {
                    offset -= 12;
                }
                roundUp = offset > 6;
                offsetSet = true;
            }
            break;
        }
        if (!offsetSet) {
            int min = val.getActualMinimum(fields[i][0]);
            int max = val.getActualMaximum(fields[i][0]);
            //Calculate the offset from the minimum allowed value
            offset = val.get(fields[i][0]) - min;
            //Set roundUp if this is more than half way between the minimum and maximum
            roundUp = offset > ((max - min) / 2);
        }
        //We need to remove this field
        if (offset != 0) {
            val.set(fields[i][0], val.get(fields[i][0]) - offset);
        }
    }
    throw new IllegalArgumentException("The field " + field + " is not supported");

}

From source file:org.apache.metron.dataloads.bulk.ElasticsearchDataPrunerIntegrationTest.java

@Test
public void testDeletesCorrectIndexes() throws Exception {

    Integer numDays = 5;//from   w  w w  .  j  a v  a 2s. c  o  m

    Date createStartDate = new Date();

    createStartDate.setTime(yesterday.getTime() - TimeUnit.DAYS.toMillis(numDays - 1));

    ElasticsearchDataPruner pruner = new ElasticsearchDataPruner(yesterday, 30, configuration, client(), "*");
    String indexesToDelete = "sensor_index_" + new SimpleDateFormat("yyyy.MM.dd").format(createStartDate)
            + ".*";
    Boolean deleted = pruner.deleteIndex(admin(), indexesToDelete);

    assertTrue("Index deletion should be acknowledged", deleted);

}

From source file:dk.netarkivet.harvester.scheduler.JobSupervisor.java

/**
 * Stops any job that has been in status STARTED a very long time defined
 * by the {@link HarvesterSettings#JOB_TIMEOUT_TIME} setting.
 * // w  ww  . j  a va2  s .  c om
 * Package protected to allow unit testing.
 */
void cleanOldJobs() {
    try {
        final JobDAO dao = JobDAO.getInstance();
        final Iterator<Long> startedJobs = dao.getAllJobIds(JobStatus.STARTED);
        int stoppedJobs = 0;
        while (startedJobs.hasNext()) {
            long id = startedJobs.next();
            Job job = dao.read(id);

            long timeDiff = Settings.getLong(HarvesterSettings.JOB_TIMEOUT_TIME) * TimeUtils.SECOND_IN_MILLIS;
            Date endTime = new Date();
            endTime.setTime(job.getActualStart().getTime() + timeDiff);
            if (new Date().after(endTime)) {
                final String msg = " Job " + id + " has exceeded its timeout of "
                        + (Settings.getLong(HarvesterSettings.JOB_TIMEOUT_TIME) / TimeUtils.HOUR_IN_MINUTES)
                        + " minutes." + " Changing status to " + "FAILED.";
                log.warn(msg);
                job.setStatus(JobStatus.FAILED);
                job.appendHarvestErrors(msg);
                dao.update(job);
                stoppedJobs++;
            }
        }
        if (stoppedJobs > 0) {
            log.warn("Changed " + stoppedJobs + " jobs from STARTED to FAILED");
        }
    } catch (Throwable thr) {
        log.error("Unable to stop obsolete jobs", thr);
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.CloudFrontBinaryManager.java

@Override
protected URI getRemoteUri(String digest, ManagedBlob blob, HttpServletRequest servletRequest)
        throws IOException {
    try {//from w w w.jav  a 2s.  c  om
        URIBuilder uriBuilder = new URIBuilder(buildResourcePath(bucketNamePrefix + digest));
        if (blob != null) {
            uriBuilder.addParameter("response-content-type", getContentTypeHeader(blob));
            uriBuilder.addParameter("response-content-disposition",
                    getContentDispositionHeader(blob, servletRequest));
        }

        if (isBooleanPropertyTrue(ENABLE_CF_ENCODING_FIX)) {
            String trimmedChars = " ";
            uriBuilder.getQueryParams().stream().filter(s -> s.getValue().contains(trimmedChars))
                    .forEach(s -> uriBuilder.setParameter(s.getName(), s.getValue().replace(trimmedChars, "")));
        }

        URI uri = uriBuilder.build();
        if (privKey == null) {
            return uri;
        }

        Date expiration = new Date();
        expiration.setTime(expiration.getTime() + directDownloadExpire * 1000);

        String signedURL = CloudFrontUrlSigner.getSignedURLWithCannedPolicy(uri.toString(), privKeyId, privKey,
                expiration);
        return new URI(signedURL);
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}

From source file:org.nuxeo.wss.handlers.resources.ResourcesHandler.java

protected void addCacheHeaders(HttpServletResponse response, int cacheTime) {
    response.addHeader("Cache-Control", "max-age=" + cacheTime);
    response.addHeader("Cache-Control", "public");

    Date date = new Date();
    long newDate = date.getTime() + new Long(cacheTime) * 1000;
    date.setTime(newDate);

    response.setHeader("Expires", HTTP_EXPIRES_DATE_FORMAT.format(date));
}

From source file:org.mozilla.mozstumbler.service.scanners.ScanManager.java

public void newPassiveGpsLocation() {
    if (isBatteryLow()) {
        return;/*w w w  .jav  a  2  s . c  om*/
    }

    if (AppGlobals.isDebug)
        Log.d(LOGTAG, "New passive location");

    mWifiScanner.start(ActiveOrPassiveStumbling.PASSIVE_STUMBLING);
    mCellScanner.start(ActiveOrPassiveStumbling.PASSIVE_STUMBLING);

    // how often to flush a leftover bundle to the reports table
    // If there is a bundle, and nothing happens for 10sec, then flush it
    final int flushRate_ms = 10000;

    if (mPassiveModeFlushTimer != null) {
        mPassiveModeFlushTimer.cancel();
    }

    Date when = new Date();
    when.setTime(when.getTime() + flushRate_ms);
    mPassiveModeFlushTimer = new Timer();
    mPassiveModeFlushTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            Intent flush = new Intent(Reporter.ACTION_FLUSH_TO_DB);
            LocalBroadcastManager.getInstance(mContext).sendBroadcastSync(flush);
        }
    }, when);
}

From source file:com.fivesticks.time.activity.ActivityResolver.java

public Date resolve() {

    Calendar c = new GregorianCalendar();
    c.setTime(date);//w ww  .jav a 2 s  .  c  o m

    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);

    parseActivityString();

    Calendar c2 = new GregorianCalendar(year, month, day, this.getResolvedHours(), this.getResolvedMinutes());
    Date ret = new Date();
    ret.setTime(c2.getTimeInMillis());

    return ret;
}

From source file:org.jfree.data.time.DateRangeTest.java

/**
 * Confirm that a DateRange is immutable.
 *///  ww w . j av a  2  s .  c  om
@Test
public void testImmutable() {
    Date d1 = new Date(10L);
    Date d2 = new Date(20L);
    DateRange r = new DateRange(d1, d2);
    d1.setTime(11L);
    assertEquals(new Date(10L), r.getLowerDate());
    r.getUpperDate().setTime(22L);
    assertEquals(new Date(20L), r.getUpperDate());
}

From source file:org.openmrs.module.sync.SyncRecordTest.java

/**
 * Auto generated method comment/*from  ww w  . j  a v  a2  s  .  c o  m*/
 * 
 * @throws Exception
 */
@Test
@NotTransactional
@SkipBaseSetup
public void shouldEquality() throws Exception {

    //setup instance 1
    String uuid1 = UUID.randomUUID().toString();
    SyncRecord syncRecord1 = new SyncRecord();
    syncRecord1.setTimestamp(new Date());
    syncRecord1.setUuid(uuid1);
    SyncItem item11 = new SyncItem();
    item11.setContent("<Person><Name>Some Person</Name></Person>");
    item11.setState(SyncItemState.NEW);
    item11.setKey(new SyncItemKey<String>(UUID.randomUUID().toString(), String.class));
    List<SyncItem> items1 = new ArrayList<SyncItem>();
    items1.add(item11);
    syncRecord1.setItems(items1);

    //setup instance 2
    SyncRecord syncRecord2 = new SyncRecord();
    syncRecord2.setTimestamp(syncRecord1.getTimestamp());
    syncRecord2.setUuid(syncRecord1.getUuid());
    SyncItem item21 = new SyncItem();
    item21.setContent("<Person><Name>Some Person</Name></Person>");
    item21.setState(SyncItemState.NEW);
    item21.setKey(item11.getKey());
    List<SyncItem> items2 = new ArrayList<SyncItem>();
    items2.add(item21);
    syncRecord2.setItems(items2);

    //assert now
    assertEquals(syncRecord1, syncRecord2);

    syncRecord1.setItems(null);
    assertNotSame(syncRecord1, syncRecord2);

    //some variations
    Date date2 = new Date();
    date2.setTime(syncRecord1.getTimestamp().getTime() + 1);
    syncRecord2.setTimestamp(date2);
    assertTrue(!syncRecord1.equals(syncRecord2));

    date2.setTime(syncRecord1.getTimestamp().getTime());
    assertTrue(syncRecord1.equals(syncRecord2));

    item21.setContent("<Person><Name>Some Person Name</Name></Person>");
    assertTrue(!syncRecord1.equals(syncRecord2));
}