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.openmrs.module.drughistory.api.DrugEventServiceTest.java

@Test
@ExpectedException(IllegalArgumentException.class)
public void generateAllDrugEvents_shouldThrowExceptionIfSinceWhenIsGreaterThanToday() throws Exception {
    GregorianCalendar gc = new GregorianCalendar();
    gc.add(GregorianCalendar.DAY_OF_MONTH, 1);
    Date sinceWhen = gc.getTime();
    Context.getService(DrugEventService.class).generateAllDrugEvents(sinceWhen);
}

From source file:org.openmrs.module.drughistory.api.DrugEventServiceTest.java

/**
 * @verifies throw exception when sinceWhen is in the future
 * @see DrugEventService#generateDrugEventsFromTrigger(org.openmrs.module.drughistory.DrugEventTrigger, java.util.Date)
 *///from www.  j  a  v  a2s.  c o m
@Test
@ExpectedException(IllegalArgumentException.class)
public void generateDrugEventsFromTrigger_shouldThrowExceptionWhenSinceWhenIsInTheFuture() throws Exception {
    GregorianCalendar gc = new GregorianCalendar();
    gc.add(GregorianCalendar.DAY_OF_MONTH, 1);
    AtomicReference<Date> sinceWhen = new AtomicReference<Date>();
    sinceWhen.set(gc.getTime());
    DrugEventTrigger trigger = new DrugEventTrigger();
    drugEventService.generateDrugEventsFromTrigger(trigger, sinceWhen.get());
}

From source file:de.arago.rike.task.action.StartTask.java

@Override
public void execute(IDataWrapper data) throws Exception {
    if (data.getRequestAttribute("id") != null) {
        String user = SecurityHelper.getUserEmail(data.getUser());

        if (TaskHelper.getTasksInProgressForUser(user).size() < Integer
                .parseInt(GlobalConfig.get(WORKFLOW_WIP_LIMIT))) {
            Task task = TaskHelper.getTask(data.getRequestAttribute("id"));

            if (!TaskHelper.canDoTask(user, task) || task.getStatusEnum() != Task.Status.OPEN) {
                return;
            }//from ww w . j  a v  a  2 s .  c  om

            task.setOwner(user);
            task.setStart(new Date());
            task.setStatus(Task.Status.IN_PROGRESS);
            if (GlobalConfig.get(WORKFLOW_TYPE).equalsIgnoreCase("arago Technologies")) {
                GregorianCalendar c = new GregorianCalendar();
                c.setTime(task.getStart());
                c.add(Calendar.DAY_OF_MONTH, Integer.parseInt(GlobalConfig.get(WORKFLOW_DAYS_TO_FINISH_TASK)));
                task.setDueDate(c.getTime());
            }

            TaskHelper.save(task);
            StatisticHelper.update();

            data.setSessionAttribute("task", task);

            HashMap<String, Object> notificationParam = new HashMap<String, Object>();

            notificationParam.put("id", task.getId().toString());
            data.setEvent("TaskUpdateNotification", notificationParam);

            ActivityLogHelper.log(
                    " started Task #" + task.getId() + " <a href=\"/web/guest/rike/-/show/task/" + task.getId()
                            + "\">" + StringEscapeUtils.escapeHtml(task.getTitle()) + "</a> ",
                    task.getStatus(), user, data, task.toMap());
        }
    }
}

From source file:airport.dispatcher.infrastructure.AirportRunawaysImpl.java

