Example usage for java.util GregorianCalendar getTime

List of usage examples for java.util GregorianCalendar getTime

Introduction

In this page you can find the example usage for java.util GregorianCalendar getTime.

Prototype

public final Date getTime() 

Source Link

Document

Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").

Usage

From source file:edu.uga.cs.fluxbuster.features.FeatureCalculator.java

/**
 * Gets run dates previous to a specific date within a window
 * of days from that date./*from   w  w  w. j  av  a  2  s .  co m*/
 *
 * @param log_date the run date
 * @param window the number of days previous to the current date
 * @return the list of previous run dates
 * @throws SQLException if there is an error retrieving the previous
 *       run dates
 */
public ArrayList<Date> getPrevDates(Date log_date, int window) throws SQLException {
    ArrayList<Date> prevDates = new ArrayList<Date>();
    if (prevDateBufDate != null && prevDateBuf != null && prevDateBufDate.equals(log_date)
            && prevDateBufWindow >= window) {

        //pull the dates within the day window from the prevDateBuf cache
        Date pd = null;
        int windowcount = 0;
        for (Date d : prevDateBuf) {
            if (windowcount >= window) {
                break;
            }
            if (pd == null) {
                pd = d;
                windowcount++;
            } else {
                DateTime morerecent = new DateTime(d.getTime());
                DateTime lessrecent = new DateTime(pd.getTime());
                Days days = Days.daysBetween(morerecent, lessrecent);
                windowcount += days.getDays();
                pd = d;
            }
            prevDates.add(d);
        }

    } else {
        String domainsprefix = properties.getProperty(DOMAINSPREFIXKEY);
        String resipsprefix = properties.getProperty(RESIPSPREFIXKEY);

        ArrayList<String> tablenames = new ArrayList<String>();
        ResultSet rs1 = null;
        try {
            rs1 = dbi.executeQueryWithResult(properties.getProperty(TABLES_QUERY1KEY));
            while (rs1.next()) {
                tablenames.add(rs1.getString(1));
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error(e);
            }
        } finally {
            if (rs1 != null && !rs1.isClosed()) {
                rs1.close();
            }
        }

        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(log_date);
        for (int i = 0; i < window; i++) {
            cal.roll(Calendar.DAY_OF_YEAR, false);
            Date temp = cal.getTime();
            String datestr = df.format(temp);
            if (tablenames.contains(domainsprefix + "_" + datestr)
                    && tablenames.contains(resipsprefix + "_" + datestr)) {
                prevDates.add(temp);
            }
        }

        //cache the values for later
        if (prevDateBuf == null) {
            prevDateBuf = new ArrayList<Date>();
        } else {
            prevDateBuf.clear();
        }
        prevDateBuf.addAll(prevDates);
        prevDateBufDate = log_date;
        prevDateBufWindow = window;
    }
    return prevDates;
}

From source file:org.eurekastreams.server.persistence.TabGroupMapper.java

/**
 * Mark the input tab as deleted so that it's no longer returned in queries
 * but can be undeleted later on. The tab would have just been removed from
 * the TabGroup, so we need to set the tabGroupId back to the Tab, and the
 * tabIndex=null so that it's ignored by the collection.
 *
 * Conditionally mark the tab template as deleted, if this tab is the last
 * one so you can undelete the tab template with it
 *
 * @param tabGroup/*from  w  ww  .  j  av a2  s  .c  om*/
 *            The tab group that contains tab.
 * @param tab
 *            The tab to mark as deleted.
 */
private void markTabAsDeleted(final TabGroup tabGroup, final Tab tab) {
    GregorianCalendar currentDateTime = new GregorianCalendar();

    long count = getTabCountForTemplate(tab.getTemplate());

    // if you only have one tab left, mark the template and its gadgets
    // deleted too so you can undelete them
    if (count == 1) {
        getEntityManager()
                .createQuery("update versioned Gadget set deleted = true, " + "dateDeleted = :deletedTimestamp "
                        + "where template.id = :tabTemplateId")
                .setParameter("deletedTimestamp", currentDateTime.getTime())
                .setParameter("tabTemplateId", tab.getTemplate().getId()).executeUpdate();

        getEntityManager()
                .createQuery("update versioned TabTemplate set deleted = true, "
                        + "dateDeleted = :deletedTimestamp " + "where id = :tabTemplateId")
                .setParameter("deletedTimestamp", currentDateTime.getTime())
                .setParameter("tabTemplateId", tab.getTemplate().getId()).executeUpdate();
    }

    // still mark the tab deleted
    getEntityManager()
            .createQuery("update versioned Tab set deleted = true, " + "dateDeleted = :deletedTimestamp, "
                    + "tabIndex = :tabIndex, " + "tabGroupId = :tabGroupId " + "where id = :tabId")
            .setParameter("deletedTimestamp", currentDateTime.getTime()).setParameter("tabId", tab.getId())
            .setParameter("tabGroupId", tabGroup.getId()).setParameter("tabIndex", tab.getTabIndex())
            .executeUpdate();

}

