Example usage for javax.xml.datatype Duration addTo

List of usage examples for javax.xml.datatype Duration addTo

Introduction

In this page you can find the example usage for javax.xml.datatype Duration addTo.

Prototype

public void addTo(Date date) 

Source Link

Document

Adds this duration to a Date object.

Usage

From source file:com.adaptris.core.fs.LastModifiedFilter.java

protected Date filterDate() throws Exception {
    Date filterDate = new Date();
    if (NumberUtils.isDigits(when)) {
        filterDate.setTime(Long.parseLong(when));
    } else {//from w  ww .  ja  v a 2s  . c  om
        Duration duration = DatatypeFactory.newInstance().newDuration(when);
        duration.addTo(filterDate);
    }
    return filterDate;
}

From source file:com.evolveum.midpoint.task.quartzimpl.CleanupTest.java

@Test
public void testTasksCleanup() throws Exception {

    // GIVEN/*from w w  w . java  2s .c om*/
    final File file = new File(FOLDER_REPO, "tasks-for-cleanup.xml");
    List<PrismObject<? extends Objectable>> elements = prismContext.parseObjects(file);

    OperationResult result = new OperationResult("tasks cleanup");
    for (int i = 0; i < elements.size(); i++) {
        PrismObject object = elements.get(i);

        String oid = repositoryService.addObject(object, null, result);
        AssertJUnit.assertTrue(StringUtils.isNotEmpty(oid));
    }

    // 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_2013_07_12_12_00_Calendar();
    CleanupPolicyType policy = createPolicy(when, NOW);

    taskManager.cleanupTasks(policy, taskManager.createTaskInstance(), result);

    // THEN
    List<PrismObject<TaskType>> tasks = repositoryService.searchObjects(TaskType.class, null, null, result);
    AssertJUnit.assertNotNull(tasks);
    display("tasks", tasks);
    AssertJUnit.assertEquals(1, tasks.size());

    PrismObject<TaskType> task = tasks.get(0);
    XMLGregorianCalendar timestamp = task.getPropertyRealValue(TaskType.F_COMPLETION_TIMESTAMP,
            XMLGregorianCalendar.class);
    Date finished = XMLGregorianCalendarType.asDate(timestamp);

    Date mark = new Date(NOW);
    Duration duration = policy.getMaxAge();
    duration.addTo(mark);

    AssertJUnit.assertTrue("finished: " + finished + ", mark: " + mark, finished.after(mark));
}

From source file:com.adaptris.core.services.metadata.timestamp.OffsetTimestampGenerator.java

@Override
public Date generateTimestamp(AdaptrisMessage msg) throws ServiceException {
    Date timestamp = new Date();
    try {// www .j  a  v  a2 s . c  o  m
        if (!isBlank(offset)) {
            Duration duration;
            duration = DatatypeFactory.newInstance().newDuration(msg.resolve(offset));
            duration.addTo(timestamp);
        }
    } catch (Exception e) {
        throw new ServiceException("Failed to parse " + offset + " using ISO8601", e);
    }
    return timestamp;
}

From source file:com.evolveum.midpoint.repo.sql.CleanupTest.java

License:asdf

@Test
public void testAuditCleanup() throws Exception {
    //GIVEN/*from  w  ww  . ja v  a  2 s  .  c om*/
    Calendar calendar = create_2013_07_12_12_00_Calendar();
    for (int i = 0; i < 3; i++) {
        long timestamp = calendar.getTimeInMillis();
        AuditEventRecord record = new AuditEventRecord();
        record.addDelta(createObjectDeltaOperation(i));
        record.setTimestamp(timestamp);
        LOGGER.info("Adding audit record with timestamp {}", new Object[] { new Date(timestamp) });

        auditService.audit(record, new SimpleTaskAdapter());
        calendar.add(Calendar.HOUR_OF_DAY, 1);
    }

    Session session = getFactory().openSession();
    try {
        session.beginTransaction();

        Query query = session.createQuery("select count(*) from " + RAuditEventRecord.class.getSimpleName());
        Long count = (Long) query.uniqueResult();

        AssertJUnit.assertEquals(3L, (long) count);
        session.getTransaction().commit();
    } finally {
        session.close();
    }

    //WHEN
    calendar = create_2013_07_12_12_00_Calendar();
    calendar.add(Calendar.HOUR_OF_DAY, 1);
    calendar.add(Calendar.MINUTE, 1);

    final long NOW = System.currentTimeMillis();
    CleanupPolicyType policy = createPolicy(calendar, NOW);

    OperationResult result = new OperationResult("Cleanup audit");
    auditService.cleanupAudit(policy, result);
    result.recomputeStatus();

    //THEN
    AssertJUnit.assertTrue(result.isSuccess());

    session = getFactory().openSession();
    try {
        session.beginTransaction();

        Query query = session.createQuery("from " + RAuditEventRecord.class.getSimpleName());
        List<RAuditEventRecord> records = query.list();

        AssertJUnit.assertEquals(1, records.size());
        RAuditEventRecord record = records.get(0);

        Date finished = new Date(record.getTimestamp().getTime());

        Date mark = new Date(NOW);
        Duration duration = policy.getMaxAge();
        duration.addTo(mark);

        AssertJUnit.assertTrue("finished: " + finished + ", mark: " + mark, finished.after(mark));

        session.getTransaction().commit();
    } finally {
        session.close();
    }
}

