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:org.kuali.kra.external.award.impl.AccountCreationClientBase.java

/**
 * This method sets the necessary values in the AccountParametersDTO object to be sent 
 * across to the financial service.//from  w  ww  .j av  a 2s  .  c om
 * @param award
 * @throws DatatypeConfigurationException
 */
protected AccountParametersDTO getAccountParameters(Award award) throws DatatypeConfigurationException {

    AccountParametersDTO accountParameters = new AccountParametersDTO();

    setName(award, accountParameters);
    //Account number
    accountParameters.setAccountNumber(award.getAccountNumber());
    setDefaultAddress(award, accountParameters);
    setAdminAddress(award, accountParameters);

    //cfdaNumber
    String cfdaNumber = award.getCfdaNumber();
    if (cfdaNumber != null) {
        accountParameters.setCfdaNumber(cfdaNumber);
    }

    //effective date
    Date effectiveDate = award.getAwardEffectiveDate();
    GregorianCalendar dateEffective = new GregorianCalendar();
    dateEffective.setTime(effectiveDate);
    XMLGregorianCalendar gregorianDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(dateEffective);
    accountParameters.setEffectiveDate(gregorianDate);

    //expiration date
    Date expirationDate = award.getProjectEndDate();
    GregorianCalendar dateExpiration = new GregorianCalendar();
    dateExpiration.setTime(expirationDate);
    gregorianDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(dateExpiration);
    accountParameters.setExpirationDate(gregorianDate);

    // expense guideline text
    String expenseGuidelineText = award.getAwardNumber();
    accountParameters.setExpenseGuidelineText(expenseGuidelineText);

    setIncomeGuidelineText(award, accountParameters);

    //account purpose text
    accountParameters.setPurposeText(award.getTitle());

    // unit number
    accountParameters.setUnit(award.getUnitNumber());
    //Principal id
    accountParameters.setPrincipalId(GlobalVariables.getUserSession().getPrincipalId());

    AwardFandaRate currentFandaRate = award.getCurrentFandaRate();

    String rateClassCode = currentFandaRate.getFandaRateType().getRateClassCode();
    String rateTypeCode = currentFandaRate.getFandaRateType().getRateTypeCode();
    String icrTypeCode = getIndirectCostTypeCode(rateClassCode, rateTypeCode);
    accountParameters.setOffCampusIndicator(!currentFandaRate.getOnOffCampusFlag());

    String icrRateCode = award.getIcrRateCode();
    if (Award.ICR_RATE_CODE_NONE.equals(icrRateCode)) {
        accountParameters.setIndirectCostRate("");
    } else {
        accountParameters.setIndirectCostRate(icrRateCode);
    }

    accountParameters.setIndirectCostTypeCode(icrTypeCode + "");

    accountParameters.setHigherEdFunctionCode(award.getActivityType().getHigherEducationFunctionCode());

    return accountParameters;

}

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

/**
 * Test of durationToString method, of class Utility.
 *//*  w  ww. ja  v a2s .com*/
@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);//from  w  w w. ja  v a2s .com
    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.
 *///from  w  w  w  .ja  v a2s .c  om
@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  ww  .jav a  2 s .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");
    }

}

From source file:org.miloss.fgsms.presentation.Helper.java

/**
     * returns a duration parsed from xyr xmo xd xhr xmin xs
     * //www . j a  v  a2s  .c  o m
     * first it will parse it as a xml representation then as a Long then the
     * specific format
     */
    public static Duration StringToDuration(String d) throws DatatypeConfigurationException {
        if (Utility.stringIsNullOrEmpty(d)) {
            return null;
        }
        String[] s = d.split(" ");
        if (s == null || s.length == 0) {
            return null;
        }
        DatatypeFactory fac = DatatypeFactory.newInstance();
        try {
            Duration dur = fac.newDuration(d);
            return dur;
        } catch (Exception ex) {
        }
        try {
            Duration dur = fac.newDuration(Long.parseLong(d));
            return dur;
        } catch (Exception ex) {
        }
        long durationInMilliSeconds = 0;
        String temp;
        long x = 0;
        for (int i = 0; i < s.length; i++) {
            if (s[i].contains("yr")) {
                temp = s[i].replace("yr", "").trim();
                x = Long.parseLong(temp);
                durationInMilliSeconds += (x * 365 * 24 * 60 * 60 * 1000);
            } else if (s[i].contains("mo")) {
                temp = s[i].replace("mo", "").trim();
                x = Long.parseLong(temp);
                durationInMilliSeconds += (x * 30 * 24 * 60 * 60 * 1000);
            } else if (s[i].contains("d")) {
                temp = s[i].replace("d", "").trim();
                x = Long.parseLong(temp);
                durationInMilliSeconds += (x * 24 * 60 * 60 * 1000);
            } else if (s[i].contains("hr")) {
                temp = s[i].replace("hr", "").trim();
                x = Long.parseLong(temp);
                durationInMilliSeconds += (x * 60 * 60 * 1000);
            } else if (s[i].contains("min")) {
                temp = s[i].replace("min", "").trim();
                x = Long.parseLong(temp);
                durationInMilliSeconds += (x * 60 * 1000);
            } else if (s[i].contains("s")) {
                temp = s[i].replace("s", "").trim();
                x = Long.parseLong(temp);
                durationInMilliSeconds += (x * 1000);
            }
        }
        Duration dur = fac.newDuration(durationInMilliSeconds);
        return dur;
    }

