Search in sources :

Example 61 with Duration

use of javax.xml.datatype.Duration in project Tundra by Permafrost.

the class service method retry.

public static final void retry(IData pipeline) throws ServiceException {
    // --- <<IS-START(retry)>> ---
    // @subtype unknown
    // @sigtype java 3.5
    // [i] field:0:required $service
    // [i] record:0:optional $pipeline
    // [i] field:0:optional $retry.limit
    // [i] field:0:optional $retry.wait
    // [i] field:0:optional $retry.factor
    // [i] field:0:optional $thread.priority
    // [o] record:0:optional $pipeline
    // [o] field:0:optional $duration
    // [o] field:0:optional $retry.count
    IDataCursor cursor = pipeline.getCursor();
    Thread currentThread = Thread.currentThread();
    int currentThreadPriority = currentThread.getPriority();
    boolean changeThreadPriority = false;
    try {
        IData scope = IDataHelper.remove(cursor, "$pipeline", IData.class);
        boolean scoped = scope != null;
        if (!scoped)
            scope = IDataHelper.clone(pipeline, "$service", "$mode", "$raise?", "$retry.limit", "$retry.wait", "$retry.factor");
        String service = IDataHelper.get(cursor, "$service", String.class);
        int retryLimit = IDataHelper.getOrDefault(cursor, "$retry.limit", Integer.class, 0);
        Duration retryWait = IDataHelper.get(cursor, "$retry.wait", Duration.class);
        float retryFactor = IDataHelper.getOrDefault(cursor, "$retry.factor", Float.class, 1.0f);
        BigDecimal newThreadPriority = IDataHelper.get(cursor, "$thread.priority", BigDecimal.class);
        if (newThreadPriority != null) {
            int priority = ThreadHelper.normalizePriority(newThreadPriority.intValue());
            changeThreadPriority = priority != currentThreadPriority;
            if (changeThreadPriority)
                currentThread.setPriority(priority);
        }
        int retryCount = 0;
        long retryWaitMilliseconds = retryWait == null ? 0 : retryWait.getTimeInMillis(Calendar.getInstance());
        long start = System.nanoTime();
        while (!Thread.interrupted()) {
            IData invokePipeline = IDataHelper.clone(scope);
            try {
                invokePipeline = ServiceHelper.invoke(service, invokePipeline, true, false, true);
                scope = invokePipeline;
                break;
            } catch (ServiceException ex) {
                if (retryCount < retryLimit) {
                    long wait = retryWaitMilliseconds * Double.valueOf(Math.pow(retryFactor, retryCount - 1)).longValue();
                    retryCount++;
                    Thread.sleep(wait);
                } else {
                    throw ex;
                }
            }
        }
        long end = System.nanoTime();
        if (scoped) {
            IDataHelper.put(cursor, "$pipeline", scope);
        } else {
            IDataHelper.mergeInto(pipeline, scope);
        }
        IDataHelper.put(cursor, "$duration", DurationHelper.format(end - start, DurationPattern.NANOSECONDS, DurationPattern.XML_MILLISECONDS));
        IDataHelper.put(cursor, "$retry.count", retryCount, String.class);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        ExceptionHelper.raiseUnchecked(ex);
    } finally {
        if (changeThreadPriority)
            currentThread.setPriority(currentThreadPriority);
        cursor.destroy();
    }
// --- <<IS-END>> ---
}
Also used : ServiceException(com.wm.app.b2b.server.ServiceException) Duration(javax.xml.datatype.Duration) BigDecimal(java.math.BigDecimal) ServiceThread(com.wm.app.b2b.server.ServiceThread)

Example 62 with Duration

use of javax.xml.datatype.Duration in project Tundra by Permafrost.

the class file method purge.

public static final void purge(IData pipeline) throws ServiceException {
    // --- <<IS-START(purge)>> ---
    // @subtype unknown
    // @sigtype java 3.5
    // [i] field:0:required $directory
    // [i] field:0:required $duration
    // [i] field:0:optional $duration.pattern {&quot;xml&quot;,&quot;milliseconds&quot;,&quot;seconds&quot;,&quot;minutes&quot;,&quot;hours&quot;,&quot;days&quot;,&quot;weeks&quot;,&quot;months&quot;,&quot;years&quot;}
    // [o] field:0:required $purged?
    // [o] field:0:optional $count
    IDataCursor cursor = pipeline.getCursor();
    try {
        File directory = IDataHelper.get(cursor, "$directory", File.class);
        String durationString = IDataHelper.get(cursor, "$duration", String.class);
        String durationPattern = IDataHelper.get(cursor, "$duration.pattern", String.class);
        Duration duration = DurationHelper.parse(durationString, durationPattern);
        boolean shouldPurge = shouldPurge(directory, duration);
        if (shouldPurge) {
            long count = DirectoryHelper.purge(directory, duration, null, false);
            hasPurged(directory);
            IDataHelper.put(cursor, "$count", count, String.class);
        }
        IDataHelper.put(cursor, "$purged?", shouldPurge, String.class);
    } catch (FileNotFoundException ex) {
        ExceptionHelper.raise(ex);
    } finally {
        cursor.destroy();
    }
// --- <<IS-END>> ---
}
Also used : FileNotFoundException(java.io.FileNotFoundException) Duration(javax.xml.datatype.Duration) File(java.io.File)

