Example usage for javax.xml.datatype DatatypeFactory newDuration

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

Introduction

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

Prototype

public abstract Duration newDuration(final long durationInMilliSeconds);

Source Link

Document

Obtain a new instance of a Duration specifying the Duration as milliseconds.

Usage

From source file:DatatypeAPIUsage.java

public static void main(String[] args) {
    try {//from  w  w w  . ja va 2s.  c o  m
        DatatypeFactory df = DatatypeFactory.newInstance();
        // my work number in milliseconds:
        Duration myPhone = df.newDuration(9054133519l);
        Duration myLife = df.newDuration(true, 29, 2, 15, 13, 45, 0);
        int compareVal = myPhone.compare(myLife);
        switch (compareVal) {
        case DatatypeConstants.LESSER:
            System.out.println("There are fewer milliseconds in my phone number than my lifespan.");
            break;
        case DatatypeConstants.EQUAL:
            System.out.println("The same number of milliseconds are in my phone number and my lifespan.");
            break;
        case DatatypeConstants.GREATER:
            System.out.println("There are more milliseconds in my phone number than my lifespan.");
            break;
        case DatatypeConstants.INDETERMINATE:
            System.out.println("The comparison could not be carried out.");
        }

        // create a yearMonthDuration
        Duration ymDuration = df.newDurationYearMonth("P12Y10M");
        System.out.println("P12Y10M is of type: " + ymDuration.getXMLSchemaType());

        // create a dayTimeDuration (really this time)
        Duration dtDuration = df.newDurationDayTime("P10DT10H12M0S");
        System.out.println("P10DT10H12M0S is of type: " + dtDuration.getXMLSchemaType());

        // try to fool the factory!
        try {
            ymDuration = df.newDurationYearMonth("P12Y10M1D");
        } catch (IllegalArgumentException e) {
            System.out.println("'duration': P12Y10M1D is not 'yearMonthDuration'!!!");
        }

        XMLGregorianCalendar xgc = df.newXMLGregorianCalendar();
        xgc.setYear(1975);
        xgc.setMonth(DatatypeConstants.AUGUST);
        xgc.setDay(11);
        xgc.setHour(6);
        xgc.setMinute(44);
        xgc.setSecond(0);
        xgc.setMillisecond(0);
        xgc.setTimezone(5);
        xgc.add(myPhone);
        System.out.println("The approximate end of the number of milliseconds in my phone number was " + xgc);

        // adding a duration to XMLGregorianCalendar
        xgc.add(myLife);
        System.out.println("Adding the duration myLife to the above calendar:" + xgc);

        // create a new XMLGregorianCalendar using the string format of xgc.
        XMLGregorianCalendar xgcCopy = df.newXMLGregorianCalendar(xgc.toXMLFormat());

        // should be equal-if not what happened!!
        if (xgcCopy.compare(xgc) != DatatypeConstants.EQUAL) {
            System.out.println("oooops!");
        } else {
            System.out.println("Very good: " + xgc + " is equal to " + xgcCopy);
        }
    } catch (DatatypeConfigurationException dce) {
        System.err.println("error: Datatype error occurred - " + dce.getMessage());
        dce.printStackTrace(System.err);
    }
}

From source file:com.msopentech.odatajclient.engine.data.ODataDuration.java

public ODataDuration(final String input) {
    try {/*from   ww  w  .  jav a2  s.  c o  m*/
        final DatatypeFactory dtFactory = DatatypeFactory.newInstance();
        this.duration = dtFactory.newDuration(input);
    } catch (DatatypeConfigurationException e) {
        throw new IllegalArgumentException("Could not parse '" + input + "' as Duration", e);
    }
}

From source file:de.fischer.thotti.core.runner.NDRunner.java

