javax.xml.datatype.DatatypeFactory Java Examples

The following examples show how to use javax.xml.datatype.DatatypeFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DateUtils.java    From training with MIT License 6 votes vote down vote up
public static XMLGregorianCalendar extractXmlDateTime(Date timestamp) {
	if (timestamp == null) {
		return null;
	}
	XMLGregorianCalendar date = null;
	try {
		GregorianCalendar startDate = new GregorianCalendar();
		startDate.setTime(timestamp);
		date = DatatypeFactory.newInstance().newXMLGregorianCalendar(startDate);
		date.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
		date.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	return date;
}
 
Example #2
Source File: AnalyzedIntervalXmlStorer.java    From ade with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void setupSourceAndFlowType(ISource source,
        FramingFlowType framingFlowType) throws AdeException {
    m_source = source;
    synchronized (AnalyzedIntervalXmlStorer.class) {
        if (s_dataTypeFactory == null) {
            try {
                s_dataTypeFactory = DatatypeFactory.newInstance();
            } catch (DatatypeConfigurationException e) {
                throw new AdeInternalException("Failed to instantiate data factory for calendar", e);
            }
        }
    }
    // FIXME this is not thread safe

    m_gc = new GregorianCalendar(m_outputTimeZone);
    m_framingFlowType = framingFlowType;
}
 
Example #3
Source File: ExtAnalyzedIntervaFast18lXmlStorer.java    From ade with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void setupSourceAndFlowType(ISource source,
        FramingFlowType framingFlowType) throws AdeException {
    m_source = source;
    if (s_dataTypeFactory == null) {
        try {
            s_dataTypeFactory = DatatypeFactory.newInstance();
        } catch (DatatypeConfigurationException e) {
            throw new AdeInternalException("Failed to instantiate data factory for calendar", e);
        }
    }

    // FIXME this is not thread safe
    m_gc = new GregorianCalendar(m_outputTimeZone);
    m_framingFlowType = framingFlowType;
}
 
Example #4
Source File: DurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testDurationMultiply() {
    int num = 5000; // millisends. 5 seconds
    int factor = 2;
    try {
        Duration dur = DatatypeFactory.newInstance().newDuration(num);
        if (dur.multiply(factor).getSeconds() != 10) {
            Assert.fail("duration.multiply() return wrong value");
        }
        // factor is 2*10^(-1)
        if (dur.multiply(new BigDecimal(new BigInteger("2"), 1)).getSeconds() != 1) {
            Assert.fail("duration.multiply() return wrong value");
        }
        if (dur.subtract(DatatypeFactory.newInstance().newDuration(1000)).multiply(new BigDecimal(new BigInteger("2"), 1)).getSeconds() != 0) {
            Assert.fail("duration.multiply() return wrong value");
        }
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
    }
}
 
Example #5
Source File: BirtDuration.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
protected Object getValue( Object[] args ) throws BirtException
{
	Duration duration1, duration2;
	try
	{
		duration1 = DatatypeFactory.newInstance( )
				.newDuration( args[0].toString( ) );
		duration2 = DatatypeFactory.newInstance( )
				.newDuration( args[1].toString( ) );
	}
	catch ( DatatypeConfigurationException e )
	{
		throw new IllegalArgumentException( Messages.getFormattedString( "error.BirtDuration.literal.invalidArgument",
				args ) );
	}
	return duration1.subtract( duration2 ).toString( );
}
 
Example #6
Source File: PaymentsAPIResponseTest.java    From amazon-pay-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetServiceStatusGreenI() throws Exception {
    final String rawResponse = loadTestFile("GetServiceStatusResponseGreenI.xml");
    final ResponseData response = new ResponseData(HttpURLConnection.HTTP_OK, rawResponse);
    final GetServiceStatusResponseData res = Parser.getServiceStatus(response);

    Assert.assertEquals(res.getStatus(), ServiceStatus.GREEN_I);
    final XMLGregorianCalendar xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar("2010-11-01T21:38:09.676Z");
    Assert.assertEquals(res.getTimestamp(), xgc);
    Assert.assertEquals(res.getMessageId(), "173964729I");

    final MessageList messages = res.getMessages();
    final List<Message> messageList = messages.getMessages();
    final Message message1 = messageList.get(0);
    final Message message2 = messageList.get(1);

    Assert.assertEquals(message1.getLocale(), "en_UK");
    Assert.assertEquals(message1.getText(), "We are experiencing high latency in UK because of heavy traffic.");
    Assert.assertEquals(message2.getLocale(), "en_US");
    Assert.assertEquals(message2.getText(), "Service is once again operating at normal capacity at 6:53 PST.");

    Assert.assertEquals(res.getRequestId(), "d80c6c7b-f7c7-4fa7-bdd7-854711cb3bcc");
    Assert.assertEquals(res.toXML(), rawResponse);
}
 
Example #7
Source File: DateTimeWithinPeriodTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testDays() throws DatatypeConfigurationException, ValueExprEvaluationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance();

    ZonedDateTime zTime = testThisTimeDate;
    String time = zTime.format(DateTimeFormatter.ISO_INSTANT);

    ZonedDateTime zTime1 = zTime.minusDays(1);
    String time1 = zTime1.format(DateTimeFormatter.ISO_INSTANT);

    Literal now = VF.createLiteral(dtf.newXMLGregorianCalendar(time));
    Literal nowMinusOne = VF.createLiteral(dtf.newXMLGregorianCalendar(time1));

    DateTimeWithinPeriod func = new DateTimeWithinPeriod();

    assertEquals(TRUE, func.evaluate(VF, now, now, VF.createLiteral(1), OWLTime.DAYS_URI));
    assertEquals(FALSE, func.evaluate(VF, now, nowMinusOne, VF.createLiteral(1), OWLTime.DAYS_URI));
    assertEquals(TRUE, func.evaluate(VF, now, nowMinusOne, VF.createLiteral(2), OWLTime.DAYS_URI));
}
 