Example 63 with Duration

use of javax.xml.datatype.Duration in project Tundra by Permafrost.

the class memory method replace.

public static final void replace(IData pipeline) throws ServiceException {
    // --- <<IS-START(replace)>> ---
    // @subtype unknown
    // @sigtype java 3.5
    // [i] field:0:required $cache.name
    // [i] field:0:required $cache.key
    // [i] object:0:optional $cache.value.old
    // [i] object:0:required $cache.value.new
    // [i] field:0:optional $cache.expiry.duration
    // [i] field:0:optional $cache.expiry.datetime
    // [o] field:0:required $cache.value.replaced? {"false","true"}
    IDataCursor cursor = pipeline.getCursor();
    try {
        String name = IDataHelper.get(cursor, "$cache.name", String.class);
        String key = IDataHelper.get(cursor, "$cache.key", String.class);
        Object oldValue = IDataHelper.get(cursor, "$cache.value.old", Object.class);
        Object newValue = IDataHelper.get(cursor, "$cache.value.new", Object.class);
        Duration expiryDuration = IDataHelper.get(cursor, "$cache.expiry.duration", Duration.class);
        Calendar expiryDateTime = IDataHelper.get(cursor, "$cache.expiry.datetime", Calendar.class);
        boolean replaced;
        if (expiryDuration != null) {
            replaced = CacheManager.getInstance().replace(name, key, oldValue, newValue, expiryDuration);
        } else {
            replaced = CacheManager.getInstance().replace(name, key, oldValue, newValue, expiryDateTime);
        }
        IDataHelper.put(cursor, "$cache.value.replaced?", replaced, String.class);
    } finally {
        cursor.destroy();
    }
// --- <<IS-END>> ---
}
Also used : Calendar(java.util.Calendar) Duration(javax.xml.datatype.Duration)

Example 64 with Duration

use of javax.xml.datatype.Duration in project ldp-coap-framework by sisinflab-swot.

the class DurationImpl method add.

/**
 * <p>Computes a new duration whose value is <code>this+rhs</code>.</p>
 *
 * <p>For example,</p>
 * <pre>
 * "1 day" + "-3 days" = "-2 days"
 * "1 year" + "1 day" = "1 year and 1 day"
 * "-(1 hour,50 minutes)" + "-20 minutes" = "-(1 hours,70 minutes)"
 * "15 hours" + "-3 days" = "-(2 days,9 hours)"
 * "1 year" + "-1 day" = IllegalStateException
 * </pre>
 *
 * <p>Since there's no way to meaningfully subtract 1 day from 1 month,
 * there are cases where the operation fails in
 * {@link IllegalStateException}.</p>
 *
 * <p>
 * Formally, the computation is defined as follows.</p>
 * <p>
 * Firstly, we can assume that two {@link Duration}s to be added
 * are both positive without losing generality (i.e.,
 * <code>(-X)+Y=Y-X</code>, <code>X+(-Y)=X-Y</code>,
 * <code>(-X)+(-Y)=-(X+Y)</code>)
 *
 * <p>
 * Addition of two positive {@link Duration}s are simply defined as
 * field by field addition where missing fields are treated as 0.
 * <p>
 * A field of the resulting {@link Duration} will be unset if and
 * only if respective fields of two input {@link Duration}s are unset.
 * <p>
 * Note that <code>lhs.add(rhs)</code> will be always successful if
 * <code>lhs.signum()*rhs.signum()!=-1</code> or both of them are
 * normalized.</p>
 *
 * @param rhs <code>Duration</code> to add to this <code>Duration</code>
 *
 * @return
 *      non-null valid Duration object.
 *
 * @throws NullPointerException
 *      If the rhs parameter is null.
 * @throws IllegalStateException
 *      If two durations cannot be meaningfully added. For
 *      example, adding negative one day to one month causes
 *      this exception.
 *
 * @see #subtract(Duration)
 */