From source file:org.miloss.fgsms.tests.ManualLoadTests.java

public void setPolicy(String url) throws ConfigurationException, ServiceUnavailableException,
        AccessDeniedException, DatatypeConfigurationException {
    System.out.println("Setting up policy");
    TransactionalWebServicePolicy pol = new TransactionalWebServicePolicy();
    pol.setAgentsEnabled(true);/*w w  w  . j av a  2s . c o  m*/
    pol.setBuellerEnabled(false);
    pol.setDataTTL(DatatypeFactory.newInstance().newDuration(600000));
    pol.setHealthStatusEnabled(false);
    pol.setMachineName(Utility.getHostName());
    pol.setPolicyType(PolicyType.TRANSACTIONAL);
    pol.setURL(url);
    SetServicePolicyRequestMsg req = new SetServicePolicyRequestMsg();
    req.setClassification(new SecurityWrapper());
    req.setURL(pol.getURL());
    req.setPolicy(pol);
    pcsport.setServicePolicy(req);
}

From source file:org.mitre.stix.examples.CIQIdentity.java

/**
 * @param args/*from  ww w.  j  a  v a  2s.com*/
 * @throws DatatypeConfigurationException
 * @throws JAXBException
 * @throws ParserConfigurationException
 */
@SuppressWarnings("serial")
public static void main(String[] args) {

    try {
        // Get time for now.
        XMLGregorianCalendar now = DatatypeFactory.newInstance()
                .newXMLGregorianCalendar(new GregorianCalendar(TimeZone.getTimeZone("UTC")));

        ContactNumbers contactNumbers = new ContactNumbers()
                .withContactNumbers(new ContactNumbers.ContactNumber().withContactNumberElements(
                        new ContactNumbers.ContactNumber.ContactNumberElement().withValue("555-555-5555"),
                        new ContactNumbers.ContactNumber.ContactNumberElement().withValue("555-555-5556")));

        ElectronicAddressIdentifiers electronicAddressIdentifiers = new ElectronicAddressIdentifiers()
                .withElectronicAddressIdentifiers(new ElectronicAddressIdentifiers.ElectronicAddressIdentifier()
                        .withValue("jsmith@example.com"));

        FreeTextLines freeTextLines = new FreeTextLines()
                .withFreeTextLines(new FreeTextLines.FreeTextLine().withValue("Demonstrating Free Text!"));

        PartyNameType partyName = new PartyNameType()
                .withNameLines(new NameLine().withValue("Foo"), new NameLine().withValue("Bar"))
                .withPersonNames(new PersonName().withNameElements(
                        new oasis.names.tc.ciq.xnl._3.PersonNameType.NameElement().withValue("John Smith")),
                        new PersonName()
                                .withNameElements(new oasis.names.tc.ciq.xnl._3.PersonNameType.NameElement()
                                        .withValue("Jill Smith")))
                .withOrganisationNames(new OrganisationName().withNameElements(
                        new oasis.names.tc.ciq.xnl._3.OrganisationNameType.NameElement().withValue("Foo Inc.")),
                        new OrganisationName().withNameElements(
                                new oasis.names.tc.ciq.xnl._3.OrganisationNameType.NameElement()
                                        .withValue("Bar Corp.")));

        STIXCIQIdentity30Type specification = new STIXCIQIdentity30Type().withContactNumbers(contactNumbers)
                .withElectronicAddressIdentifiers(electronicAddressIdentifiers).withFreeTextLines(freeTextLines)
                .withPartyName(partyName);

        CIQIdentity30InstanceType identity = new CIQIdentity30InstanceType().withSpecification(specification);

        InformationSourceType producer = new InformationSourceType()
                .withDescriptions(new StructuredTextType()
                        .withValue("An indicator containing a File observable with an associated hash"))
                .withTime(new TimeType().withProducedTime(new DateTimeWithPrecisionType(now, null)))
                .withIdentity(identity);

        FileObjectType fileObject = new FileObjectType().withHashes(new HashListType(new ArrayList<HashType>() {
            {
                add(new HashType().withType(new HashNameVocab10().withValue("MD5")).withSimpleHashValue(
                        new SimpleHashValueType().withValue("4EC0027BEF4D7E1786A04D021FA8A67F")));
            }
        }));

        ObjectType obj = new ObjectType().withProperties(fileObject)
                .withId(new QName("http://example.com/", "file-" + UUID.randomUUID().toString(), "example"));

        Observable observable = new Observable().withId(
                new QName("http://example.com/", "observable-" + UUID.randomUUID().toString(), "example"));

        observable.setObject(obj);

        final Indicator indicator = new Indicator()
                .withId(new QName("http://example.com/", "indicator-" + UUID.randomUUID().toString(),
                        "example"))
                .withTimestamp(now).withTitle("File Hash Example")
                .withDescriptions(new StructuredTextType()
                        .withValue("An indicator containing a File observable with an associated hash"))
                .withProducer(producer).withObservable(observable);

        IndicatorsType indicators = new IndicatorsType(new ArrayList<IndicatorBaseType>() {
            {
                add(indicator);
            }
        });

        STIXHeaderType header = new STIXHeaderType()
                .withDescriptions(new StructuredTextType().withValue("Example"));

        STIXPackage stixPackage = new STIXPackage().withSTIXHeader(header).withIndicators(indicators)
                .withVersion("1.2").withTimestamp(now)
                .withId(new QName("http://example.com/", "package-" + UUID.randomUUID().toString(), "example"));

        System.out.println(stixPackage.toXMLString(true));

        System.out.println(StringUtils.repeat("-", 120));

        System.out.println("Validates: " + stixPackage.validate());

        System.out.println(StringUtils.repeat("-", 120));

        System.out.println(STIXPackage.fromXMLString(stixPackage.toXMLString()).toXMLString(true));

    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        e.printStackTrace();
    }
}