private void setTaimer(int runawayId) {
    if (LOG.isInfoEnabled()) {
        LOG.info("create task");
    }// w  w w  . j  a  v a  2  s .  co  m

    JobDataMap dataMap = new JobDataMap();
    dataMap.put(PARAMETER_RUNAWAY_ID, runawayId);
    dataMap.put(PARAMETER_RUNAWAY_DAO, runawayDao);

    GregorianCalendar calendar = new GregorianCalendar();
    calendar.add(GregorianCalendar.SECOND, DELAY_TIMER_LEBIRATE);

    JobDetail jobDetail = newJob(JobLebirateRunaway.class)
            .withIdentity(SCHEDULLER_JOBDET_NAME + schedduler_name_count, SCHEDULLER_GROUP_NAME)
            .setJobData(dataMap).build();

    Trigger trigger = newTrigger()
            .withIdentity(SCHEDULLER_TRIGGER_NAME + schedduler_name_count, SCHEDULLER_GROUP_NAME)
            .startAt(calendar.getTime()).withSchedule(SimpleScheduleBuilder.simpleSchedule()).build();

    if (schedduler_name_count == Integer.MAX_VALUE) {
        schedduler_name_count = 0;
    } else {
        schedduler_name_count++;
    }

    try {
        scheduler.scheduleJob(jobDetail, trigger);

        scheduler.start();
    } catch (SchedulerException ex) {
        if (LOG.isInfoEnabled()) {
            LOG.info("error start taimer", ex);
        }
    }
}

From source file:ma.glasnost.orika.test.converter.CloneableConverterNoSetAccessibleTestCase.java

@Test
public void cloneableConverterWithoutSetAccessible() throws DatatypeConfigurationException {

    final SecurityManager initialSm = System.getSecurityManager();
    try {//from w  ww .jav  a2 s .c  o  m
        System.setSecurityManager(new SecurityManager() {
            public void checkPermission(java.security.Permission perm) {
                if ("suppressAccessChecks".equals(perm.getName())) {
                    for (StackTraceElement ste : new Throwable().getStackTrace()) {
                        if (ste.getClassName().equals(CloneableConverter.class.getCanonicalName())) {
                            throw new SecurityException("not permitted");
                        }
                    }
                }
            }
        });

        CloneableConverter cc = new CloneableConverter(SampleCloneable.class);

        MapperFactory factory = MappingUtil.getMapperFactory();
        factory.getConverterFactory().registerConverter(cc);

        GregorianCalendar cal = new GregorianCalendar();
        cal.add(Calendar.YEAR, 10);
        XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance()
                .newXMLGregorianCalendar((GregorianCalendar) cal);
        cal.add(Calendar.MONTH, 3);

        ClonableHolder source = new ClonableHolder();
        source.value = new SampleCloneable();
        source.value.id = 5L;
        source.date = new Date(System.currentTimeMillis() + 100000);
        source.timestamp = new Timestamp(System.currentTimeMillis() + 50000);
        source.calendar = cal;
        source.xmlCalendar = xmlCal;

        ClonableHolder dest = factory.getMapperFacade().map(source, ClonableHolder.class);
        Assert.assertEquals(source.value, dest.value);
        Assert.assertNotSame(source.value, dest.value);
        Assert.assertEquals(source.date, dest.date);
        Assert.assertNotSame(source.date, dest.date);
        Assert.assertEquals(source.timestamp, dest.timestamp);
        Assert.assertNotSame(source.timestamp, dest.timestamp);
        Assert.assertEquals(source.calendar, dest.calendar);
        Assert.assertNotSame(source.calendar, dest.calendar);
        Assert.assertEquals(source.xmlCalendar, dest.xmlCalendar);
        Assert.assertNotSame(source.xmlCalendar, dest.xmlCalendar);
    } finally {
        System.setSecurityManager(initialSm);
    }
}

From source file:ma.glasnost.orika.test.converter.CloneableConverterTestCase.java

/**
 * This test method demonstrates that you can decide to treat one of the default cloneable types
 * as immutable if desired by registering your own PassThroughConverter for that type
 * //from w  ww  .ja va  2 s  .c  o  m
 * @throws DatatypeConfigurationException
 */
