Example usage for java.util GregorianCalendar add

List of usage examples for java.util GregorianCalendar add

Introduction

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

Prototype

@Override
public void add(int field, int amount) 

Source Link

Document

Adds the specified (signed) amount of time to the given calendar field, based on the calendar's rules.

Usage

From source file:org.squale.squalecommon.daolayer.component.AuditDAOImpl.java

/**
 * Dcale l'audit de rotation des partitions  la prochaine date prvue Le dlai prvu entre 2 rotations est de 12
 * semaines//from ww w . j  a v a2s .c  o m
 * 
 * @param pSession la session
 * @throws JrafDaoException en cas d'chec
 */
public void reportRotationAudit(ISession pSession) throws JrafDaoException {
    // Rcupre l'audit de rotation
    Collection result = findRotationAudit(pSession);
    if (result != null && result.size() != 0) {
        // il ne doit y avoir qu'un seul lment
        Iterator it = result.iterator();
        AuditBO rotationAudit = (AuditBO) it.next();
        Date currentDate = rotationAudit.getDate();
        // ajout le dlai prvu
        GregorianCalendar currentCal = new GregorianCalendar();
        currentCal.setTime(currentDate);
        currentCal.add(Calendar.WEEK_OF_YEAR, ROTATION_DELAY_IN_WEEKS);
        rotationAudit.setDate(currentCal.getTime());
        // et mise  jour en base
        save(pSession, rotationAudit);
    }
}

From source file:org.accada.epcis.repository.query.QuerySubscription.java

/**
 * Runs the query assigned to this subscription. Advances lastTimeExecuted.
 *//*from  w w  w.j a va  2  s  .co m*/
public void executeQuery() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("--------------------------------------------");
        LOG.debug("Executing subscribed query '" + subscriptionID + "' with " + queryParams.getParam().size()
                + " parameters:");
        for (QueryParam p : queryParams.getParam()) {
            LOG.debug(" param name:  " + p.getName());
            Object val = p.getValue();
            if (val instanceof GregorianCalendar) {
                LOG.debug(" param value: " + ((GregorianCalendar) val).getTime());
            } else {
                LOG.debug(" param value: " + val);
            }
        }
    }

    // poll the query
    Poll poll = new Poll();
    poll.setQueryName(queryName);
    poll.setParams(queryParams);
    QueryResults result = null;
    try {
        // get current time and send the query
        GregorianCalendar cal = new GregorianCalendar();
        result = executePoll(poll);
        LOG.debug("Subscribed query '" + subscriptionID + "' has been executed");

        // set new lastTimeExecuted (must be <= to time when query is
        // executed, otherwise we loose results)
        int offset = TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings();
        cal.add(Calendar.MILLISECOND, offset);
        cal.add(Calendar.SECOND, 1);
        this.lastTimeExecuted = cal;
    } catch (QueryTooLargeExceptionResponse e) {
        // send exception back to client
        QueryTooLargeException qtle = e.getFaultInfo();
        if (qtle == null) {
            qtle = new QueryTooLargeException();
            qtle.setQueryName(queryName);
            qtle.setSubscriptionID(subscriptionID);
            qtle.setReason(e.getMessage());
            LOG.info("USER ERROR: " + qtle.getReason());
        }
        callbackQueryTooLargeException(qtle);
        return;
    } catch (ImplementationExceptionResponse e) {
        // send exception back to client
        ImplementationException ie = e.getFaultInfo();
        if (ie == null) {
            ie = new ImplementationException();
            ie.setQueryName(queryName);
            ie.setReason(e.getMessage());
            ie.setSubscriptionID(subscriptionID);
            LOG.info("USER ERROR: " + ie.getReason());
        }
        callbackImplementationException(ie);
        return;
    } catch (Exception e) {
        String msg = "An unexpected error occurred while executing a subscribed query";
        LOG.error(msg + ": " + e.getMessage(), e);
        // send exception back to client
        ImplementationException ie = new ImplementationException();
        ie.setQueryName(queryName);
        ie.setReason(msg);
        ie.setSubscriptionID(subscriptionID);
        callbackImplementationException(ie);
        return;
    }
    result.setSubscriptionID(subscriptionID);
    EventListType eventList = result.getResultsBody().getEventList();

    // check if we have an empty result list
    boolean isEmpty = false;
    isEmpty = (eventList == null) ? true
            : eventList.getObjectEventOrAggregationEventOrQuantityEvent().isEmpty();
    if (!reportIfEmpty.booleanValue() && isEmpty) {
        LOG.debug("Subscribed query '" + subscriptionID + "' returned no results, nothing to report.");
        return;
    }

    callbackResults(result);

    // update query params with new lastTimeExecuted
    updateRecordTime(queryParams, lastTimeExecuted);
}

