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.kcs.core.utilities.Utility.java

public static XMLGregorianCalendar getXMLGregorianCalendarDate(Date date)
        throws DatatypeConfigurationException {
    if (Utility.isNotNull(date)) {
        GregorianCalendar arrgCtrDate = new GregorianCalendar();
        arrgCtrDate.setTime(date);// w ww  .j a v a2 s .  c o m
        DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
        XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendarDate(
                arrgCtrDate.get(Calendar.YEAR), arrgCtrDate.get(Calendar.MONTH) + 1,
                arrgCtrDate.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);
        return xmlGregorianCalendar;
    }
    return null;
}

From source file:de.unikassel.puma.openaccess.sword.PumaData.java

/**
 * @param phdoralexam the phdoralexam to set
 *//*from   w w  w  . ja va 2s.  c o m*/
public void setPhdoralexam(String phdoralexamString) {
    // convert string to date

    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    Date phdoralexamDate = null;
    XMLGregorianCalendar phdoralexamXMLDate = null;

    try {
        phdoralexamDate = sdf.parse(phdoralexamString);
        GregorianCalendar c = new GregorianCalendar();
        c.setTime(phdoralexamDate);
        try {
            phdoralexamXMLDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
        } catch (DatatypeConfigurationException e) {
            log.warn("DatatypeConfigurationException");
        }
    } catch (ParseException e) {
        // Quellzeit hat ein falsches Format
    }

    this.phdoralexam = phdoralexamXMLDate;
}

From source file:eu.dasish.annotation.backend.dao.impl.JdbcNotebookDaoTest.java

/**
 * Test of createNotebookWithoutAccesssAndAnnotations method, of class
 * JdbcNotebookDao./*from  w  w  w. j a v a  2  s.  com*/
 */
@Test
public void testCreateNotebookWithoutAccesssAndAnnotations()
        throws NotInDataBaseException, DatatypeConfigurationException {
    System.out.println("test createNotebookWithoutAccesssAndAnnotations");
    jdbcNotebookDao.setResourcePath("/api/notebooks/");
    Notebook notebook = new Notebook();
    notebook.setTitle("New test notebook");
    notebook.setLastModified(
            DatatypeFactory.newInstance().newXMLGregorianCalendar("2014-02-12T09:25:00.383000Z"));
    Number result = jdbcNotebookDao.createNotebookWithoutAccesssAndAnnotations(notebook, 3);
    assertEquals(5, result);
    assertEquals(3, jdbcNotebookDao.getOwner(result));
    assertNotNull(jdbcNotebookDao.getExternalID(result));
    assertEquals("New test notebook",
            jdbcNotebookDao.getNotebookWithoutAnnotationsAndAccesssAndOwner(result).getTitle());
}

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

@Test
@DirtiesContext/* w w  w.j  av a 2 s  .c o m*/
public void testJmsFailure() throws Exception {
    RouteDefinition routeDef = context.getRouteDefinition(FileIngestorRouteBuilder.ENQUEUE_RECORD_ROUTE_ID);

    routeDef.adviceWith(context, new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            interceptSendToEndpoint(builder.getEnqueueRecordsDestinationUri()).choice().when()
                    .xpath("/example:record/example:id[text() = '1']", FileIngestorRouteBuilder.NAMESPACES)
                    .throwException(new JMSException("Simulated JMS Error!")).end();
        }
    });

    context.start();

    DatatypeFactory dtf = DatatypeFactory.newInstance();

    Set<String> expectedIds = new HashSet<String>();
    AggregateRecordType agt = new AggregateRecordType();
    agt.setDate(dtf.newXMLGregorianCalendar(new GregorianCalendar()));

    output.setExpectedMessageCount(9);

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

        if (i != 1) {
            expectedIds.add(String.valueOf(i));
        }
    }

    createAndMoveFile(agt);

    output.assertIsSatisfied();
    validateFileMove(true);

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

    assertTrue(expectedIds.isEmpty());

}

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

@Test
@DirtiesContext//  w ww  .  ja  va 2  s .co m
public void testDuplicates() throws Exception {
    context.start();

    DatatypeFactory dtf = DatatypeFactory.newInstance();

    output.setExpectedMessageCount(1);
    output.setResultWaitTime(3000l);

    RecordType recordType = new RecordType();
    recordType.setId("1");
    recordType.setDate(dtf.newXMLGregorianCalendar(new GregorianCalendar()));
    recordType.setDescription("Record number: 1");

    trigger.sendBody(SimpleFileIngestorRouteBuilder.HANDLE_RECORD_ROUTE_ENDPOINT_URI,
            marshallToXml(recordType));

    trigger.sendBody(SimpleFileIngestorRouteBuilder.HANDLE_RECORD_ROUTE_ENDPOINT_URI,
            marshallToXml(recordType));

    output.assertIsSatisfied();
}