@Test
public void overrideDefaultCloneableToImmutable() throws DatatypeConfigurationException {

    PassThroughConverter cc = new PassThroughConverter(Date.class, Calendar.class);

    MapperFactory factory = MappingUtil.getMapperFactory();
    factory.getConverterFactory().registerConverter(cc);

    GregorianCalendar cal = new GregorianCalendar();
    cal.add(Calendar.YEAR, 10);
    XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar((GregorianCalendar) cal);
    cal.add(Calendar.MONTH, 3);

    ClonableHolder source = new ClonableHolder();
    source.value = new SampleCloneable();
    source.value.id = 5L;
    source.date = new Date(System.currentTimeMillis() + 100000);
    source.calendar = cal;
    source.xmlCalendar = xmlCal;

    ClonableHolder dest = factory.getMapperFacade().map(source, ClonableHolder.class);
    Assert.assertEquals(source.value, dest.value);
    Assert.assertNotSame(source.value, dest.value);
    Assert.assertEquals(source.date, dest.date);
    Assert.assertSame(source.date, dest.date);
    Assert.assertEquals(source.calendar, dest.calendar);
    Assert.assertSame(source.calendar, dest.calendar);
    Assert.assertEquals(source.xmlCalendar, dest.xmlCalendar);
    Assert.assertNotSame(source.xmlCalendar, dest.xmlCalendar);

}

From source file:ma.glasnost.orika.test.converter.CloneableConverterTestCase.java

@Test
public void cloneableConverter() throws DatatypeConfigurationException {

    CloneableConverter cc = new CloneableConverter(SampleCloneable.class);

    MapperFactory factory = MappingUtil.getMapperFactory();
    factory.getConverterFactory().registerConverter(cc);

    GregorianCalendar cal = new GregorianCalendar();
    cal.add(Calendar.YEAR, 10);
    XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar((GregorianCalendar) cal);
    cal.add(Calendar.MONTH, 3);/*from  w w w  .j a  v a  2s .  c o  m*/

    ClonableHolder source = new ClonableHolder();
    source.value = new SampleCloneable();
    source.value.id = 5L;
    source.date = new Date(System.currentTimeMillis() + 100000);
    source.timestamp = new Timestamp(System.currentTimeMillis() + 50000);
    source.calendar = cal;
    source.xmlCalendar = xmlCal;

    ClonableHolder dest = factory.getMapperFacade().map(source, ClonableHolder.class);
    Assert.assertEquals(source.value, dest.value);
    Assert.assertNotSame(source.value, dest.value);
    Assert.assertEquals(source.date, dest.date);
    Assert.assertNotSame(source.date, dest.date);
    Assert.assertEquals(source.timestamp, dest.timestamp);
    Assert.assertNotSame(source.timestamp, dest.timestamp);
    Assert.assertEquals(source.calendar, dest.calendar);
    Assert.assertNotSame(source.calendar, dest.calendar);
    Assert.assertEquals(source.xmlCalendar, dest.xmlCalendar);
    Assert.assertNotSame(source.xmlCalendar, dest.xmlCalendar);
}

From source file:org.squale.welcom.outils.DateUtil.java

/**
 * @param dateDebut : date de dbut (java.util.Date)
 * @param dateFin : date de fin (java.util.Date)
 * @param unit : unit de temps dans laquelle doit tre calcule la dure (MILLI_SEC,SEC,DAY,HOUR,MIN)
 * @return retourne le nombre de jour entre deux dates les samedi et dimanche n'tant pas inclu
 *//*from  w w w  . ja v a2  s  .  com*/
public static long durationNoWeekEnd(final java.util.Date dateDebut, final java.util.Date dateFin,
        final long unit) {
    long duration = duration(dateDebut, dateFin, unit);
    final GregorianCalendar gc = new GregorianCalendar();

    if (duration != 0) {
        gc.setTime(dateDebut);

        while (gc.getTime().getTime() <= dateFin.getTime()) {
            if ((gc.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY)
                    || (gc.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)) {
                duration--;
            }

            gc.add(Calendar.DATE, 1);
        }
    }

    return duration;
}