Example #8
Source File: SupplierShareResultAssembler.java    From development with Apache License 2.0 6 votes vote down vote up
private Period preparePeriod(long periodStartTime, long periodEndTime)
        throws DatatypeConfigurationException {

    Period period = new Period();

    DatatypeFactory df = DatatypeFactory.newInstance();
    GregorianCalendar gc = new GregorianCalendar();

    period.setStartDate(BigInteger.valueOf(periodStartTime));
    gc.setTimeInMillis(periodStartTime);
    period.setStartDateIsoFormat(df.newXMLGregorianCalendar(gc).normalize());

    period.setEndDate(BigInteger.valueOf(periodEndTime));
    gc.setTimeInMillis(periodEndTime);
    period.setEndDateIsoFormat(df.newXMLGregorianCalendar(gc).normalize());

    return period;
}
 
Example #9
Source File: BirtDuration.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
protected Object getValue( Object[] args ) throws BirtException
{
	Duration duration;
	try
	{
		duration = DatatypeFactory.newInstance( )
				.newDuration( args[0].toString( ) );
	}
	catch ( DatatypeConfigurationException e )
	{
		throw new IllegalArgumentException( Messages.getFormattedString( "error.BirtDuration.literal.invalidArgument",
				new Object[]{
					args[0].toString( )
				} ) );
	}
	return Long.valueOf( duration.getTimeInMillis( DataTypeUtil.toDate( args[1] ) ) );
}
 