private TestSuiteResult generatedTestResult(List<NDTestResult> resultList) throws RunnerException {
    if (null == resultList) {
        throw new NullPointerException();
    }//from  ww w  . jav a2  s  . c o m

    DatatypeFactory datatypeFac = null;

    try {
        datatypeFac = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        throw new RunnerException("Failed to instanciate datatype factory.", e);
    }

    de.fischer.thotti.core.resources.ndtest.ObjectFactory factory = new de.fischer.thotti.core.resources.ndtest.ObjectFactory();

    de.fischer.thotti.core.resources.ndresult.ObjectFactory factory2 = new de.fischer.thotti.core.resources.ndresult.ObjectFactory();

    TestSuiteResult suiteResult = factory2.createTestSuiteResult();

    for (NDTestResult result : resultList) {
        NonDistributedTestResultType ndResult = factory2.createNonDistributedTestResultType();

        Duration execTime = datatypeFac.newDuration(result.getExecutionTime());
        XMLGregorianCalendar startTime = datatypeFac.newXMLGregorianCalendar(result.getStartTime());
        ndResult.setTestID(result.getTestId());
        ndResult.setExitCode(BigInteger.valueOf(result.getExitCode()));
        ndResult.setJvmArgsID(result.getJVMArgsID());
        ndResult.setJvmArgs(result.getJvmArgs());
        ndResult.setExecutionTimeMS(execTime);
        ndResult.setStartedAt(startTime);
        ndResult.setParamGrpID(result.getParamGrpID());

        try {
            ndResult.setMahoutVersion(org.apache.mahout.Version.versionFromResource());
        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
        suiteResult.getNonDistributedTestResults().add(ndResult);
    }

    suiteResult.setUuid(generateResultUUID());
    return suiteResult;
}

From source file:org.apache.juddi.v3.tck.UDDI_080_SubscriptionIntegrationTest.java

/**
 * asynch subscriptions , binding key doesn't exist
 *
 * @throws DatatypeConfigurationException
 *///from  w ww .j  a  v  a 2  s  . c  o m
@Test
public void JUDDI_606_9() throws DatatypeConfigurationException {
    Assume.assumeTrue(TckPublisher.isEnabled());
    System.out.println("JUDDI_606_9");
    Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());
    //

    DatatypeFactory df = DatatypeFactory.newInstance();

    try {

        Holder<List<Subscription>> data = new Holder<List<Subscription>>();
        data.value = new ArrayList<Subscription>();
        Subscription sub = new Subscription();
        sub.setBrief(true);
        sub.setExpiresAfter(null);
        sub.setMaxEntities(null);
        sub.setNotificationInterval(df.newDuration(5000));
        sub.setBindingKey("uddi:uddi.joepublisher.com:mykey");
        sub.setSubscriptionFilter(new SubscriptionFilter());
        sub.getSubscriptionFilter().setFindService(new FindService());
        sub.getSubscriptionFilter().getFindService().setFindQualifiers(new FindQualifiers());
        sub.getSubscriptionFilter().getFindService().getFindQualifiers().getFindQualifier()
                .add(UDDIConstants.APPROXIMATE_MATCH);
        sub.getSubscriptionFilter().getFindService().getName().add(new Name("%", null));
        data.value.add(sub);

        tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);
        Assert.fail();
    } catch (Exception ex) {
        logger.info("Expected exception: " + ex.getMessage());
    }
}

From source file:org.apache.juddi.v3.tck.UDDI_141_JIRAIntegrationTest.java

/**
 * testing upper case subscription callbacks
 *
 * @throws Exception//from   w  w w.ja  va2 s.  com
 */
