Java Code Examples for javax.xml.datatype.DatatypeFactory#newInstance()

The following examples show how to use javax.xml.datatype.DatatypeFactory#newInstance() . 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: SingleMessageWrapper.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SingleMessageWrapper(CareServiceIdType type, String id) throws GFDDPPException {
   DatatypeFactory dataTypeFactory;
   try {
      dataTypeFactory = DatatypeFactory.newInstance();
   } catch (DatatypeConfigurationException var8) {
      throw new RuntimeException(var8);
   }

   ObjectFactory schemaObjectFactory = new ObjectFactory();
   SmoaMessageType message = schemaObjectFactory.createSmoaMessageType();
   HeaderType headerType = schemaObjectFactory.createHeaderType();
   headerType.setMessageCreateDate(dataTypeFactory.newXMLGregorianCalendar(new GregorianCalendar()));
   headerType.setMessageID(Utils.generateGUID("M" + type.toString() + id));
   headerType.setVersion(getSMCVersion());
   headerType.setSender(this.createCareServiceSender(type, id));
   message.setHeader(headerType);
   EventFolderType eventFolderType = schemaObjectFactory.createEventFolderType();
   eventFolderType.setEvents(schemaObjectFactory.createEventFolderTypeEvents());
   eventFolderType.setEntitySpace(schemaObjectFactory.createEventFolderTypeEntitySpace());
   message.setAbstractFolder(schemaObjectFactory.createEventFolder(eventFolderType));
   this.singleMessage = schemaObjectFactory.createSingleMessage();
   this.singleMessage.setUnsigned(message);
}
 
Example 2
Source File: XMLTimeUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new {@link DatatypeFactory}
 *
 * @return
 *
 * @throws DatatypeConfigurationException
 */
private static DatatypeFactory newDatatypeFactory() throws DatatypeConfigurationException {
    boolean tccl_jaxp = SystemPropertiesUtil.getSystemProperty(GeneralConstants.TCCL_JAXP, "false")
            .equalsIgnoreCase("true");
    ClassLoader prevTCCL = SecurityActions.getTCCL();
    try {
        if (tccl_jaxp) {
            SecurityActions.setTCCL(XMLTimeUtil.class.getClassLoader());
        }
        return DatatypeFactory.newInstance();
    } finally {
        if (tccl_jaxp) {
            SecurityActions.setTCCL(prevTCCL);
        }
    }
}
 
Example 3
Source File: DatatypeConverterImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static DatatypeFactory getDatatypeFactory() {
    ClassLoader tccl = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        public ClassLoader run() {
            return Thread.currentThread().getContextClassLoader();
        }
    });
    DatatypeFactory df = DF_CACHE.get(tccl);
    if (df == null) {
        synchronized (DatatypeConverterImpl.class) {
            df = DF_CACHE.get(tccl);
            if (df == null) { // to prevent multiple initialization
                try {
                    df = DatatypeFactory.newInstance();
                } catch (DatatypeConfigurationException e) {
                    throw new Error(Messages.FAILED_TO_INITIALE_DATATYPE_FACTORY.format(),e);
                }
                DF_CACHE.put(tccl, df);
            }
        }
    }
    return df;
}
 
Example 4
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 5
Source File: DateUtil.java    From database-transform-tool with Apache License 2.0 5 votes vote down vote up
/**
 * <pre>
 * 描述:日期转XMLGregorianCalendar
 * 作者:ZhangYi
 * 时间:2016年5月5日 下午4:13:36
 * 参数:(参数列表)
 * @param date
 * @return
 * </pre>
 */
public static XMLGregorianCalendar getXMLCalendar(Date date) {
	DatatypeFactory datatypeFactory = null;
	try {
		datatypeFactory = DatatypeFactory.newInstance();
	} catch (DatatypeConfigurationException e) {
		logger.error("获取时间转换工厂时发生错误", e);
	}
	GregorianCalendar calendar = new GregorianCalendar();
	calendar.setTime(date);
	XMLGregorianCalendar datetime = datatypeFactory.newXMLGregorianCalendar(calendar);
	return datetime;
}
 
