Example usage for javax.xml.datatype XMLGregorianCalendar compare

List of usage examples for javax.xml.datatype XMLGregorianCalendar compare

Introduction

In this page you can find the example usage for javax.xml.datatype XMLGregorianCalendar compare.

Prototype

public abstract int compare(XMLGregorianCalendar xmlGregorianCalendar);

Source Link

Document

Compare two instances of W3C XML Schema 1.0 date/time datatypes according to partial order relation defined in <a href="http://www.w3.org/TR/xmlschema-2/#dateTime-order">W3C XML Schema 1.0 Part 2, Section 3.2.7.3, <i>Order relation on dateTime</i></a>.

Usage

From source file:DatatypeAPIUsage.java

public static void main(String[] args) {
    try {/*from w  ww .  j  a v a2s  .  c  o  m*/
        DatatypeFactory df = DatatypeFactory.newInstance();
        // my work number in milliseconds:
        Duration myPhone = df.newDuration(9054133519l);
        Duration myLife = df.newDuration(true, 29, 2, 15, 13, 45, 0);
        int compareVal = myPhone.compare(myLife);
        switch (compareVal) {
        case DatatypeConstants.LESSER:
            System.out.println("There are fewer milliseconds in my phone number than my lifespan.");
            break;
        case DatatypeConstants.EQUAL:
            System.out.println("The same number of milliseconds are in my phone number and my lifespan.");
            break;
        case DatatypeConstants.GREATER:
            System.out.println("There are more milliseconds in my phone number than my lifespan.");
            break;
        case DatatypeConstants.INDETERMINATE:
            System.out.println("The comparison could not be carried out.");
        }

        // create a yearMonthDuration
        Duration ymDuration = df.newDurationYearMonth("P12Y10M");
        System.out.println("P12Y10M is of type: " + ymDuration.getXMLSchemaType());

        // create a dayTimeDuration (really this time)
        Duration dtDuration = df.newDurationDayTime("P10DT10H12M0S");
        System.out.println("P10DT10H12M0S is of type: " + dtDuration.getXMLSchemaType());

        // try to fool the factory!
        try {
            ymDuration = df.newDurationYearMonth("P12Y10M1D");
        } catch (IllegalArgumentException e) {
            System.out.println("'duration': P12Y10M1D is not 'yearMonthDuration'!!!");
        }

        XMLGregorianCalendar xgc = df.newXMLGregorianCalendar();
        xgc.setYear(1975);
        xgc.setMonth(DatatypeConstants.AUGUST);
        xgc.setDay(11);
        xgc.setHour(6);
        xgc.setMinute(44);
        xgc.setSecond(0);
        xgc.setMillisecond(0);
        xgc.setTimezone(5);
        xgc.add(myPhone);
        System.out.println("The approximate end of the number of milliseconds in my phone number was " + xgc);

        // adding a duration to XMLGregorianCalendar
        xgc.add(myLife);
        System.out.println("Adding the duration myLife to the above calendar:" + xgc);

        // create a new XMLGregorianCalendar using the string format of xgc.
        XMLGregorianCalendar xgcCopy = df.newXMLGregorianCalendar(xgc.toXMLFormat());

        // should be equal-if not what happened!!
        if (xgcCopy.compare(xgc) != DatatypeConstants.EQUAL) {
            System.out.println("oooops!");
        } else {
            System.out.println("Very good: " + xgc + " is equal to " + xgcCopy);
        }
    } catch (DatatypeConfigurationException dce) {
        System.err.println("error: Datatype error occurred - " + dce.getMessage());
        dce.printStackTrace(System.err);
    }
}

From source file:Main.java

/**
 * Validate that the current time falls between the two boundaries
 *
 * @param now//w  w  w  . j a v  a  2  s  .c om
 * @param notbefore
 * @param notOnOrAfter
 *
 * @return
 */
public static boolean isValid(XMLGregorianCalendar now, XMLGregorianCalendar notbefore,
        XMLGregorianCalendar notOnOrAfter) {
    int val = 0;

    if (notbefore != null) {
        val = notbefore.compare(now);

        if (val == DatatypeConstants.INDETERMINATE || val == DatatypeConstants.GREATER)
            return false;
    }

    if (notOnOrAfter != null) {
        val = notOnOrAfter.compare(now);

        if (val != DatatypeConstants.GREATER)
            return false;
    }

    return true;
}

From source file:Main.java

public static Duration subtract(XMLGregorianCalendar x1, XMLGregorianCalendar x2) {
    boolean positive = x1.compare(x2) >= 0;

    if (!positive) {
        XMLGregorianCalendar temp = x1;
        x1 = x2;/*from w  w  w. jav a 2  s. c  o  m*/
        x2 = temp;
    }

    BigDecimal s1 = getSeconds(x1);
    BigDecimal s2 = getSeconds(x2);
    BigDecimal seconds = s1.subtract(s2);
    if (seconds.compareTo(BigDecimal.ZERO) < 0)
        seconds = seconds.add(BigDecimal.valueOf(60));

    GregorianCalendar g1 = x1.toGregorianCalendar();
    GregorianCalendar g2 = x2.toGregorianCalendar();

    int year = 0;
    for (int f : reverseFields) {
        if (f == Calendar.YEAR) {
            int year1 = g1.get(f);
            int year2 = g2.get(f);
            year = year1 - year2;
        } else {
            subtractField(g1, g2, f);
        }
    }

    return FACTORY.newDuration(positive, BigInteger.valueOf(year), BigInteger.valueOf(g1.get(Calendar.MONTH)),
            BigInteger.valueOf(g1.get(Calendar.DAY_OF_MONTH) - 1),
            BigInteger.valueOf(g1.get(Calendar.HOUR_OF_DAY)), BigInteger.valueOf(g1.get(Calendar.MINUTE)),
            seconds);
}

