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:com.YOMPsolutions.YOMP.mobile.metric.MetricDetailActivity.java

@Override
protected Fragment createTabFragment(Tab tab) {
    MetricDetailFragment fragment = new MetricDetailFragment();
    AggregationType type = (AggregationType) tab.getTag();
    Metric metric = getMetric();//  w  w w. ja v  a 2 s  . c  om
    MetricAnomalyChartData metricData = new MetricAnomalyChartData(metric, type);
    Date endDate = new Date();
    if (getDate() != null) {
        final long currentSpan = endDate.getTime() - getDate().getTime();
        final int halfWeekMinutes = (AggregationType.Week.minutes() * YOMPApplication.getTotalBarsOnChart())
                / 2;
        int numMinutes = AggregationType.Hour.minutes() * YOMPApplication.getTotalBarsOnChart() / 4;
        if (AggregationType.Day.equals(type)) {
            numMinutes = AggregationType.Day.minutes() * YOMPApplication.getTotalBarsOnChart() / 2;
        } else if (AggregationType.Week.equals(type)) {
            long maxWeekSpan = MINUTES.convert(YOMPApplication.getNumberOfDaysToSync(), DAYS)
                    - AggregationType.Week.minutes() * YOMPApplication.getTotalBarsOnChart();
            if (MINUTES.convert(currentSpan, MILLISECONDS) > maxWeekSpan) {
                numMinutes = (int) maxWeekSpan;
            } else if (MINUTES.convert(currentSpan, MILLISECONDS) > halfWeekMinutes) {
                numMinutes = (int) MINUTES.convert(currentSpan, MILLISECONDS);
            } else {
                numMinutes = halfWeekMinutes;
            }
        }
        final long maxSpan = MILLISECONDS.convert(numMinutes, MINUTES);
        if (currentSpan > maxSpan) {
            endDate.setTime(getDate().getTime() + maxSpan);
        }
    }
    if (YOMPApplication.getAggregation().equals(type)) {
        metricData.setEndDate(endDate);
        setCurrentDate(endDate);
    }
    fragment.setMetricAnomalyData(metricData);

    // Google Analytics: Track metric name as first Custom Dimension for
    // this App.
    Tracker tracker = YOMPApplication.getInstance().getGoogleAnalyticsTracker();
    tracker.send(new HitBuilders.AppViewBuilder().setCustomDimension(1, metric.getName()).build());
    return fragment;
}

From source file:com.groksolutions.grok.mobile.metric.MetricDetailActivity.java

@Override
protected Fragment createTabFragment(Tab tab) {
    MetricDetailFragment fragment = new MetricDetailFragment();
    AggregationType type = (AggregationType) tab.getTag();
    Metric metric = getMetric();//from  www . j a  v  a  2  s  .com
    MetricAnomalyChartData metricData = new MetricAnomalyChartData(metric, type);
    Date endDate = new Date();
    if (getDate() != null) {
        final long currentSpan = endDate.getTime() - getDate().getTime();
        final int halfWeekMinutes = (AggregationType.Week.minutes() * HTMITApplication.getTotalBarsOnChart())
                / 2;
        int numMinutes = AggregationType.Hour.minutes() * HTMITApplication.getTotalBarsOnChart() / 4;
        if (AggregationType.Day.equals(type)) {
            numMinutes = AggregationType.Day.minutes() * HTMITApplication.getTotalBarsOnChart() / 2;
        } else if (AggregationType.Week.equals(type)) {
            long maxWeekSpan = MINUTES.convert(HTMITApplication.getNumberOfDaysToSync(), DAYS)
                    - AggregationType.Week.minutes() * HTMITApplication.getTotalBarsOnChart();
            if (MINUTES.convert(currentSpan, MILLISECONDS) > maxWeekSpan) {
                numMinutes = (int) maxWeekSpan;
            } else if (MINUTES.convert(currentSpan, MILLISECONDS) > halfWeekMinutes) {
                numMinutes = (int) MINUTES.convert(currentSpan, MILLISECONDS);
            } else {
                numMinutes = halfWeekMinutes;
            }
        }
        final long maxSpan = MILLISECONDS.convert(numMinutes, MINUTES);
        if (currentSpan > maxSpan) {
            endDate.setTime(getDate().getTime() + maxSpan);
        }
    }
    if (HTMITApplication.getAggregation().equals(type)) {
        metricData.setEndDate(endDate);
        setCurrentDate(endDate);
    }
    fragment.setMetricAnomalyData(metricData);

    // Google Analytics: Track metric name as first Custom Dimension for
    // this App.
    Tracker tracker = HTMITApplication.getInstance().getGoogleAnalyticsTracker();
    tracker.send(new HitBuilders.AppViewBuilder().setCustomDimension(1, metric.getName()).build());
    return fragment;
}

