Java Code Examples for javax.xml.datatype.DatatypeFactory#newDuration()

The following examples show how to use javax.xml.datatype.DatatypeFactory#newDuration() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * A time span as defined in the W3C XML Schema 1.0 specification:
 * "PnYnMnDTnHnMnS, where nY represents the number of years, nM the number of months, nD the number of days,
 * 'T' is the date/time separator, nH the number of hours, nM the number of minutes and nS the number of seconds.
 * The number of seconds can include decimal digits to arbitrary precision."
 *
 * @param text parse this text, format PnYnMnDTnHnMnS
 * @return TimeDuration
 * @throws java.text.ParseException when text is misformed
 */
public static TimeDuration parseW3CDuration(String text) throws java.text.ParseException {
  TimeDuration td = new TimeDuration();

  text = (text == null) ? "" : text.trim();
  td.text = text;

  try {
    DatatypeFactory factory = DatatypeFactory.newInstance();
    Duration d = factory.newDuration(text);
    // long secs = d.getTimeInMillis(new Date()) / 1000;

    Calendar c = Calendar.getInstance();
    c.set(1900, 0, 1, 0, 0, 0);
    long secs = d.getTimeInMillis(c.getTime()) / 1000;

    td.timeUnit = new TimeUnit(secs + " secs");
  } catch (Exception e) {
    throw new java.text.ParseException(e.getMessage(), 0);
  }
  return td;
}
 
Example 2
Source Project: keycloak   File: XMLTimeUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Given a string, get the Duration object. The string can be an ISO 8601 period representation (Eg.: P10M) or a
 * numeric
 * value. If a ISO 8601 period, the duration will reflect the defined format. If a numeric (Eg.: 1000) the duration
 * will
 * be calculated in milliseconds.
 *
 * @param timeValue
 *
 * @return
 */
public static Duration parseAsDuration(String timeValue) {
    if (timeValue == null) {
        PicketLinkLoggerFactory.getLogger().nullArgumentError("duration time");
    }

    DatatypeFactory factory = DATATYPE_FACTORY.get();

    try {
        // checks if it is a ISO 8601 period. If not it must be a numeric value.
        if (timeValue.startsWith("P")) {
            return factory.newDuration(timeValue);
        } else {
            return factory.newDuration(Long.valueOf(timeValue));
        }
    } catch (Exception e) {
        throw logger.samlMetaDataFailedToCreateCacheDuration(timeValue);
    }
}
 
Example 3
@Test
public void testStuff2() throws DatatypeConfigurationException {
  DatatypeFactory factory = DatatypeFactory.newInstance();

  Duration d = factory.newDuration("P3D");
  long secs1 = d.getTimeInMillis(new Date()) / 1000;
  Calendar c = Calendar.getInstance();
  c.set(1970, 0, 1, 0, 0, 0);
  long secs2 = d.getTimeInMillis(c.getTime()) / 1000;

  System.out.printf("%d %d same = %s%n", secs1, secs2, secs1 == secs2);
}
 
Example 4
/**
 * Create test files
 *
 * @param javaVersion JDK version
 */