Example #10
Source File: ValueFactoryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test method for
 * {@link org.eclipse.rdf4j.model.impl.AbstractValueFactory#createLiteral(javax.xml.datatype.XMLGregorianCalendar)}
 * .
 */
@Test
public void testCreateLiteralXMLGregorianCalendar() {
	GregorianCalendar c = new GregorianCalendar();
	c.setTime(new Date());
	try {
		XMLGregorianCalendar xmlGregCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
		Literal l = f.createLiteral(xmlGregCalendar);
		assertNotNull(l);
		assertEquals(l.getDatatype(), XMLSchema.DATETIME);
		// TODO check lexical value?
	} catch (DatatypeConfigurationException e) {
		e.printStackTrace();
		fail("Could not instantiate javax.xml.datatype.DatatypeFactory");
	}
}
 
Example #11
Source File: DateConverter.java    From OpenESPI-Common-java with Apache License 2.0 6 votes vote down vote up
public static DateTimeType toDateTimeType(Date date) {
	DateTimeType dateTimeType = new DateTimeType();
	GregorianCalendar gregorianCalendar = new DateTime(date)
			.toGregorianCalendar();
	gregorianCalendar.setTimeZone(TimeZone.getTimeZone("UTC"));
	DatatypeFactory datatypeFactory;

	try {
		datatypeFactory = DatatypeFactory.newInstance();
	} catch (DatatypeConfigurationException e) {
		throw new RuntimeException(e);
	}

	XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory
			.newXMLGregorianCalendar(gregorianCalendar);
	xmlGregorianCalendar.setFractionalSecond(null);
	dateTimeType.setValue(xmlGregorianCalendar);

	return dateTimeType;
}
 
Example #12
Source File: MpOwnerShareResultAssembler.java    From development with Apache License 2.0 6 votes vote down vote up
void setPeriod(long periodStartTime, long periodEndTime)
        throws DatatypeConfigurationException {

    this.periodStartTime = periodStartTime;
    this.periodEndTime = periodEndTime;

    Period period = new Period();

    DatatypeFactory df = DatatypeFactory.newInstance();
    GregorianCalendar gc = new GregorianCalendar();

    // start date
    period.setStartDate(BigInteger.valueOf(periodStartTime));
    gc.setTimeInMillis(periodStartTime);
    period.setStartDateIsoFormat(df.newXMLGregorianCalendar(gc).normalize());

    // end date
    period.setEndDate(BigInteger.valueOf(periodEndTime));
    gc.setTimeInMillis(periodEndTime);
    period.setEndDateIsoFormat(df.newXMLGregorianCalendar(gc).normalize());

    result.setPeriod(period);
}
 
Example #13
Source File: AutoRefreshCredentialProviderTest.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * The getAwsCredential method should return the cached credential if the session hasn't expired. If the session expired, a new credential should be
 * generated.
 *
 * @throws Exception
 */
@Test
public void testAssertCredentialCachingBehavior() throws Exception
{
    AutoRefreshCredentialProvider autoRefreshCredentialProvider = new AutoRefreshCredentialProvider()
    {
        @Override
        public AwsCredential getNewAwsCredential() throws Exception
        {
            AwsCredential awsCredential = new AwsCredential();
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTimeInMillis(System.currentTimeMillis() + 1000);
            awsCredential.setAwsSessionExpirationTime(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));
            return awsCredential;
        }
    };

    AwsCredential firstAwsCredential = autoRefreshCredentialProvider.getAwsCredential();
    AwsCredential secondAwsCredential = autoRefreshCredentialProvider.getAwsCredential();
    assertEquals(firstAwsCredential, secondAwsCredential);
    Thread.sleep(1000);
    secondAwsCredential = autoRefreshCredentialProvider.getAwsCredential();
    assertNotEquals(firstAwsCredential, secondAwsCredential);
}
 
Example #14
Source File: BrokerShareResultAssemblerTest.java    From development with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setup() throws Exception {
    SharesDataRetrievalServiceLocal sharesRetrievalService = mock(SharesDataRetrievalServiceLocal.class);
    BillingDataRetrievalServiceLocal billingRetrievalService = mock(BillingDataRetrievalServiceLocal.class);
    brokerShareAssembler = spy(new BrokerShareResultAssembler(
            sharesRetrievalService, billingRetrievalService));

    // create test data
    createBillingResults();

    // mock service methods
    mockGetBrokerData();
    mockGetBrokerRevenueSharePercentage();
    mockGetOrgData(NUMBER_SUPPLIERS);
    mockGetOrgData(NUMBER_CUSTOMER);
    mockGetSupplierKeyForSubscription();
    mockGetProductHistoryData();
    mockGetSubscriptionHistoryData();
    mockGetBillingResults();
    mockXmlSearch();
    datatypeFactory = DatatypeFactory.newInstance();
}
 
