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:io.uengine.util.DateUtils.java

/**
 * YYYY-MM-DDTHH:MI:SS ? ?(:2007-02-13T10:25:00) XMLGregorianCalendar ? ?.
 *
 * @param stringTypeDate YYYY-MM-DDTHH:MI:SS ? ?(:2007-02-13T10:25:00)
 * @return XMLGregorianCalendar//  w w w  . j av a 2 s .com
 */
public static XMLGregorianCalendar toXMLGregorianCalendar(String stringTypeDate)
        throws DatatypeConfigurationException {
    String yyyy = stringTypeDate.substring(0, 4);
    String mm = stringTypeDate.substring(5, 7);
    String dd = stringTypeDate.substring(8, 10);
    String hh = stringTypeDate.substring(11, 13);
    String mi = stringTypeDate.substring(14, 16);
    String ss = stringTypeDate.substring(17, 19);

    int iyyyy = Integer.parseInt(yyyy);
    int imm = Integer.parseInt(mm);
    int idd = Integer.parseInt(dd);
    int ihh = Integer.parseInt(hh);
    int imi = Integer.parseInt(mi);
    int iss = Integer.parseInt(ss);

    DatatypeFactory dataTypeFactory = DatatypeFactory.newInstance();
    return dataTypeFactory.newXMLGregorianCalendar(iyyyy, imm, idd, ihh, imi, iss, 0, 0);
}

From source file:com.cisco.dvbu.ps.common.util.CommonUtils.java

public static XMLGregorianCalendar getXMLGregorianCalendarFromTimestamp(String timestamp)
        throws CompositeException {

    // -- e.g. "2011-02-10T14:18:42.000Z"

    timestamp = timestamp.replace("T", " ");
    timestamp = timestamp.replace("Z", "");

    Date date = Timestamp.valueOf(timestamp);

    DatatypeFactory df;/*  w  w w  . j a  va2  s.  co m*/
    try {
        df = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        throw new CompositeException(e);
    }

    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);
    XMLGregorianCalendar retval = df.newXMLGregorianCalendar(cal);

    return retval;

}

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

@Test
@DirtiesContext// ww  w  . j a  v  a2 s  .c  om
public void testNonRecoverableExternalServiceException() throws Exception {
    configureProcessRecordFailure(1, false);

    context.start();

    DatatypeFactory dtf = DatatypeFactory.newInstance();

    output.setExpectedMessageCount(0);

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

    try {
        trigger.sendBody(SimpleFileIngestorRouteBuilder.HANDLE_RECORD_ROUTE_ENDPOINT_URI,
                marshallToXml(recordType));
    } catch (CamelExecutionException e) {
        // expected
    }

    output.assertIsSatisfied(1000);
}

From source file:org.bedework.synch.cnctrs.orgSyncV2.OrgSyncV2ConnectorInstance.java

private DateDatetimePropertyType makeDt(final DateDatetimePropertyType dt, final String val) {
    try {/* w ww. j  a va  2  s.c o m*/
        final DatatypeFactory dtf = DatatypeFactory.newInstance();

        final XMLGregorianCalendar xgc = dtf.newXMLGregorianCalendar(val);
        if (val.length() == 10) {
            dt.setDate(xgc);
            return dt;
        }

        dt.setDateTime(xgc);
        return dt;
    } catch (final DatatypeConfigurationException dce) {
        error(dce);
        return null;
    }
}

From source file:gov.nih.nci.cabig.caaers.service.migrator.StudyConverter.java

private XMLGregorianCalendar convertCalendar2XmlGregorianCalendar(Calendar c) throws Exception {
    XMLGregorianCalendar xml = DatatypeFactory.newInstance().newXMLGregorianCalendar();
    xml.setYear(c.get(Calendar.YEAR));
    xml.setMonth(c.get(Calendar.MONTH) + 1);
    xml.setDay(c.get(Calendar.DAY_OF_MONTH));
    return xml;// ww w  .  ja  v  a2 s  . c om
}

From source file:eu.openminted.registry.service.generate.WorkflowOutputMetadataGenerate.java

protected VersionInfo generateVersionInfo() {
    VersionInfo versionInfo = new VersionInfo();
    versionInfo.setVersion("0.0.1");
    // Set creation date and last date updated
    XMLGregorianCalendar calendar = null;
    try {/* w  ww.ja v  a 2s .  c om*/
        calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregory);
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
    }

    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
    String str = format.format(calendar.toGregorianCalendar().getTime());
    versionInfo.setVersionDate(str);
    return versionInfo;
}