From source file:org.apache.juddi.api.impl.UDDISubscriptionImpl.java

/**
 * Will add the expiration date to the provided subscription request.  Date is earlier of user provided date and the system default
 * //from   ww w .  j ava 2  s  .  c om
 * @param apiSubscription
 * @throws DispositionReportFaultMessage
 */
private void doSubscriptionExpirationDate(org.uddi.sub_v3.Subscription apiSubscription)
        throws DispositionReportFaultMessage {

    int subscriptionExpirationDays = DEFAULT_SUBSCRIPTIONEXPIRATION_DAYS;
    try {
        subscriptionExpirationDays = AppConfig.getConfiguration()
                .getInt(Property.JUDDI_SUBSCRIPTION_EXPIRATION_DAYS);
    } catch (ConfigurationException ce) {
        throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval"));
    }

    GregorianCalendar expirationDate = new GregorianCalendar();
    expirationDate.add(GregorianCalendar.DAY_OF_MONTH, subscriptionExpirationDays);

    // The expiration date is the earlier of the provided date and that specified by the parameter.
    if (apiSubscription.getExpiresAfter() != null) {
        GregorianCalendar userExpiration = apiSubscription.getExpiresAfter().toGregorianCalendar();
        if (userExpiration.getTimeInMillis() < expirationDate.getTimeInMillis())
            expirationDate.setTimeInMillis(userExpiration.getTimeInMillis());
    }

    try {
        DatatypeFactory df = DatatypeFactory.newInstance();
        apiSubscription.setExpiresAfter(df.newXMLGregorianCalendar(expirationDate));
    } catch (DatatypeConfigurationException ce) {
        throw new FatalErrorException(new ErrorMessage("errors.Unspecified"));
    }

}

From source file:mekhq.campaign.mission.Contract.java

/**
 * Only do this at the time the contract is set up, otherwise amounts may change after
 * the ink is signed, which is a no-no./*from  w w w .  j  a  v a2  s  . co  m*/
 * @param c
 */
public void calculateContract(Campaign c) {

    //calculate base amount
    baseAmount = (long) (paymentMultiplier * getLength() * c.getContractBase());

    //calculate overhead
    switch (overheadComp) {
    case OH_HALF:
        overheadAmount = (long) (0.5 * c.getOverheadExpenses() * getLength());
        break;
    case OH_FULL:
        overheadAmount = 1 * c.getOverheadExpenses() * getLength();
        break;
    default:
        overheadAmount = 0;
    }

    //calculate support amount
    if (c.getCampaignOptions().usePeacetimeCost() && c.getCampaignOptions().getUnitRatingMethod()
            .equals(mekhq.campaign.rating.UnitRatingMethod.CAMPAIGN_OPS)) {
        supportAmount = (long) ((straightSupport / 100.0) * c.getPeacetimeCost() * getLength());
    } else {
        long maintCosts = 0;
        for (Unit u : c.getUnits()) {
            if (u.getEntity() instanceof Infantry && !(u.getEntity() instanceof BattleArmor)) {
                continue;
            }
            maintCosts += u.getWeeklyMaintenanceCost();
        }
        maintCosts *= 4;
        supportAmount = (long) ((straightSupport / 100.0) * maintCosts * getLength());
    }

    //calculate transportation costs
    if (null != getPlanet()) {
        JumpPath jumpPath = c.calculateJumpPath(c.getCurrentPlanet(), getPlanet());

        // FM:Mercs transport payments take into account owned transports and do not use CampaignOps dropship costs.
        // CampaignOps doesn't care about owned transports and does use its own dropship costs.
        boolean campaignOps = c.getCampaignOptions().useEquipmentContractBase();
        transportAmount = (long) ((transportComp / 100.0) * 2 * c.calculateCostPerJump(campaignOps, campaignOps)
                * jumpPath.getJumps());
    }

    //calculate transit amount for CO
    if (c.getCampaignOptions().usePeacetimeCost() && c.getCampaignOptions().getUnitRatingMethod()
            .equals(mekhq.campaign.rating.UnitRatingMethod.CAMPAIGN_OPS)) {
        //contract base * transport period * reputation * employer modifier
        transitAmount = (long) (c.getContractBase()
                * (((c.calculateJumpPath(c.getCurrentPlanet(), getPlanet()).getJumps()) * 2) / 4)
                * (c.getUnitRatingMod() * .2 + .5) * 1.2);
    } else {
        transitAmount = 0;
    }

    signingAmount = (long) ((signBonus / 100.0)
            * (baseAmount + overheadAmount + transportAmount + transitAmount + supportAmount));

    advanceAmount = (long) ((advancePct / 100.0)
            * (baseAmount + overheadAmount + transportAmount + transitAmount + supportAmount));

    if (mrbcFee) {
        feeAmount = (long) (0.05
                * (baseAmount + overheadAmount + transportAmount + transitAmount + supportAmount));
    } else {
        feeAmount = 0;
    }

    // only adjust the start date for travel if the start date is currently null
    boolean adjustStartDate = false;
    if (null == startDate) {
        startDate = c.getCalendar().getTime();
        adjustStartDate = true;
    }
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(startDate);
    if (adjustStartDate && null != c.getPlanet(planetId)) {
        int days = (int) Math.ceil(c.calculateJumpPath(c.getCurrentPlanet(), getPlanet())
                .getTotalTime(Utilities.getDateTimeDay(cal), c.getLocation().getTransitTime()));
        while (days > 0) {
            cal.add(Calendar.DAY_OF_YEAR, 1);
            days--;
        }
        startDate = cal.getTime();
    }
    int months = getLength();
    while (months > 0) {
        cal.add(Calendar.MONTH, 1);
        months--;
    }
    endDate = cal.getTime();
}