From source file:org.mitre.stix.examples.CreationToolMetadata.java

public static void main(String[] args) {

    try {/*from  w  w w .j  a v a2 s  .  com*/
        // Get time for now.
        XMLGregorianCalendar now = DatatypeFactory.newInstance()
                .newXMLGregorianCalendar(new GregorianCalendar(TimeZone.getTimeZone("UTC")));

        STIXHeaderType header = new STIXHeaderType()
                .withDescriptions(new StructuredTextType().withValue("Example"))
                .withInformationSource(new InformationSourceType()
                        .withTools(new ToolsInformationType().withTools(new ToolInformationType()
                                .withName("org.mitre.stix.examples.CreationToolMetadata")
                                .withVendor("The MITRE Corporation"))));

        STIXPackage stixPackage = new STIXPackage().withSTIXHeader(header).withVersion("1.2").withTimestamp(now)
                .withId(new QName("http://example.com/", "package-" + UUID.randomUUID().toString(), "example"));

        System.out.println(stixPackage.toXMLString(true));

        System.out.println(StringUtils.repeat("-", 120));

        System.out.println("Validates: " + stixPackage.validate());

    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        e.printStackTrace();
    }
}

From source file:org.mitre.stix.examples.IndicatorHash.java

@SuppressWarnings("serial")
public static void main(String[] args) {

    try {//from w ww.j  av a 2  s .co  m
        // Get time for now.
        XMLGregorianCalendar now = DatatypeFactory.newInstance()
                .newXMLGregorianCalendar(new GregorianCalendar(TimeZone.getTimeZone("UTC")));

        FileObjectType fileObject = new FileObjectType().withHashes(new HashListType(new ArrayList<HashType>() {
            {
                add(new HashType().withType(new HashNameVocab10().withValue("MD5")).withSimpleHashValue(
                        new SimpleHashValueType().withValue("4EC0027BEF4D7E1786A04D021FA8A67F")));
            }
        }));

        ObjectType obj = new ObjectType().withProperties(fileObject)
                .withId(new QName("http://example.com/", "file-" + UUID.randomUUID().toString(), "example"));

        Observable observable = new Observable().withId(
                new QName("http://example.com/", "observable-" + UUID.randomUUID().toString(), "example"));

        observable.setObject(obj);

        IdentityType identity = new IdentityType().withName("The MITRE Corporation");

        InformationSourceType producer = new InformationSourceType().withIdentity(identity)
                .withTime(new TimeType().withProducedTime(new DateTimeWithPrecisionType(now, null)));

        final Indicator indicator = new Indicator()
                .withId(new QName("http://example.com/", "indicator-" + UUID.randomUUID().toString(),
                        "example"))
                .withTimestamp(now).withTitle("File Hash Example")
                .withDescriptions(new StructuredTextType()
                        .withValue("An indicator containing a File observable with an associated hash"))
                .withObservable(observable).withProducer(producer);

        IndicatorsType indicators = new IndicatorsType(new ArrayList<IndicatorBaseType>() {
            {
                add(indicator);
            }
        });

        STIXHeaderType stixHeader = new STIXHeaderType()
                .withDescriptions(new StructuredTextType().withValue("Example"));

        STIXPackage stixPackage = new STIXPackage().withSTIXHeader(stixHeader).withIndicators(indicators)
                .withVersion("1.2").withTimestamp(now)
                .withId(new QName("http://example.com/", "package-" + UUID.randomUUID().toString(), "example"));

        System.out.println(stixPackage.toXMLString(true));

        System.out.println(StringUtils.repeat("-", 120));

        System.out.println("Validates: " + stixPackage.validate());

    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        e.printStackTrace();
    }
}