@Test
public void JIRA_597() throws Exception {
    Assume.assumeTrue(TckPublisher.isEnabled());
    System.out.println("JIRA_597");

    int port = 7000;
    String hostname = TckPublisher.getProperties().getProperty("bindaddress");
    if (hostname == null) {
        hostname = InetAddress.getLocalHost().getHostName();
    }

    TckCommon.removeAllExistingSubscriptions(authInfoJoe, subscriptionJoe);
    UDDISubscriptionListenerImpl.notifcationMap.clear();
    UDDISubscriptionListenerImpl.notificationCount = 0;
    Endpoint ep = null;
    boolean ok = false;
    do {
        try {
            logger.info("Attempting to bring up endpoint at " + "http://" + hostname + ":" + port
                    + "/UDDI_CALLBACK");
            ep = Endpoint.publish("http://" + hostname + ":" + port + "/UDDI_CALLBACK", impl);
            ok = true;
        } catch (Exception ex) {
            logger.warn("Trouble starting endpoint: " + ex.getMessage());
            port++;
        }
    } while (!ok);
    SaveBusiness sb = new SaveBusiness();
    sb.setAuthInfo(authInfoJoe);
    BusinessEntity be = new BusinessEntity();
    be.getName().add(new Name());
    be.getName().get(0).setValue("Joe's callback business");
    be.setBusinessServices(new BusinessServices());
    BusinessService bs = new BusinessService();
    bs.getName().add(new Name());
    bs.getName().get(0).setValue("Joe's callback service");
    bs.setBindingTemplates(new BindingTemplates());
    BindingTemplate bt = new BindingTemplate();
    bt.setAccessPoint(new AccessPoint());
    bt.getAccessPoint().setValue("http://" + hostname + ":" + port + "/UDDI_CALLBACK");
    bt.getAccessPoint().setUseType("endPoint");
    //Added per Kurt
    TModelInstanceInfo instanceInfo = new TModelInstanceInfo();
    instanceInfo.setTModelKey("uddi:uddi.org:transport:http");
    bt.setTModelInstanceDetails(new TModelInstanceDetails());
    bt.getTModelInstanceDetails().getTModelInstanceInfo().add(instanceInfo);

    bs.getBindingTemplates().getBindingTemplate().add(bt);

    bs.getBindingTemplates().getBindingTemplate().add(bt);
    be.getBusinessServices().getBusinessService().add(bs);
    sb.getBusinessEntity().add(be);
    BusinessDetail saveBusiness = publicationJoe.saveBusiness(sb);

    List<String> deleteme = new ArrayList<String>();
    deleteme.add(saveBusiness.getBusinessEntity().get(0).getBusinessKey());
    //ok Joe's callback is setup

    //Setup a business to subscribe to
    sb = new SaveBusiness();
    sb.setAuthInfo(authInfoSam);
    be = new BusinessEntity();
    be.getName().add(new Name());
    be.getName().get(0).setValue("Sam's business");
    sb.getBusinessEntity().add(be);
    BusinessDetail saveBusiness1 = publicationSam.saveBusiness(sb);

    //ok Joe now needs to subscribe for Sam's business
    Holder<List<Subscription>> list = new Holder<List<Subscription>>();
    list.value = new ArrayList<Subscription>();
    Subscription s = new Subscription();
    s.setBindingKey(saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().get(0)
            .getBindingTemplates().getBindingTemplate().get(0).getBindingKey());
    s.setSubscriptionFilter(new SubscriptionFilter());
    s.getSubscriptionFilter().setGetBusinessDetail(new GetBusinessDetail());
    s.getSubscriptionFilter().getGetBusinessDetail().getBusinessKey()
            .add(saveBusiness1.getBusinessEntity().get(0).getBusinessKey());
    DatatypeFactory df = DatatypeFactory.newInstance();
    GregorianCalendar gcal = new GregorianCalendar();
    gcal.setTimeInMillis(System.currentTimeMillis());
    gcal.add(Calendar.HOUR, 1);
    s.setExpiresAfter(df.newXMLGregorianCalendar(gcal));

    s.setNotificationInterval(df.newDuration(5000));
    list.value.add(s);
    subscriptionJoe.saveSubscription(authInfoJoe, list);

    //ok have sam change his business around.
    sb = new SaveBusiness();
    sb.setAuthInfo(authInfoSam);
    be = saveBusiness1.getBusinessEntity().get(0);
    be.getName().get(0).setLang("en");
    sb.getBusinessEntity().add(be);
    publicationSam.saveBusiness(sb);
    int maxwait = 30000;
    logger.info("waiting for callbacks");
    while (maxwait > 0) {
        if (UDDISubscriptionListenerImpl.notifcationMap.size() > 0) {
            break;
        }
        Thread.sleep(1000);
        maxwait = maxwait - 1000;
    }
    TckCommon.removeAllExistingSubscriptions(authInfoJoe, subscriptionJoe);
    this.DeleteBusinesses(deleteme, authInfoJoe, publicationJoe);
    deleteme.clear();
    deleteme.add(saveBusiness1.getBusinessEntity().get(0).getBusinessKey());
    this.DeleteBusinesses(deleteme, authInfoSam, publicationSam);
    ep.stop();
    if (UDDISubscriptionListenerImpl.notifcationMap.isEmpty()) {
        Assert.fail("no callbacks were recieved.");
    }

}

