Example usage for java.util Calendar setTimeInMillis

List of usage examples for java.util Calendar setTimeInMillis

Introduction

In this page you can find the example usage for java.util Calendar setTimeInMillis.

Prototype

public void setTimeInMillis(long millis) 

Source Link

Document

Sets this Calendar's current time from the given long value.

Usage

From source file:fr.paris.lutece.plugins.workflow.modules.alert.service.daemon.AlertDaemon.java

/**
 * Daemon's treatment method/*from w ww .  j  a  v  a  2s.c o  m*/
 */
public void run() {
    StringBuilder sbLog = new StringBuilder();
    ITaskConfigService configService = SpringContextService.getBean(AlertConstants.BEAN_ALERT_CONFIG_SERVICE);
    IAlertService alertService = SpringContextService.getBean(AlertService.BEAN_SERVICE);

    for (Alert alert : alertService.findAll()) {
        Record record = alertService.getRecord(alert);
        TaskAlertConfig config = configService.findByPrimaryKey(alert.getIdTask());

        Locale locale = I18nService.getDefaultLocale();

        if (record != null && config != null) {
            if (alertService.isRecordStateValid(config, record, locale)) {
                Long lDate = alert.getDateReference().getTime();

                if (lDate != null) {
                    int nNbDaysToDate = config.getNbDaysToDate();

                    Calendar calendar = new GregorianCalendar();
                    calendar.setTimeInMillis(lDate);
                    calendar.add(Calendar.DATE, nNbDaysToDate);

                    Calendar calendarToday = new GregorianCalendar();

                    if (calendar.before(calendarToday)) {
                        sbLog.append("\n-Running alert (ID record : " + record.getIdRecord() + ", ID history : "
                                + alert.getIdResourceHistory() + ", ID task : " + alert.getIdTask() + ")");
                        alertService.doChangeRecordState(config, record.getIdRecord(), alert);
                    }
                }
            }
        } else {
            // If the record is null or the config is null, we remove the alert
            alertService.removeByHistory(alert.getIdResourceHistory(), alert.getIdTask());
        }
    }

    if (StringUtils.isBlank(sbLog.toString())) {
        sbLog.append("\nNo alert to run.");
    }

    setLastRunLogs(sbLog.toString());
}

From source file:io.wcm.dam.assetservice.impl.dataversion.ChecksumDataVersionStrategyTest.java

