Example usage for javax.xml.datatype DatatypeFactory newInstance

List of usage examples for javax.xml.datatype DatatypeFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.datatype DatatypeFactory newInstance.

Prototype

public static DatatypeFactory newInstance() throws DatatypeConfigurationException 

Source Link

Document

Obtain a new instance of a DatatypeFactory .

Usage

From source file:com.retroduction.carma.eventlisteners.ReportEventListener.java

ProcessingInfo createTimingInformation(long classProcessingStart, long classProcessingEnd)
        throws DatatypeConfigurationException {
    ProcessingInfo info = new ProcessingInfo();
    info.setDuration(classProcessingEnd - classProcessingStart);
    this.calendar.setTimeInMillis(classProcessingStart);
    info.setStart(DatatypeFactory.newInstance().newXMLGregorianCalendar(this.calendar));
    this.calendar.setTimeInMillis(classProcessingEnd);
    info.setEnd(DatatypeFactory.newInstance().newXMLGregorianCalendar(this.calendar));
    return info;/*  ww w  .j ava  2  s .co m*/
}

From source file:com.orange.cepheus.broker.LocalRegistrations.java

/**
 * @return the duration of the registration
 * @throws RegistrationException/*w  w w  .  jav a  2 s  . c  o m*/
 */
private Duration registrationDuration(RegisterContext registerContext) throws RegistrationException {
    // Use java.xml.datatype functions as java.time do not handle durations with months and years...
    try {
        long duration = DatatypeFactory.newInstance().newDuration(registerContext.getDuration())
                .getTimeInMillis(new Date());
        return Duration.ofMillis(duration);
    } catch (Exception e) {
        throw new RegistrationException("bad duration: " + registerContext.getDuration(), e);
    }
}

From source file:fr.xebia.springframework.jms.support.converter.JaxbMessageConverterTest.java

@Test
public void testToMessage() throws Exception {

    JaxbMessageConverter jaxbMessageConverter = createJaxbMessageConverter(Employee.class, Gender.class);

    Employee employee = new Employee(1, "Cyrille", "Le Clerc", Gender.MALE, DatatypeFactory.newInstance()
            .newXMLGregorianCalendarDate(1976, 01, 05, DatatypeConstants.FIELD_UNDEFINED));

    TextMessage actualMessage = (TextMessage) jaxbMessageConverter.toMessage(employee, session);

    String actual = actualMessage.getText();
    String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<Employee>"
            + "<id>1</id>" + "<lastName>Le Clerc</lastName>" + "<firstName>Cyrille</firstName>"
            + "<gender>MALE</gender>" + "<birthdate>1976-01-05</birthdate>" + "</Employee>";

    Assert.assertEquals(expected, actual);
}

From source file:ebay.dts.client.BulkDataExchangeActions.java

private static XMLGregorianCalendar parseDate(String cal) throws DatatypeConfigurationException {
    GregorianCalendar ret = null;
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    try {/*from  w w  w.  ja  va  2 s  . c o m*/
        df.parse(cal);
        String[] parts = cal.split("-");
        ret = (GregorianCalendar) Calendar.getInstance();
        ret.set(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]) - 1, Integer.parseInt(parts[2]), 0, 0,
                0);
        // get here and we know the format is correct
    } catch (ParseException e) {
        logger.error("ParseException caught when parsing your date string, please fix it and retry.");
        return null;
    }
    DatatypeFactory factory = DatatypeFactory.newInstance();
    XMLGregorianCalendar xmlGregorianCalendar = factory.newXMLGregorianCalendar(ret);
    return xmlGregorianCalendar;
}

From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java