Example 6
Source File: API_010_PublisherTest.java    From juddi with Apache License 2.0 5 votes vote down vote up
/**
 * Sam saves a subscription on Sam's behalf (not authorized
 *
 * @throws Exception
 */
@Test(expected = UserMismatchException.class)
public void testAdminSaveSubscriptionNotAuthorized() throws Exception {
        saveJoePublisher();
        saveSamSyndicator();
        DatatypeFactory fac = DatatypeFactory.newInstance();
        List<Subscription> subs = new ArrayList<Subscription>();
        Subscription s = new Subscription();

        s.setMaxEntities(10);
        s.setBrief(false);
        GregorianCalendar gcal = new GregorianCalendar();
        gcal.setTimeInMillis(System.currentTimeMillis());
        gcal.add(Calendar.HOUR, 1);
        s.setExpiresAfter(fac.newXMLGregorianCalendar(gcal));
        s.setSubscriptionFilter(new SubscriptionFilter());
        s.getSubscriptionFilter().setFindBusiness(new FindBusiness());
        s.getSubscriptionFilter().getFindBusiness().setFindQualifiers(new FindQualifiers());
        s.getSubscriptionFilter().getFindBusiness().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);
        s.getSubscriptionFilter().getFindBusiness().getName().add(new Name(UDDIConstants.WILDCARD, null));
        subs.add(s);
        Holder<List<Subscription>> items = new Holder<List<Subscription>>();
        items.value = subs;
        publisher.adminSaveSubscription(authInfoSam(), TckPublisher.getJoePublisherId(), items);
        deleteJoePublisher();
        deleteSamSyndicator();

}
 
Example 7
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 8
Source File: Bug6937964Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testNewDurationYearMonthMilliseconds() throws DatatypeConfigurationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance();
    Duration d = dtf.newDurationYearMonth(671976000000L);
    int years = d.getYears();
    System.out.println("Years: " + years);
    Assert.assertTrue(years == 21, "Return value should be normalized");
}
 
Example 9
Source File: SealedProcessor.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static XMLGregorianCalendar getXMLGregorianCalendar (Date dateValue) {
	XMLGregorianCalendar dateTime = null;
	try {
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(dateValue);
		DatatypeFactory df;
		df = DatatypeFactory.newInstance();
		dateTime = df.newXMLGregorianCalendar(calendar);
	} catch (DatatypeConfigurationException e) {
		//printStackTrace(e,startTimeStamp,procedure,info);
	}
	return dateTime;
}
 
Example 10
Source File: TestIVComparator.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public V() {

            final DatatypeFactory df;
            try {
                df = DatatypeFactory.newInstance();
            } catch (DatatypeConfigurationException e) {
                throw new RuntimeException(e);
            }
            
            final IDatatypeURIResolver resolver = new IDatatypeURIResolver() {
                public BigdataURI resolve(final URI uri) {
                    final BigdataURI buri = f.createURI(uri.stringValue());
                    buri.setIV(new TermId<BigdataLiteral>(VTE.URI,termId++));
                    return buri;
                }
            };
            
            final DateTimeExtension<BigdataValue> dtExt = new DateTimeExtension<BigdataValue>(
        			resolver, TimeZone.getTimeZone("GMT"));

            dtExt.createIV(f.createLiteral(df
                    .newXMLGregorianCalendar("2001-10-26T21:32:52.126Z")));
            dtExt.createIV(f.createLiteral("2001-10-26", XSD.DATE));
            dtExt.createIV(f.createLiteral("21:32:52.126Z", XSD.TIME));

            noninline_plain_lit1.setValue(f.createLiteral("bigdata"));
            noninline_plain_lit2.setValue(f.createLiteral("systap"));
            noninline_languageCode_en_lit1.setValue(f.createLiteral("bigdata","en"));
            noninline_languageCode_en_lit2.setValue(f.createLiteral("systap","en"));
            noninline_languageCode_de_lit1.setValue(f.createLiteral("bigdata","de"));
            noninline_languageCode_de_lit2.setValue(f.createLiteral("systap","de"));
            noninline_xsd_string_lit1.setValue(f.createLiteral("bigdata",XSD.STRING));
            noninline_xsd_string_lit2.setValue(f.createLiteral("systap",XSD.STRING));
            
            noninline_uri1.setValue(f.createURI("http://www.bigdata.com/"));
            noninline_uri2.setValue(f.createURI("http://www.bigdata.com/blog/"));

        }
 