private void setLastModified(Asset asset, long time) {
    Resource metadata = context.resourceResolver().getResource(asset.getPath() + "/jcr:content");
    ModifiableValueMap props = metadata.adaptTo(ModifiableValueMap.class);
    Calendar lastModified = Calendar.getInstance();
    lastModified.setTimeInMillis(time);
    props.put(JcrConstants.JCR_LASTMODIFIED, lastModified);
    try {/*from   w w w . ja v  a2s  .  c o  m*/
        context.resourceResolver().commit();
    } catch (PersistenceException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.c123.billbuddy.events.ProcessingFeeEventContainer.java

@SpaceDataEvent
public Payment processPayments(Payment payment) {

    log.info("Starting ProcessingFeeTransaction SpaceDataEvent.");

    // Read Merchant Account
    log.info("Read Merchant Id: " + payment.getReceivingMerchantId() + " account.");
    Merchant merchantTemplate = new Merchant();
    merchantTemplate.setMerchantAccountId(payment.getReceivingMerchantId());

    Merchant merchant = gigaSpace.read(merchantTemplate);

    // Read Contract Account
    log.info("Read Contract Id: " + payment.getReceivingMerchantId() + " account.");

    SQLQuery<SpaceDocument> queryContract = new SQLQuery<SpaceDocument>("ContractDocument", "merchantId = ?");
    queryContract.setParameter(1, payment.getReceivingMerchantId());

    SpaceDocument contract = gigaSpace.read(queryContract);

    // Get transactionPrecentFee 
    Double transactionFeeAmount = ((Double) contract.getProperty("transactionPrecentFee"))
            * payment.getPaymentAmount();

    // Withdraw payment amount from merchant account
    updateMerchantBalance(merchant, transactionFeeAmount);

    ProcessingFee processingFee = new ProcessingFee();

    processingFee.setDescription(payment.getDescription());
    processingFee.setDependentPaymentId(payment.getPaymentId());
    processingFee.setPayingAccountId(merchant.getMerchantAccountId());

    processingFee.setAmount(transactionFeeAmount);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    processingFee.setCreatedDate(calendar.getTime());

    processingFee.setStatus(TransactionStatus.PROCESSED);

    // Write the ProcessingFee object
    gigaSpace.write(processingFee);//from  w w  w.  j av  a 2s .  co  m

    // Set payment status
    payment.setStatus(TransactionStatus.PROCESSED);

    return payment;
}

From source file:com.github.dozermapper.core.converters.DateConverter.java

public Object convert(Class destClass, Object srcObj) {
    final Class srcFieldClass = srcObj.getClass();

    long time;//from w  w w  . j  a v a 2s. co m
    int nanos = 0;
    if (Calendar.class.isAssignableFrom(srcFieldClass)) {
        Calendar inVal = (Calendar) srcObj;
        time = inVal.getTime().getTime();
    } else if (Timestamp.class.isAssignableFrom(srcFieldClass)) {
        Timestamp timestamp = (Timestamp) srcObj;
        time = timestamp.getTime();
        nanos = timestamp.getNanos();
    } else if (java.util.Date.class.isAssignableFrom(srcFieldClass)) {
        time = ((java.util.Date) srcObj).getTime();
    } else if (XMLGregorianCalendar.class.isAssignableFrom(srcFieldClass)) {
        time = ((XMLGregorianCalendar) srcObj).toGregorianCalendar().getTimeInMillis();
    } else if (dateFormat != null && String.class.isAssignableFrom(srcObj.getClass())) {
        try {
            if ("".equals(srcObj)) {
                return null;
            }
            time = dateFormat.parse((String) srcObj).getTime();
        } catch (ParseException e) {
            throw new ConversionException("Unable to parse source object using specified date format", e);
        }
        // Default conversion
    } else {
        try {
            time = Long.parseLong(srcObj.toString());
        } catch (NumberFormatException e) {
            throw new ConversionException("Unable to determine time in millis of source object", e);
        }
    }

    try {
        if (Calendar.class.isAssignableFrom(destClass)) {
            Constructor constructor = destClass.getConstructor();
            Calendar result = (Calendar) constructor.newInstance();
            result.setTimeInMillis(time);
            return result;
        }

        if (dateFormat != null && String.class.isAssignableFrom(destClass)) {
            return dateFormat.format(new java.util.Date(time));
        }

        Constructor constructor = destClass.getConstructor(Long.TYPE);
        Object result = constructor.newInstance(time);
        if (nanos != 0 && (Timestamp.class.isAssignableFrom(destClass))) {
            ((Timestamp) result).setNanos(nanos);
        }
        return result;
    } catch (Exception e) {
        throw new ConversionException(e);
    }
}

From source file:com.rsltc.profiledata.main.MainActivity.java

private static void processSpeedSumary(DataSet dataSet, InfoType type, SpeedSummary summary,
        String currentType) {//from   w  w  w  . j a  v a  2s. c  om
    Calendar calendar = Calendar.getInstance();
    for (DataPoint dp : dataSet.getDataPoints()) {
        Float min = null, max = null, avg = null;
        Log.i(TAG, "Data point:");
        Log.i(TAG, "\tType: " + dp.getDataType().getName());
        Long startTime = dp.getStartTime(TimeUnit.MILLISECONDS);
        calendar.setTimeInMillis(startTime);
        Log.i(TAG, "\tStart: " + calendar.getTime());
        Long stopTime = dp.getEndTime(TimeUnit.MILLISECONDS);
        calendar.setTimeInMillis(stopTime);
        Log.i(TAG, "\tStop: " + calendar.getTime());

        Long duration = stopTime - startTime;
        Log.i(TAG, "Timezone: " + calendar.getTimeZone().getDisplayName());
        for (Field field : dp.getDataType().getFields()) {
            Log.i(TAG, "\tField: " + field.getName() + " Value: " + dp.getValue(field));
            if (field.equals(Field.FIELD_AVERAGE)) {
                avg = dp.getValue(field).asFloat();
            } else if (field.equals(Field.FIELD_MIN)) {
                min = dp.getValue(field).asFloat();
            } else if (field.equals(Field.FIELD_MAX)) {
                max = dp.getValue(field).asFloat();
            } else {
                Log.e(TAG, "Unsupported field found");
            }
        }
        boolean valid = false;
        if (min != null && max != null && avg != null) {
            // TODO: build check for speeds
            if (!(valid = HealthStatValidityChecker.checkAvgSpeed(avg, currentType))) {
                avg = (max + min) / 2;
                valid = HealthStatValidityChecker.checkAvgSpeed(avg, currentType);
            }
        }
        if (valid) {
            summary.setMaxSpeedIfGreater(max);
            summary.setMinSpeedIfSmaller(min);
            summary.setMaxDurationIfLonger(duration);
            summary.setMinDurationIfShorter(duration);
            double count = summary.getCount();
            summary.setAvgSpeed((summary.getAvgSpeed() * count + avg) / (count + 1));
            summary.setAvgDuration((float) ((summary.getAvgDuration() * count + duration) / (count + 1)));
            summary.increaseCount();
        }

    }
}

From source file:me.lehrner.newsgroupsndy.presenter.tasks.UpdateGroupListAsyncTask.java

@Override
protected Boolean doInBackground(Server... servers) {
    mServerId = servers[0].getId();/*w  w w .  jav a  2 s .c o m*/

    String hostName = servers[0].getServerUrl();
    int lastVisitInt = servers[0].getLastVisit();

    NewsgroupInfo[] newsgroupInfos;
    ArrayList<String> groupNames = new ArrayList<>();

    try {
        NNTPClient nntpClient = new NNTPClient();
        nntpClient.connect(hostName, 119);

        Log.d(LOG_TAG, "lastVisitInt: " + lastVisitInt);

        if (lastVisitInt != 0) {
            Calendar lastVisit = Calendar.getInstance();
            lastVisit.setTimeInMillis(lastVisitInt * 1000L);

            NewGroupsOrNewsQuery query = new NewGroupsOrNewsQuery(lastVisit, false);
            newsgroupInfos = nntpClient.listNewNewsgroups(query);

            Log.d(LOG_TAG, "listNewNewsgroups");

        } else {
            newsgroupInfos = nntpClient.listNewsgroups();

            Log.d(LOG_TAG, "listNewsgroups");

        }

        nntpClient.disconnect();
    } catch (IOException e) {
        Log.d(LOG_TAG, "IOException");

        GroupPresenter groupPresenter = mGroupPresenterWeakReference.get();

        if (groupPresenter != null) {
            groupPresenter.updateNotSuccessful();
        }
        return false;
    }

    if (newsgroupInfos == null) {
        Log.d(LOG_TAG, "newsgroupInfos is null");
        return false;
    }

    for (NewsgroupInfo newsgroupInfo : newsgroupInfos) {
        groupNames.add(newsgroupInfo.getNewsgroup());
    }

    return mGroupRepository.saveGroups(mServerId, groupNames);
}

From source file:com.taobao.itest.util.DateConverter.java

/**
 * get GMT Time//from   ww  w.j a  va2s .c om
 * 
 * @param calendar
 * @return
 */
public Date getGmtDate(Long time) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(time);
    int offset = calendar.get(Calendar.ZONE_OFFSET) / 3600000 + calendar.get(Calendar.DST_OFFSET) / 3600000;
    calendar.add(Calendar.HOUR, -offset);
    Date date = calendar.getTime();

    return date;
}

From source file:com.alibaba.otter.shared.common.utils.cache.RefreshMemoryMirror.java

/**
 * ?/*from ww  w  . j a va  2 s. c  o m*/
 * 
 * @param refreshObject
 * @return
 */
private boolean isExpired(RefreshObject refreshObject) {
    if (refreshObject == null) {
        return false;
    }

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(refreshObject.getTimestamp());
    // calendar.add(Calendar.SECOND, period.intValue());
    calendar.add(Calendar.MILLISECOND, period.intValue());

    Date now = new Date();
    return now.after(calendar.getTime());
}

From source file:com.wso2.mobile.mdm.api.TrackCallSMS.java

/**
 * Returns a JSONArray of SMS objects Ex: [{number:"0772345666", date:"dd/MM/yyyy hh:mm:ss.SSS", content:"Hello"}]
 * // www  . jav  a 2 s .  com
 * @param type
 *            - Folder type should be passed in (1 for Inbox, 2 for Sent box)
 */
public JSONArray getSMS(int type) {
    JSONArray jsonArray = null;
    try {
        Uri uriSms = Uri.parse("content://sms");

        Cursor cursor = cr.query(uriSms, new String[] { "_id", "address", "date", "body", "type", "read" },
                "type=" + type, null, "date" + " COLLATE LOCALIZED ASC");

        if (cursor != null) {
            cursor.moveToLast();
            if (cursor.getCount() > 0) {
                jsonArray = new JSONArray();
                do {
                    JSONObject jsonObj = new JSONObject();
                    String date = cursor.getString(cursor.getColumnIndex("date"));
                    Long timestamp = Long.parseLong(date);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(timestamp);
                    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
                    jsonObj.put("number", cursor.getString(cursor.getColumnIndex("address")));
                    jsonObj.put("date", formatter.format(calendar.getTime()));
                    /*jsonObj.put("content",
                          cursor.getString(cursor.getColumnIndex("body")));*/
                    //jsonObj.put("content","Testing SMS");
                    jsonArray.add(jsonObj);
                } while (cursor.moveToPrevious());
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return jsonArray;

}

From source file:org.n52.server.io.DiagramGenerator.java

/**
 * Creates a time series chart diagram and writes it to the OutputStream.
 *//*w  w  w.j  av  a2  s  . co m*/
public void producePresentation(Map<String, OXFFeatureCollection> entireCollMap, DesignOptions options,
        FileOutputStream out, boolean compress) throws OXFException, IOException {

    // render features:
    int width = options.getWidth();
    int height = options.getHeight();
    Calendar begin = Calendar.getInstance();
    begin.setTimeInMillis(options.getBegin());
    Calendar end = Calendar.getInstance();
    end.setTimeInMillis(options.getEnd());

    DiagramRenderer renderer = new DiagramRenderer(false);

    JFreeChart diagramChart = renderer.renderChart(entireCollMap, options, begin, end, compress);
    diagramChart.removeLegend();

    // draw chart into image:
    BufferedImage diagramImage = new BufferedImage(width, height, TYPE_INT_RGB);
    Graphics2D chartGraphics = diagramImage.createGraphics();
    chartGraphics.setColor(Color.white);
    chartGraphics.fillRect(0, 0, width, height);

    diagramChart.draw(chartGraphics, new Rectangle2D.Float(0, 0, width, height));

    JPEGImageWriteParam p = new JPEGImageWriteParam(null);
    p.setCompressionMode(JPEGImageWriteParam.MODE_DEFAULT);
    write(diagramImage, FORMAT, out);
}