@Override
public Date getSigningTime() {
    try {//from   www. j  a va  2s .  co m

        Element signingTimeEl = XMLUtils.getElement(signatureElement,
                "ds:Object/xades:QualifyingProperties/xades:SignedProperties/xades:SignedSignatureProperties/"
                        + "./xades:SigningTime");
        if (signingTimeEl == null) {
            return null;
        }
        String text = signingTimeEl.getTextContent();
        DatatypeFactory factory = DatatypeFactory.newInstance();
        XMLGregorianCalendar cal = factory.newXMLGregorianCalendar(text);
        return cal.toGregorianCalendar().getTime();
    } catch (DOMException e) {
        throw new RuntimeException(e);
    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException(e);
    } catch (XPathExpressionException e) {
        throw new EncodingException(MSG.SIGNING_TIME_ENCODING);
    }
}

From source file:it.cnr.icar.eric.server.persistence.rdb.AuditableEventDAO.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected void loadObject(Object obj, ResultSet rs) throws RegistryException {
    try {/* w w  w.j  a  v a  2  s . c  om*/
        if (!(obj instanceof AuditableEventType)) {
            throw new RegistryException(ServerResourceBundle.getInstance()
                    .getString("message.AuditableEventExpected", new Object[] { obj }));
        }

        AuditableEventType ebAuditableEventType = (AuditableEventType) obj;
        super.loadObject(obj, rs);

        //TODO: Fix so requestId is properly supported
        String requestId = rs.getString("requestId");
        if (requestId == null) {
            requestId = "Unknown";
        }
        ebAuditableEventType.setRequestId(requestId);

        String eventType = rs.getString("eventType");
        ebAuditableEventType.setEventType(eventType);

        //Workaround for bug in PostgreSQL 7.2.2 JDBC driver
        //java.sql.Timestamp timeStamp = rs.getTimestamp("timeStamp_"); --old
        String timestampStr = rs.getString("timeStamp_").substring(0, 19);
        Timestamp timeStamp = Timestamp.valueOf(timestampStr);

        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(timeStamp);
        XMLGregorianCalendar cal = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);

        ebAuditableEventType.setTimestamp(cal);

        String userId = rs.getString("user_");
        ObjectRefType ebObjectRefType = bu.rimFac.createObjectRefType();
        ebObjectRefType.setId(userId);
        context.getObjectRefs().add(ebObjectRefType);
        ebAuditableEventType.setUser(userId);

        AffectedObjectDAO affectedDAO = new AffectedObjectDAO(context);
        affectedDAO.setParent(ebAuditableEventType);
        List affectedObjects = affectedDAO.getByParent();
        ObjectRefListType orefList = BindingUtility.getInstance().rimFac.createObjectRefListType();
        orefList.getObjectRef().addAll(affectedObjects);
        ebAuditableEventType.setAffectedObjects(orefList);

    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } catch (DatatypeConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:jenkins.plugins.coverity.DefectFiltersTest.java

@Test
public void defectCutOffDates() throws FormException, java.text.ParseException, DatatypeConfigurationException {
    String cutOffDate = null;//  w  w w  .j a  va 2s .  c o m
    DefectFilters filters = new DefectFilters(null, null, null, null, null, null, cutOffDate);

    assertNull(filters.getCutOffDate());
    assertNull(filters.getXMLCutOffDate());

    cutOffDate = "unparsable-date-format";
    filters = new DefectFilters(null, null, null, null, null, null, cutOffDate);

    assertNull(filters.getCutOffDate());
    assertNull(filters.getXMLCutOffDate());

    cutOffDate = "2010-01-31";
    filters = new DefectFilters(null, null, null, null, null, null, cutOffDate);

    assertEquals(cutOffDate, filters.getCutOffDate());

    GregorianCalendar calender = new GregorianCalendar();
    calender.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(cutOffDate));
    XMLGregorianCalendar expectedXmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(calender);
    assertEquals(expectedXmlDate, filters.getXMLCutOffDate());
}

From source file:ca.phon.session.io.xml.v12.XMLSessionWriter_v12.java

/**
 * copy participant info//from   w  ww .j a va  2s  . c  o m
 */