public void createTestFile(String javaVersion) {
    try {
        DatatypeFactory dtf = DatatypeFactory.newInstance();
        XMLGregorianCalendar c = dtf.newXMLGregorianCalendar(EXPECTED_CAL);
        Duration d = dtf.newDuration(EXPECTED_DURATION);
        toFile((Serializable) c, filePath + javaVersion + FILENAME_CAL);
        toFile((Serializable) d, filePath + javaVersion + FILENAME_DURATION);
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
 
Example 5
@Test
public void test() throws DatatypeConfigurationException {
    DatatypeFactory df = DatatypeFactory.newInstance();
    Duration durationx = df.newDuration(Long.MIN_VALUE);
    Assert.assertEquals(durationx.toString(), "-P292277024Y7M16DT7H12M55.808S");
    durationx = df.newDuration(Long.MAX_VALUE);
    Assert.assertEquals(durationx.toString(), "P292277024Y7M16DT7H12M55.807S");
}
 
Example 6
private void newDurationTester(boolean isPositive, boolean normalizedIsPositive, BigInteger years, BigInteger normalizedYears, BigInteger months,
        BigInteger normalizedMonths, BigInteger days, BigInteger normalizedDays, BigInteger hours, BigInteger normalizedHours, BigInteger minutes,
        BigInteger normalizedMinutes, BigDecimal seconds, BigDecimal normalizedSeconds, long durationInMilliSeconds, long normalizedDurationInMilliSeconds,
        String lexicalRepresentation, String normalizedLexicalRepresentation) {

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

    // create 4 Durations using the 4 different constructors

    Duration durationBigInteger = datatypeFactory.newDuration(isPositive, years, months, days, hours, minutes, seconds);
    durationAssertEquals(durationBigInteger, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
            normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
            normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);

    Duration durationInt = datatypeFactory.newDuration(isPositive, years.intValue(), months.intValue(), days.intValue(), hours.intValue(),
            minutes.intValue(), seconds.intValue());
    durationAssertEquals(durationInt, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
            normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
            normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);

    Duration durationMilliseconds = datatypeFactory.newDuration(durationInMilliSeconds);
    durationAssertEquals(durationMilliseconds, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
            normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
            normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);

    Duration durationLexical = datatypeFactory.newDuration(lexicalRepresentation);
    durationAssertEquals(durationLexical, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
            normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
            normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);
}
 
Example 7
@Test
public final void testGetDurationValueLiteralDuration() throws Exception {
	DatatypeFactory dtFactory = DatatypeFactory.newInstance();

	Duration fallback = dtFactory.newDuration(true, 1, 1, 1, 1, 1, 1);

	Duration result = Literals.getDurationValue(vf.createLiteral("P5Y"), fallback);

	assertNotNull(result);
	assertFalse(result.equals(fallback));
	assertEquals(5, result.getYears());
}
 
Example 8
public static void setDurationValue(Element element, long value)
{
	try
	{
		DatatypeFactory df = DatatypeFactory.newInstance();
		Duration dur = df.newDuration(value);
		setStringValue(element, String.valueOf(dur.toString()));
	}
	catch (Exception e)
	{
		logger.error("'" + element.getName() + "' must be Duration, " + e.getMessage());
	}
}
 
Example 9
Source Project: yawl   File: Utils.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * converts minute string x to lexical representation of duration
 * 
 * @param minutes
 * @return
 */
public static String stringMinutes2stringXMLDuration(String minutes)
           throws DatatypeConfigurationException {
	Long millis = Long.parseLong(minutes) * 60 * 1000;
	DatatypeFactory df = DatatypeFactory.newInstance();
	Duration d = df.newDuration(millis);
	return d.toString();
}
 
Example 10
private boolean validateDuration(String value, String fieldName, boolean untreated) {
    try {
        DatatypeFactory factory = DatatypeFactory.newInstance();
        factory.newDuration(value);
        return true;
    }
    catch (Exception e) {
        addValidationErrorMessage(value, fieldName, "duration", untreated) ;
        return false ;
    }
}
 
Example 11
@Test
public void testConvertFromJavaDuration() throws DatatypeConfigurationException {
  DatatypeFactory f = DatatypeFactory.newInstance();
  Duration d = f.newDuration(true, 1, 2, 3, 4, 5, 6);
  ValueConverter.convertFromJava(d, processor);
  checkProcessor("duration", "xs:duration", d);

  d = f.newDurationYearMonth(true, 1, 2);
  ValueConverter.convertFromJava(d, processor);
  checkProcessor("year month duration", "xs:yearMonthDuration", d);

  d = f.newDurationDayTime(true, 3, 4, 5, 6);
  ValueConverter.convertFromJava(d, processor);
  checkProcessor("day time duration", "xs:dayTimeDuration", d);
}
 
Example 12
Source Project: juddi   File: TypeConvertor.java    License: Apache License 2.0 5 votes vote down vote up
public static Duration convertStringToDuration(String duration) throws DispositionReportFaultMessage {
	if (duration==null) return null;
	Duration result = null;
	try { 
		
		DatatypeFactory df = DatatypeFactory.newInstance();
		result = df.newDuration(duration);
	}
	catch(DatatypeConfigurationException ce) { 
		throw new FatalErrorException(new ErrorMessage("errors.Unspecified"));
	}

	return result;
}
 
Example 13
Source Project: lemon   File: DeadlineHumanTaskListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(TaskInfo taskInfo) {
    String taskDefinitionKey = taskInfo.getCode();

    String processDefinitionId = taskInfo.getProcessDefinitionId();
    List<DeadlineDTO> deadlines = taskDefinitionConnector.findDeadlines(
            taskDefinitionKey, processDefinitionId);

    for (DeadlineDTO deadline : deadlines) {
        try {
            String durationText = deadline.getDuration();

            Date now = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);

            DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
            Duration duration = datatypeFactory.newDuration(durationText);
            duration.addTo(calendar);

            Date deadlineTime = calendar.getTime();
            TaskDeadline taskDeadline = new TaskDeadline();
            taskDeadline.setTaskInfo(taskInfo);
            taskDeadline.setType(deadline.getType());
            taskDeadline.setDeadlineTime(deadlineTime);
            taskDeadline
                    .setNotificationType(deadline.getNotificationType());
            taskDeadline.setNotificationTemplateCode(deadline
                    .getNotificationTemplateCode());
            taskDeadline.setNotificationReceiver(deadline
                    .getNotificationReceiver());
            taskDeadlineManager.save(taskDeadline);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
}
 
Example 14
/**
 * See JDK-5077522, Duration.compare returns equal for INDETERMINATE
 * comparisons
 */
public void testCompareWithInderterminateRelation() {

    final String [][] partialOrder = { // partialOrder
       {"P1Y", "<>", "P365D"},
       {"P1Y", "<>", "P366D"},
       {"P1M", "<>", "P28D"},
       {"P1M", "<>", "P29D"},
       {"P1M", "<>", "P30D"},
       {"P1M", "<>", "P31D"},
       {"P5M", "<>", "P150D"},
       {"P5M", "<>", "P151D"},
       {"P5M", "<>", "P152D"},
       {"P5M", "<>", "P153D"},
       {"PT2419200S", "<>", "P1M"},
       {"PT2678400S", "<>", "P1M"},
       {"PT31536000S", "<>", "P1Y"},
       {"PT31622400S", "<>", "P1Y"},
       {"PT525600M", "<>", "P1Y"},
       {"PT527040M", "<>", "P1Y"},
       {"PT8760H", "<>", "P1Y"},
       {"PT8784H", "<>", "P1Y"},
       {"P365D", "<>", "P1Y"},
    };

    DatatypeFactory df = null;
    try {
        df = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException ex) {
        ex.printStackTrace();
        fail(ex.toString());
    }

    for (int valueIndex = 0; valueIndex < partialOrder.length; ++valueIndex) {
        Duration duration1 = df.newDuration(partialOrder[valueIndex][0]);
        Duration duration2 = df.newDuration(partialOrder[valueIndex][2]);
        int cmp = duration1.compare(duration2);
        int expected = ">".equals(partialOrder[valueIndex][1])
                 ? DatatypeConstants.GREATER
                 : "<".equals(partialOrder[valueIndex][1])
                 ? DatatypeConstants.LESSER
                 : "==".equals(partialOrder[valueIndex][1])
                 ? DatatypeConstants.EQUAL
                 : DatatypeConstants.INDETERMINATE;

        if (expected != cmp) {
            fail("returned " + cmp2str(cmp)
                + " for durations \'" + duration1 + "\' and "
                + duration2 + "\', but expected " + cmp2str(expected));
        } else {
            success("Comparing " + duration1 + " and " + duration2 +
                    ": INDETERMINATE");
        }
    }
}
 
Example 15
/**
 * Verify cases around the INDETERMINATE relations
 */
public void testVerifyOtherRelations() {

    final String [][] partialOrder = { // partialOrder
       {"P1Y", ">", "P364D"},
       {"P1Y", "<", "P367D"},
       {"P1Y2D", ">", "P366D"},
       {"P1M", ">", "P27D"},
       {"P1M", "<", "P32D"},
       {"P1M", "<", "P31DT1H"},
       {"P5M", ">", "P149D"},
       {"P5M", "<", "P154D"},
       {"P5M", "<", "P153DT1H"},
       {"PT2419199S", "<", "P1M"},  //PT2419200S -> P28D
       {"PT2678401S", ">", "P1M"},  //PT2678400S -> P31D
       {"PT31535999S", "<", "P1Y"}, //PT31536000S -> P365D
       {"PT31622401S", ">", "P1Y"}, //PT31622400S -> P366D
       {"PT525599M59S", "<", "P1Y"},  //PT525600M -> P365D
       {"PT527040M1S", ">", "P1Y"},  //PT527040M -> P366D
       {"PT8759H59M59S", "<", "P1Y"},    //PT8760H -> P365D
       {"PT8784H1S", ">", "P1Y"},    //PT8784H -> P366D
    };

    DatatypeFactory df = null;
    try {
        df = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException ex) {
        ex.printStackTrace();
        fail(ex.toString());
    }

    for (int valueIndex = 0; valueIndex < partialOrder.length; ++valueIndex) {
        Duration duration1 = df.newDuration(partialOrder[valueIndex][0]);
        Duration duration2 = df.newDuration(partialOrder[valueIndex][2]);
        int cmp = duration1.compare(duration2);
        int expected = ">".equals(partialOrder[valueIndex][1])
                 ? DatatypeConstants.GREATER
                 : "<".equals(partialOrder[valueIndex][1])
                 ? DatatypeConstants.LESSER
                 : "==".equals(partialOrder[valueIndex][1])
                 ? DatatypeConstants.EQUAL
                 : DatatypeConstants.INDETERMINATE;

        if (expected != cmp) {
            fail("returned " + cmp2str(cmp)
                + " for durations \'" + duration1 + "\' and "
                + duration2 + "\', but expected " + cmp2str(expected));
        } else {
            success("Comparing " + duration1 + " and " + duration2 +
                    ": expected: " + cmp2str(expected) +
                    " actual: " + cmp2str(cmp));
        }
    }
}
 
Example 16
/**
 * Inspired by CR 5077522 Duration.compare makes mistakes for some values.
 */
@Test
public void testCompareWithInderterminateRelation() {

    final String[][] partialOrder = { // partialOrder
    { "P1Y", "<>", "P365D" }, { "P1Y", "<>", "P366D" }, { "P1M", "<>", "P28D" }, { "P1M", "<>", "P29D" }, { "P1M", "<>", "P30D" }, { "P1M", "<>", "P31D" },
            { "P5M", "<>", "P150D" }, { "P5M", "<>", "P151D" }, { "P5M", "<>", "P152D" }, { "P5M", "<>", "P153D" }, { "PT2419200S", "<>", "P1M" },
            { "PT2678400S", "<>", "P1M" }, { "PT31536000S", "<>", "P1Y" }, { "PT31622400S", "<>", "P1Y" }, { "PT525600M", "<>", "P1Y" },
            { "PT527040M", "<>", "P1Y" }, { "PT8760H", "<>", "P1Y" }, { "PT8784H", "<>", "P1Y" }, { "P365D", "<>", "P1Y" }, };

    DatatypeFactory df = null;
    try {
        df = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException ex) {
        ex.printStackTrace();
        Assert.fail(ex.toString());
    }

    boolean compareErrors = false;

    for (int valueIndex = 0; valueIndex < partialOrder.length; ++valueIndex) {
        Duration duration1 = df.newDuration(partialOrder[valueIndex][0]);
        Duration duration2 = df.newDuration(partialOrder[valueIndex][2]);
        int cmp = duration1.compare(duration2);
        int expected = ">".equals(partialOrder[valueIndex][1]) ? DatatypeConstants.GREATER
                : "<".equals(partialOrder[valueIndex][1]) ? DatatypeConstants.LESSER : "==".equals(partialOrder[valueIndex][1]) ? DatatypeConstants.EQUAL
                        : DatatypeConstants.INDETERMINATE;

        // just note any errors, do not fail until all cases have been
        // tested
        if (expected != cmp) {
            compareErrors = true;
            System.err.println("returned " + cmp2str(cmp) + " for durations \'" + duration1 + "\' and " + duration2 + "\', but expected "
                    + cmp2str(expected));
        }
    }

    if (compareErrors) {
        // TODO; fix bug, these tests should pass
        if (false) {
            Assert.fail("Errors in comparing indeterminate relations, see Stderr");
        } else {
            System.err.println("Please fix this bug: " + "Errors in comparing indeterminate relations, see Stderr");
        }
    }
}
 
Example 17
@Test(dataProvider = "parameters")
public void testNewInstance(String factoryClassName, ClassLoader classLoader) throws DatatypeConfigurationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance(DATATYPE_FACTORY_CLASSNAME, null);
    Duration duration = dtf.newDuration(true, 1, 1, 1, 1, 1, 1);
    assertNotNull(duration);
}
 
Example 18
Source Project: lemon   File: TimeoutNotice.java    License: Apache License 2.0 4 votes vote down vote up
public void processTimeout(DelegateTask delegateTask,
        BpmConfNotice bpmConfNotice) {
    try {
        Date dueDate = delegateTask.getDueDate();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dueDate);

        DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
        Duration duration = datatypeFactory.newDuration("-"
                + bpmConfNotice.getDueDate());
        duration.addTo(calendar);

        Date noticeDate = calendar.getTime();
        Date now = new Date();

        if ((now.getTime() < noticeDate.getTime())
                && ((noticeDate.getTime() - now.getTime()) < (60 * 1000))) {
            UserConnector userConnector = ApplicationContextHelper
                    .getBean(UserConnector.class);
            NotificationConnector notificationConnector = ApplicationContextHelper
                    .getBean(NotificationConnector.class);

            //
            Map<String, Object> data = new HashMap<String, Object>();
            TaskEntity taskEntity = new TaskEntity();
            taskEntity.setId(delegateTask.getId());
            taskEntity.setName(delegateTask.getName());
            taskEntity.setAssigneeWithoutCascade(userConnector.findById(
                    delegateTask.getAssignee()).getDisplayName());
            taskEntity.setVariableLocal("initiator",
                    getInitiator(userConnector, delegateTask));
            //
            data.put("task", taskEntity);
            data.put("initiator",
                    this.getInitiator(userConnector, delegateTask));

            String receiver = bpmConfNotice.getReceiver();

            /*
             * BpmMailTemplate bpmMailTemplate = bpmConfNotice .getBpmMailTemplate(); ExpressionManager
             * expressionManager = Context .getProcessEngineConfiguration().getExpressionManager();
             */
            UserDTO userDto = null;

            if ("任务接收人".equals(receiver)) {
                userDto = userConnector
                        .findById(delegateTask.getAssignee());
            } else if ("流程发起人".equals(receiver)) {
                userDto = userConnector.findById((String) delegateTask
                        .getVariables().get("initiator"));
            } else {
                HistoricProcessInstanceEntity historicProcessInstanceEntity = Context
                        .getCommandContext()
                        .getHistoricProcessInstanceEntityManager()
                        .findHistoricProcessInstance(
                                delegateTask.getProcessInstanceId());
                userDto = userConnector
                        .findById(historicProcessInstanceEntity
                                .getStartUserId());
            }

            /*
             * String subject = expressionManager .createExpression(bpmMailTemplate.getSubject())
             * .getValue(taskEntity).toString();
             * 
             * String content = expressionManager .createExpression(bpmMailTemplate.getContent())
             * .getValue(taskEntity).toString();
             * 
             * this.sendMail(userDto, subject, content); this.sendSiteMessage(userDto, subject, content);
             */
            NotificationDTO notificationDto = new NotificationDTO();
            notificationDto.setReceiver(userDto.getId());
            notificationDto.setReceiverType("userid");
            notificationDto.setTypes(Arrays.asList(bpmConfNotice
                    .getNotificationType().split(",")));
            notificationDto.setData(data);
            notificationDto.setTemplate(bpmConfNotice.getTemplateCode());

            notificationConnector.send(notificationDto,
                    delegateTask.getTenantId());
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}