Java Code Examples for javax.xml.datatype.Duration#getDays()

The following examples show how to use javax.xml.datatype.Duration#getDays() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DoubleDurationType.java    From jdmn with Apache License 2.0 6 votes vote down vote up
@Override
public Duration durationDivide(Duration first, Double second) {
    if (first == null || second == null) {
        return null;
    }

    try {
        if (isYearsAndMonths(first)) {
            long months = (first.getYears() * 12 + first.getMonths()) / second.intValue();
            return this.dataTypeFactory.newDurationYearMonth(String.format("P%dM", months));
        } else if (isDaysAndTime(first)) {
            long hours = 24L * first.getDays() + first.getHours();
            long minutes = 60L * hours + first.getMinutes();
            long seconds = 60L * minutes + first.getSeconds();
            seconds = seconds / second.intValue();
            return this.dataTypeFactory.newDurationDayTime(seconds * 1000L);
        } else {
            throw new DMNRuntimeException(String.format("Cannot divide '%s' by '%s'", first, second));
        }
    } catch (Exception e) {
        String message = String.format("durationDivide(%s, %s)", first, second);
        logError(message, e);
        return null;
    }
}
 
Example 2
Source File: DefaultDurationType.java    From jdmn with Apache License 2.0 6 votes vote down vote up
@Override
public Duration durationDivide(Duration first, BigDecimal second) {
    if (first == null || second == null) {
        return null;
    }

    try {
        if (isYearsAndMonths(first)) {
            long months = (first.getYears() * 12 + first.getMonths()) / second.intValue();
            return this.dataTypeFactory.newDurationYearMonth(String.format("P%dM", months));
        } else if (isDaysAndTime(first)) {
            long hours = 24L * first.getDays() + first.getHours();
            long minutes = 60L * hours + first.getMinutes();
            long seconds = 60L * minutes + first.getSeconds();
            seconds = seconds / second.intValue();
            return this.dataTypeFactory.newDurationDayTime(seconds * 1000L);
        } else {
            throw new DMNRuntimeException(String.format("Cannot divide '%s' by '%s'", first, second));
        }
    } catch (Exception e) {
        String message = String.format("durationDivide(%s, %s)", first, second);
        logError(message, e);
        return null;
    }
}
 
Example 3
Source File: ContextInfo.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
public static Validity parse(String duration) {
    try {
        if (dtFactory == null) {
            dtFactory = DatatypeFactory.newInstance();
        }
        Duration d = dtFactory.newDuration(duration);
        Validity result = new Validity(
                d.getYears(),
                d.getMonths(),
                d.getDays()
        );
        return result;
    } catch (DatatypeConfigurationException e) {
        throw new SlaGeneratorException("Could not instantiate DatatypeFactory", e);
    }
}
 
Example 4
Source File: DefaultDurationLib.java    From jdmn with Apache License 2.0 5 votes vote down vote up
public Integer days(Duration duration) {
    if (duration == null) {
        return null;
    }

    return duration.getDays();
}
 
Example 5
Source File: Bug6937964Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testNewDurationDayTimeLexicalRepresentation() throws DatatypeConfigurationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance();
    Duration d = dtf.newDurationDayTime("P1DT23H59M65S");
    int days = d.getDays();
    Assert.assertTrue(days == 2, "Return value should be normalized");
}
 
Example 6
Source File: Bug6937964Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testNewDurationDayTimeMilliseconds() throws DatatypeConfigurationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance();
    Duration d = dtf.newDurationDayTime(172805000L);
    int days = d.getDays();
    Assert.assertTrue(days == 2, "Return value should be normalized");
}
 
Example 7
Source File: Bug6937964Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testNewDurationDayTimeBigInteger() throws DatatypeConfigurationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance();
    BigInteger day = new BigInteger("1");
    BigInteger hour = new BigInteger("23");
    BigInteger min = new BigInteger("59");
    BigInteger sec = new BigInteger("65");
    Duration d = dtf.newDurationDayTime(true, day, hour, min, sec);
    int days = d.getDays();
    System.out.println("Days: " + days);
    Assert.assertTrue(days == 2, "Return value should be normalized");
}
 
Example 8
Source File: Bug6937964Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testNewDurationDayTimeInt() throws DatatypeConfigurationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance();
    Duration d = dtf.newDurationDayTime(true, 1, 23, 59, 65);
    int days = d.getDays();
    System.out.println("Days: " + days);
    Assert.assertTrue(days == 2, "Return value should be normalized");
}
 
Example 9
Source File: Utils.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * converts duration, e.g. PTxxxM to minute int xxx
 * 
 * @param d
 * @return
 */
public static int duration2Minutes(Duration d) {
	long millis = d.getYears() * 12;
	millis = (millis + d.getMonths()) * 31;
	millis = (millis + d.getDays()) * 24;
	millis = (millis + d.getHours()) * 60;
	millis = (millis + d.getMinutes()) * 60;
	millis = (millis + d.getSeconds()) * 1000;

	int minutes = (int) (millis / 60 / 1000) * d.getSign();
	// logger.debug("Duration: "+d+" = "+minutes+" min");
	return minutes;
}
 