From source file:com.qubit.solution.fenixedu.integration.cgd.services.form43.CgdForm43Sender.java

private static Person createPerson(org.fenixedu.academic.domain.Person person) {
    Person personData = new Person();

    executeIfAllowed(person, CgdAuthorizationCodes.BASIC_INFO, () -> personData.setName(person.getName()));
    executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_EMAIL, () -> personData
            .setEmail(objectFactory.createPersonEmail(person.getInstitutionalEmailAddressValue())));
    executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_GENDER, () -> personData
            .setGenderCode(objectFactory.createPersonGenderCode(getCodeForGender(person.getGender()))));

    YearMonthDay dateOfBirthYearMonthDay = person.getDateOfBirthYearMonthDay();
    if (dateOfBirthYearMonthDay != null) {
        executeIfAllowed(person, CgdAuthorizationCodes.BASIC_INFO, () -> {
            try {
                personData.setBirthDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(
                        dateOfBirthYearMonthDay.toDateTimeAtMidnight().toGregorianCalendar()));
            } catch (DatatypeConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//from  ww w  .ja va 2s  . c o  m
            }
        });
    }
    executeIfAllowed(person, CgdAuthorizationCodes.BASIC_INFO, () -> personData
            .setFiscalNumber(objectFactory.createPersonFiscalNumber(person.getSocialSecurityNumber())));

    PersonalIngressionData personalIngressionDataByExecutionYear = person.getStudent()
            .getPersonalIngressionDataByExecutionYear(ExecutionYear.readCurrentExecutionYear());
    if (personalIngressionDataByExecutionYear != null) {
        org.fenixedu.academic.domain.person.MaritalStatus maritalStatus = personalIngressionDataByExecutionYear
                .getMaritalStatus();
        executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_MARITAL_STATUS,
                () -> personData.setMaritalStatusCode(
                        objectFactory.createPersonMaritalStatusCode(getCodeForMaritalStatus(maritalStatus))));

    }

    executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_FATHER_NAME, () -> personData
            .setFather(objectFactory.createPersonFather(getShortNameFor(person.getNameOfFather()))));

    executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_MOTHER_NAME, () -> personData
            .setMother(objectFactory.createPersonMother(getShortNameFor(person.getNameOfMother()))));

    if (person.getCountryOfBirth() != null) {
        executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_BIRTH_COUNTRY,
                () -> personData.setPlaceOfBirthCountryCode(objectFactory
                        .createPersonPlaceOfBirthCountryCode(person.getCountryOfBirth().getCode())));
    }

    executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_BIRTH_DISTRICT,
            () -> personData.setPlaceOfBirthDistrict(
                    objectFactory.createPersonPlaceOfBirthDistrict(person.getDistrictOfBirth())));

    executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_BIRTH_COUNTY,
            () -> personData.setPlaceOfBirthCounty(
                    objectFactory.createPersonPlaceOfBirthCounty(person.getDistrictSubdivisionOfBirth())));

    executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_BIRTH_PARISH, () -> personData
            .setPlaceOfBirthParish(objectFactory.createPersonPlaceOfBirthParish(person.getParishOfBirth())));

    ArrayOfstring nationality = new ArrayOfstring();
    nationality.getString().add(person.getCountry().getCode());
    Country countryOfResidence = person.getCountryOfResidence();

    executeIfAllowed(person, CgdAuthorizationCodes.BASIC_INFO, () -> {
        personData.setNationalities(nationality);
        if (countryOfResidence != null) {
            personData.setCountryOfResidenceCode(
                    objectFactory.createPersonCountryOfResidenceCode(countryOfResidence.getCode()));
        } else {
            personData.setCountryOfResidenceCode(objectFactory.createPersonCountryOfResidenceCode("PT"));
        }
    });

    PhysicalAddress defaultPhysicalAddress = person.getDefaultPhysicalAddress();
    if (defaultPhysicalAddress != null) {
        executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_ADDRESS_PLACE, () -> {
            personData.setAddress(objectFactory.createPersonAddress(defaultPhysicalAddress.getAddress()));
            personData.setPlace(objectFactory.createPersonPlace(defaultPhysicalAddress.getArea()));
        });
        executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_ADDRESS_POSTAL_CODE, () -> personData
                .setPostalCode(objectFactory.createPersonPostalCode(defaultPhysicalAddress.getAreaCode())));
        executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_ADDRESS_DISTRICT,
                () -> personData.setDistrict(
                        objectFactory.createPersonDistrict(defaultPhysicalAddress.getDistrictOfResidence())));
        executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_ADDRESS_POSTAL_COUNTY,
                () -> personData.setCounty(objectFactory
                        .createPersonCounty(defaultPhysicalAddress.getDistrictSubdivisionOfResidence())));
        executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_ADDRESS_POSTAL_PARISH, () -> personData
                .setParish(objectFactory.createPersonParish(defaultPhysicalAddress.getParishOfResidence())));
    }

    executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_PHONE, () -> personData.setPhone(
            objectFactory.createPersonPhone(getPhoneNumberWithoutCountryCode(person.getDefaultPhoneNumber()))));
    executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_MOBILE_PHONE,
            () -> personData.setMobilePhone(objectFactory.createPersonMobilePhone(
                    getPhoneNumberWithoutCountryCode(person.getDefaultMobilePhoneNumber()))));

    IdentificationCard card = new IdentificationCard();

    // skipping issuer
    String codeForDocumentType = getCodeForDocumentType(person.getIdDocumentType());
    if (codeForDocumentType != null) {
        card.setTypeCode(objectFactory.createIdentificationCardTypeCode(codeForDocumentType));
    }
    card.setNumber(person.getDocumentIdNumber());
    // skipping issuer country code
    executeIfAllowed(person, CgdAuthorizationCodes.EXTENDED_INFO_ID_CARD_EXPIRATION_DATE, () -> {
        try {
            YearMonthDay expirationDateOfDocumentIdYearMonthDay = person
                    .getExpirationDateOfDocumentIdYearMonthDay();
            if (expirationDateOfDocumentIdYearMonthDay != null) {
                card.setExpirationDate(objectFactory.createIdentificationCardExpirationDate(DatatypeFactory
                        .newInstance().newXMLGregorianCalendar(expirationDateOfDocumentIdYearMonthDay
                                .toDateTimeAtMidnight().toGregorianCalendar())));
            }
        } catch (DatatypeConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    });
    personData.setIdentificationCard(objectFactory.createIdentificationCard(card));

    return personData;
}

