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:edu.cornell.mannlib.semservices.util.DateConverter.java

public static XMLGregorianCalendar toXMLGregorianCalendar(Date date) {
    try {//from  w ww  .j a  v  a  2  s.  c om
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
    } catch (DatatypeConfigurationException e) {
        return null;
    }
}

From source file:org.mitre.stixwebtools.services.TaxiiService.java

/**
 * Makes a poll request from a Taxii server to get a Taxii document.
 * //from w  w w  . j  a v  a  2  s.  c  o m
 * @param serverUrl
 * @param collection
 * @param subId
 * @param beginStr
 * @param endStr
 * @return 
 */
public String getTaxiiDocument(URI serverUrl, String collection, String subId, String beginStr, String endStr) {

    HttpClient taxiiClient = getTaxiiClient("gatekeeper.mitre.org", 80);

    ObjectFactory factory = new ObjectFactory();

    PollRequest pollRequest = factory.createPollRequest().withMessageId(MessageHelper.generateMessageId())
            .withCollectionName(collection);

    if (!subId.isEmpty()) {
        pollRequest.setSubscriptionID(subId);
    } else {
        pollRequest.withPollParameters(factory.createPollParametersType());
    }

    if (!beginStr.isEmpty()) {
        try {
            pollRequest.setExclusiveBeginTimestamp(
                    DatatypeFactory.newInstance().newXMLGregorianCalendar(beginStr));
        } catch (DatatypeConfigurationException eeeee) {

        }
    }
    if (!endStr.isEmpty()) {
        try {
            pollRequest
                    .setExclusiveBeginTimestamp(DatatypeFactory.newInstance().newXMLGregorianCalendar(endStr));
        } catch (DatatypeConfigurationException eeeee) {

        }
    }

    String content;

    try {
        Object responseObj = taxiiClient.callTaxiiService(serverUrl, pollRequest);

        content = taxiiXml.marshalToString(responseObj, true);

        /*if (responseObj instanceof DiscoveryResponse) {
        DiscoveryResponse dResp = (DiscoveryResponse) responseObj;
        //processDiscoveryResponse(dResp);
        } else if (responseObj instanceof StatusMessage) {
        StatusMessage sm = (StatusMessage) responseObj;
        //processStatusMessage(sm);
        }*/

    } catch (JAXBException e) {
        content = e.getMessage();
    } catch (UnsupportedEncodingException eee) {
        content = eee.getMessage();
    } catch (IOException eeee) {
        content = eeee.getMessage();
    }

    return content;

}

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

protected void loadObject(Object obj, ResultSet rs) throws RegistryException {
    try {//from  w w  w.j  a va 2s .c  om
        if (!(obj instanceof FederationType)) {
            throw new RegistryException(ServerResourceBundle.getInstance()
                    .getString("message.FederationExpected", new Object[] { obj }));
        }

        FederationType federation = (FederationType) obj;
        super.loadObject(obj, rs);

        String replicationSyncLatencyString = rs.getString("replicationSyncLatency");
        Duration replicationSyncLatency = DatatypeFactory.newInstance()
                .newDuration(replicationSyncLatencyString); // conversion
        federation.setReplicationSyncLatency(replicationSyncLatency);

    } 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:eu.europa.ec.markt.dss.DSSUtils.java

/**
 * Converts a given <code>Date</code> to a new <code>XMLGregorianCalendar</code>.
 *
 * @param date the date to be converted//from  w w  w.  j a  v a 2 s  .  co  m
 * @return the new <code>XMLGregorianCalendar</code> or null
 */
public static XMLGregorianCalendar createXMGregorianCalendar(Date date) {

    if (date == null) {
        return null;
    }

    final GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(date);

    try {
        XMLGregorianCalendar gc = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
        gc.setFractionalSecond(null);
        gc = gc.normalize(); // to UTC = Zulu
        return gc;
    } catch (DatatypeConfigurationException e) {

        // LOG.log(Level.WARNING, "Unable to properly convert a Date to an XMLGregorianCalendar",e);
    }

    return null;
}

From source file:com.rogers.ute.creditservice.util.CreditServiceUtils.java

private static XMLGregorianCalendar asXMLGregorianCalendar(String date) {
    try {//w w  w . j  av  a2s.  co m
        XMLGregorianCalendar result = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        GregorianCalendar gregorianCalendar = (GregorianCalendar) GregorianCalendar.getInstance();
        /*Date date = simpleDateFormat.parse(date);*/
        gregorianCalendar.setTime(simpleDateFormat.parse(date));
        result = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
        return result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:be.fedict.eid.pkira.portal.util.TypeMapper.java

public synchronized static DatatypeFactory getDatatypeFactory() {
    if (datatypeFactory == null) {
        try {/* w w w  .  j a va  2 s .  co  m*/
            datatypeFactory = DatatypeFactory.newInstance();
        } catch (DatatypeConfigurationException e) {
            throw new RuntimeException("Cannot get DatatypeFactory", e);
        }
    }
    return datatypeFactory;
}

From source file:com.fusesource.example.camel.process.camel.ProcessorRouteBuilderTest.java

@Test
@DirtiesContext// w  w  w . j  a  v a  2 s  .  c o m
public void testPositive() throws Exception {
    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));

        trigger.sendBody(recordType);
    }

    output.assertIsSatisfied();

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

    assertTrue(expectedIds.isEmpty());
}