Example 10
Source File: DurationTypeInfoCompiler.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public JSAssignmentExpression createValue(MappingCompiler<T, C> mappingCompiler, String item) {
	final JSCodeModel codeModel = mappingCompiler.getCodeModel();
	final JSObjectLiteral result = codeModel.object();
	final Duration duration = datatypeFactory.newDuration(item);
	if (duration.getSign() <= 0) {
		result.append("sign", codeModel.integer(duration.getSign()));
	}
	if (duration.getYears() > 0) {
		result.append("years", codeModel.integer(duration.getYears()));
	}
	if (duration.getMonths() > 0) {
		result.append("months", codeModel.integer(duration.getMonths()));
	}
	if (duration.getDays() > 0) {
		result.append("days", codeModel.integer(duration.getDays()));
	}
	if (duration.getHours() > 0) {
		result.append("hours", codeModel.integer(duration.getHours()));
	}
	if (duration.getMinutes() > 0) {
		result.append("minutes", codeModel.integer(duration.getMinutes()));
	}
	if (duration.getSeconds() > 0) {
		result.append("seconds", codeModel.integer(duration.getSeconds()));
	}
	return result;
}
 
Example 11
Source File: DurationTypeInfoProducer.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public JsonValue createValue(JsonSchemaMappingCompiler<T, C> mappingCompiler, String item) {
	final JsonObjectBuilder objectBuilder = mappingCompiler.getJsonBuilderFactory().createObjectBuilder();
	final Duration duration = datatypeFactory.newDuration(item);
	if (duration.getSign() <= 0) {
		objectBuilder.add("sign", duration.getSign());
	}
	if (duration.getYears() > 0) {
		objectBuilder.add("years", duration.getYears());
	}
	if (duration.getMonths() > 0) {
		objectBuilder.add("months", duration.getMonths());
	}
	if (duration.getDays() > 0) {
		objectBuilder.add("days", duration.getDays());
	}
	if (duration.getHours() > 0) {
		objectBuilder.add("hours", duration.getHours());
	}
	if (duration.getMinutes() > 0) {
		objectBuilder.add("minutes", duration.getMinutes());
	}
	if (duration.getSeconds() > 0) {
		objectBuilder.add("seconds", duration.getSeconds());
	}
	return objectBuilder.build();
}
 
Example 12
Source File: TM_PeriodDuration.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the given Java XML duration into an ISO 19108 duration.
 */
static PeriodDuration toISO(final Duration duration) {
    if (duration != null) try {
        final TemporalFactory factory = TemporalUtilities.getTemporalFactory();
        InternationalString years = null;
        int value;
        if ((value = duration.getYears()) != 0) {
            years = new SimpleInternationalString(Integer.toString(value));
        }
        InternationalString months = null;
        if ((value = duration.getMonths()) != 0) {
            months = new SimpleInternationalString(Integer.toString(value));
        }
        InternationalString weeks = null;                   // No weeks in javax.xml.datatype.Duration
        InternationalString days = null;
        if ((value = duration.getDays()) != 0) {
            days = new SimpleInternationalString(Integer.toString(value));
        }
        InternationalString hours = null;
        if ((value = duration.getHours()) != 0) {
            hours = new SimpleInternationalString(Integer.toString(value));
        }
        InternationalString minutes = null;
        if ((value = duration.getMinutes()) != 0) {
            minutes = new SimpleInternationalString(Integer.toString(value));
        }
        InternationalString seconds = null;
        if ((value = duration.getSeconds()) != 0) {
            seconds = new SimpleInternationalString(Integer.toString(value));
        }
        return factory.createPeriodDuration(years, months, weeks, days, hours, minutes, seconds);
    } catch (UnsupportedOperationException e) {
        warningOccured("toISO", e);
    }
    return null;
}
 
Example 13
Source File: DatatypeFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test {@link DatatypeFactory.newDurationYearMonth(long milliseconds)}.
 *
 */