Example #15
Source File: CityGMLWriter.java    From web-feature-service with Apache License 2.0 6 votes vote down vote up
public CityGMLWriter(SAXWriter saxWriter, CityGMLVersion version, TransformerChainFactory transformerChainFactory, GeometryStripper geometryStripper, UIDCacheManager uidCacheManager, Object eventChannel, Config config) throws DatatypeConfigurationException {
	this.saxWriter = saxWriter;
	this.version = version;
	this.transformerChainFactory = transformerChainFactory;
	this.geometryStripper = geometryStripper;
	this.uidCacheManager = uidCacheManager;
	this.config = config;
	
	cityGMLBuilder = ObjectRegistry.getInstance().getCityGMLBuilder();
	jaxbMarshaller = cityGMLBuilder.createJAXBMarshaller(version);
	wfsFactory = new ObjectFactory();
	datatypeFactory = DatatypeFactory.newInstance();
	additionalObjectsHandler = new AdditionalObjectsHandler(saxWriter, version, cityGMLBuilder, transformerChainFactory, eventChannel);
	
	int queueSize = config.getProject().getExporter().getResources().getThreadPool().getDefaultPool().getMaxThreads() * 2;
	
	writerPool = new SingleWorkerPool<>(
			"citygml_writer_pool",
			new XMLWriterWorkerFactory(saxWriter, ObjectRegistry.getInstance().getEventDispatcher()),
			queueSize,
			false);

	writerPool.setEventSource(eventChannel);
	writerPool.prestartCoreWorkers();
}
 
Example #16
Source File: DynFormValidator.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
private boolean validateDuration(String value, String fieldName, boolean untreated) {
    try {
        DatatypeFactory factory = DatatypeFactory.newInstance();
        factory.newDuration(value);
        return true;
    }
    catch (Exception e) {
        addValidationErrorMessage(value, fieldName, "duration", untreated) ;
        return false ;
    }
}
 
Example #17
Source File: TestXMLGregorianCalendarTimeZone.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void test(int offsetMinutes)
        throws DatatypeConfigurationException {
    XMLGregorianCalendar calendar = DatatypeFactory.newInstance().
            newXMLGregorianCalendar();
    calendar.setTimezone(60 + offsetMinutes);
    TimeZone timeZone = calendar.getTimeZone(DatatypeConstants.FIELD_UNDEFINED);
    String expected = (offsetMinutes < 10 ? "GMT+01:0" : "GMT+01:")
            + offsetMinutes;
    if (!timeZone.getID().equals(expected)) {
        throw new RuntimeException("Test failed: expected timezone: " +
                expected + " Actual: " + timeZone.getID());
    }
}
 
Example #18
Source File: XmlUtils.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
public static XMLGregorianCalendar getXmlGregCal(long millis) throws DatatypeConfigurationException {
	//this is now
	GregorianCalendar cal = new GregorianCalendar();
	cal.setTimeInMillis(millis);
	XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
	return xmlCal;
}
 
Example #19
Source File: DurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void newDurationTester(boolean isPositive, boolean normalizedIsPositive, BigInteger years, BigInteger normalizedYears, BigInteger months,
        BigInteger normalizedMonths, BigInteger days, BigInteger normalizedDays, BigInteger hours, BigInteger normalizedHours, BigInteger minutes,
        BigInteger normalizedMinutes, BigDecimal seconds, BigDecimal normalizedSeconds, long durationInMilliSeconds, long normalizedDurationInMilliSeconds,
        String lexicalRepresentation, String normalizedLexicalRepresentation) {

    DatatypeFactory datatypeFactory = null;
    try {
        datatypeFactory = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException ex) {
        ex.printStackTrace();
        Assert.fail(ex.toString());
    }

    // create 4 Durations using the 4 different constructors

    Duration durationBigInteger = datatypeFactory.newDuration(isPositive, years, months, days, hours, minutes, seconds);
    durationAssertEquals(durationBigInteger, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
            normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
            normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);

    Duration durationInt = datatypeFactory.newDuration(isPositive, years.intValue(), months.intValue(), days.intValue(), hours.intValue(),
            minutes.intValue(), seconds.intValue());
    durationAssertEquals(durationInt, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
            normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
            normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);

    Duration durationMilliseconds = datatypeFactory.newDuration(durationInMilliSeconds);
    durationAssertEquals(durationMilliseconds, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
            normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
            normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);

    Duration durationLexical = datatypeFactory.newDuration(lexicalRepresentation);
    durationAssertEquals(durationLexical, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
            normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
            normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);
}
 
Example #20
Source File: DurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testEqualsWithEqualObjectParam() {
    try {
        AssertJUnit.assertTrue("equals method is expected to return true", duration.equals(DatatypeFactory.newInstance().newDuration(100)));
    } catch (DatatypeConfigurationException dce) {
        dce.printStackTrace();
        Assert.fail("Failed to create instance of DatatypeFactory " + dce.getMessage());
    }
}
 