From source file:eionet.cr.util.sesame.ResultCompareUtil.java

/**
 *
 * @param bs1//from ww  w .  jav a 2  s  . c  om
 * @param bs2
 * @param bNodeMapping
 * @return
 */
private static boolean bindingSetsMatch(BindingSet bs1, BindingSet bs2, Map<BNode, BNode> bNodeMapping) {

    if (bs1.size() != bs2.size()) {
        return false;
    }

    for (Binding binding1 : bs1) {
        Value value1 = binding1.getValue();
        Value value2 = bs2.getValue(binding1.getName());

        if (value1 instanceof BNode && value2 instanceof BNode) {
            BNode mappedBNode = bNodeMapping.get(value1);

            if (mappedBNode != null) {
                // bNode 'value1' was already mapped to some other bNode
                if (!value2.equals(mappedBNode)) {
                    // 'value1' and 'value2' do not match
                    return false;
                }
            } else {
                // 'value1' was not yet mapped, we need to check if 'value2' is a
                // possible mapping candidate
                if (bNodeMapping.containsValue(value2)) {
                    // 'value2' is already mapped to some other value.
                    return false;
                }
            }
        } else {

            if (!StringUtils.equals(value1.stringValue(), value2.stringValue())) {
                return false;
            }
            // values are not (both) bNodes
            if (value1 instanceof Literal && value2 instanceof Literal) {
                // do literal value-based comparison for supported datatypes
                Literal leftLit = (Literal) value1;
                Literal rightLit = (Literal) value2;

                URI dt1 = leftLit.getDatatype();
                URI dt2 = rightLit.getDatatype();

                if (dt1 != null && dt2 != null && dt1.equals(dt2)
                        && XMLDatatypeUtil.isValidValue(leftLit.getLabel(), dt1)
                        && XMLDatatypeUtil.isValidValue(rightLit.getLabel(), dt2)) {
                    Integer compareResult = null;
                    if (dt1.equals(XMLSchema.DOUBLE)) {
                        compareResult = Double.compare(leftLit.doubleValue(), rightLit.doubleValue());
                    } else if (dt1.equals(XMLSchema.FLOAT)) {
                        compareResult = Float.compare(leftLit.floatValue(), rightLit.floatValue());
                    } else if (dt1.equals(XMLSchema.DECIMAL)) {
                        compareResult = leftLit.decimalValue().compareTo(rightLit.decimalValue());
                    } else if (XMLDatatypeUtil.isIntegerDatatype(dt1)) {
                        compareResult = leftLit.integerValue().compareTo(rightLit.integerValue());
                    } else if (dt1.equals(XMLSchema.BOOLEAN)) {
                        Boolean leftBool = Boolean.valueOf(leftLit.booleanValue());
                        Boolean rightBool = Boolean.valueOf(rightLit.booleanValue());
                        compareResult = leftBool.compareTo(rightBool);
                    } else if (XMLDatatypeUtil.isCalendarDatatype(dt1)) {
                        XMLGregorianCalendar left = leftLit.calendarValue();
                        XMLGregorianCalendar right = rightLit.calendarValue();

                        compareResult = left.compare(right);
                    }

                    if (compareResult != null) {
                        if (compareResult.intValue() != 0) {
                            return false;
                        }
                    } else if (!value1.equals(value2)) {
                        return false;
                    }
                } else if (!value1.equals(value2)) {
                    return false;
                }
            } else if (!value1.equals(value2)) {
                return false;
            }
        }
    }

    return true;
}

From source file:com.evolveum.midpoint.util.MiscUtil.java

public static boolean isBetween(XMLGregorianCalendar date, XMLGregorianCalendar start,
        XMLGregorianCalendar end) {
    return (date.compare(start) == DatatypeConstants.GREATER || date.compare(start) == DatatypeConstants.EQUAL)
            && (date.compare(end) == DatatypeConstants.LESSER || date.compare(end) == DatatypeConstants.EQUAL);
}

From source file:com.evolveum.midpoint.test.util.TestUtil.java

public static void assertEqualsTimestamp(String message, XMLGregorianCalendar expected,
        XMLGregorianCalendar actual) {
    assertNotNull(message + "; expected " + expected, actual);
    assertTrue(message + "; expected " + expected + " but was " + actual, expected.compare(actual) == 0);
}

From source file:com.evolveum.midpoint.test.util.TestUtil.java