From source file:com.mothsoft.alexis.engine.numeric.TopicActivityDataSetImporter.java

@Override
public void importData() {
    if (this.transactionTemplate == null) {
        this.transactionTemplate = new TransactionTemplate(this.transactionManager);
    }//from  www  .j  av a  2 s .c  om

    final List<Long> userIds = listUserIds();

    final GregorianCalendar calendar = new GregorianCalendar();
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    int minute = calendar.get(Calendar.MINUTE);

    if (minute >= 45) {
        calendar.set(Calendar.MINUTE, 30);
    } else if (minute >= 30) {
        calendar.set(Calendar.MINUTE, 15);
    } else if (minute >= 15) {
        calendar.set(Calendar.MINUTE, 0);
    } else if (minute >= 0) {
        calendar.set(Calendar.MINUTE, 45);
        calendar.add(Calendar.HOUR_OF_DAY, -1);
    }

    final Date startDate = calendar.getTime();

    calendar.add(Calendar.MINUTE, 15);
    calendar.add(Calendar.MILLISECOND, -1);
    final Date endDate = calendar.getTime();

    for (final Long userId : userIds) {
        importTopicDataForUser(userId, startDate, endDate);
    }
}

From source file:com.ephesoft.dcma.workflows.service.engine.impl.EngineServiceImpl.java

@Override
@Transactional//from ww  w . j  av  a 2  s  .  c o  m
public JobEntity lockJob(final CommandContext commandContext, final JobEntity job, String lockOwner,
        final int lockTimeInMillis) {
    JobEntity modifiedJobEntity;

    // Providing check again before locking a job and using activiti command listener class for reset retry count for job.
    if (EphesoftStringUtil.isNullOrEmpty(job.getLockOwner())) {
        String jobId = job.getId();
        resetJobRetries(jobId, WorkflowConstants.MAX_NUMBER_OF_JOB_RETRIES);
        modifiedJobEntity = commandContext.getJobEntityManager().findJobById(jobId);
        GregorianCalendar gregorianCalendar = new GregorianCalendar();
        Date currentTime = getCurrentTime(commandContext);
        gregorianCalendar.setTime(currentTime);
        gregorianCalendar.add(Calendar.MILLISECOND, lockTimeInMillis);
        Date date = gregorianCalendar.getTime();
        LOGGER.info("Trying to obtain a lock for job with id: ", jobId, " with expiration time: ",
                timeFormat.format(date), " by lock owner: ", lockOwner);
        modifiedJobEntity.setLockOwner(lockOwner);
        modifiedJobEntity.setLockExpirationTime(date);
    } else {
        modifiedJobEntity = null;
    }
    return modifiedJobEntity;
}

From source file:org.mule.modules.zuora.zuora.api.CxfZuoraClient.java