From source file:eu.europa.fisheries.uvms.rules.service.mapper.fact.ActivityFactMapperTest.java

@Before
@SneakyThrows//from w  ww  .  j a  va2s.c om
public void before() {

    SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
    date = sdf.parse("31-08-1982 10:20:56");

    idType = new IDType();
    idType.setValue("value");
    idType.setSchemeID("schemeId");

    codeType = new CodeType();
    codeType.setValue("value");

    quantityType = new QuantityType();
    quantityType.setUnitCode("unitCode");
    quantityType.setValue(new BigDecimal(10));

    measureType = new MeasureType();
    measureType.setUnitCode("unitCode");
    measureType.setValue(new BigDecimal(10));

    delimitedPeriod = new DelimitedPeriod();
    MeasureType durationMeasure = new MeasureType();
    durationMeasure.setUnitCode("unitCode");
    durationMeasure.setValue(new BigDecimal(10));
    delimitedPeriod.setDurationMeasure(durationMeasure);

    GregorianCalendar c = new GregorianCalendar();
    c.setTime(date);

    dateTimeType = new DateTimeType();
    dateTimeType.setDateTime(DatatypeFactory.newInstance().newXMLGregorianCalendar(c));
    delimitedPeriod.setStartDateTime(dateTimeType);
    delimitedPeriod.setEndDateTime(dateTimeType);

    fluxLocation = new FLUXLocation();
    fluxLocation.setID(idType);

    fishingTrip = new FishingTrip();
    fishingTrip.setIDS(singletonList(idType));

    faCatch = new FACatch();
    faCatch.setTypeCode(codeType);

    fishingGear = new FishingGear();
    fishingGear.setTypeCode(codeType);
    fishingGear.setRoleCodes(singletonList(codeType));

    codeTypeList = singletonList(codeType);

    appliedAAPProcesses = new ArrayList<>();
    AAPProcess aapProcess = new AAPProcess();
    aapProcess.setTypeCodes(singletonList(codeType));

    measureType = new MeasureType();
    measureType.setUnitCode("unitCode");
    measureType.setValue(new BigDecimal(10));

    aapProduct = new AAPProduct();
    aapProduct.setWeightMeasure(measureType);
    aapProduct.setPackagingUnitQuantity(quantityType);

    aapProcess.setResultAAPProducts(singletonList(aapProduct));
    appliedAAPProcesses.add(aapProcess);

    GearCharacteristic gearCharacteristic = new GearCharacteristic();
    gearCharacteristic.setTypeCode(codeType);
    gearCharacteristic.setValue(new TextType("testValue", null, null));

    applicableGearCharacteristics = new ArrayList<>();
    applicableGearCharacteristics.add(gearCharacteristic);

    fluxGeographicalCoordinate = new FLUXGeographicalCoordinate();
    fluxGeographicalCoordinate.setAltitudeMeasure(measureType);
    fluxGeographicalCoordinate.setLatitudeMeasure(measureType);

    fluxLocation = new FLUXLocation();
    fluxLocation.setTypeCode(codeType);
    faCatch = new FACatch();
    faCatch.setTypeCode(codeType);
    specifiedFluxLocation = new ArrayList<>();
    specifiedFluxLocation.add(fluxLocation);
    faCatch.setSpecifiedFLUXLocations(specifiedFluxLocation);
    specifiedFACatch = new ArrayList<>();
    specifiedFACatch.add(faCatch);

    fluxFaTestMessage = loadTestData();

    faQueryParameterList = new ArrayList<>();
    FAQueryParameter faQueryParameter = new FAQueryParameter();
    faQueryParameter.setTypeCode(codeType);
    faQueryParameter.setValueCode(codeType);
    faQueryParameter.setValueDateTime(dateTimeType);
    faQueryParameter.setValueID(idType);
    faQueryParameterList.add(faQueryParameter);

    faQuery = new FAQuery();
    faQuery.setID(idType);
    faQuery.setSimpleFAQueryParameters(faQueryParameterList);
    faQuery.setSpecifiedDelimitedPeriod(delimitedPeriod);
    faQuery.setSubmittedDateTime(dateTimeType);
    faQuery.setTypeCode(codeType);

    flapDocumentList = new ArrayList<>();
    flapDocumentList.add(RuleTestHelper.getFLAPDocument());

    fluxResponseMessage = new FLUXResponseMessage();
    FLUXResponseDocument fluxResponseDocument = new FLUXResponseDocument();
    fluxResponseDocument.setResponseCode(codeType);
    fluxResponseDocument.setIDS(Arrays.asList(idType));

    List<ValidationResultDocument> validationResultDocuments = new ArrayList<>();
    validationResultDocument = new ValidationResultDocument();
    validationResultDocument.setCreationDateTime(dateTimeType);
    validationResultDocument.setValidatorID(idType);

    List<ValidationQualityAnalysis> validationQualityAnalysisList = new ArrayList<>();
    validationQualityAnalysis = new ValidationQualityAnalysis();
    validationQualityAnalysis.setTypeCode(codeType);
    validationQualityAnalysis.setLevelCode(codeType);
    validationQualityAnalysis.setID(idType);

    validationQualityAnalysisList.add(validationQualityAnalysis);
    validationResultDocument.setRelatedValidationQualityAnalysises(validationQualityAnalysisList);
    validationResultDocuments.add(validationResultDocument);

    fluxResponseDocument.setRelatedValidationResultDocuments(validationResultDocuments);

    fluxResponseMessage.setFLUXResponseDocument(fluxResponseDocument);

}