public static void assertBetween(String message, XMLGregorianCalendar start, XMLGregorianCalendar end,
        XMLGregorianCalendar actual) {
    assertNotNull(message + " is null", actual);
    if (start != null) {
        assertTrue(message + ": expected time to be after " + start + " but it was " + actual,
                actual.compare(start) == DatatypeConstants.GREATER
                        || actual.compare(start) == DatatypeConstants.EQUAL);
    }/*  w  w  w. j av  a2  s.c om*/
    if (end != null) {
        assertTrue(message + ": expected time to be before " + end + " but it was " + actual,
                actual.compare(end) == DatatypeConstants.LESSER
                        || actual.compare(end) == DatatypeConstants.EQUAL);
    }
}

From source file:com.evolveum.midpoint.model.common.stringpolicy.ObjectValuePolicyEvaluator.java

private void validateMinAge(List<LocalizableMessage> messages, OperationResult result) {
    if (oldCredentialType == null) {
        return;/*w  w  w. j  a  v  a  2s.c o  m*/
    }
    Duration minAge = getMinAge();
    if (minAge == null) {
        return;
    }
    MetadataType currentCredentialMetadata = oldCredentialType.getMetadata();
    if (currentCredentialMetadata == null) {
        return;
    }
    XMLGregorianCalendar lastChangeTimestamp = currentCredentialMetadata.getModifyTimestamp();
    if (lastChangeTimestamp == null) {
        lastChangeTimestamp = currentCredentialMetadata.getCreateTimestamp();
    }
    if (lastChangeTimestamp == null) {
        return;
    }

    XMLGregorianCalendar changeAllowedTimestamp = XmlTypeConverter.addDuration(lastChangeTimestamp, minAge);
    if (changeAllowedTimestamp.compare(now) == DatatypeConstants.GREATER) {
        LOGGER.trace("Password minAge violated. lastChange={}, minAge={}, now={}", lastChangeTimestamp, minAge,
                now);
        LocalizableMessage msg = LocalizableMessageBuilder.buildKey("ValuePolicy.minAgeNotReached");
        result.addSubresult(
                new OperationResult("Password minimal age", OperationResultStatus.FATAL_ERROR, msg));
        messages.add(msg);
    }
}

From source file:com.evolveum.midpoint.model.common.stringpolicy.ObjectValuePolicyEvaluator.java

private List<PasswordHistoryEntryType> getSortedHistoryList(
        PrismContainer<PasswordHistoryEntryType> historyEntries, boolean ascending) {
    if (historyEntries == null || historyEntries.isEmpty()) {
        return new ArrayList<>();
    }//from  w  w  w. j  ava  2s .  c o  m
    List<PasswordHistoryEntryType> historyEntryValues = (List<PasswordHistoryEntryType>) historyEntries
            .getRealValues();

    historyEntryValues.sort((o1, o2) -> {
        XMLGregorianCalendar changeTimestampFirst = o1.getChangeTimestamp();
        XMLGregorianCalendar changeTimestampSecond = o2.getChangeTimestamp();

        if (ascending) {
            return changeTimestampFirst.compare(changeTimestampSecond);
        } else {
            return changeTimestampSecond.compare(changeTimestampFirst);
        }
    });
    return historyEntryValues;
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

public boolean checkRSS() throws Exception {
    if (forceAll || pages == null || pages.isEmpty()) {
        return false;
    }/*from www.  jav  a 2s.c  o  m*/
    URL url = new URL(ROOT + "/createrssfeed.action?types=page&types=blogpost&types=mail&"
    //+ "types=comment&"  //cannot handle comment updates yet
            + "types=attachment&statuses=created&statuses=modified" + "&spaces=" + spaceKey
            + "&rssType=atom&maxResults=20&timeSpan=2" + "&publicFeed=true");
    InputStream ins = url.openStream();
    Document doc = StaxUtils.read(ins);
    ins.close();
    List<Element> els = DOMUtils.getChildrenWithName(doc.getDocumentElement(), "http://www.w3.org/2005/Atom",
            "entry");
    // XMLUtils.printDOM(doc);
    for (Element el : els) {
        Element e2 = DOMUtils.getFirstChildWithName(el, "http://www.w3.org/2005/Atom", "updated");
        String val = DOMUtils.getContent(e2);
        XMLGregorianCalendar cal = DatatypeFactory.newInstance().newXMLGregorianCalendar(val);
        e2 = DOMUtils.getFirstChildWithName(el, "http://www.w3.org/2005/Atom", "title");
        String title = DOMUtils.getContent(e2);

        Page p = findPage(title);
        if (p != null) {
            //found a modified page - need to rebuild
            if (cal.compare(p.getModifiedTime()) > 0) {
                System.out.println("(" + spaceKey + ") Changed page found: " + title);
                return false;
            }
        } else {
            BlogEntrySummary entry = findBlogEntry(title);
            if (entry != null) {
                // we don't have modified date so just assume it's modified
                // we'll use version number to actually figure out if page is modified or not
                System.out.println("(" + spaceKey + ") Possible changed blog page found: " + title);
                return false;
            } else {
                System.out.println("(" + spaceKey + ") Did not find page for: " + title);
                return false;
            }
        }
    }

    return true;
}