Example 11
Source File: DurationHelper.java    From activiti6-boot2 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 ActivitiIllegalArgumentException("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();
  }

}
 
Example 12
Source File: SerializationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create test files
 *
 * @param javaVersion JDK version
 */
public void createTestFile(String javaVersion) {
    try {
        DatatypeFactory dtf = DatatypeFactory.newInstance();
        XMLGregorianCalendar c = dtf.newXMLGregorianCalendar(EXPECTED_CAL);
        Duration d = dtf.newDuration(EXPECTED_DURATION);
        toFile((Serializable) c, filePath + javaVersion + FILENAME_CAL);
        toFile((Serializable) d, filePath + javaVersion + FILENAME_DURATION);
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
 
Example 13
Source File: SealedProcessor.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static XMLGregorianCalendar getXMLGregorianCalendar(Date dateValue) {
   XMLGregorianCalendar dateTime = null;

   try {
      GregorianCalendar calendar = new GregorianCalendar();
      calendar.setTime(dateValue);
      DatatypeFactory df = DatatypeFactory.newInstance();
      dateTime = df.newXMLGregorianCalendar(calendar);
   } catch (DatatypeConfigurationException var4) {
      ;
   }

   return dateTime;
}
 
Example 14
Source File: SingleMessageBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public SingleMessageBuilder() {
   try {
      this.dataTypeFactory = DatatypeFactory.newInstance();
   } catch (DatatypeConfigurationException var2) {
      throw new RuntimeException(var2);
   }
}
 
Example 15
Source File: SqlTimeMarshall.java    From anno4j with Apache License 2.0 4 votes vote down vote up
public SqlTimeMarshall(ValueFactory vf)
		throws DatatypeConfigurationException {
	this.vf = vf;
	factory = DatatypeFactory.newInstance();
	datatype = ValueFactoryImpl.getInstance().createURI(DATATYPE);
}
 
Example 16
Source File: BenchmarkStatementGenerator.java    From rya with Apache License 2.0 4 votes vote down vote up
public BenchmarkStatementGenerator() throws DatatypeConfigurationException {
    dtf = DatatypeFactory.newInstance();
}
 
Example 17
Source File: SearchFieldAdaptersTest.java    From components with Apache License 2.0 4 votes vote down vote up
@Test
public void testAdapterForDateSearchField() throws Exception {
    XMLGregorianCalendarToDateTimeConverter calendarValueConverter = new XMLGregorianCalendarToDateTimeConverter(
            DatatypeFactory.newInstance());

    DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");

    String dateString1 = "2017-01-01";
    String dateString2 = "2017-02-01";
    XMLGregorianCalendar xmlGregorianCalendar1 = calendarValueConverter.convertToDatum(
            dateFormatter.parseDateTime(dateString1).getMillis());
    XMLGregorianCalendar xmlGregorianCalendar2 = calendarValueConverter.convertToDatum(
            dateFormatter.parseDateTime(dateString2).getMillis());

    SearchDateFieldAdapter adapter1 = new SearchDateFieldAdapter(basicMetaData,
            SearchFieldType.DATE, SearchDateField.class);
    SearchDateField field1 = (SearchDateField) adapter1.populate(null,
            "Date.onOrAfter", Arrays.asList(dateString1));
    assertNotNull(field1);
    assertEquals(SearchDateFieldOperator.ON_OR_AFTER, field1.getOperator());
    assertEquals(xmlGregorianCalendar1, field1.getSearchValue());

    field1 = (SearchDateField) adapter1.populate(null,
            "Date.within", Arrays.asList(dateString1, dateString2));
    assertEquals(SearchDateFieldOperator.WITHIN, field1.getOperator());
    assertEquals(xmlGregorianCalendar1, field1.getSearchValue());
    assertEquals(xmlGregorianCalendar2, field1.getSearchValue2());

    field1 = (SearchDateField) adapter1.populate(null,
            "Date.before", null);
    assertEquals(SearchDateFieldOperator.BEFORE, field1.getOperator());
    assertNull(field1.getSearchValue());

    SearchDateFieldAdapter adapter2 = new SearchDateFieldAdapter(basicMetaData,
            SearchFieldType.CUSTOM_DATE, SearchDateCustomField.class);
    SearchDateCustomField field2 = (SearchDateCustomField) adapter2.populate(null,
            "Date.notBefore", Arrays.asList(dateString1));
    assertNotNull(field2);
    assertEquals(SearchDateFieldOperator.NOT_BEFORE, field2.getOperator());
    assertEquals(xmlGregorianCalendar1, field2.getSearchValue());
    assertNull(field2.getSearchValue2());

    field2 = (SearchDateCustomField) adapter2.populate(null,
            "PredefinedDate.lastFiscalQuarter", null);
    assertNotNull(field2);
    assertEquals(SearchDate.LAST_FISCAL_QUARTER, field2.getPredefinedSearchValue());
    assertNull(field2.getSearchValue());
    assertNull(field2.getSearchValue2());
}
 
Example 18
Source File: UDDI_150_CustodyTransferIntegrationTest.java    From juddi with Apache License 2.0 4 votes vote down vote up
@Test
public void InvalidTransferTokenEmptyNullAuthToken() {
     Assume.assumeTrue(TckPublisher.isEnabled());
        String keyJoeBiz = null;
        try {
                DatatypeFactory df = DatatypeFactory.newInstance();
                GregorianCalendar gcal = new GregorianCalendar();
                gcal.setTimeInMillis(System.currentTimeMillis());
                XMLGregorianCalendar xcal = df.newXMLGregorianCalendar(gcal);


                BusinessEntity myBusEntity = new BusinessEntity();
                Name myBusName = new Name();
                myBusName.setLang("en");
                myBusName.setValue("InvalidTransferTokenEmptyNullAuthToken UDDI's Business" + " " + xcal.toString());
                myBusEntity.getName().add(myBusName);
                myBusEntity.setBusinessServices(new BusinessServices());
                myBusEntity.getBusinessServices().getBusinessService().add(CreateBusiness("UDDI"));
                SaveBusiness sb = new SaveBusiness();
                sb.getBusinessEntity().add(myBusEntity);
                sb.setAuthInfo(authInfoJoe);
                BusinessDetail bd = publishJoe.saveBusiness(sb);

                keyJoeBiz = bd.getBusinessEntity().get(0).getBusinessKey();

                //transfers from Joe to Sam
                KeyBag kb = new KeyBag();
                kb.getKey().add(keyJoeBiz);

                Holder<String> nodeidOUT = new Holder<String>();
                Holder<XMLGregorianCalendar> expiresOUT = new Holder<XMLGregorianCalendar>();
                Holder<byte[]> tokenOUT = new Holder<byte[]>();
                custodyTransferPortTypeJoe.getTransferToken(null, kb, nodeidOUT, expiresOUT, tokenOUT);

                Assert.fail();
        } catch (Exception ex) {
                logger.info("Expected exception: " + ex.getMessage());

        } finally {
                TckCommon.DeleteBusiness(keyJoeBiz, authInfoJoe, publishJoe);

        }

}
 
Example 19
Source File: TestEncodeDecodeKeys.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
     * Unit test for round-trip of xsd:dateTime values.
     */
    public void test_encodeDecodeDateTime() throws Exception {
        
        final BigdataValueFactory vf = BigdataValueFactoryImpl.getInstance("test");
        
        final DatatypeFactory df = DatatypeFactory.newInstance();

        final DateTimeExtension<BigdataValue> ext = 
            new DateTimeExtension<BigdataValue>(new IDatatypeURIResolver() {
                public BigdataURI resolve(URI uri) {
                    final BigdataURI buri = vf.createURI(uri.stringValue());
                    buri.setIV(newTermId(VTE.URI));
                    return buri;
                }
            },
            TimeZone.getDefault()
            );
        
        final BigdataLiteral[] dt = {
            vf.createLiteral(
                df.newXMLGregorianCalendar("2001-10-26T21:32:52")),
            vf.createLiteral(
                df.newXMLGregorianCalendar("2001-10-26T21:32:52+02:00")),
            vf.createLiteral(
                df.newXMLGregorianCalendar("2001-10-26T19:32:52Z")),
            vf.createLiteral(
                df.newXMLGregorianCalendar("2001-10-26T19:32:52+00:00")),
            vf.createLiteral(
                df.newXMLGregorianCalendar("-2001-10-26T21:32:52")),
            vf.createLiteral(
                df.newXMLGregorianCalendar("2001-10-26T21:32:52.12679")),
            vf.createLiteral(
                df.newXMLGregorianCalendar("1901-10-26T21:32:52")),
                };
        
        final IV<?, ?>[] e = new IV[dt.length];
        
        for (int i = 0; i < dt.length; i++) {

            e[i] = ext.createIV(dt[i]);
            
        }
        
        final IV<?, ?>[] a = doEncodeDecodeTest(e);

        if (log.isInfoEnabled()) {
            for (int i = 0; i < e.length; i++) {
                log.info("original: " + dt[i]);
                log.info("asValue : " + ext.asValue((LiteralExtensionIV<?>) e[i], vf));
                log.info("decoded : " + ext.asValue((LiteralExtensionIV<?>) a[i], vf));
                log.info("");
            }
//          log.info(svf.createLiteral(
//                df.newXMLGregorianCalendar("2001-10-26T21:32:52.12679")));
        }
        
        doComparatorTest(e);
        
    }
 
Example 20
Source File: QueryIT.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void dateTimeWithin() throws Exception {

    final ValueFactory vf = SimpleValueFactory.getInstance();
    final DatatypeFactory dtf = DatatypeFactory.newInstance();
    FunctionRegistry.getInstance().add(new DateTimeWithinPeriod());

    final String sparql = "PREFIX fn: <" + FN.NAMESPACE +">"
            + "SELECT ?event ?startTime ?endTime WHERE { ?event <uri:startTime> ?startTime; <uri:endTime> ?endTime. "
            + "FILTER(fn:dateTimeWithin(?startTime, ?endTime, 2,<" + OWLTime.HOURS_URI + "> ))}";

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

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

    final ZonedDateTime zTime2 = zTime.minusHours(2);
    final String time2 = zTime2.format(DateTimeFormatter.ISO_INSTANT);

    final Literal lit = vf.createLiteral(dtf.newXMLGregorianCalendar(time));
    final Literal lit1 = vf.createLiteral(dtf.newXMLGregorianCalendar(time1));
    final Literal lit2 = vf.createLiteral(dtf.newXMLGregorianCalendar(time2));

    // Create the Statements that will be loaded into Rya.
    final Collection<Statement> statements = Sets.newHashSet(
            vf.createStatement(vf.createIRI("uri:event1"), vf.createIRI("uri:startTime"), lit),
            vf.createStatement(vf.createIRI("uri:event1"), vf.createIRI("uri:endTime"), lit1),
            vf.createStatement(vf.createIRI("uri:event2"), vf.createIRI("uri:startTime"), lit),
            vf.createStatement(vf.createIRI("uri:event2"), vf.createIRI("uri:endTime"), lit2)
           );

    // Create the expected results of the SPARQL query once the PCJ has been computed.
    final Set<BindingSet> expectedResults = new HashSet<>();

    final MapBindingSet bs = new MapBindingSet();
    bs.addBinding("event", vf.createIRI("uri:event1"));
    bs.addBinding("startTime", lit);
    bs.addBinding("endTime", lit1);
    expectedResults.add(bs);

    // Verify the end results of the query match the expected results.
    runTest(sparql, statements, expectedResults, ExportStrategy.RYA);
}