public Duration add(final Duration rhs) {
    Duration lhs = this;
    BigDecimal[] buf = new BigDecimal[6];
    buf[0] = sanitize((BigInteger) lhs.getField(DatatypeConstants.YEARS), lhs.getSign()).add(sanitize((BigInteger) rhs.getField(DatatypeConstants.YEARS), rhs.getSign()));
    buf[1] = sanitize((BigInteger) lhs.getField(DatatypeConstants.MONTHS), lhs.getSign()).add(sanitize((BigInteger) rhs.getField(DatatypeConstants.MONTHS), rhs.getSign()));
    buf[2] = sanitize((BigInteger) lhs.getField(DatatypeConstants.DAYS), lhs.getSign()).add(sanitize((BigInteger) rhs.getField(DatatypeConstants.DAYS), rhs.getSign()));
    buf[3] = sanitize((BigInteger) lhs.getField(DatatypeConstants.HOURS), lhs.getSign()).add(sanitize((BigInteger) rhs.getField(DatatypeConstants.HOURS), rhs.getSign()));
    buf[4] = sanitize((BigInteger) lhs.getField(DatatypeConstants.MINUTES), lhs.getSign()).add(sanitize((BigInteger) rhs.getField(DatatypeConstants.MINUTES), rhs.getSign()));
    buf[5] = sanitize((BigDecimal) lhs.getField(DatatypeConstants.SECONDS), lhs.getSign()).add(sanitize((BigDecimal) rhs.getField(DatatypeConstants.SECONDS), rhs.getSign()));
    // align sign
    // Y,M
    alignSigns(buf, 0, 2);
    // D,h,m,s
    alignSigns(buf, 2, 6);
    // make sure that the sign bit is consistent across all 6 fields.
    int s = 0;
    for (int i = 0; i < 6; i++) {
        if (s * buf[i].signum() < 0) {
            throw new IllegalStateException();
        }
        if (s == 0) {
            s = buf[i].signum();
        }
    }
    return new DurationImpl(s >= 0, toBigInteger(sanitize(buf[0], s), lhs.getField(DatatypeConstants.YEARS) == null && rhs.getField(DatatypeConstants.YEARS) == null), toBigInteger(sanitize(buf[1], s), lhs.getField(DatatypeConstants.MONTHS) == null && rhs.getField(DatatypeConstants.MONTHS) == null), toBigInteger(sanitize(buf[2], s), lhs.getField(DatatypeConstants.DAYS) == null && rhs.getField(DatatypeConstants.DAYS) == null), toBigInteger(sanitize(buf[3], s), lhs.getField(DatatypeConstants.HOURS) == null && rhs.getField(DatatypeConstants.HOURS) == null), toBigInteger(sanitize(buf[4], s), lhs.getField(DatatypeConstants.MINUTES) == null && rhs.getField(DatatypeConstants.MINUTES) == null), (buf[5].signum() == 0 && lhs.getField(DatatypeConstants.SECONDS) == null && rhs.getField(DatatypeConstants.SECONDS) == null) ? null : sanitize(buf[5], s));
}
Also used : Duration(javax.xml.datatype.Duration) BigDecimal(java.math.BigDecimal)

Example 65 with Duration

use of javax.xml.datatype.Duration in project ldp-coap-framework by sisinflab-swot.

the class XMLGregorianCalendarImpl method normalizeToTimezone.

/**
 * <p>Normalize this instance to UTC.</p>
 *
 * <p>2000-03-04T23:00:00+03:00 normalizes to 2000-03-04T20:00:00Z</p>
 * <p>Implements W3C XML Schema Part 2, Section 3.2.7.3 (A).</p>
 */
private XMLGregorianCalendar normalizeToTimezone(XMLGregorianCalendar cal, int timezone) {
    int minutes = timezone;
    XMLGregorianCalendar result = (XMLGregorianCalendar) cal.clone();
    // normalizing to UTC time negates the timezone offset before
    // addition.
    minutes = -minutes;
    Duration d = new // isPositive
    DurationImpl(// isPositive
    minutes >= 0, // years
    0, // months
    0, // days
    0, // hours
    0, // absolute
    minutes < 0 ? -minutes : minutes, // seconds
    0);
    result.add(d);
    // set to zulu UTC time.
    result.setTimezone(0);
    return result;
}
Also used : XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) Duration(javax.xml.datatype.Duration)

Aggregations

Duration (javax.xml.datatype.Duration)137 XMLGregorianCalendar (javax.xml.datatype.XMLGregorianCalendar)57 Test (org.junit.Test)16 ArrayList (java.util.ArrayList)14 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)12 Date (java.util.Date)12 BigDecimal (java.math.BigDecimal)9 Calendar (java.util.Calendar)9 GregorianCalendar (java.util.GregorianCalendar)9 ObjectDeltaType (com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType)8 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)7 CleanupPolicyType (com.evolveum.midpoint.xml.ns._public.common.common_3.CleanupPolicyType)6 ItemDelta (com.evolveum.midpoint.prism.delta.ItemDelta)5 IOException (java.io.IOException)5 XSDayTimeDuration (org.eclipse.wst.xml.xpath2.processor.internal.types.XSDayTimeDuration)5 FileNotFoundException (java.io.FileNotFoundException)4 Collection (java.util.Collection)4 DatatypeFactory (javax.xml.datatype.DatatypeFactory)4 NotNull (org.jetbrains.annotations.NotNull)4 PrismObject (com.evolveum.midpoint.prism.PrismObject)3