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.finra.herd.service.helper.BusinessObjectDataHelperTest.java

@Test
public void testValidateRegistrationDateRangeFilter() throws DatatypeConfigurationException {
    XMLGregorianCalendar start = DatatypeFactory.newInstance().newXMLGregorianCalendar("2018-04-01");
    XMLGregorianCalendar end = DatatypeFactory.newInstance().newXMLGregorianCalendar("2018-04-02");

    // Start date is less then end date
    businessObjectDataHelper.validateRegistrationDateRangeFilter(new RegistrationDateRangeFilter(start, end));

    // Start date is equel end date
    businessObjectDataHelper.validateRegistrationDateRangeFilter(new RegistrationDateRangeFilter(start, start));
}

From source file:org.finra.herd.service.helper.BusinessObjectDataHelperTest.java

@Test
public void testValidateRegistrationDateRangeFilterStartDateIsGreaterThenEndDate()
        throws DatatypeConfigurationException {
    XMLGregorianCalendar end = DatatypeFactory.newInstance().newXMLGregorianCalendar("2018-04-01");
    XMLGregorianCalendar start = DatatypeFactory.newInstance().newXMLGregorianCalendar("2018-04-02");
    try {/*from   www .jav a  2 s. co m*/
        businessObjectDataHelper
                .validateRegistrationDateRangeFilter(new RegistrationDateRangeFilter(start, end));
        fail();
    } catch (IllegalArgumentException e) {
        assertEquals(String.format(
                "The start registration date\"%s\"cannot be greater than the end registration date\"%s\".",
                start, end), e.getMessage());
    }
}

From source file:org.finra.herd.tools.downloader.DownloaderControllerTest.java

/**
 * Asserts that the controller is sending the proper implementation of credentials provider when calling S3.
 */// w  ww.j a  v a  2  s .c  om