@Override
public Map<String, Object> accountProfile(String accountId) throws Exception {
    // TODO Auto-generated method stub

    HashMap<String, Object> accountMap = new HashMap<String, Object>();
    Validate.notEmpty(accountId);//from w  w w  .  ja  va 2s.  c o m

    String accountQuery = "select AccountNumber,AdditionalEmailAddresses,AllowInvoiceEdit,AutoPay,Balance,Batch,BillCycleDay,BillToId,CommunicationProfileId,CreatedById,CreatedDate,CreditBalance,CrmId,Currency,CustomerServiceRepName,DefaultPaymentMethodId,InvoiceDeliveryPrefsEmail,InvoiceDeliveryPrefsPrint,InvoiceTemplateId,LastInvoiceDate,Name,Notes,ParentId,PaymentGateway,PaymentTerm,PurchaseOrderNumber,SalesRepName,SoldToId,Status,TaxExemptCertificateId,TaxExemptCertificateType,TaxExemptDescription,TaxExemptEffectiveDate,TaxExemptExpirationDate,TaxExemptIssuingJurisdiction,TaxExemptStatus,TotalInvoiceBalance,UpdatedById,UpdatedDate  from Account where id = '"
            + accountId + "'";

    QueryResult qr = this.soap.query(accountQuery);

    if (qr.getSize() != 0) {

        Collection<Entry<String, Object>> accountCollection = qr.getRecords().get(0).properties();

        accountMap = getAsHashMap(accountCollection);
        if (accountMap.get("defaultPaymentMethodId") != null) {
            String paymentMethodQuery = "SELECT AchAbaCode,AchAccountName,AchAccountNumberMask,AchAccountType,AchBankName,Active,BankBranchCode,BankCheckDigit,BankCity,BankCode,BankIdentificationNumber,BankName,BankPostalCode,BankStreetName,BankStreetNumber,BankTransferAccountName,BankTransferAccountType,BankTransferType,CreatedById,CreatedDate,CreditCardAddress1,CreditCardAddress2,CreditCardCity,CreditCardCountry,Id, CreditCardExpirationMonth, CreditCardExpirationYear, CreditCardMaskNumber,CreditCardHolderName,CreditCardPostalCode,CreditCardState,CreditCardType,DeviceSessionId,Email,IPAddress,LastFailedSaleTransactionDate,LastTransactionDateTime,LastTransactionStatus,MaxConsecutivePaymentFailures,Name,NumConsecutiveFailures,PaymentMethodStatus,PaymentRetryWindow,PaypalBaid,PaypalEmail,PaypalPreapprovalKey,PaypalType,Phone,TotalNumberOfErrorPayments,TotalNumberOfProcessedPayments,Type,UpdatedById,UpdatedDate,UseDefaultRetryRule from PaymentMethod where Id = '"
                    + accountMap.get("defaultPaymentMethodId") + "'";

            Collection<Entry<String, Object>> paymentMethodCollection = this.soap.query(paymentMethodQuery)
                    .getRecords().get(0).properties();

            if (paymentMethodCollection.size() > 0) {
                accountMap.put("paymentMethod", getAsHashMap(paymentMethodCollection));
            }
        }
        GregorianCalendar lastMonth = new GregorianCalendar();
        lastMonth.add(GregorianCalendar.MONTH, -1);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        String lastMonthString = df.format(lastMonth.getTime());

        String paymentQuery = "SELECT AccountingCode,Amount,AppliedCreditBalanceAmount,AuthTransactionId,BankIdentificationNumber,CancelledOn,Comment,CreatedById,CreatedDate,EffectiveDate,GatewayOrderId,GatewayResponse,GatewayResponseCode,GatewayState,MarkedForSubmissionOn,PaymentMethodID,PaymentNumber,ReferenceId,RefundAmount,SecondPaymentReferenceId,SettledOn,SoftDescriptor, SoftDescriptorPhone, Status, SubmittedOn,TransferredToAccounting,Type,UpdatedById,UpdatedDate from Payment where Id = '"
                + accountId + "' and EffectiveDate >= '" + lastMonthString + "'";

        List<ZObject> paymentZList = this.soap.query(paymentQuery).getRecords();

        List<Map<String, Object>> paymentResultList = new ArrayList<Map<String, Object>>();
        for (ZObject zPayment : paymentZList) {
            if (zPayment != null) {
                Collection<Entry<String, Object>> paymentCollection = zPayment.properties();
                paymentResultList.add(getAsHashMap(paymentCollection));
            }
        }

        if (paymentResultList.size() > 0) {
            accountMap.put("payments", paymentResultList);
        }
        String billToQuery = "select AccountId, Address1, Address2, City, Country, County, CreatedById, CreatedDate, Description, Fax, FirstName, HomePhone, LastName, MobilePhone, NickName, OtherPhone, OtherPhoneType, PersonalEmail, PostalCode, State, TaxRegion, UpdatedById, UpdatedDate, WorkEmail, WorkPhone from contact where id='"
                + accountMap.get("billToId") + "'";
        QueryResult qrBillTo = this.soap.query(billToQuery);
        if (qrBillTo.getSize() > 0) {
            Collection<Entry<String, Object>> billToCollection = qrBillTo.getRecords().get(0).properties();
            HashMap<String, Object> billToMap = new HashMap<String, Object>();
            billToMap = getAsHashMap(billToCollection);
            if (billToMap.size() > 0) {
                accountMap.put("billTo", billToMap);
            }
        }

        String subscriptionQuery = "SELECT AutoRenew,CancelledDate,ContractAcceptanceDate,ContractEffectiveDate,CreatedById,CreatedDate,CreatorAccountId,InitialTerm,IsInvoiceSeparate,Name,Notes,OriginalCreatedDate,OriginalId,PreviousSubscriptionId,RenewalTerm,ServiceActivationDate,Status,SubscriptionEndDate,SubscriptionStartDate,TermEndDate,TermStartDate,TermType,UpdatedById,UpdatedDate,Version from Subscription where AccountId = '"
                + accountId + "' and status='Active'";

        List<ZObject> subscriptionZList = this.soap.query(subscriptionQuery).getRecords();

        List<Map<String, Object>> subscriptionResultList = new ArrayList<Map<String, Object>>();
        for (ZObject zSubscription : subscriptionZList) {
            if (zSubscription != null) {
                Collection<Entry<String, Object>> subscriptionCollection = zSubscription.properties();

                Map<String, Object> subscriptionMap = getAsHashMap(subscriptionCollection);

                String rateplanQuery = "SELECT AmendmentId,AmendmentSubscriptionRatePlanId,AmendmentType,CreatedById,CreatedDate,Name,ProductRatePlanId,UpdatedById,UpdatedDate from RatePlan where SubscriptionId ='"
                        + subscriptionMap.get("id") + "'";

                List<ZObject> ratePlanZList = this.soap.query(rateplanQuery).getRecords();

                List<Map<String, Object>> ratePlanResultList = new ArrayList<Map<String, Object>>();
                for (ZObject zRatePlan : ratePlanZList) {
                    if (zRatePlan != null) {
                        Collection<Entry<String, Object>> ratePlanCollection = zRatePlan.properties();

                        Map<String, Object> ratePlanMap = getAsHashMap(ratePlanCollection);
                        List<Map<String, Object>> ratePlanChargeResultList = new ArrayList<Map<String, Object>>();
                        String rateplanchargeQuery = "SELECT AccountingCode,ApplyDiscountTo,BillCycleDay,BillCycleType,BillingPeriodAlignment,ChargedThroughDate,ChargeModel,ChargeNumber,ChargeType,CreatedById,CreatedDate,Description,DiscountLevel,DMRC,DTCV,EffectiveEndDate,EffectiveStartDate,IsLastSegment,MRR,Name,NumberOfPeriods,OriginalId,OverageCalculationOption,OverageUnusedUnitsCreditOption,Price,ProcessedThroughDate,ProductRatePlanChargeId,Quantity,Segment,TCV,TriggerDate,TriggerEvent,UnusedUnitsCreditRates,UOM,UpdatedById,UpdatedDate,UpToPeriods,Version from RatePlanCharge where RatePlanId ='"
                                + ratePlanMap.get("id") + "'";
                        List<ZObject> ratePlanChargeZList = this.soap.query(rateplanchargeQuery).getRecords();
                        for (ZObject zRatePlanCharge : ratePlanChargeZList) {
                            if (zRatePlanCharge != null) {
                                Collection<Entry<String, Object>> ratePlanChargeCollection = zRatePlanCharge
                                        .properties();
                                ratePlanChargeResultList.add(getAsHashMap(ratePlanChargeCollection));

                            }
                        }
                        ratePlanMap.put("ratePlanCharges", ratePlanChargeResultList);
                        ratePlanResultList.add(ratePlanMap);
                    }
                }
                subscriptionMap.put("ratePlans", ratePlanResultList);

                subscriptionResultList.add(subscriptionMap);
            }
        }

        if (subscriptionResultList.size() > 0) {
            accountMap.put("subscriptions", subscriptionResultList);
        }

    } else {
        accountMap.put("error", "Unable to find an account with the id: " + accountId);
    }

    return accountMap;
}