From source file:com.evolveum.midpoint.report.BasicReportTest.java

@Test
public void test011CleanupReports() throws Exception {

    final String TEST_NAME = "test011CleanupReports";
    TestUtil.displayTestTile(this, TEST_NAME);

    // GIVEN/*from   w w w.  j a v  a2s . c o  m*/
    List<PrismObject<? extends Objectable>> elements = prismContext.parseObjects(REPORTS_FOR_CLEANUP_FILE);

    Task task = taskManager.createTaskInstance(CLEANUP_REPORTS);
    OperationResult result = task.getResult();

    for (int i = 0; i < elements.size(); i++) {
        PrismObject object = elements.get(i);

        ObjectDelta objectDelta = ObjectDelta.createAddDelta(object);
        Collection<ObjectDelta<? extends ObjectType>> deltas = MiscSchemaUtil.createCollection(objectDelta);

        modelService.executeChanges(deltas, null, task, result);

        result.computeStatus();
        display(result);
        TestUtil.assertSuccess(result);
        String oid = objectDelta.getOid();

        AssertJUnit.assertTrue(StringUtils.isNotEmpty(oid));
        if (objectDelta.getObjectTypeClass() != ReportType.class) {
            ReportOutputType reportOutput = getReportOutput(oid).asObjectable();
            reportOutput.setFilePath(reportOutput.getFilePath().replace("${midpointhome}", MIDPOINT_HOME));

            MetadataType metadata = new MetadataType();
            Date date = new Date();

            if (reportOutput.getName().getOrig().contains("01")) {
                Calendar calendar = create_2013_06_01_00_00_Calendar();
                date.setTime(calendar.getTimeInMillis());
            }

            if (reportOutput.getName().getOrig().contains("02")) {
                Calendar calendar = create_2013_07_01_00_00_Calendar();
                date.setTime(calendar.getTimeInMillis());
            }

            if (reportOutput.getName().getOrig().contains("03")) {
                Calendar calendar = create_2013_08_01_00_00_Calendar();
                date.setTime(calendar.getTimeInMillis());
            }

            metadata.setCreateTimestamp(XmlTypeConverter.createXMLGregorianCalendar(date));
            reportOutput.setMetadata(metadata);

            deltas = new ArrayList<ObjectDelta<? extends ObjectType>>();
            PrismObject<ReportOutputType> reportOutputOld = getReportOutput(oid);
            deltas.add(reportOutputOld.diff(reportOutput.asPrismObject()));

            modelService.executeChanges(deltas, null, task, result);

            File file = new File(reportOutput.getFilePath());
            boolean blnCreated = false;
            try {
                blnCreated = file.createNewFile();
            } catch (IOException ex) {
                LOGGER.error("Error while creating a new empty file : {}", ex);
            }

            LOGGER.trace("Was file " + file.getPath() + " created ? : " + blnCreated);

        }
    }

    // WHEN
    // because now we can't move system time (we're not using DI for it) we create policy
    // which should always point to 2013-05-07T12:00:00.000+02:00
    final long NOW = System.currentTimeMillis();
    Calendar when = create_2014_01_01_12_00_Calendar();
    CleanupPolicyType policy = createPolicy(when, NOW);

    reportManager.cleanupReports(policy, result);

    // THEN
    List<PrismObject<ReportOutputType>> reportOutputs = modelService.searchObjects(ReportOutputType.class, null,
            null, task, result);
    AssertJUnit.assertNotNull(reportOutputs);
    AssertJUnit.assertEquals(1, reportOutputs.size());

}

From source file:org.alfresco.mobile.android.application.fragments.node.details.NodeDetailsFragment.java

public Date getDownloadDateTime() {
    Date d = null;
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    long activationTime = sharedPref.getLong("Dltime", -1);
    if (activationTime != -1) {
        d = new Date();
        d.setTime(activationTime);
    }/*from   w w  w .  j av a  2s.  c o m*/
    return d;
}