@Test
public void testPerformDownloadAssertCredentialsRetrieved() throws Exception {
    /*
     * Create and inject mock objects
     */
    DownloaderWebClient mockDownloaderWebClient = mock(DownloaderWebClient.class);
    DownloaderWebClient originalDownloaderWebClient = (DownloaderWebClient) ReflectionTestUtils
            .getField(downloaderController, "downloaderWebClient");
    ReflectionTestUtils.setField(downloaderController, "downloaderWebClient", mockDownloaderWebClient);

    DownloaderManifestReader mockDownloaderManifestReader = mock(DownloaderManifestReader.class);
    DownloaderManifestReader originalDownloaderManifestReader = (DownloaderManifestReader) ReflectionTestUtils
            .getField(downloaderController, "manifestReader");
    ReflectionTestUtils.setField(downloaderController, "manifestReader", mockDownloaderManifestReader);

    BusinessObjectDataHelper mockBusinessObjectDataHelper = mock(BusinessObjectDataHelper.class);
    BusinessObjectDataHelper originalBusinessObjectDataHelper = (BusinessObjectDataHelper) ReflectionTestUtils
            .getField(downloaderController, "businessObjectDataHelper");
    ReflectionTestUtils.setField(downloaderController, "businessObjectDataHelper",
            mockBusinessObjectDataHelper);

    S3Service mockS3Service = mock(S3Service.class);
    S3Service originalS3Service = (S3Service) ReflectionTestUtils.getField(downloaderController, "s3Service");
    ReflectionTestUtils.setField(downloaderController, "s3Service", mockS3Service);

    StorageFileHelper mockStorageFileHelper = mock(StorageFileHelper.class);
    StorageFileHelper originalStorageFileHelper = (StorageFileHelper) ReflectionTestUtils
            .getField(downloaderController, "storageFileHelper");
    ReflectionTestUtils.setField(downloaderController, "storageFileHelper", mockStorageFileHelper);

    StorageHelper mockStorageHelper = mock(StorageHelper.class);
    StorageHelper originalStorageHelper = (StorageHelper) ReflectionTestUtils.getField(downloaderController,
            "storageHelper");
    ReflectionTestUtils.setField(downloaderController, "storageHelper", mockStorageHelper);

    /*
     * Start test
     */
    Path localPath = Files.createTempDirectory(null);
    try {
        String s3KeyPrefix = "s3KeyPrefix";
        String storageName = "storageName";

        DownloaderInputManifestDto downloaderInputManifestDto = new DownloaderInputManifestDto();
        downloaderInputManifestDto.setStorageName(storageName);
        BusinessObjectData businessObjectData = new BusinessObjectData();
        StorageUnit storageUnit = new StorageUnit(new Storage(storageName, null, null), null, null,
                StorageUnitStatusEntity.ENABLED, null, null, null);
        S3KeyPrefixInformation s3KeyPrefixInformation = new S3KeyPrefixInformation();
        s3KeyPrefixInformation.setS3KeyPrefix(s3KeyPrefix);

        /*
         * Mock operations on mocked dependencies
         */
        when(mockDownloaderManifestReader.readJsonManifest(any())).thenReturn(downloaderInputManifestDto);
        when(mockDownloaderWebClient.getBusinessObjectData(any())).thenReturn(businessObjectData);
        when(mockBusinessObjectDataHelper.getStorageUnitByStorageName(any(), any())).thenReturn(storageUnit);
        when(mockDownloaderWebClient.getS3KeyPrefix(any())).thenReturn(s3KeyPrefixInformation);
        when(mockDownloaderWebClient.getStorageUnitDownloadCredential(any(), any()))
                .thenReturn(new StorageUnitDownloadCredential(new AwsCredential("awsAccessKey", "awsSecretKey",
                        "awsSessionToken", DatatypeFactory.newInstance().newXMLGregorianCalendar())));
        when(mockS3Service.downloadDirectory(any())).then(new Answer<S3FileTransferResultsDto>() {
            @Override
            public S3FileTransferResultsDto answer(InvocationOnMock invocation) throws Throwable {
                /*
                 * Call the providers' getAwsCredentials(), just like real implementation would.
                 */
                S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto = invocation.getArgument(0);
                List<HerdAWSCredentialsProvider> additionalAwsCredentialsProviders = s3FileTransferRequestParamsDto
                        .getAdditionalAwsCredentialsProviders();
                for (HerdAWSCredentialsProvider herdAWSCredentialsProvider : additionalAwsCredentialsProviders) {
                    herdAWSCredentialsProvider.getAwsCredential();
                }
                return null;
            }
        });

        /*
         * Make the call to the method under test
         */
        RegServerAccessParamsDto regServerAccessParamsDto = null;
        File manifestPath = null;
        S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto = new S3FileTransferRequestParamsDto();
        s3FileTransferRequestParamsDto.setLocalPath(localPath.toString());
        s3FileTransferRequestParamsDto.setMaxThreads(1);

        downloaderController.performDownload(regServerAccessParamsDto, manifestPath,
                s3FileTransferRequestParamsDto);

        // Assert that the proper delegate method is called with the expected params to retrieve credentials
        verify(mockDownloaderWebClient).getStorageUnitDownloadCredential(downloaderInputManifestDto,
                storageName);
    } finally {
        /*
         * Restore mocked dependencies to their original implementation
         */
        ReflectionTestUtils.setField(downloaderController, "downloaderWebClient", originalDownloaderWebClient);
        ReflectionTestUtils.setField(downloaderController, "manifestReader", originalDownloaderManifestReader);
        ReflectionTestUtils.setField(downloaderController, "businessObjectDataHelper",
                originalBusinessObjectDataHelper);
        ReflectionTestUtils.setField(downloaderController, "s3Service", originalS3Service);
        ReflectionTestUtils.setField(downloaderController, "storageFileHelper", originalStorageFileHelper);
        ReflectionTestUtils.setField(downloaderController, "storageHelper", originalStorageHelper);

        // Clean up any temporary files
        FileUtils.deleteDirectory(localPath.toFile());
    }
}

From source file:org.force66.beantester.utils.InstantiationUtils.java

public static XMLGregorianCalendar newXMLGregorianCalendar() {
    try {//from  www .j  a v  a2s  .com
        return DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
    } catch (DatatypeConfigurationException e) {
        throw new BeanTesterException("This shouldn't happen", e);
    }
}

From source file:org.fosstrak.epcis.repository.query.QueryOperationsBackendSQL.java

