Example usage for javax.xml.datatype Duration getSign

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

Introduction

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

Prototype

public abstract int getSign();

Source Link

Document

Returns the sign of this duration in -1,0, or 1.

Usage

From source file:Main.java

/**
 * Add one Duration to another, avoiding the runtime library bug that gives
 * incorrect results when using decimal seconds.
 * @param d1 The first duration//from  ww w  .j  av  a2 s. c o m
 * @param d2 The second duration
 * @return The result of adding d1 to d2
 */
public static Duration add(Duration d1, Duration d2) {
    boolean sign1 = d1.getSign() >= 0;
    boolean sign2 = d2.getSign() >= 0;

    if (sign1 && sign2)
        return addPositiveDurations(d1, d2);

    if (!sign1 && !sign2)
        return addPositiveDurations(d1.negate(), d2.negate()).negate();

    if (sign1 && !sign2)
        return subtract(d1, d2.negate());

    //if( ! sign1 && sign2 )
    return subtract(d2, d1.negate());
}

From source file:Main.java

/**
 * Subtract one Duration from another, avoiding the runtime library bug that gives
 * incorrect results when using decimal seconds.
 * @param d1 The first duration/* ww w  .  ja v  a  2s. c  om*/
 * @param d2 The second duration
 * @return The result of subtracting d2 from d1
 */
public static Duration subtract(Duration d1, Duration d2) {
    boolean sign1 = d1.getSign() >= 0;
    boolean sign2 = d2.getSign() >= 0;

    if (sign1 && sign2) {
        int comparison = d1.compare(d2);
        comparison = compare(d1, d2);
        if (comparison >= 0)
            return subtractSmallerPositiveDurationFromLargerPositiveDuration(d1, d2);
        else
            return subtractSmallerPositiveDurationFromLargerPositiveDuration(d2, d1).negate();
    }

    if (!sign1 && !sign2) {
        d1 = d1.negate();
        d2 = d2.negate();

        int comparison = d1.compare(d2);
        comparison = compare(d1, d2);
        if (comparison < 0)
            return subtractSmallerPositiveDurationFromLargerPositiveDuration(d2, d1);
        else
            return subtractSmallerPositiveDurationFromLargerPositiveDuration(d1, d2).negate();
    }

    if (sign1 && !sign2)
        return add(d1, d2.negate());

    //if( ! sign1 && sign2 )
    return add(d2, d1.negate()).negate();
}

From source file:Main.java

/**
 * Special compare method that gets around the problem in java 1.5,
 * where years and months are converted to days after arithmetic.
 * @param d1 First duration/*  w  ww.  j  av a 2 s .c om*/
 * @param d2 Second duration
 * @return -1 if d1 < d2, 0 if d1 == d2 and +1 if d1 > d2
 */
public static int compare(Duration d1, Duration d2) {
    if (d1 == null && d2 == null)
        return 0;

    if (d1 == null)
        return -1;

    if (d2 == null)
        return 1;

    boolean b1 = d1.getSign() >= 0;
    boolean b2 = d2.getSign() >= 0;

    if (!b1 && b2)
        return -1;

    if (b1 && !b2)
        return 1;

    // Now normalise in case we are running with java 1.5 runtime
    javax.xml.datatype.Duration n1 = normaliseDays(d1);
    javax.xml.datatype.Duration n2 = normaliseDays(d2);

    if (n1.getDays() < n2.getDays())
        return -1;
    if (n1.getDays() > n2.getDays())
        return 1;

    if (n1.getHours() < n2.getHours())
        return -1;
    if (n1.getHours() > n2.getHours())
        return 1;

    if (n1.getMinutes() < n2.getMinutes())
        return -1;
    if (n1.getMinutes() > n2.getMinutes())
        return 1;

    BigDecimal s1 = (BigDecimal) n1.getField(DatatypeConstants.SECONDS);
    BigDecimal s2 = (BigDecimal) n2.getField(DatatypeConstants.SECONDS);

    return s1.compareTo(s2);
}

From source file:Main.java

/**
 * Create a new Duration object without any fractional second component.
 * @param duration The duration object to strip
 * @return The input Duration with the fractional second part stripped off.
 */// w  w w .j  av  a2 s . co m