Example #21
Source File: Bug6937951Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test() throws DatatypeConfigurationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance();
    XMLGregorianCalendar c1 = dtf.newXMLGregorianCalendar("1999-12-31T24:00:00");
    XMLGregorianCalendar c2 = dtf.newXMLGregorianCalendar("2000-01-01T00:00:00");
    System.out.println("c1: " + c1.getYear() + "-" + c1.getMonth() + "-" + c1.getDay() + "T" + c1.getHour());
    System.out.println(c1.equals(c2) ? "pass" : "fail"); // fails
    if (!c1.equals(c2))
        Assert.fail("hour 24 needs to be treated as equal to hour 0 of the next day");
    if (c1.getYear() != 2000 && c1.getHour() != 0)
        Assert.fail("hour 24 needs to be treated as equal to hour 0 of the next day");

}
 
Example #22
Source File: LiteralTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
public void setADate(Date date) {
	DatatypeFactory factory;
	try {
		factory = DatatypeFactory.newInstance();
	} catch (DatatypeConfigurationException e) {
		throw new ObjectConversionException(e);
	}
	GregorianCalendar gc = new GregorianCalendar(0, 0, 0);
	gc.setTime(date);
	XMLGregorianCalendar xgc = factory.newXMLGregorianCalendar(gc);
	setXMLGregorianCalendar(xgc);
}
 
Example #23
Source File: TFDv11c33.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
private TimbreFiscalDigital createStamp(UUID uuid, Date date, String PAC, String leyenda) throws DatatypeConfigurationException {
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    ObjectFactory of = new ObjectFactory();
    TimbreFiscalDigital tfds = of.createTimbreFiscalDigital();
    tfds.setVersion("1.1");
    tfds.setUUID(uuid.toString());
    tfds.setFechaTimbrado(DatatypeFactory.newInstance().newXMLGregorianCalendar(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), c.get(Calendar.HOUR), c.get(Calendar.MINUTE), c.get(Calendar.SECOND), DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED));
    tfds.setRfcProvCertif(PAC);
    tfds.setLeyenda(leyenda);
    tfds.setSelloCFD(document.getSello());
    BigInteger bi = cert.getSerialNumber();
    tfds.setNoCertificadoSAT(new String(bi.toByteArray()));
    return tfds;
}
 
Example #24
Source File: XMLMetaDataRetriever.java    From ade with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructor
 * @throws AdeException
 */
public XMLMetaDataRetriever() throws AdeException {
    if (s_dataTypeFactory == null) {
        try {
            s_dataTypeFactory = DatatypeFactory.newInstance();
        } catch (DatatypeConfigurationException e) {
            throw new AdeInternalException("Failed to instantiate data factory for calendar", e);
        }
    }

    m_gc = new GregorianCalendar(ExtOutputFilenameGenerator.getOutputTimeZone().toTimeZone());
}
 
Example #25
Source File: FiqlParserTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseDateDuration() throws Exception {
    SearchCondition<Condition> filter = parser.parse("time=gt=-PT1M");
    Date now = new Date();
    Date tenMinutesAgo = new Date();
    DatatypeFactory.newInstance().newDuration("-PT10M").addTo(tenMinutesAgo);
    assertTrue(filter.isMet(new Condition(null, null, now)));
    assertFalse(filter.isMet(new Condition(null, null, tenMinutesAgo)));
}
 