/**
 * Creates a new XMLGregorianCalendar from the given milliseconds time.
 * //  w  w w  . jav a  2s  .  co  m
 * @param time
 *            The time in ms to convert.
 * @return The XML calendar object representing the given timestamp.
 * @throws ImplementationExceptionResponse
 *             If an error occurred when parsing the given timestamp into a
 *             calendar instance.
 */
private XMLGregorianCalendar timeToXmlCalendar(long time) throws ImplementationExceptionResponse {
    try {
        DatatypeFactory factory = DatatypeFactory.newInstance();
        Calendar cal = GregorianCalendar.getInstance();
        cal.setTimeInMillis(time);
        return factory.newXMLGregorianCalendar((GregorianCalendar) cal);
    } catch (DatatypeConfigurationException e) {
        String msg = "Unable to instantiate an XML representation for a date/time datatype.";
        ImplementationException iex = new ImplementationException();
        iex.setReason(msg);
        iex.setSeverity(ImplementationExceptionSeverity.SEVERE);
        throw new ImplementationExceptionResponse(msg, iex, e);
    }
}

From source file:org.jasig.portlet.calendar.adapter.ExchangeCalendarAdapter.java

/**
 * Return an internal API CalendarEvent for an Microsoft CalendarEvent object.
 *
 * @param calendarId//from   www . j  a  v  a 2  s  . c  o m
 * @param msEvent
 * @return
 * @throws DatatypeConfigurationException
 */
protected VEvent getInternalEvent(long calendarId, com.microsoft.exchange.types.CalendarEvent msEvent)
        throws DatatypeConfigurationException {
    DatatypeFactory factory = DatatypeFactory.newInstance();

    // create a new UTC-based DateTime to represent the event start time
    net.fortuna.ical4j.model.DateTime eventStart = new net.fortuna.ical4j.model.DateTime();
    eventStart.setUtc(true);
    Calendar startCal = msEvent.getStartTime().toGregorianCalendar(java.util.TimeZone.getTimeZone(UTC),
            Locale.getDefault(), factory.newXMLGregorianCalendar());
    eventStart.setTime(startCal.getTimeInMillis());

    // create a new UTC-based DateTime to represent the event ent time
    net.fortuna.ical4j.model.DateTime eventEnd = new net.fortuna.ical4j.model.DateTime();
    eventEnd.setUtc(true);
    Calendar endCal = msEvent.getEndTime().toGregorianCalendar(java.util.TimeZone.getTimeZone(UTC),
            Locale.getDefault(), factory.newXMLGregorianCalendar());
    eventEnd.setTime(endCal.getTimeInMillis());

    // create a property list representing the new event
    PropertyList newprops = new PropertyList();
    newprops.add(new Uid(msEvent.getCalendarEventDetails().getID()));
    newprops.add(new DtStamp());

    newprops.add(new DtStart(eventStart));
    newprops.add(new DtEnd(eventEnd));
    newprops.add(new Summary(msEvent.getCalendarEventDetails().getSubject()));
    if (StringUtils.isNotBlank(msEvent.getCalendarEventDetails().getLocation())) {
        newprops.add(new Location(msEvent.getCalendarEventDetails().getLocation()));
    }

    VEvent event = new VEvent(newprops);
    return event;

}

From source file:org.jasig.portlet.calendar.adapter.ExchangeCalendarAdapterTest.java