From source file:org.flowable.job.service.impl.asyncexecutor.DefaultJobManager.java

protected void internalCreateLockedAsyncJob(JobEntity jobEntity, boolean exclusive) {
    fillDefaultAsyncJobInfo(jobEntity, exclusive);

    GregorianCalendar gregorianCalendar = new GregorianCalendar();
    gregorianCalendar.setTime(jobServiceConfiguration.getClock().getCurrentTime());
    gregorianCalendar.add(Calendar.MILLISECOND, getAsyncExecutor().getAsyncJobLockTimeInMillis());
    jobEntity.setLockExpirationTime(gregorianCalendar.getTime());
    jobEntity.setLockOwner(getAsyncExecutor().getLockOwner());
}

From source file:org.oscarehr.web.Cds4ReportUIBean.java

private static HashMap<Integer, Admission> getAdmissionMap(String functionalCentreId,
        GregorianCalendar startDate, GregorianCalendar endDate) {

    // put admissions into map so it's easier to retrieve by id.
    HashMap<Integer, Admission> admissionMap = new HashMap<Integer, Admission>();

    LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get();
    List<Program> programs = programDao.getProgramsByFacilityIdAndFunctionalCentreId(
            loggedInInfo.currentFacility.getId(), functionalCentreId);

    for (Program program : programs) {
        List<Admission> admissions = admissionDao.getAdmissionsByProgramAndDate(program.getId(),
                startDate.getTime(), endDate.getTime());

        logger.debug("corresponding cds admissions count:" + admissions.size());

        for (Admission admission : admissions) {
            admissionMap.put(admission.getId().intValue(), admission);
            logger.debug("valid cds admission, id=" + admission.getId());
        }/*from ww  w  .ja  v  a  2 s  .  co  m*/
    }

    return admissionMap;
}