From source file:com.att.ajsc.csilogging.util.UtilLib.java

public static String getStartTimestamp(String epoch) {
    long stime = Long.parseLong((String) epoch);
    XmlCalendar cal = new XmlCalendar(new Date(stime));
    XMLGregorianCalendar initTime = null;
    try {/* ww  w.  j a v  a  2s . c  o  m*/
        initTime = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY),
                cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND), cal.get(Calendar.MILLISECOND),
                Math.round(cal.get(Calendar.ZONE_OFFSET) / 1000 / 60));
    } catch (Exception ex) {
        initTime = null;
    }
    if (initTime == null)
        return null;
    else
        return initTime.toString();
}

From source file:name.persistent.behaviours.RemoteGraphSupport.java

@Override
public boolean reload(String origin) throws Exception {
    String url = getResource().stringValue();
    BasicHttpRequest req = new BasicHttpRequest("GET", url);
    String type = getPurlContentType();
    if (type == null) {
        req.setHeader("Accept", "application/rdf+xml");
    } else {/*  w  ww.jav a  2 s  .c om*/
        req.setHeader("Accept", type);
    }
    String etag = getPurlEtag();
    if (etag != null) {
        req.setHeader("If-None-Match", etag);
    }
    XMLGregorianCalendar modified = getPurlLastModified();
    if (modified != null) {
        Date date = modified.toGregorianCalendar().getTime();
        req.setHeader("If-Modified-Since", DateUtil.formatDate(date));
    }
    HttpResponse resp = requestRDF(req, 20);
    int code = resp.getStatusLine().getStatusCode();
    if (code == 304) {
        DatatypeFactory df = DatatypeFactory.newInstance();
        GregorianCalendar gc = new GregorianCalendar();
        setPurlLastValidated(df.newXMLGregorianCalendar(gc));
        setPurlCacheControl(getHeader(resp, "Cache-Control"));
    }
    if (code == 304 || code == 404) {
        HttpEntity entity = resp.getEntity();
        if (entity != null) {
            entity.consumeContent();
        }
        return true;
    }
    return importResponse(resp, origin);
}

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

@Test
@DirtiesContext/*from w ww.j ava 2 s.c o  m*/
public void testTerminalJdbcFailure() throws Exception {

    configureJdbcFailure(3);

    context.start();

    DatatypeFactory dtf = DatatypeFactory.newInstance();

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

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

    dlq.setExpectedMessageCount(1);

    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);

        if (i != 1) {
            expectedIds.add(String.valueOf(i));
        }

        trigger.sendBody(recordType);
    }

    output.assertIsSatisfied();
    dlq.assertIsSatisfied();

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

    assertTrue(expectedIds.isEmpty());

    assertTrue(dlq.getReceivedExchanges().get(0).getIn().getBody(String.class).contains("id>1</"));
}

From source file:org.apache.metron.dataloads.taxii.TaxiiHandler.java

/**
 * The action to be performed by this timer task.
 *//*from  ww w.  ja v a  2s . c o m*/