Example #26
Source File: XmlAdapterUtilsTest.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void testXMLGregorianCalendarXmlAdapter() throws Exception {

		final XMLGregorianCalendar alpha = DatatypeFactory.newInstance()
				.newXMLGregorianCalendar("2005-01-01T11:00:00.012+04:00");

		final XMLGregorianCalendar omega = DatatypeFactory.newInstance()
				.newXMLGregorianCalendar("2005-01-01T09:00:00.012+02:00");

		final XMLGregorianCalendar beta = XmlAdapterUtils.marshall(
				XMLGregorianCalendarAsDateTime.class,
				XmlAdapterUtils.unmarshall(
						XMLGregorianCalendarAsDateTime.class, alpha));
		// Assert.assertEquals("Conversion failed.", alpha.normalize(),
		// omega.normalize());
		// Assert.assertEquals("Conversion failed.", alpha.normalize(),
		// beta.normalize());
		// Assert.assertEquals("Conversion failed.", beta.normalize(),
		// omega.normalize());
		Assert.assertEquals("Conversion failed.", XMLGregorianCalendarUtils
				.getTimeInMillis(alpha), XMLGregorianCalendarUtils
				.getTimeInMillis(beta));
		Assert.assertEquals("Conversion failed.", XMLGregorianCalendarUtils
				.getTimeInMillis(alpha), XMLGregorianCalendarUtils
				.getTimeInMillis(omega));
		Assert.assertEquals("Conversion failed.", XMLGregorianCalendarUtils
				.getTimeInMillis(beta), XMLGregorianCalendarUtils
				.getTimeInMillis(omega));
	}
 
Example #27
Source File: NowBOp.java    From database with GNU General Public License v2.0 5 votes vote down vote up
final public IV get(final IBindingSet bs) {

        final Calendar cal = Calendar.getInstance();
        final Date now = cal.getTime();
        final GregorianCalendar c = new GregorianCalendar();
        c.setTime(now);
        try {
            final XMLGregorianCalendar date = 
                    DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
            return super.asIV(getValueFactory().createLiteral(date), bs);
        } catch (DatatypeConfigurationException e) {
            throw new RuntimeException(e);
        }
    }
 
Example #28
Source File: PaymentsAPIResponseTest.java    From amazon-pay-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateBillingAgreementResponse() throws Exception {
    final String rawResponse = loadTestFile("ValidateBillingAgreementResponse.xml");
    final ResponseData response = new ResponseData(HttpURLConnection.HTTP_OK, rawResponse);
    final ValidateBillingAgreementResponseData res = Parser.getValidateBillingAgreementResponse(response);
    Assert.assertEquals(RequestStatus.SUCCESS, res.getResult().getValidationResult());
    Assert.assertEquals("Open", res.getResult().getBillingAgreementStatus().getState());
    final XMLGregorianCalendar xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar("2015-11-02T17:38:29.511Z");
    Assert.assertEquals(xgc, res.getResult().getBillingAgreementStatus().getLastUpdatedTimestamp());
    Assert.assertEquals(res.getRequestId(), "0f48a4e0-2a7c-4036-9a8a-339e419fd53f");
    Assert.assertEquals(res.toXML(), rawResponse);
}
 
Example #29
Source File: SearchDateFieldAdapter.java    From components with Apache License 2.0 5 votes vote down vote up
public SearchDateFieldAdapter(BasicMetaData metaData, SearchFieldType fieldType, Class<T> fieldClass) {
    super(metaData, fieldType, fieldClass);

    try {
        datatypeFactory = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        throw new NetSuiteException("Failed to create XML data type factory", e);
    }
}
 
Example #30
Source File: DurationHelper.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public DurationHelper(String expressionS, int maxIterations, ClockReader clockReader) throws Exception {
    this.clockReader = clockReader;
    this.maxIterations = maxIterations;
    List<String> expression = Arrays.asList(expressionS.split("/"));
    datatypeFactory = DatatypeFactory.newInstance();

    if (expression.size() > 3 || expression.isEmpty()) {
        throw new FlowableIllegalArgumentException("Cannot parse duration");
    }
    if (expression.get(0).startsWith("R")) {
        isRepeat = true;
        times = expression.get(0).length() == 1 ? Integer.MAX_VALUE - 1 : Integer.parseInt(expression.get(0).substring(1));

        if (expression.get(0).equals("R")) { // R without params
            repeatWithNoBounds = true;
        }

        expression = expression.subList(1, expression.size());
    }

    if (isDuration(expression.get(0))) {
        period = parsePeriod(expression.get(0));
        end = expression.size() == 1 ? null : parseDate(expression.get(1));
    } else {
        start = parseDate(expression.get(0));
        if (isDuration(expression.get(1))) {
            period = parsePeriod(expression.get(1));
        } else {
            end = parseDate(expression.get(1));
            period = datatypeFactory.newDuration(end.getTimeInMillis() - start.getTimeInMillis());
        }
    }
    if (start == null) {
        start = clockReader.getCurrentCalendar();
    }

}