From source file:org.oscarehr.PMmodule.caisi_integrator.CaisiIntegratorUpdateTask.java

/**
 * A check to compare the time being requested from the integrator and that last time the integrator requested. If the date being requested is before the last date requested return true. If a last date hasn't been stored return true.
 *
 * @param lastDataUpdated time requested from the integrator
 * @param lastPushUpdated prior time requested from the integrator
 * @return/*w  ww  .  j av a2  s  . c  o  m*/
 */
private boolean isIntegratorRequestDateOlderThanLastKnownDate(Date lastDataUpdated,
        UserProperty lastPushUpdated) {
    if (lastPushUpdated == null)
        return (true);

    boolean ret = false;
    try {
        Date lastDateRequested = new Date();
        // If lastPushUpdated is null that means this is the first time this has run, return true
        lastDateRequested.setTime(Long.parseLong(lastPushUpdated.getValue()));
        if (lastDataUpdated.before(lastDateRequested)) {
            ret = true;
        }
        logger.debug("lastDataUpdated " + lastDataUpdated + " lastDateRequested " + lastDateRequested
                + " lastDataUpdated is before lastDateRequested: " + ret);
    } catch (Exception e) {
        logger.error("Unexpected error", e);
        return true;
    }
    return ret;
}

From source file:uk.org.funcube.fcdw.server.processor.WholeOrbitDataProcessorImpl.java

private void extractAndSaveWod(final Long satelliteId, final long seqNo, final List<String> frames,
        final Date receivedDate) {

    final Date frameTime = new Date(receivedDate.getTime() - 104 * 60 * 1000);

    final StringBuffer sb = new StringBuffer();

    for (int i = 0; i < 12; i++) {
        sb.append(StringUtils.right(frames.get(i), 400));
    }//from ww  w.  j  a va2  s  .c om

    int start = 0;
    int end = 46;

    for (int i = 0; i < 104; i++) {

        final long frameNumber = seqNo * 2 + i;

        if (wholeOrbitDataDao.findBySatelliteIdAndFrameNumber(satelliteId, frameNumber).size() == 0) {

            WholeOrbitDataEntity wod = null;

            switch (satelliteId.intValue()) {
            case 0:
                wod = new GomSpaceWODEntity(satelliteId, seqNo, frameNumber,
                        convertHexBytePairToBinary(sb.substring(start, end)), frameTime);
                break;
            case 1:
                wod = new ClydeSpaceWODEntity(satelliteId, seqNo, frameNumber,
                        convertHexBytePairToBinary(sb.substring(start, end)), frameTime);
                break;
            case 2:
                wod = new GomSpaceWODEntity(satelliteId, seqNo, frameNumber,
                        convertHexBytePairToBinary(sb.substring(start, end)), frameTime);
                break;
            default:
                break;
            }

            if (wod != null) {
                wholeOrbitDataDao.save(wod);
            }

            start += 46;
            end += 46;
        }

        // move the frame time forward a minute
        frameTime.setTime(frameTime.getTime() + 60 * 1000);
    }
}

From source file:com.s3d.webapps.util.time.DateUtils.java

/**
 * <p>Internal calculation method.</p>
 * /*from  ww  w. j a v  a2  s  . co m*/
 * @param val  the calendar
 * @param field  the field constant
 * @param modType  type to truncate, round or ceiling
 * @throws ArithmeticException if the year is over 280 million
 */