From source file:sample.S3EmitterWithMetadata.java

@Override
public List<byte[]> emit(final UnmodifiableBuffer<byte[]> buffer) throws IOException {
    List<byte[]> records = buffer.getRecords();
    // Write all of the records to a compressed output stream
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    for (byte[] record : records) {
        try {//w w w .  java2s.  c  o m
            baos.write(record);
        } catch (Exception e) {
            LOG.error("Error writing record to output stream. Failing this emit attempt. Record: "
                    + Arrays.toString(record), e);
            return buffer.getRecords();
        }
    }
    // Get the Amazon S3 filename
    String s3FileName = getS3FileName(buffer.getFirstSequenceNumber(), buffer.getLastSequenceNumber());
    String s3URI = getS3URI(s3FileName);
    try {
        ByteArrayInputStream object = new ByteArrayInputStream(baos.toByteArray());
        LOG.debug("Starting upload of file " + s3URI + " to Amazon S3 containing " + records.size()
                + " records.");
        ObjectMetadata meta = new ObjectMetadata();
        Date date = new Date();
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, 14);
        meta.setExpirationTime(calendar.getTime());
        meta.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
        meta.setContentLength(baos.size());
        s3client.putObject(s3Bucket, s3FileName, object, meta);
        LOG.info("Successfully emitted " + buffer.getRecords().size() + " records to Amazon S3 in " + s3URI);
        return Collections.emptyList();
    } catch (Exception e) {
        LOG.error("Caught exception when uploading file " + s3URI + "to Amazon S3. Failing this emit attempt.",
                e);
        return buffer.getRecords();
    }
}

From source file:org.xdi.oxauth.model.crypto.signature.ECDSAKeyFactory.java

public ECDSAKeyFactory(SignatureAlgorithm signatureAlgorithm, String dnName) throws InvalidParameterException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        SignatureException, InvalidKeyException, CertificateEncodingException {
    if (signatureAlgorithm == null) {
        throw new InvalidParameterException("The signature algorithm cannot be null");
    }//from   ww w  . j  a v a 2 s  .c o m

    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(signatureAlgorithm.getCurve());

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", "BC");
    keyGen.initialize(ecSpec, new SecureRandom());

    KeyPair keyPair = keyGen.generateKeyPair();
    JCEECPrivateKey privateKeySpec = (JCEECPrivateKey) keyPair.getPrivate();
    JCEECPublicKey publicKeySpec = (JCEECPublicKey) keyPair.getPublic();

    BigInteger x = publicKeySpec.getQ().getX().toBigInteger();
    BigInteger y = publicKeySpec.getQ().getY().toBigInteger();
    BigInteger d = privateKeySpec.getD();

    ecdsaPrivateKey = new ECDSAPrivateKey(d);
    ecdsaPublicKey = new ECDSAPublicKey(signatureAlgorithm, x, y);

    if (StringUtils.isNotBlank(dnName)) {
        // Create certificate
        GregorianCalendar startDate = new GregorianCalendar(); // time from which certificate is valid
        GregorianCalendar expiryDate = new GregorianCalendar(); // time after which certificate is not valid
        expiryDate.add(Calendar.YEAR, 1);
        BigInteger serialNumber = new BigInteger(1024, new Random()); // serial number for certificate

        X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
        X500Principal principal = new X500Principal(dnName);

        certGen.setSerialNumber(serialNumber);
        certGen.setIssuerDN(principal);
        certGen.setNotBefore(startDate.getTime());
        certGen.setNotAfter(expiryDate.getTime());
        certGen.setSubjectDN(principal); // note: same as issuer
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm("SHA256WITHECDSA");

        X509Certificate x509Certificate = certGen.generate(privateKeySpec, "BC");
        certificate = new Certificate(signatureAlgorithm, x509Certificate);
    }
}