From source file:com.microsoft.exchange.ExchangeEventConverterImplTest.java

@Test
public void convertedCalendarMatchesSubject() throws DatatypeConfigurationException {
    CalendarItemType calendarItem = new CalendarItemType();
    String randomSubject = RandomStringUtils.random(32);

    calendarItem.setStart(DateHelp.convertDateToXMLGregorianCalendar(new Date()));
    Duration duration = DatatypeFactory.newInstance().newDuration(1000 * 60 * 60);
    XMLGregorianCalendar end = calendarItem.getStart();
    end.add(duration);//from   w  w  w . jav  a2 s.c o  m
    calendarItem.setEnd(end);

    calendarItem.setSubject(randomSubject);
    log.info("created calendar item with subject=" + randomSubject);
    Calendar calendar = eventConverter.convertToCalendar(Collections.singleton(calendarItem), null);

    //calendar should not be null
    assertNotNull(calendar);
    ComponentList components = calendar.getComponents();
    //calendar should have components
    assertNotNull(components);

    //calendar should have exactly one component
    assertEquals(1, components.size());

    //components should be events
    assertEquals(components, calendar.getComponents(VEvent.VEVENT));

    Object object = components.get(0);
    assertNotNull(object);
    assertTrue(object instanceof VEvent);

    VEvent event = (VEvent) object;
    assertNotNull(event);

    Summary summary = event.getSummary();
    assertNotNull(summary);
    assertNotNull(summary.getValue());
    assertEquals(randomSubject, summary.getValue());
    log.info("converted event summary[" + summary.getValue() + "] matches calendar item sujbect["
            + calendarItem.getSubject() + "]");
}

From source file:be.e_contract.mycarenet.xkms2.XKMS2Client.java

/**
 * Main constructor.//from ww  w  .  j  a  v a 2s  .c  o m
 * 
 * @param location
 *            the URL of the MyCareNet XKMS 2.0 web service.
 */
public XKMS2Client(String location) {
    XMLKeyManagementService service = XKMS2ServiceFactory.newInstance();
    this.keyServicePort = service.getKeyServiceSoapPort();
    BindingProvider bindingProvider = (BindingProvider) this.keyServicePort;
    bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, location);

    Binding binding = bindingProvider.getBinding();
    @SuppressWarnings("rawtypes")
    List<Handler> handlerChain = binding.getHandlerChain();
    this.proofOfPossessionSignatureSOAPHandler = new ProofOfPossessionSignatureSOAPHandler();
    handlerChain.add(new LoggingHandler());
    handlerChain.add(this.proofOfPossessionSignatureSOAPHandler);
    this.keyBindingAuthenticationSignatureSOAPHandler = new KeyBindingAuthenticationSignatureSOAPHandler();
    handlerChain.add(this.keyBindingAuthenticationSignatureSOAPHandler);
    handlerChain.add(new LoggingHandler());
    binding.setHandlerChain(handlerChain);

    this.objectFactory = new ObjectFactory();
    this.xmldsigObjectFactory = new be.e_contract.mycarenet.jaxb.xmldsig.ObjectFactory();
    try {
        this.datatypeFactory = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException("DatatypeFactory error: " + e.getMessage(), e);
    }

}

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

/**
 * Returns the SQL fragment string needed by insert or update statements 
 * within insert or update method of sub-classes. This is done to avoid code
 * duplication.//from  www  .  j a  v  a 2  s  .  com
 */
protected String getSQLStatementFragment(Object ro) throws RegistryException {

    AuditableEventType auditableEvent = (AuditableEventType) ro;

    String stmtFragment = null;

    try {

        String requestId = auditableEvent.getRequestId();
        String eventType = auditableEvent.getEventType();

        if (auditableEvent.getTimestamp() == null) {
            XMLGregorianCalendar timeNow;
            timeNow = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());

            auditableEvent.setTimestamp(timeNow);
        }

        Timestamp timestamp = new Timestamp(
                auditableEvent.getTimestamp().toGregorianCalendar().getTimeInMillis());

        // ??The timestamp is being truncated to work around a bug in
        // PostgreSQL 7.2.2 JDBC driver
        String timestampStr = timestamp.toString().substring(0, 19);

        String aeUser = auditableEvent.getUser();
        if (aeUser == null) {
            UserType user = context.getUser();
            if (user != null) {
                aeUser = user.getId();
            }
        }

        if (action == DAO_ACTION_INSERT) {
            stmtFragment = "INSERT INTO AuditableEvent " + super.getSQLStatementFragment(ro) + ", '" + requestId
                    + "', '" + eventType + "', '" + timestampStr + "', '" + aeUser + "' ) ";
        } else if (action == DAO_ACTION_UPDATE) {
            stmtFragment = "UPDATE AuditableEvent SET " + super.getSQLStatementFragment(ro) + ", requestId='"
                    + requestId + "', eventType='" + eventType + "', timestamp_='" + timestampStr + "', user_='"
                    + aeUser + "' WHERE id = '" + ((RegistryObjectType) ro).getId() + "' ";
        } else if (action == DAO_ACTION_DELETE) {
            stmtFragment = super.getSQLStatementFragment(ro);
        }
    } catch (DatatypeConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return stmtFragment;
}