From source file:org.apache.juddi.v3.tck.UDDI_141_JIRAIntegrationTest.java

/**
 * testing callbacks with undefined transport type with a uppercase path
 * this also tests the case of one user subscribing to a specific entity
 * via GetBusinessDetail subscription filter
 *
 * @throws Exception//from   ww w  .j av a2 s .  c  o m
 */
@Test
public void JIRA_596() throws Exception {
    Assume.assumeTrue(TckPublisher.isEnabled());
    System.out.println("JIRA_596");
    int port = 9000;

    String hostname = TckPublisher.getProperties().getProperty("bindaddress");
    if (hostname == null) {
        hostname = InetAddress.getLocalHost().getHostName();
    }

    // String localhostname = "localhost";//java.net.InetAddress.getLocalHost().getHostName();
    TckCommon.removeAllExistingSubscriptions(authInfoJoe, subscriptionJoe);
    //UDDISubscriptionListenerImpl impl = new UDDISubscriptionListenerImpl();
    UDDISubscriptionListenerImpl.notifcationMap.clear();
    UDDISubscriptionListenerImpl.notificationCount = 0;

    Endpoint ep = null;
    boolean ok = false;
    do {
        try {
            ep = Endpoint.publish("http://" + hostname + ":" + port + "/UDDI_CALLBACK", impl);
            ok = true;
        } catch (Exception ex) {
            port++;
        }
    } while (!ok);
    SaveBusiness sb = new SaveBusiness();
    sb.setAuthInfo(authInfoJoe);
    BusinessEntity be = new BusinessEntity();
    be.getName().add(new Name());
    be.getName().get(0).setValue("Joe's callback business");
    be.setBusinessServices(new BusinessServices());
    BusinessService bs = new BusinessService();
    bs.getName().add(new Name());
    bs.getName().get(0).setValue("Joe's callback service");
    bs.setBindingTemplates(new BindingTemplates());
    BindingTemplate bt = new BindingTemplate();
    bt.setAccessPoint(new AccessPoint());
    bt.getAccessPoint().setValue("http://" + hostname + ":" + port + "/UDDI_CALLBACK");
    bt.getAccessPoint().setUseType("endPoint");
    //obmitted as part of the jira test case
    /*TModelInstanceInfo instanceInfo = new TModelInstanceInfo();
         instanceInfo.setTModelKey("uddi:uddi.org:transport:http");
         bt.setTModelInstanceDetails(new TModelInstanceDetails());
         bt.getTModelInstanceDetails().getTModelInstanceInfo().add(instanceInfo);
         */
    bs.getBindingTemplates().getBindingTemplate().add(bt);
    be.getBusinessServices().getBusinessService().add(bs);
    sb.getBusinessEntity().add(be);
    logger.info("setting up joe's callback business");
    BusinessDetail saveBusiness = publicationJoe.saveBusiness(sb);

    List<String> deleteme = new ArrayList<String>();
    deleteme.add(saveBusiness.getBusinessEntity().get(0).getBusinessKey());
    //ok Joe's callback is setup

    //Setup a business to subscribe to
    sb = new SaveBusiness();
    sb.setAuthInfo(authInfoSam);
    be = new BusinessEntity();
    be.getName().add(new Name());
    be.getName().get(0).setValue("Sam's business");
    sb.getBusinessEntity().add(be);
    logger.info("saving sam's business");
    BusinessDetail saveBusiness1 = publicationSam.saveBusiness(sb);

    //ok Joe now needs to subscribe for Sam's business
    Holder<List<Subscription>> list = new Holder<List<Subscription>>();
    list.value = new ArrayList<Subscription>();
    Subscription s = new Subscription();
    s.setBindingKey(saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().get(0)
            .getBindingTemplates().getBindingTemplate().get(0).getBindingKey());
    s.setSubscriptionFilter(new SubscriptionFilter());
    s.getSubscriptionFilter().setGetBusinessDetail(new GetBusinessDetail());
    s.getSubscriptionFilter().getGetBusinessDetail().getBusinessKey()
            .add(saveBusiness1.getBusinessEntity().get(0).getBusinessKey());
    DatatypeFactory df = DatatypeFactory.newInstance();
    GregorianCalendar gcal = new GregorianCalendar();
    gcal.setTimeInMillis(System.currentTimeMillis());
    gcal.add(Calendar.HOUR, 1);
    s.setExpiresAfter(df.newXMLGregorianCalendar(gcal));

    s.setNotificationInterval(df.newDuration(5000));
    list.value.add(s);
    logger.info("subscribing joe's to updates for sam's business");
    subscriptionJoe.saveSubscription(authInfoJoe, list);

    //ok have sam change his business around.
    sb = new SaveBusiness();
    sb.setAuthInfo(authInfoSam);
    be = saveBusiness1.getBusinessEntity().get(0);
    be.getName().get(0).setLang("en");
    sb.getBusinessEntity().add(be);
    logger.info("altering sam's business");
    publicationSam.saveBusiness(sb);
    logger.info("Waiting...");
    int maxwait = 30000;
    while (maxwait > 0) {
        if (UDDISubscriptionListenerImpl.notifcationMap.size() > 0) {
            break;
        }
        Thread.sleep(1000);
        maxwait = maxwait - 1000;
    }
    TckCommon.removeAllExistingSubscriptions(authInfoJoe, subscriptionJoe);
    DeleteBusinesses(deleteme, authInfoJoe, publicationJoe);
    deleteme.clear();
    deleteme.add(saveBusiness1.getBusinessEntity().get(0).getBusinessKey());
    DeleteBusinesses(deleteme, authInfoSam, publicationSam);
    ep.stop();
    if (UDDISubscriptionListenerImpl.notifcationMap.isEmpty()) {
        logger.error("no callbacks were recieved");
        Assert.fail("no callbacks were recieved.");
    }
    logger.info("callback response was " + UDDISubscriptionListenerImpl.notifcationMap.get(0));
    logger.info("PASS");

}