From source file:com.evolveum.midpoint.repo.sql.SqlAuditServiceImpl.java

@Override
public void cleanupAudit(CleanupPolicyType policy, OperationResult parentResult) {
    Validate.notNull(policy, "Cleanup policy must not be null.");
    Validate.notNull(parentResult, "Operation result must not be null.");

    final String operation = "deleting";
    int attempt = 1;

    SqlPerformanceMonitor pm = getPerformanceMonitor();
    long opHandle = pm.registerOperationStart("cleanupAudit");

    if (policy.getMaxAge() == null) {
        return;//from  ww  w  .  j a  v a 2  s .  c o m
    }

    Duration duration = policy.getMaxAge();
    if (duration.getSign() > 0) {
        duration = duration.negate();
    }
    Date minValue = new Date();
    duration.addTo(minValue);

    // factored out because it produces INFO-level message
    Dialect dialect = Dialect.getDialect(getSessionFactoryBean().getHibernateProperties());
    if (!dialect.supportsTemporaryTables()) {
        LOGGER.error("Dialect {} doesn't support temporary tables, couldn't cleanup audit logs.", dialect);
        throw new SystemException(
                "Dialect " + dialect + " doesn't support temporary tables, couldn't cleanup audit logs.");
    }

    long start = System.currentTimeMillis();
    boolean first = true;
    Holder<Integer> totalCountHolder = new Holder<>(0);
    try {
        while (true) {
            try {
                LOGGER.info("{} audit cleanup, deleting up to {} (duration '{}'), batch size {}{}.",
                        first ? "Starting" : "Restarting", minValue, duration, CLEANUP_AUDIT_BATCH_SIZE,
                        first ? "" : ", up to now deleted " + totalCountHolder.getValue() + " entries");
                first = false;
                int count;
                do {
                    // the following method may restart due to concurrency (or any other) problem - in any iteration
                    count = cleanupAuditAttempt(minValue, duration, totalCountHolder, dialect, parentResult);
                } while (count > 0);
                return;
            } catch (RuntimeException ex) {
                attempt = logOperationAttempt(null, operation, attempt, ex, parentResult);
                pm.registerOperationNewTrial(opHandle, attempt);
            }
        }
    } finally {
        pm.registerOperationFinish(opHandle, attempt);
        LOGGER.info("Audit cleanup finished; deleted {} entries in {} seconds.", totalCountHolder.getValue(),
                (System.currentTimeMillis() - start) / 1000L);
    }
}

From source file:com.evolveum.midpoint.report.impl.ReportManagerImpl.java