From source file:fr.efl.chaine.xslt.GauloisPipe.java

/**
 * Launch the pipe./*  ww  w . j a  v a 2s .c o m*/
 *
 * @throws fr.efl.chaine.xslt.InvalidSyntaxException If config's syntax is incorrect
 * @throws java.io.FileNotFoundException If a file is not found...
 * @throws net.sf.saxon.s9api.SaxonApiException If a SaxonApi problem occurs
 * @throws java.net.URISyntaxException Because MVN forces to have comments...
 */
@SuppressWarnings("ThrowFromFinallyBlock")
public void launch() throws InvalidSyntaxException, FileNotFoundException, SaxonApiException,
        URISyntaxException, IOException {
    initDebugDirectory();
    Runtime.getRuntime().addShutdownHook(new Thread(new ErrorCollector(errors)));
    long start = System.currentTimeMillis();
    errors = Collections.synchronizedList(new ArrayList<Exception>());
    documentCache = new DocumentCache(config.getMaxDocumentCacheSize());
    if (this.messageListenerclass != null) {
        try {
            this.messageListener = this.messageListenerclass.newInstance();
        } catch (InstantiationException | IllegalAccessException ex) {
            System.err.println("[WARN] Fail to instanciate " + this.messageListenerclass.getName());
            ex.printStackTrace(System.err);
        }
    }
    boolean retCode = true;
    try {
        Configuration saxonConfig = configurationFactory.getConfiguration();
        LOGGER.debug("configuration is a " + saxonConfig.getClass().getName());
        // this is now done in constructor
        // saxonConfig.setURIResolver(buildUriResolver(saxonConfig.getURIResolver()));
        processor = new Processor(saxonConfig);
        xsltCompiler = processor.newXsltCompiler();
        builder = processor.newDocumentBuilder();

        List<CfgFile> sourceFiles = config.getSources().getFiles();
        LOGGER.info("[" + instanceName + "] works on {} files", sourceFiles.size());

        if (config.getPipe().getTraceOutput() != null) {
            traceListener = buildTraceListener(config.getPipe().getTraceOutput());
        }

        if (config.getPipe().getNbThreads() > 1) {
            if (config.hasFilesOverMultiThreadLimit()) {
                List<ParametrableFile> files = new ArrayList<>(sourceFiles.size());
                for (CfgFile f : config.getSources()
                        .getFilesOverLimit(config.getPipe().getMultithreadMaxSourceSize())) {
                    files.add(resolveInputFile(f));
                }
                if (!files.isEmpty()) {
                    LOGGER.info("[" + instanceName + "] Running mono-thread for {} huge files", files.size());
                    retCode = executesPipeOnMultiThread(config.getPipe(), files, 1,
                            config.getSources().getListener());
                }
            }
            List<ParametrableFile> files = new ArrayList<>(sourceFiles.size());
            for (CfgFile f : config.getSources()
                    .getFilesUnderLimit(config.getPipe().getMultithreadMaxSourceSize())) {
                files.add(resolveInputFile(f));
            }
            if (!files.isEmpty() || config.getSources().getListener() != null) {
                LOGGER.info("[" + instanceName + "] Running multi-thread for {} regular-size files",
                        files.size());
                retCode = executesPipeOnMultiThread(config.getPipe(), files, config.getPipe().getNbThreads(),
                        config.getSources().getListener());
            }
        } else {
            List<ParametrableFile> files = new ArrayList<>(sourceFiles.size());
            for (CfgFile f : sourceFiles) {
                files.add(resolveInputFile(f));
            }
            LOGGER.info("[" + instanceName + "] Running mono-thread on all {} files", files.size());
            retCode = executesPipeOnMultiThread(config.getPipe(), files, 1, config.getSources().getListener());
        }

    } catch (Throwable e) {
        LOGGER.warn("[" + instanceName + "] " + e.getMessage(), e);
        // on sort avec des codes d'erreur non-zero
        throw e;
    } finally {
        if (!retCode) {
            throw new SaxonApiException("An error occurs. See previous logs.");
        }
    }
    try {
        if (config.getSources().getListener() == null) {
            long duration = System.currentTimeMillis() - start;
            Duration duree = DatatypeFactory.newInstance().newDuration(duration);
            LOGGER.info("[" + instanceName + "] Process terminated: " + duree.toString());
        }
    } catch (Exception ex) {
        LOGGER.info("[" + instanceName + "] Process terminated.");
    }
}