private static Duration stripFractionalSeconds(Duration duration) {
    int year = duration.getYears();
    int month = duration.getMonths();
    int day = duration.getDays();
    int hour = duration.getHours();
    int minute = duration.getMinutes();
    int second = duration.getSeconds();

    boolean positive = duration.getSign() >= 0;

    return FACTORY.newDuration(positive, year, month, day, hour, minute, second);
}

From source file:Main.java

private static javax.xml.datatype.Duration normaliseSeconds(javax.xml.datatype.Duration duration) {
    BigInteger years = (BigInteger) duration.getField(DatatypeConstants.YEARS);
    BigInteger months = (BigInteger) duration.getField(DatatypeConstants.MONTHS);
    BigInteger days = (BigInteger) duration.getField(DatatypeConstants.DAYS);

    BigInteger hours = (BigInteger) duration.getField(DatatypeConstants.HOURS);
    BigInteger minutes = (BigInteger) duration.getField(DatatypeConstants.MINUTES);
    BigDecimal seconds = (BigDecimal) duration.getField(DatatypeConstants.SECONDS);

    seconds = seconds.stripTrailingZeros();

    boolean positive = duration.getSign() >= 0;

    return FACTORY.newDuration(positive, years, months, days, hours, minutes, seconds);
}

From source file:com.evolveum.midpoint.schema.util.WfContextUtil.java

@NotNull
private static XMLGregorianCalendar computeTriggerTime(Duration duration, WfTimeBaseType base, Date start,
        Date deadline) {/*from  w  w w  .  j  a v  a  2 s.c om*/
    Date baseTime;
    if (base == null) {
        base = duration.getSign() <= 0 ? WfTimeBaseType.DEADLINE : WfTimeBaseType.WORK_ITEM_CREATION;
    }
    switch (base) {
    case DEADLINE:
        if (deadline == null) {
            throw new IllegalStateException("Couldn't set timed action relative to work item's deadline because"
                    + " the deadline is not set. Requested interval: " + duration);
        }
        baseTime = deadline;
        break;
    case WORK_ITEM_CREATION:
        if (start == null) {
            throw new IllegalStateException("Task's start time is null");
        }
        baseTime = start;
        break;
    default:
        throw new IllegalArgumentException("base: " + base);
    }
    XMLGregorianCalendar rv = XmlTypeConverter.createXMLGregorianCalendar(baseTime);
    rv.add(duration);
    return rv;
}

From source file:Main.java

/**
 * Java runtime 1.5 is inconsistent with its handling of days in Duration objects.
 * @param duration A duration object to be normalised
 * @return A day-normalised duration, i.e. all years and months converted to days,
 * e.g. 1Y 3M 3D => 458 days//from  www. java2s .  co  m
 */
private static javax.xml.datatype.Duration normaliseDays(javax.xml.datatype.Duration duration) {
    final long DAYS_PER_MONTH = 30;
    final long DAYS_PER_YEAR = 365;

    BigInteger days = (BigInteger) duration.getField(DatatypeConstants.DAYS);
    BigInteger months = (BigInteger) duration.getField(DatatypeConstants.MONTHS);
    BigInteger years = (BigInteger) duration.getField(DatatypeConstants.YEARS);

    BigInteger normalisedDays = years.multiply(BigInteger.valueOf(DAYS_PER_YEAR));
    normalisedDays = normalisedDays.add(months.multiply(BigInteger.valueOf(DAYS_PER_MONTH)));
    normalisedDays = normalisedDays.add(days);

    BigInteger hours = (BigInteger) duration.getField(DatatypeConstants.HOURS);
    BigInteger minutes = (BigInteger) duration.getField(DatatypeConstants.MINUTES);
    BigDecimal seconds = (BigDecimal) duration.getField(DatatypeConstants.SECONDS);

    boolean positive = duration.getSign() >= 0;

    return FACTORY.newDuration(positive, BigInteger.ZERO, BigInteger.ZERO, normalisedDays, hours, minutes,
            seconds);
}

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;/*  w  w w.j  a  va2s  .  co 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.test.DummyAuditService.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.");

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

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

    Iterator<AuditEventRecord> iterator = records.iterator();
    while (iterator.hasNext()) {
        AuditEventRecord record = iterator.next();
        Long timestamp = record.getTimestamp();
        if (timestamp == null) {
            continue;
        }

        if (timestamp < minValue) {
            iterator.remove();
        }
    }
}

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 2  s  .co m*/
    }

    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.");
    }
}