@Override
public void cleanupReports(CleanupPolicyType cleanupPolicy, OperationResult parentResult) {
    OperationResult result = parentResult.createSubresult(CLEANUP_REPORT_OUTPUTS);

    if (cleanupPolicy.getMaxAge() == null) {
        return;// ww w . j a va 2s.c om
    }

    Duration duration = cleanupPolicy.getMaxAge();
    if (duration.getSign() > 0) {
        duration = duration.negate();
    }
    Date deleteReportOutputsTo = new Date();
    duration.addTo(deleteReportOutputsTo);

    LOGGER.info("Starting cleanup for report outputs deleting up to {} (duration '{}').",
            new Object[] { deleteReportOutputsTo, duration });

    XMLGregorianCalendar timeXml = XmlTypeConverter.createXMLGregorianCalendar(deleteReportOutputsTo.getTime());

    List<PrismObject<ReportOutputType>> obsoleteReportOutputs = new ArrayList<PrismObject<ReportOutputType>>();
    try {
        ObjectQuery obsoleteReportOutputsQuery = ObjectQuery.createObjectQuery(LessFilter.createLess(
                new ItemPath(ReportOutputType.F_METADATA, MetadataType.F_CREATE_TIMESTAMP),
                ReportOutputType.class, prismContext, timeXml, true));
        obsoleteReportOutputs = modelService.searchObjects(ReportOutputType.class, obsoleteReportOutputsQuery,
                null, null, result);
    } catch (Exception e) {
        throw new SystemException("Couldn't get the list of obsolete report outputs: " + e.getMessage(), e);
    }

    LOGGER.debug("Found {} report output(s) to be cleaned up", obsoleteReportOutputs.size());

    boolean interrupted = false;
    int deleted = 0;
    int problems = 0;

    for (PrismObject<ReportOutputType> reportOutputPrism : obsoleteReportOutputs) {
        ReportOutputType reportOutput = reportOutputPrism.asObjectable();

        LOGGER.trace("Removing report output {} along with {} file.", reportOutput.getName().getOrig(),
                reportOutput.getFilePath());
        boolean problem = false;
        try {
            deleteReportOutput(reportOutput, result);
        } catch (Exception e) {
            LoggingUtils.logException(LOGGER, "Couldn't delete obsolete report output {} due to a exception", e,
                    reportOutput);
            problem = true;
        }

        if (problem) {
            problems++;
        } else {
            deleted++;
        }
    }
    result.computeStatusIfUnknown();

    LOGGER.info("Report cleanup procedure " + (interrupted ? "was interrupted" : "finished")
            + ". Successfully deleted {} report outputs; there were problems with deleting {} report ouptuts.",
            deleted, problems);
    String suffix = interrupted ? " Interrupted." : "";
    if (problems == 0) {
        parentResult.createSubresult(CLEANUP_REPORT_OUTPUTS + ".statistics").recordStatus(
                OperationResultStatus.SUCCESS,
                "Successfully deleted " + deleted + " report output(s)." + suffix);
    } else {
        parentResult.createSubresult(CLEANUP_REPORT_OUTPUTS + ".statistics")
                .recordPartialError("Successfully deleted " + deleted + " report output(s), "
                        + "there was problems with deleting " + problems + " report outputs.");
    }
}

From source file:com.evolveum.midpoint.task.quartzimpl.TaskManagerQuartzImpl.java