From source file:org.flowable.job.service.impl.asyncexecutor.DefaultJobManager.java

protected JobEntity createExecutableJobFromOtherJob(AbstractRuntimeJobEntity job) {
    JobEntity executableJob = jobServiceConfiguration.getJobEntityManager().create();
    copyJobInfo(executableJob, job);// www.  java  2  s  .c om

    if (isAsyncExecutorActive()) {
        GregorianCalendar gregorianCalendar = new GregorianCalendar();
        gregorianCalendar.setTime(jobServiceConfiguration.getClock().getCurrentTime());
        gregorianCalendar.add(Calendar.MILLISECOND, getAsyncExecutor().getTimerLockTimeInMillis());
        executableJob.setLockExpirationTime(gregorianCalendar.getTime());
        executableJob.setLockOwner(getAsyncExecutor().getLockOwner());
    }

    return executableJob;
}

From source file:org.mariotaku.twidere.api.twitter.util.TwitterDateConverter.java

private Date parseTwitterDate(String string) {
    final String[] segs = StringUtils.split(string, ' ');
    if (segs.length != 6) {
        return null;
    }/*  ww w.j  ava2  s .c o  m*/
    final String[] timeSegs = StringUtils.split(segs[3], ':');
    if (timeSegs.length != 3) {
        return null;
    }

    final GregorianCalendar calendar = new GregorianCalendar(TIME_ZONE, LOCALE);
    calendar.clear();
    final int monthIdx = ArrayUtils.indexOf(MONTH_NAMES, segs[1]);
    if (monthIdx < 0) {
        return null;
    }
    calendar.set(Calendar.YEAR, Integer.parseInt(segs[5]));
    calendar.set(Calendar.MONTH, monthIdx);
    calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(segs[2]));
    calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeSegs[0]));
    calendar.set(Calendar.MINUTE, Integer.parseInt(timeSegs[1]));
    calendar.set(Calendar.SECOND, Integer.parseInt(timeSegs[2]));
    calendar.set(Calendar.ZONE_OFFSET, SimpleTimeZone.getTimeZone("GMT" + segs[4]).getRawOffset());
    final Date date = calendar.getTime();
    if (!WEEK_NAMES[calendar.get(Calendar.DAY_OF_WEEK) - 1].equals(segs[0])) {
        AbsLogger.error("Week mismatch " + string + " => " + date);
        return null;
    }
    return date;
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.operations.FetchActivityOperation.java

private boolean needsAnotherFetch(GregorianCalendar lastSyncTimestamp) {
    if (fetchCount > 5) {
        LOG.warn("Already jave 5 fetch rounds, not doing another one.");
        return false;
    }//w w w.j av  a2 s  .  c om

    if (DateUtils.isToday(lastSyncTimestamp.getTimeInMillis())) {
        LOG.info("Hopefully no further fetch needed, last synced timestamp is from today.");
        return false;
    }
    if (lastSyncTimestamp.getTimeInMillis() > System.currentTimeMillis()) {
        LOG.warn("Not doing another fetch since last synced timestamp is in the future: "
                + DateTimeUtils.formatDateTime(lastSyncTimestamp.getTime()));
        return false;
    }
    LOG.info("Doing another fetch since last sync timestamp is still too old: "
            + DateTimeUtils.formatDateTime(lastSyncTimestamp.getTime()));
    return true;
}