From source file:gov.nih.nci.cabig.caaers.api.ResearchStaffMigratorServiceTest.java

private void modifyDates(gov.nih.nci.cabig.caaers.integration.schema.researchstaff.Staff staff)
        throws Exception {

    DatatypeFactory df = DatatypeFactory.newInstance();
    Calendar gcNow = GregorianCalendar.getInstance();
    int year = gcNow.get(Calendar.YEAR);
    int month = gcNow.get(Calendar.MONTH) + 1;
    int day = gcNow.get(Calendar.DAY_OF_MONTH);
    int tz = DatatypeConstants.FIELD_UNDEFINED;

    XMLGregorianCalendar currXmlCal = df.newXMLGregorianCalendarDate(year, month, day, tz);
    XMLGregorianCalendar furXmlCal = df.newXMLGregorianCalendarDate(year + 1, month, day, tz);

    List<ResearchStaffType> researchStaffList = staff.getResearchStaff();
    List<SiteResearchStaffType> siteRsTypeList;
    List<SiteResearchStaffRoleType> siteRsRoleTypeList;
    for (ResearchStaffType researchStaffType : researchStaffList) {
        siteRsTypeList = researchStaffType.getSiteResearchStaffs().getSiteResearchStaff();
        for (SiteResearchStaffType sRsType : siteRsTypeList) {
            siteRsRoleTypeList = sRsType.getSiteResearchStaffRoles().getSiteResearchStaffRole();
            for (SiteResearchStaffRoleType sRsRoleType : siteRsRoleTypeList) {
                sRsRoleType.setStartDate(currXmlCal);
                sRsRoleType.setEndDate(furXmlCal);
            }//  ww w .  ja va 2  s.co  m
        }
    }
}