@Override
public void cleanupTasks(CleanupPolicyType policy, Task executionTask, OperationResult parentResult)
        throws SchemaException {
    OperationResult result = parentResult.createSubresult(CLEANUP_TASKS);

    if (policy.getMaxAge() == null) {
        return;/*from   w  w w  .j  a  va2 s . c o m*/
    }

    Duration duration = policy.getMaxAge();
    if (duration.getSign() > 0) {
        duration = duration.negate();
    }
    Date deleteTasksClosedUpTo = new Date();
    duration.addTo(deleteTasksClosedUpTo);

    LOGGER.info("Starting cleanup for closed tasks deleting up to {} (duration '{}').",
            new Object[] { deleteTasksClosedUpTo, duration });

    XMLGregorianCalendar timeXml = XmlTypeConverter.createXMLGregorianCalendar(deleteTasksClosedUpTo.getTime());

    List<PrismObject<TaskType>> obsoleteTasks;
    try {
        ObjectQuery obsoleteTasksQuery = ObjectQuery.createObjectQuery(AndFilter.createAnd(
                LessFilter.createLess(TaskType.F_COMPLETION_TIMESTAMP, TaskType.class, getPrismContext(),
                        timeXml, true),
                EqualFilter.createEqual(TaskType.F_PARENT, TaskType.class, getPrismContext(), null)));

        obsoleteTasks = repositoryService.searchObjects(TaskType.class, obsoleteTasksQuery, null, result);
    } catch (SchemaException e) {
        throw new SchemaException("Couldn't get the list of obsolete tasks: " + e.getMessage(), e);
    }

    LOGGER.debug("Found {} task tree(s) to be cleaned up", obsoleteTasks.size());

    boolean interrupted = false;
    int deleted = 0;
    int problems = 0;
    int bigProblems = 0;
    for (PrismObject<TaskType> rootTaskPrism : obsoleteTasks) {

        if (!executionTask.canRun()) {
            result.recordPartialError("Interrupted");
            LOGGER.warn("Task cleanup was interrupted.");
            interrupted = true;
            break;
        }

        // get whole tree
        Task rootTask = createTaskInstance(rootTaskPrism, result);
        List<Task> taskTreeMembers = rootTask.listSubtasksDeeply(result);
        taskTreeMembers.add(rootTask);

        LOGGER.trace("Removing task {} along with its {} children.", rootTask, taskTreeMembers.size() - 1);

        boolean problem = false;
        for (Task task : taskTreeMembers) {
            try {
                deleteTask(task.getOid(), result);
            } catch (SchemaException e) {
                LoggingUtils.logException(LOGGER, "Couldn't delete obsolete task {} due to schema exception", e,
                        task);
                problem = true;
            } catch (ObjectNotFoundException e) {
                LoggingUtils.logException(LOGGER,
                        "Couldn't delete obsolete task {} due to object not found exception", e, task);
                problem = true;
            } catch (RuntimeException e) {
                LoggingUtils.logException(LOGGER, "Couldn't delete obsolete task {} due to a runtime exception",
                        e, task);
                problem = true;
            }

            if (problem) {
                problems++;
                if (!task.getTaskIdentifier().equals(rootTask.getTaskIdentifier())) {
                    bigProblems++;
                }
            } else {
                deleted++;
            }
        }
    }
    result.computeStatusIfUnknown();

    LOGGER.info(
            "Task cleanup procedure " + (interrupted ? "was interrupted" : "finished")
                    + ". Successfully deleted {} tasks; there were problems with deleting {} tasks.",
            deleted, problems);
    if (bigProblems > 0) {
        LOGGER.error(
                "{} subtask(s) couldn't be deleted. Inspect that manually, otherwise they might reside in repo forever.",
                bigProblems);
    }
    String suffix = interrupted ? " Interrupted." : "";
    if (problems == 0) {
        parentResult.createSubresult(CLEANUP_TASKS + ".statistics").recordStatus(OperationResultStatus.SUCCESS,
                "Successfully deleted " + deleted + " task(s)." + suffix);
    } else {
        parentResult.createSubresult(CLEANUP_TASKS + ".statistics")
                .recordPartialError("Successfully deleted " + deleted + " task(s), "
                        + "there was problems with deleting " + problems + " tasks." + suffix
                        + (bigProblems > 0
                                ? (" " + bigProblems + " subtask(s) couldn't be deleted, please see the log.")
                                : ""));
    }

}

From source file:nl.clockwork.mule.ebms.util.EbMSMessageUtils.java

public static MessageHeader createMessageHeader(CollaborationProtocolAgreement cpa, EbMSMessageContext context,
        String hostname) throws DatatypeConfigurationException {
    String uuid = UUID.getUUID();
    PartyInfo sendingPartyInfo = CPAUtils.getSendingPartyInfo(cpa, context.getFromRole(),
            context.getServiceType(), context.getService(), context.getAction());
    PartyInfo receivingPartyInfo = CPAUtils.getReceivingPartyInfo(cpa, context.getToRole(),
            context.getServiceType(), context.getService(), context.getAction());
    //PartyInfo receivingPartyInfo = CPAUtils.getOtherReceivingPartyInfo(cpa,context.getFromRole(),context.getServiceType(),context.getService(),context.getAction());

    MessageHeader messageHeader = new MessageHeader();

    messageHeader.setVersion(Constants.EBMS_VERSION);
    messageHeader.setMustUnderstand(true);

    messageHeader.setCPAId(cpa.getCpaid());
    messageHeader.setConversationId(context.getConversationId() != null ? context.getConversationId() : uuid);

    messageHeader.setFrom(new From());
    PartyId from = new PartyId();
    from.setType(sendingPartyInfo.getPartyId().get(0).getType());
    from.setValue(sendingPartyInfo.getPartyId().get(0).getValue());
    messageHeader.getFrom().getPartyId().add(from);
    messageHeader.getFrom().setRole(sendingPartyInfo.getCollaborationRole().get(0).getRole().getName());

    messageHeader.setTo(new To());
    PartyId to = new PartyId();
    to.setType(receivingPartyInfo.getPartyId().get(0).getType());
    to.setValue(receivingPartyInfo.getPartyId().get(0).getValue());
    messageHeader.getTo().getPartyId().add(to);
    messageHeader.getTo().setRole(receivingPartyInfo.getCollaborationRole().get(0).getRole().getName());

    messageHeader.setService(new Service());
    messageHeader.getService()//from  w w w.  j  a  v  a  2 s. com
            .setType(sendingPartyInfo.getCollaborationRole().get(0).getServiceBinding().getService().getType());
    messageHeader.getService().setValue(
            sendingPartyInfo.getCollaborationRole().get(0).getServiceBinding().getService().getValue());
    messageHeader.setAction(sendingPartyInfo.getCollaborationRole().get(0).getServiceBinding().getCanSend()
            .get(0).getThisPartyActionBinding().getAction());

    messageHeader.setMessageData(new MessageData());
    messageHeader.getMessageData().setMessageId(uuid + "@" + hostname);
    messageHeader.getMessageData().setRefToMessageId(context.getRefToMessageId());
    messageHeader.getMessageData()
            .setTimestamp(DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar()));

    ReliableMessaging rm = CPAUtils.getReliableMessaging(cpa, messageHeader);
    if (rm != null) {
        GregorianCalendar timestamp = messageHeader.getMessageData().getTimestamp().toGregorianCalendar();
        Duration d = rm.getRetryInterval().multiply(rm.getRetries().add(new BigInteger("1")).intValue());
        d.addTo(timestamp);
        timestamp.add(Calendar.SECOND, 1);
        messageHeader.getMessageData()
                .setTimeToLive(DatatypeFactory.newInstance().newXMLGregorianCalendar(timestamp));
    }

    DeliveryChannel channel = CPAUtils.getDeliveryChannel(sendingPartyInfo.getCollaborationRole().get(0)
            .getServiceBinding().getCanSend().get(0).getThisPartyActionBinding());

    messageHeader.setDuplicateElimination(PerMessageCharacteristicsType.ALWAYS
            .equals(channel.getMessagingCharacteristics().getDuplicateElimination()) ? "" : null);

    return messageHeader;
}