From source file:org.miloss.fgsms.common.UtilityTest.java

/**
 * Test of durationToString method, of class Utility.
 *//* w  w  w . j  a v  a2  s .c  o m*/
@Test
public void testDurationToString() {
    System.out.println("DurationToString");
    DatatypeFactory f;
    try {
        f = DatatypeFactory.newInstance();
        Duration d = f.newDuration(1000);

        String expResult = "1s";
        String result = Utility.durationToString(d);
        assertEquals(expResult, result);

    } catch (DatatypeConfigurationException ex) {
        Logger.getLogger(UtilityTest.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.miloss.fgsms.common.UtilityTest.java

@Test
public void testARSSerialization() throws Exception {
    JAXBContext ctx = Utility.getARSSerializationContext();
    DatatypeFactory df = DatatypeFactory.newInstance();
    //   org.miloss.fgsms.services.interfaces.automatedreportingservice.AddOrUpdateScheduledReportRequestMsg req = new AddOrUpdateScheduledReportRequestMsg();
    // req.setClassification(new SecurityWrapper());
    GregorianCalendar gcal = new GregorianCalendar();
    ReportDefinition rd = new ReportDefinition();
    rd.getAdditionalReaders().add("test");
    rd.setEnabled(true);// w w w .  j  a  v  a 2s  . c  o  m
    rd.setFriendlyName("test");
    rd.setJobId("test");
    //rd.setLastRanAt(df.newCalendar(gcal));
    rd.setOwner("test");
    rd.setSchedule(new ScheduleDefinition());
    WeeklySchedule ws = new WeeklySchedule();
    ws.getDayOfTheWeekIs().add(Daynames.SUNDAY);
    ws.setReoccurs(BigInteger.ONE);
    rd.getSchedule().getTriggers().add(ws);
    DailySchedule ds = new DailySchedule();
    ds.setReoccurs(BigInteger.ONE);
    ds.setStartingAt((gcal));

    rd.getSchedule().getTriggers().add(ds);
    MonthlySchedule ms = new MonthlySchedule();
    ms.getDayOfTheMonthIs().add(1);
    ms.getMonthNameIs().add(Monthnames.MAY);
    ds.setStartingAt((gcal));

    rd.getSchedule().getTriggers().add(ms);

    rd.setExportCSVDataRequestMsg(new ExportCSVDataRequestMsg());
    rd.getExportCSVDataRequestMsg().setClassification(new SecurityWrapper());
    rd.getExportCSVDataRequestMsg().setExportType(ExportRecordsEnum.MACHINE);
    rd.getExportCSVDataRequestMsg().setRange(new TimeRangeDiff());
    rd.getExportCSVDataRequestMsg().getURLs().add("test");
    rd.getExportCSVDataRequestMsg().getRange().setEnd(df.newDuration(1000));
    rd.getExportCSVDataRequestMsg().getRange().setStart(df.newDuration(1000));

    rd.setExportDataRequestMsg(new ExportDataRequestMsg());
    rd.getExportDataRequestMsg().setClassification(new SecurityWrapper());
    rd.getExportDataRequestMsg().getURLs().add("test");
    rd.getExportDataRequestMsg().setRange(new TimeRangeDiff());
    rd.getExportDataRequestMsg().getRange().setEnd(df.newDuration(1000));
    rd.getExportDataRequestMsg().getRange().setStart(df.newDuration(1000));
    rd.getExportDataRequestMsg().setReportTypes(new ArrayOfReportTypeContainer());
    ReportTypeContainer rtc = new ReportTypeContainer();
    rtc.setType("org.miloss.fgsms.services.rs.impl.reports.ws.MeanTimeBetweenFailureByService");
    rd.getExportDataRequestMsg().getReportTypes().getReportTypeContainer().add(rtc);
    rd.getNotifications().add(new SLAAction());
    //   req.getJobs().add(rd);
    Marshaller m = ctx.createMarshaller();
    StringWriter sw = new StringWriter();
    m.marshal(rd, sw);
    System.out.println(sw.toString());
    assertNotNull(sw.toString());
    Unmarshaller u = ctx.createUnmarshaller();
    Object unmarshal = u.unmarshal(new StringReader(sw.toString()));
    ReportDefinition rd2 = (ReportDefinition) unmarshal;
    assertNotNull(rd2);
    assertNotNull(rd2.getExportCSVDataRequestMsg());
    assertNotNull(rd2.getExportDataRequestMsg());
    assertFalse(rd2.getNotifications().isEmpty());
    assertNotNull(rd2.getSchedule());
    assertFalse(rd2.getSchedule().getTriggers().isEmpty());
}

From source file:org.miloss.fgsms.common.UtilityTest.java

/**
 * Test of durationLargestUnitToString method, of class Utility.
 *///w  ww . j a  va  2s .co m
@Test
public void testDurationLargestUnitToString() {
    try {
        System.out.println("DurationLargestUnitToString");
        DatatypeFactory f;
        f = DatatypeFactory.newInstance();
        Duration d = f.newDuration(100000);

        String expResult = "1min";
        String result = Utility.durationLargestUnitToString(d);
        assertEquals(expResult, result);
    } catch (DatatypeConfigurationException ex) {
        Logger.getLogger(UtilityTest.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.miloss.fgsms.common.UtilityTest.java

/**
 * Test of durationToTimeInMS method, of class Utility.
 *//*from   w  w w  .  ja v a 2s . c o  m*/
@Test
public void testDurationToTimeInMS() {
    try {
        System.out.println("DurationToTimeInMS");
        DatatypeFactory f = DatatypeFactory.newInstance();

        Duration d = f.newDuration(1000);
        long expResult = 1000L;
        long result = Utility.durationToTimeInMS(d);
        assertEquals(expResult, result);
    } catch (DatatypeConfigurationException ex) {
        Logger.getLogger(UtilityTest.class.getName()).log(Level.SEVERE, null, ex);
        fail("unexpected failure");
    }

}