@Test
public void testGetInternalEvent() throws DatatypeConfigurationException {
    com.microsoft.exchange.types.CalendarEvent msEvent = new com.microsoft.exchange.types.CalendarEvent();

    // set the test event start time to 4AM on November 1, 2010
    DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
    XMLGregorianCalendar start = datatypeFactory.newXMLGregorianCalendar();
    start.setYear(2010);/*from   w  w  w.java 2 s .  c  o m*/
    start.setMonth(11);
    start.setDay(1);
    start.setTime(4, 0, 0, 0);
    msEvent.setStartTime(start);

    // set the test event end time to 5AM on November 1, 2010
    XMLGregorianCalendar end = datatypeFactory.newXMLGregorianCalendar();
    end.setYear(2010);
    end.setMonth(12);
    end.setDay(1);
    end.setTime(5, 0, 0, 0);
    msEvent.setEndTime(end);

    // set the event tname and location
    CalendarEventDetails details = new CalendarEventDetails();
    details.setSubject("Naptime");
    details.setLocation("My house");
    msEvent.setCalendarEventDetails(details);

    // transform the Microsoft calendar event into a calendar portlet event
    VEvent event = adapter.getInternalEvent(3, msEvent);

    // ensure the calendar id, summary, and location are all set correctly
    assertEquals("Naptime", event.getSummary().getValue());
    assertEquals("My house", event.getLocation().getValue());

    // check the start time
    Calendar cal = Calendar.getInstance(java.util.TimeZone.getTimeZone("UTC"));
    cal.setTimeInMillis(event.getStartDate().getDate().getTime());
    assertEquals(4, cal.get(Calendar.HOUR_OF_DAY));
    assertEquals(java.util.TimeZone.getTimeZone("UTC"), cal.getTimeZone());
    assertTrue(event.getStartDate().isUtc());
    assertNull(event.getStartDate().getTimeZone());

    // check the end time
    cal.setTimeInMillis(event.getEndDate().getDate().getTime());
    assertEquals(5, cal.get(Calendar.HOUR_OF_DAY));
    assertEquals(java.util.TimeZone.getTimeZone("UTC"), cal.getTimeZone());
    assertTrue(event.getEndDate().isUtc());
    assertNull(event.getEndDate().getTimeZone());

}

From source file:org.jrecruiter.common.CalendarUtils.java

/**
 * Get a XML-date representation (ISO 8601) of the provided calendar object.
 *
 * For more details @see http://www.w3.org/TR/xmlschema-2/#dateTime
 *
 * @return XML-date as String//w  ww  .j av  a 2 s  .  c om
 */
public static String getXmlFormatedDate(final Calendar calendar) {

    if (calendar == null) {
        throw new IllegalArgumentException("Calendar is a required parameter");
    }

    final GregorianCalendar gregorianCalendar = new GregorianCalendar(calendar.getTimeZone());
    gregorianCalendar.setTime(calendar.getTime());

    final DatatypeFactory dataTypeFactory;

    try {
        dataTypeFactory = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }

    final XMLGregorianCalendar xmlCalendar = dataTypeFactory.newXMLGregorianCalendar(gregorianCalendar);

    return xmlCalendar.toXMLFormat();
}

From source file:org.kitodo.dataformat.access.MetsXmlElementAccess.java

/**
 * Creates an object of class XMLGregorianCalendar. Creating this
 * JAXB-specific class is quite complicated and has therefore been
 * outsourced to a separate method.//from   w  w w  .  j a  va 2s.  co  m
 * 
 * @param gregorianCalendar
 *            value of the calendar
 * @return an object of class XMLGregorianCalendar
 */
private static XMLGregorianCalendar convertDate(GregorianCalendar gregorianCalendar) {
    DatatypeFactory datatypeFactory;
    try {
        datatypeFactory = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        String message = e.getMessage();
        throw new NoClassDefFoundError(message != null ? message
                : "Implementation of DatatypeFactory not available or cannot be instantiated.");
    }
    return datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);
}

From source file:org.kuali.kra.award.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  w  w . j av  a 2  s .  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());

    // get the current FandaRate
    AwardFandaRate currentFandaRate = award.getCurrentFandaRate();

    String rateClassCode = currentFandaRate.getFandaRateType().getRateClassCode();
    String rateTypeCode = currentFandaRate.getFandaRateType().getRateTypeCode();
    String icrTypeCode = getIndirectCostTypeCode(rateClassCode, rateTypeCode);
    //campus on/off indicator
    accountParameters.setOffCampusIndicator(!currentFandaRate.getOnOffCampusFlag());
    //indirect cost rate
    String icrRateCode = award.getIcrRateCode();
    if (Award.ICR_RATE_CODE_NONE.equals(icrRateCode)) {
        accountParameters.setIndirectCostRate("");
    } else {
        accountParameters.setIndirectCostRate(icrRateCode);
    }

    // indirect cost type code
    accountParameters.setIndirectCostTypeCode(icrTypeCode + "");

    //higher education function code
    accountParameters.setHigherEdFunctionCode(award.getActivityType().getHigherEducationFunctionCode());

    return accountParameters;

}