From source file:org.apache.hise.engine.jaxws.TaskOperationsImpl.java

public void suspendUntil(String identifier, TTime time)
        throws IllegalAccessFault, IllegalStateFault, IllegalArgumentFault {
    Task t = Task.load(hiseEngine, Long.parseLong(identifier));
    t.setCurrentUser(getUserString());/*from  w  w w . ja va  2  s.  c o  m*/
    Date when = time.getPointOfTime();
    if (when == null) {
        Duration when2 = time.getTimePeriod();
        when = Calendar.getInstance().getTime();
        when2.addTo(when);
    }

    try {
        t.suspendUntil(when);
    } catch (HiseIllegalStateException e) {
        throw new IllegalStateFault(e.getMessage());
    }
}

From source file:org.apache.juddi.subscription.SubscriptionNotifier.java

protected GetSubscriptionResults buildGetSubscriptionResults(Subscription subscription, Date endPoint)
        throws DispositionReportFaultMessage, DatatypeConfigurationException {

    GetSubscriptionResults getSubscriptionResults = null;
    Duration duration = TypeConvertor.convertStringToDuration(subscription.getNotificationInterval());
    Date startPoint = subscription.getLastNotified();
    Date nextDesiredNotificationDate = null;
    if (startPoint == null)
        startPoint = subscription.getCreateDate();
    nextDesiredNotificationDate = new Date(startPoint.getTime());
    duration.addTo(nextDesiredNotificationDate);
    //nextDesiredNotificationDate = lastTime + the Interval Duration, which should be:
    //AFTER the lastNotified time and BEFORE the endTime (current time). If it is
    //after the endTime, then the user does not want a notification yet, so we accumulate.
    if (subscription.getLastNotified() == null
            || nextDesiredNotificationDate.after(startPoint) && nextDesiredNotificationDate.before(endPoint)) {
        getSubscriptionResults = new GetSubscriptionResults();
        CoveragePeriod period = new CoveragePeriod();
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTimeInMillis(startPoint.getTime());
        period.setStartPoint(DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar));
        calendar.setTimeInMillis(endPoint.getTime());
        period.setEndPoint(DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar));
        if (log.isDebugEnabled())
            log.debug("Period " + period.getStartPoint() + " " + period.getEndPoint());
        getSubscriptionResults.setCoveragePeriod(period);
    } else {//from   w ww  .  jav  a2  s  .  c  o m
        log.debug("Client does not yet want a notification. The next desidered notification Date "
                + nextDesiredNotificationDate + ". The current interval [" + startPoint + " , " + endPoint
                + "] therefore skipping this notification cycle.");
        if (desiredDate == null || nextDesiredNotificationDate.getTime() < desiredDate.getTime()) {
            desiredDate = nextDesiredNotificationDate;
        }
    }
    return getSubscriptionResults;

}