From source file:org.squale.squalecommon.daolayer.component.AuditDAOImplTest.java

/**
 * @see junit.framework.TestCase#setUp()
 *///from w w w .java 2  s .  c  o  m
protected void setUp() throws Exception {
    super.setUp();
    getSession().beginTransaction();
    // On va crer 2 audits de suivis et un de jalon
    // dont la date sera la plus ancienne
    GregorianCalendar cal = new GregorianCalendar();
    ApplicationBO ap1 = getComponentFactory().createApplicationWithSite(getSession(), "qvi");
    ap1.setStatus(ApplicationBO.VALIDATED);
    QualityGridBO grid = getComponentFactory().createGrid(getSession());
    p1 = getComponentFactory().createProject(getSession(), ap1, grid);
    a1 = getComponentFactory().createAudit(getSession(), p1);

    a1.setType(AuditBO.MILESTONE);
    a1.setStatus(AuditBO.TERMINATED);

    // date relle = aujourd'hui
    a1.setHistoricalDate(cal.getTime());
    a2 = getComponentFactory().createAudit(getSession(), p1);
    a2.setStatus(AuditBO.TERMINATED);
    a3 = getComponentFactory().createAudit(getSession(), p1);
    a3.setStatus(AuditBO.TERMINATED);

    a4 = getComponentFactory().createAuditWithStatus(getSession(), p1, new Integer(AuditBO.RUNNING));
    final int ten_days = 10;
    // date a2 = dans 10 jours
    cal.add(GregorianCalendar.DATE, ten_days);
    a2.setDate(cal.getTime());
    // date de ralisation de a1 = dans 20 jours
    cal.add(GregorianCalendar.DATE, ten_days);
    a1.setDate(cal.getTime());
    // date a3 = dans 30 jours
    cal.add(GregorianCalendar.DATE, ten_days);
    a3.setDate(cal.getTime());
    // date a4 = dans 40 jours
    cal.add(GregorianCalendar.DATE, ten_days);
    a4.setDate(cal.getTime());
    LOGGER.warn("Date de a1 = " + a1.getDate() + " date historique = " + a1.getHistoricalDate());
    LOGGER.warn("Date de a2 = " + a2.getDate());
    LOGGER.warn("Date de a3 = " + a3.getDate());
    LOGGER.warn("Date de a4 = " + a4.getDate());
    dao.save(getSession(), a1);
    dao.save(getSession(), a2);
    dao.save(getSession(), a3);
    dao.save(getSession(), a4);
    getSession().commitTransactionWithoutClose();
}

From source file:com.kyleszombathy.sms_scheduler.AddMessage.java

private void validateDateTime() {
    Calendar selDateTime = datePicker.getSelectedDate();
    // Get time 5 minutes from now
    GregorianCalendar in5Mins = new GregorianCalendar();
    in5Mins.add(Calendar.MINUTE, 5);

    if (selDateTime.before(new GregorianCalendar())) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.ValidateDateTimeDialogTitle1)
                .setMessage(R.string.ValidateDateTimeDialogMessage1)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // Do nothing
                    }//ww  w .  j a  v  a2 s .co m
                }).show();
        dateTimeIsValid = false;
    } else if (selDateTime.before(in5Mins)) {
        showValidateDateTimeDialog();
        dateTimeIsValid = false;
    } else {
        dateTimeIsValid = true;
    }
}

From source file:org.squale.squalix.core.Scheduler.java

/**
 * Ralise les tches de niveau application (cration des graphes, calculs,...)
 * /*w w  w  .  ja v  a 2  s.  c o  m*/
 * @param pCurrentAudit l'audit courant.
 * @param pApplicationBO l'application sur lequel calculer les rsultats.
 * @roseuid 42CE40E102B8
 */