private static void modify(Calendar val, int field, int modType) {
    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 (MODIFY_TRUNCATE == modType || millisecs < 500) {
        time = time - millisecs;
    }
    if (field == Calendar.SECOND) {
        done = true;
    }

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

    // truncate minutes
    int minutes = val.get(Calendar.MINUTE);
    if (!done && (MODIFY_TRUNCATE == modType || 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 (modType == MODIFY_CEILING || (modType == MODIFY_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);
                        }
                        // ----------------- Fix for LANG-440 ---------------------- START ---------------
                    } else if (field == Calendar.AM_PM) {
                        // This is a special case
                        // If the time is 0, we round up to 12, otherwise
                        //  we subtract 12 hours and add 1 day
                        if (val.get(Calendar.HOUR_OF_DAY) == 0) {
                            val.add(Calendar.HOUR_OF_DAY, 12);
                        } else {
                            val.add(Calendar.HOUR_OF_DAY, -12);
                            val.add(Calendar.DATE, 1);
                        }
                        // ----------------- Fix for LANG-440 ---------------------- END ---------------
                    } 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.agnitas.beans.impl.MailingImpl.java

@Override
public boolean sendEventMailing(int customerID, int delayMinutes, String userStatus,
        Hashtable<String, String> overwrite, ApplicationContext con) {
    boolean exitValue = true;
    Mailgun aMailgun = null;/*from w  w w  . j  av  a  2  s. c om*/
    TimeoutLRUMap mailgunCache = (TimeoutLRUMap) con.getBean("mailgunCache");
    MaildropEntry entry = null;
    int maildropStatusID = 0;
    try {
        aMailgun = (Mailgun) mailgunCache
                .get(Integer.toString(this.companyID) + "_" + Integer.toString(this.id));

        if (aMailgun == null) {
            Iterator<MaildropEntry> it = this.getMaildropStatus().iterator();
            while (it.hasNext()) {
                entry = it.next();
                if (entry.getStatus() == MaildropEntry.STATUS_ACTIONBASED) {
                    maildropStatusID = entry.getId();
                }
            }
            if (maildropStatusID == 0) {
                throw new Exception("maildropStatusID is 0");
            }
            aMailgun = (Mailgun) con.getBean("Mailgun");
            if (aMailgun == null) {
                logger.error("Mailgun could not be created: " + this.id);
            }
            aMailgun.initializeMailgun(Integer.toString(maildropStatusID));
            aMailgun.prepareMailgun(new Hashtable<String, Object>());

            mailgunCache.put(Integer.toString(this.companyID) + "_" + Integer.toString(this.id), aMailgun);
        }

        if (aMailgun != null) {
            Hashtable<String, Object> opts = new Hashtable<String, Object>();
            opts.put("customer-id", Integer.toString(customerID));
            if (overwrite != null) {
                opts.put("overwrite", overwrite);
            }
            java.util.Date aDate = new java.util.Date();
            long millis = aDate.getTime();
            millis += (delayMinutes * 60000);
            aDate.setTime(millis);
            opts.put("send-date", aDate);

            if (userStatus != null) {
                opts.put("user-status", userStatus);
            }
            aMailgun.executeMailgun(opts);
        }

    } catch (Exception e) {
        logger.error("Fire Campaign-Mail", e);

        exitValue = false;
    }

    return exitValue;
}

From source file:org.oscarehr.PMmodule.caisi_integrator.CaisiIntegratorUpdateTask.java

private void findChangedRecordsFromIntegrator(Facility facility) throws MalformedURLException {//throws IOException, ShutdownException {
    logger.info("Start fetch data for facility : " + facility.getId() + " : " + facility.getName());
    boolean integratorLocalStore = OscarProperties.getInstance().getBooleanProperty("INTEGRATOR_LOCAL_STORE",
            "yes");
    if (!integratorLocalStore) {
        logger.info("local store not enabled");
        return;/*from w w w  . j  a  v  a 2s. c o  m*/
    }
    DemographicWs demographicService = CaisiIntegratorManager.getDemographicWs();

    Calendar nextTime = Calendar.getInstance();

    Date lastPushDate = new Date(0);
    try {
        UserProperty lastPull = userPropertyDao
                .getProp(UserProperty.INTEGRATOR_LAST_PULL_PRIMARY_EMR + "+" + facility.getId());
        lastPushDate.setTime(Long.parseLong(lastPull.getValue()));
    } catch (Exception epull) {
        MiscUtils.getLogger().error("lastPull Error:", epull);
        lastPushDate = new Date(0);
    }
    Calendar cal = Calendar.getInstance();
    cal.setTime(lastPushDate);

    List<Integer> demographicNos = demographicService.getDemographicIdPushedAfterDateByRequestingFacility(cal);

    if (demographicNos.isEmpty()) {
        logger.debug("No demographics updated on the integrator");
    } else {
        logger.debug("demos changed " + demographicNos.size());
    }
    int demographicFetchCount = 0;
    for (Integer demographicNo : demographicNos) {
        logger.debug("Demographic " + demographicNo + " updated on the integrator, primary emr ? ");
        DemographicExt demographicExt = demographicExtDao.getLatestDemographicExt(demographicNo, "primaryEMR");
        if (demographicExt != null && demographicExt.getValue().equals("1")) {
            demographicFetchCount++;
            BenchmarkTimer benchTimer = new BenchmarkTimer(
                    "fetch and save for facilityId:" + facility.getId() + ", demographicId:" + demographicNo
                            + "  " + demographicFetchCount + " of " + demographicNos.size());
            IntegratorFallBackManager.saveLinkNotes(demographicNo);
            benchTimer.tag("saveLinkedNotes");
            IntegratorFallBackManager.saveRemoteForms(demographicNo);
            benchTimer.tag("saveRemoteForms");

            IntegratorFallBackManager.saveDemographicIssues(demographicNo);
            benchTimer.tag("saveDemographicIssues");
            IntegratorFallBackManager.saveDemographicPreventions(demographicNo);
            benchTimer.tag("saveDemographicPreventions");
            IntegratorFallBackManager.saveDemographicDrugs(demographicNo);
            benchTimer.tag("saveDemographicDrugs");
            IntegratorFallBackManager.saveAdmissions(demographicNo);
            benchTimer.tag("saveAdmissions");
            IntegratorFallBackManager.saveAppointments(demographicNo);
            benchTimer.tag("saveAppointments");
            IntegratorFallBackManager.saveAllergies(demographicNo);
            benchTimer.tag("saveAllergies");
            IntegratorFallBackManager.saveDocuments(demographicNo);
            benchTimer.tag("saveDocuments");
            IntegratorFallBackManager.saveLabResults(demographicNo);
            benchTimer.tag("saveLabResults");

            //These don't exist
            //IntegratorFallBackManager.saveMeasurements(demographicNo); // Not being displayed yet
            //IntegratorFallBackManager.saveDxresearchs(demographicNo);  //Not being displayed yet
            //IntegratorFallBackManager.saveBillingItems(demographicNo);//Not being displayed yet
            //IntegratorFallBackManager.saveEforms(demographicNo);//Not being displayed yet

            logger.debug(benchTimer.report());
        }
        userPropertyDao.saveProp(UserProperty.INTEGRATOR_LAST_PULL_PRIMARY_EMR + "+" + facility.getId(),
                "" + nextTime.getTime().getTime());
    }
    logger.info("End fetch data for facility : " + facility.getId() + " : " + facility.getName());
}

From source file:io.realm.RealmTest.java

public void testCopyToRealmObject() {
    Date date = new Date();
    date.setTime(1000); // Remove ms. precision as Realm doesn't support it yet.
    Dog dog = new Dog();
    dog.setName("Fido");
    RealmList<Dog> list = new RealmList<Dog>();
    list.add(dog);//from  w  ww . ja  v a  2  s .  co m

    AllTypes allTypes = new AllTypes();
    allTypes.setColumnString("String");
    allTypes.setColumnLong(1l);
    allTypes.setColumnFloat(1f);
    allTypes.setColumnDouble(1d);
    allTypes.setColumnBoolean(true);
    allTypes.setColumnDate(date);
    allTypes.setColumnBinary(new byte[] { 1, 2, 3 });
    allTypes.setColumnRealmObject(dog);
    allTypes.setColumnRealmList(list);

    testRealm.beginTransaction();
    AllTypes realmTypes = testRealm.copyToRealm(allTypes);
    testRealm.commitTransaction();

    assertNotSame(allTypes, realmTypes); // Objects should not be considered equal
    assertEquals(allTypes.getColumnString(), realmTypes.getColumnString()); // But they contain the same data
    assertEquals(allTypes.getColumnLong(), realmTypes.getColumnLong());
    assertEquals(allTypes.getColumnFloat(), realmTypes.getColumnFloat());
    assertEquals(allTypes.getColumnDouble(), realmTypes.getColumnDouble());
    assertEquals(allTypes.isColumnBoolean(), realmTypes.isColumnBoolean());
    assertEquals(allTypes.getColumnDate(), realmTypes.getColumnDate());
    assertArrayEquals(allTypes.getColumnBinary(), realmTypes.getColumnBinary());
    assertEquals(allTypes.getColumnRealmObject().getName(), dog.getName());
    assertEquals(list.size(), realmTypes.getColumnRealmList().size());
    assertEquals(list.get(0).getName(), realmTypes.getColumnRealmList().get(0).getName());
}