@Test
public final void testNewDurationYearMonthMilliseconds() {

    /**
     * Millisecond test values to test.
     */
    final long[] TEST_VALUES_MILLISECONDS = { 0L, 1L, -1L, 2678400000L, // 31
                                                                        // days,
                                                                        // e.g.
                                                                        // 1
                                                                        // month
            -2678400000L, 5270400000L, // 61 days, e.g. 2 months
            -5270400000L, 31622400000L, // 366 days, e.g. 1 year
            -31622400000L, 34300800000L, // 397 days, e.g. 1 year, 1 month
            -34300800000L };

    /**
     * Millisecond test value results of test.
     */
    final String[] TEST_VALUES_MILLISECONDS_RESULTS = { "P0Y0M", "P0Y0M", "P0Y0M", "P0Y1M", "-P0Y1M", "P0Y2M", "-P0Y2M", "P1Y0M", "-P1Y0M", "P1Y1M",
            "-P1Y1M" };

    DatatypeFactory datatypeFactory = null;
    try {
        datatypeFactory = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException datatypeConfigurationException) {
        Assert.fail(datatypeConfigurationException.toString());
    }

    if (DEBUG) {
        System.err.println("DatatypeFactory created: " + datatypeFactory.toString());
    }

    // test each value
    for (int onTestValue = 0; onTestValue < TEST_VALUES_MILLISECONDS.length; onTestValue++) {

        if (DEBUG) {
            System.err.println("testing value: \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\", expecting: \""
                    + TEST_VALUES_MILLISECONDS_RESULTS[onTestValue] + "\"");
        }

        try {
            Duration duration = datatypeFactory.newDurationYearMonth(TEST_VALUES_MILLISECONDS[onTestValue]);

            if (DEBUG) {
                System.err.println("Duration created: \"" + duration.toString() + "\"");
            }

            // was this expected to fail?
            if (TEST_VALUES_MILLISECONDS_RESULTS[onTestValue].equals(TEST_VALUE_FAIL)) {
                Assert.fail("the value \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" is invalid yet it created the Duration \"" + duration.toString()
                        + "\"");
            }

            // right XMLSchemaType?
            QName xmlSchemaType = duration.getXMLSchemaType();
            if (!xmlSchemaType.equals(DatatypeConstants.DURATION_YEARMONTH)) {
                Assert.fail("Duration created with XMLSchemaType of\"" + xmlSchemaType + "\" was expected to be \"" + DatatypeConstants.DURATION_YEARMONTH
                        + "\" and has the value \"" + duration.toString() + "\"");
            }

            // does it have the right value?
            if (!TEST_VALUES_MILLISECONDS_RESULTS[onTestValue].equals(duration.toString())) {
                Assert.fail("Duration created with \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" was expected to be \""
                        + TEST_VALUES_MILLISECONDS_RESULTS[onTestValue] + "\" and has the value \"" + duration.toString() + "\"");
            }

            // only YEAR & MONTH should have values
            int days = duration.getDays();
            int hours = duration.getHours();
            int minutes = duration.getMinutes();
            if (days != 0 || hours != 0 || minutes != 0) {
                Assert.fail("xdt:yearMonthDuration created without discarding remaining milliseconds: " + " days = " + days + ", hours = " + hours
                        + ", minutess = " + minutes);
            }

            // Duration created with correct values
        } catch (Exception exception) {

            if (DEBUG) {
                System.err.println("Exception in creating duration: \"" + exception.toString() + "\"");
            }

            // was this expected to succed?
            if (!TEST_VALUES_MILLISECONDS_RESULTS[onTestValue].equals(TEST_VALUE_FAIL)) {
                Assert.fail("the value \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" is valid yet it failed with \"" + exception.toString() + "\"");
            }
            // expected failure
        }
    }
}
 
Example 14
Source File: WorkCalendar.java    From lemon with Apache License 2.0 4 votes vote down vote up
/**
 * 计算结束时间.
 */
public Date add(Date startDate, Duration duration) {
    // 得到对应的时间
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(startDate);
    // 添加年数和月数,工作日方面年和月的概念不会改变
    calendar.add(Calendar.YEAR, duration.getYears());
    calendar.add(Calendar.MONTH, duration.getMonths());

    // 天数,小时,分钟可能因为工作日有概念,所以特殊处理
    int day = duration.getDays();
    int hour = duration.getHours();
    int minute = duration.getMinutes();

    if (accurateToDay) {
        // 有时需要自动把一天换算成8个小时,以实际计算工时
        hour += (day * HOUR_OF_DAY);
        day = 0;
    } else {
        Date workDate = this.findWorkDate(calendar.getTime());
        calendar.setTime(workDate);

        // 目前还没有更好的算法,所以对天数累加,再判断是否工作日
        for (int i = 0; i < day; i++) {
            calendar.add(Calendar.DATE, 1);

            int originHour = calendar.get(Calendar.HOUR_OF_DAY);
            int originMinute = calendar.get(Calendar.MINUTE);
            // 如果当前就是工作日,就返回当前时间
            // 如果当前的时间已经不是工作日了就返回最近的工作日
            workDate = this.findWorkDate(calendar.getTime());
            calendar.setTime(workDate);
            calendar.set(Calendar.HOUR_OF_DAY, originHour);
            calendar.set(Calendar.MINUTE, originMinute);
        }
    }

    Date targetDate = calendar.getTime();
    long millis = (hour * MILLIS_OF_HOUR) + (minute * MILLIS_OF_MINUTE);
    DayPart dayPart = this.findDayPart(targetDate);
    boolean isInbusinessHours = (dayPart != null);

    if (!isInbusinessHours) {
        DayPartResult dayPartResult = this.findTargetWorkDay(targetDate)
                .findNextDayPartStart(0, targetDate);
        targetDate = dayPartResult.getDate();
        dayPart = dayPartResult.getDayPart();
    }

    Date end = dayPart.add(targetDate, millis);

    return end;
}