private ParticipantType copyParticipant(ObjectFactory factory, Participant part) {
    final ParticipantType retVal = factory.createParticipantType();

    if (part.getId() != null)
        retVal.setId(part.getId());

    retVal.setName(part.getName());

    final LocalDate bday = part.getBirthDate();
    if (bday != null) {
        try {
            final DatatypeFactory df = DatatypeFactory.newInstance();
            final XMLGregorianCalendar cal = df
                    .newXMLGregorianCalendar(GregorianCalendar.from(bday.atStartOfDay(ZoneId.systemDefault())));
            cal.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
            retVal.setBirthday(cal);
        } catch (DatatypeConfigurationException e) {
            LOGGER.log(Level.WARNING, e.toString(), e);
        }
    }

    final Period age = part.getAge(null);
    if (age != null) {
        try {
            final DatatypeFactory df = DatatypeFactory.newInstance();
            final Duration ageDuration = df.newDuration(true, age.getYears(), age.getMonths(), age.getDays(), 0,
                    0, 0);
            retVal.setAge(ageDuration);
        } catch (DatatypeConfigurationException e) {
            LOGGER.log(Level.WARNING, e.toString(), e);
        }
    }

    retVal.setEducation(part.getEducation());
    retVal.setGroup(part.getGroup());

    final String lang = part.getLanguage();
    final String langs[] = (lang != null ? lang.split(",") : new String[0]);
    for (String l : langs) {
        retVal.getLanguage().add(StringUtils.strip(l));
    }

    if (part.getSex() == Sex.MALE)
        retVal.setSex(SexType.MALE);
    else if (part.getSex() == Sex.FEMALE)
        retVal.setSex(SexType.FEMALE);

    ParticipantRole prole = part.getRole();
    if (prole == null)
        prole = ParticipantRole.TARGET_CHILD;
    retVal.setRole(prole.toString());

    // create ID based on role if possible
    if (retVal.getId() == null && prole != null) {
        if (prole == ParticipantRole.TARGET_CHILD) {
            retVal.setId("CHI");
        } else if (prole == ParticipantRole.MOTHER) {
            retVal.setId("MOT");
        } else if (prole == ParticipantRole.FATHER) {
            retVal.setId("FAT");
        } else if (prole == ParticipantRole.INTERVIEWER) {
            retVal.setId("INT");
        } else {
            retVal.setId("p" + (++pIdx));
        }
    }

    retVal.setSES(part.getSES());

    return retVal;
}

From source file:com.fusesource.example.camel.ingest.SimpleFileIngestorRouteBuilderTest.java

@Test
@DirtiesContext// w  w w  .j  av  a 2s  .  c om
public void testNonTerminalJdbcFailure() throws Exception {

    configureJdbcFailure(1);

    context.start();

    DatatypeFactory dtf = DatatypeFactory.newInstance();

    Set<String> expectedIds = new HashSet<String>();

    output.setExpectedMessageCount(10);
    output.setResultWaitTime(12000l);

    for (int i = 0; i < 10; i++) {
        RecordType recordType = new RecordType();
        recordType.setId(String.valueOf(i));
        recordType.setDate(dtf.newXMLGregorianCalendar(new GregorianCalendar()));
        recordType.setDescription("Record number: " + i);
        expectedIds.add(String.valueOf(i));

        try {
            trigger.sendBody(SimpleFileIngestorRouteBuilder.HANDLE_RECORD_ROUTE_ENDPOINT_URI,
                    marshallToXml(recordType));
        } catch (CamelExecutionException e) {
            assertEquals("1", recordType.getId());
        }
    }

    output.assertIsSatisfied();

    for (Exchange exchange : output.getReceivedExchanges()) {
        assertTrue(expectedIds.remove(exchange.getIn().getBody(Record.class).getId()));
    }

    assertTrue(expectedIds.isEmpty());
}

From source file:org.osgp.adapter.protocol.dlms.infra.ws.JasperWirelessSmsClientTest.java

public XMLGregorianCalendar getXmlGregorianCalendarNow() throws DatatypeConfigurationException {
    final GregorianCalendar gregorianCalendar = new GregorianCalendar();
    final DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
    return datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);
}