@Override
public void run() {
    if (inProgress) {
        return;
    }
    Date ts = new Date();
    LOG.info("Polling..." + new SimpleDateFormat().format(ts));
    try {
        inProgress = true;
        // Prepare the message to send.
        String sessionID = MessageHelper.generateMessageId();
        PollRequest request = messageFactory.get().createPollRequest().withMessageId(sessionID)
                .withCollectionName(collection);
        if (subscriptionId != null) {
            request = request.withSubscriptionID(subscriptionId);
        } else {
            request = request.withPollParameters(messageFactory.get().createPollParametersType());
        }
        if (beginTime != null) {
            Calendar gc = GregorianCalendar.getInstance();
            gc.setTime(beginTime);
            XMLGregorianCalendar gTime = null;
            try {
                gTime = DatatypeFactory.newInstance().newXMLGregorianCalendar((GregorianCalendar) gc)
                        .normalize();
            } catch (DatatypeConfigurationException e) {
                LOG.error("Unable to set the begin time", e);
            }
            gTime.setFractionalSecond(null);
            LOG.info("Begin Time: " + gTime);
            request.setExclusiveBeginTimestamp(gTime);
        }

        try {
            PollResponse response = call(request, PollResponse.class);
            LOG.info("Got Poll Response with " + response.getContentBlocks().size() + " blocks");
            int numProcessed = 0;
            long avgTimeMS = 0;
            long timeStartedBlock = System.currentTimeMillis();
            for (ContentBlock block : response.getContentBlocks()) {
                AnyMixedContentType content = block.getContent();
                for (Object o : content.getContent()) {
                    numProcessed++;
                    long timeS = System.currentTimeMillis();
                    String xml = null;
                    if (o instanceof Element) {
                        Element element = (Element) o;
                        xml = getStringFromDocument(element.getOwnerDocument());
                        if (LOG.isDebugEnabled() && Math.random() < 0.01) {
                            LOG.debug("Random Stix doc: " + xml);
                        }
                        for (LookupKV<ThreatIntelKey, ThreatIntelValue> kv : extractor.extract(xml)) {
                            String indicatorType = kv.getValue().getMetadata().get("indicator-type");
                            TableInfo tableInfo = tableMap.get(indicatorType);
                            boolean persisted = false;
                            if (tableInfo != null) {
                                kv.getValue().getMetadata().put("source_type", "taxii");
                                kv.getValue().getMetadata().put("taxii_url", endpoint.toString());
                                kv.getValue().getMetadata().put("taxii_collection", collection);
                                Put p = converter.toPut(tableInfo.getColumnFamily(), kv.getKey(),
                                        kv.getValue());
                                HTableInterface table = getTable(tableInfo);
                                table.put(p);
                                persisted = true;
                            }
                            LOG.info("Found Threat Intel: " + persisted + ", " + kv.getKey() + " => "
                                    + kv.getValue());
                        }
                    }
                    avgTimeMS += System.currentTimeMillis() - timeS;
                }
                if ((numProcessed + 1) % 100 == 0) {
                    LOG.info("Processed " + numProcessed + " in "
                            + (System.currentTimeMillis() - timeStartedBlock) + " ms, avg time: "
                            + avgTimeMS / content.getContent().size());
                    timeStartedBlock = System.currentTimeMillis();
                    avgTimeMS = 0;
                    numProcessed = 0;
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            throw new RuntimeException("Unable to make request", e);
        }
    } finally {
        inProgress = false;
        beginTime = ts;
    }
}

From source file:fr.cnes.sitools.extensions.astro.application.uws.jobmanager.AbstractJobTask.java

/**
 * Init the specific JobTask./*from   w ww. j  a  v  a 2 s .c  om*/
 *
 * @param app Uws application
 * @param jobTaskId Job task identifier
 * @param entity www-form-urlencoded form
 * @throws UniversalWorkerException
 */
protected final void doInit(final UwsApplicationPlugin app, final String jobTaskId, final Representation entity)
        throws UniversalWorkerException {
    final long delay = Long.parseLong(UwsApplicationPlugin.APP_DESTRUCTION_DELAY);
    final SitoolsSettings settings = (SitoolsSettings) app.getContext().getAttributes()
            .get(ContextAttributes.SETTINGS);
    final String uwsAttachUrl = app.getAttachementRef();
    this.storagePublic = settings.getPublicHostDomain() + uwsAttachUrl;
    this.storagePath = app.getStorageDirectory();
    this.jobTaskId = jobTaskId;
    this.executionDuration = 0;
    try {
        this.destructionTime = Util.computeDestructionTime(new Date(), delay);
    } catch (DatatypeConfigurationException ex) {
        throw new UniversalWorkerException(Status.SERVER_ERROR_INTERNAL, ex);
    }
    this.error = null;
    this.quote = null;
    this.results = new Results();
    try {
        this.startTime = DatatypeFactory.newInstance().newXMLGregorianCalendar();
    } catch (DatatypeConfigurationException ex) {
        throw new UniversalWorkerException(Status.SERVER_ERROR_INTERNAL, ex);
    }
    try {
        this.endTime = DatatypeFactory.newInstance().newXMLGregorianCalendar();
    } catch (DatatypeConfigurationException ex) {
        throw new UniversalWorkerException(Status.SERVER_ERROR_INTERNAL, ex);
    }
    this.ownerId = Constants.NO_OWNER;
    createUserSpace();
    final Form form = computeForm(entity);
    this.phase = setPhaseAtCreation(form);
    this.parameters = createParametersForJob(form, true);
    JobTaskManager.getInstance().updateJobTask(this);
}