private void createNewAudit(final AuditBO pCurrentAudit, final ApplicationBO pApplicationBO) {
    ApplicationBO application = null;
    // on ne cre pas de nouvelles transactions car il faut faut que la transaction
    // pour cette mthode soit la meme que pour la mthode appelante de cette mthode
    try {
        Long applicationId = new Long(pApplicationBO.getId());
        application = (ApplicationBO) ApplicationDAOImpl.getInstance().get(mSession, applicationId);
        GregorianCalendar cal = new GregorianCalendar();
        // Cration d'un nouvel audit si il s'agit d'un audit de suivi
        if (pCurrentAudit.getType().equals(AuditBO.NORMAL)) {
            // Cration d'un nouvel audit
            AuditBO audit = new AuditBO();
            // Ajout de la frquence d'audit  la date courante
            cal.add(Calendar.DATE, pApplicationBO.getAuditFrequency());
            audit.setDate(cal.getTime());
            audit.setStatus(AuditBO.NOT_ATTEMPTED);
            audit.setType(pCurrentAudit.getType());
            AuditDAOImpl.getInstance().create(mSession, audit);
            // Ajout du nouvel audit  l'application
            application.addAudit(audit);
            ApplicationDAOImpl.getInstance().save(mSession, application);
        }
    } catch (Exception e) {
        LOGGER.error(CoreMessages.getString("exception"), e);
    }
}

From source file:org.webical.web.component.event.EventForm.java

/**
 * Create an empty Event and set the start and end times
 * @return Event/*  w  ww.j  a va  2s.  c o  m*/
 */
private EventWrapper createEmptyEvent() {
    this.formEvent = new Event();
    this.eventWrapper = new EventWrapper(formEvent);

    GregorianCalendar dateCalendar = CalendarUtils.duplicateCalendar(selectedDate);
    GregorianCalendar timeCalendar = CalendarUtils.newTodayCalendar(dateCalendar.getFirstDayOfWeek());
    dateCalendar.set(GregorianCalendar.HOUR_OF_DAY, timeCalendar.get(GregorianCalendar.HOUR_OF_DAY));
    dateCalendar.set(GregorianCalendar.MINUTE, timeCalendar.get(GregorianCalendar.MINUTE) / 5 * 5);

    //Fill the start and end times with proper values
    eventWrapper.setDtStart(dateCalendar.getTime());
    dateCalendar.add(GregorianCalendar.HOUR_OF_DAY, 1);
    eventWrapper.setDtEnd(dateCalendar.getTime());

    return this.eventWrapper;
}

From source file:org.apache.unomi.services.services.SegmentServiceImpl.java

private GregorianCalendar getDay(int offset) {
    GregorianCalendar gc = new GregorianCalendar();
    gc = new GregorianCalendar(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DAY_OF_MONTH));
    gc.add(Calendar.DAY_OF_MONTH, offset);
    return gc;//  w ww . ja va 2s.  c o  m
}

From source file:org.alfresco.mobile.android.application.providers.storage.StorageAccessDocumentsProvider.java

@Override
public Cursor queryRecentDocuments(String rootId, String[] projection) throws FileNotFoundException {
    // Log.v(TAG, "queryRecentDocuments" + rootId);

    final DocumentFolderCursor recentDocumentsCursor = new DocumentFolderCursor(
            resolveDocumentProjection(projection));
    Uri uri = DocumentsContract.buildRecentDocumentsUri(mAuthority, rootId);
    final EncodedQueryUri cUri = new EncodedQueryUri(rootId);

    Boolean active = mLoadingUris.get(uri);

    if (active != null) {
        for (Entry<String, Node> nodeEntry : nodesIndex.entrySet()) {
            addNodeRow(recentDocumentsCursor, nodeEntry.getValue());
        }//from   ww  w .  ja va2 s. c  om
        if (!active) {
            // loading request is finished and refreshed
            mLoadingUris.remove(uri);
        }
    }

    if (active == null) {
        new StorageProviderAsyncTask(uri, recentDocumentsCursor, true) {
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    checkSession(cUri);
                    GregorianCalendar calendar = new GregorianCalendar();
                    calendar.add(Calendar.DAY_OF_YEAR, -7);
                    String formatedDate = DateUtils.format(calendar);
                    List<Node> nodes = session.getServiceRegistry().getSearchService()
                            .search(String.format(QUERY_RECENT, formatedDate), SearchLanguage.CMIS);

                    for (Node node : nodes) {
                        nodesIndex.put(NodeRefUtils.getVersionIdentifier(node.getIdentifier()), node);
                    }

                } catch (Exception e) {
                    exception = null;
                    Log.w(TAG, Log.getStackTraceString(e));
                }
                return null;
            }
        }.execute();
    }
    return recentDocumentsCursor;
}