org.jpmml.model.JAXBUtil Java Examples

The following examples show how to use org.jpmml.model.JAXBUtil. 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: ComplexValueTest.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static
private void checkConstant(String expectedValue, Object value) throws IOException, JAXBException {
	Constant constant = new Constant()
		.setValue(value);

	String string;

	try(ByteArrayOutputStream os = new ByteArrayOutputStream()){
		JAXBUtil.marshal(constant, new StreamResult(os));

		string = os.toString("UTF-8");
	}

	// XXX
	string = string.trim();

	if(("").equals(expectedValue)){
		assertTrue(string.contains("<Constant ") && string.endsWith("/>"));
	} else

	{
		assertTrue(string.contains(">" + expectedValue + "</Constant>"));
	}
}
 
Example #2
Source File: InlineTableTest.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static
private void checkRow(Row row) throws Exception {
	InlineTable inlineTable = new InlineTable()
		.addRows(row);

	String string;

	try(ByteArrayOutputStream os = new ByteArrayOutputStream()){
		JAXBUtil.marshal(inlineTable, new StreamResult(os));

		string = os.toString("UTF-8");
	}

	assertTrue(string.contains("<row>"));
	assertTrue(string.contains("<data:input>0</data:input>"));
	assertTrue(string.contains("<data:output>zero</data:output>"));
	assertTrue(string.contains("</row>"));
}
 
Example #3
Source File: ValidationExample.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Unmarshaller createUnmarshaller() throws JAXBException {
	Unmarshaller unmarshaller = super.createUnmarshaller();

	Schema schema;

	try {
		schema = JAXBUtil.getSchema();
	} catch(Exception e){
		throw new RuntimeException(e);
	}

	unmarshaller.setSchema(schema);
	unmarshaller.setEventHandler(new SimpleValidationEventHandler());

	return unmarshaller;
}
 
Example #4
Source File: ModelProvider.java    From openscoring with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void writeTo(Model model, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
	Evaluator evaluator = model.getEvaluator();

	HasPMML hasPMML = (HasPMML)evaluator;

	httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_TYPE.withCharset("UTF-8"));
	httpHeaders.putSingle(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=model.pmml.xml"); // XXX

	PMML pmml = hasPMML.getPMML();

	try {
		Result result = new StreamResult(entityStream);

		Marshaller marshaller = JAXBUtil.createMarshaller();

		marshaller.marshal(pmml, result);
	} catch(JAXBException je){
		throw new InternalServerErrorException(je);
	}
}
 
Example #5
Source File: ConverterFactory.java    From jpmml-sparkml with GNU Affero General Public License v3.0 5 votes vote down vote up
static
public void checkApplicationClasspath(){
	String string = "<PMML xmlns=\"http://www.dmg.org/PMML-4_4\"/>";

	try {
		JAXBUtil.unmarshalPMML(new StreamSource(new StringReader(string)));
	} catch(JAXBException je){
		throw new IllegalArgumentException("Expected JPMML-Model version 1.5.X, got a legacy version. See https://issues.apache.org/jira/browse/SPARK-15526", je);
	}
}
 
Example #6
Source File: PmmlProcessorConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void setUp() throws IOException, SAXException, JAXBException {
	try (InputStream is = properties.getModelLocation().getInputStream()) {
		Source transformedSource = ImportFilter.apply(new InputSource(is));
		pmml = JAXBUtil.unmarshalPMML(transformedSource);
		Assert.state(!pmml.getModels().isEmpty(),
				"The provided PMML file at " + properties.getModelLocation() + " does not contain any model");
	}
}
 
Example #7
Source File: PMMLUtils.java    From oryx with Apache License 2.0 5 votes vote down vote up
/**
 * @param pmml model
 * @return model serialized as an XML document as a string
 */
public static String toString(PMML pmml) {
  try (StringWriter out = new StringWriter()) {
    // v JAXBUtil.marshalPMML but need to set compact, non-pretty output
    Marshaller marshaller = JAXBUtil.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
    marshaller.marshal(pmml, new StreamResult(out));
    return out.toString();
  } catch (JAXBException | IOException e) {
    // IOException should not be possible; JAXBException would only happen with XML
    // config problems.
    throw new IllegalStateException(e);
  }
}
 
Example #8
Source File: PMMLUtils.java    From oryx with Apache License 2.0 5 votes vote down vote up
/**
 * @param pmmlString PMML model encoded as an XML doc in a string
 * @return {@link PMML} object representing the model
 * @throws IOException if XML can't be unserialized
 */
public static PMML fromString(String pmmlString) throws IOException {
  try {
    SAXSource transformed = SAXUtil.createFilteredSource(
      new ByteArrayInputStream(pmmlString.getBytes(StandardCharsets.UTF_8)),
      new ImportFilter());
    return JAXBUtil.unmarshalPMML(transformed);
  } catch (JAXBException | SAXException e) {
    throw new IOException(e);
  }
}
 
Example #9
Source File: ComplexArrayTest.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static
public void checkArray(String expectedValue, Array array) throws Exception {
	String string;

	try(ByteArrayOutputStream os = new ByteArrayOutputStream()){
		JAXBUtil.marshal(array, new StreamResult(os));

		string = os.toString("UTF-8");
	}

	assertTrue(string.contains(">" + expectedValue + "</Array>"));
}
 
Example #10
Source File: MiningFieldTest.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static
private void checkImportance(Number expected, String string) throws Exception {
	Reader reader = new StringReader("<MiningField xmlns=\"" + Version.PMML_4_4.getNamespaceURI() + "\" name=\"x\" importance=\"" + string + "\"/>");

	MiningField miningField = (MiningField)JAXBUtil.unmarshal(new StreamSource(reader));

	assertEquals(FieldName.create("x"), miningField.getName());
	assertEquals(MiningField.UsageType.ACTIVE, miningField.getUsageType());

	assertEquals(expected, miningField.getImportance());
}
 
Example #11
Source File: LoadingModelEvaluatorBuilder.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
public LoadingModelEvaluatorBuilder load(InputStream is, String modelName) throws SAXException, JAXBException {
	Schema schema = getSchema();
	ValidationEventHandler validationEventHandler = getValidationEventHandler();
	List<? extends XMLFilter> filters = getFilters();
	boolean locatable = getLocatable();
	VisitorBattery visitors = getVisitors();

	Unmarshaller unmarshaller = JAXBUtil.createUnmarshaller();
	unmarshaller.setSchema(schema);
	unmarshaller.setEventHandler(validationEventHandler);

	if(filters == null){
		filters = Collections.singletonList(new ImportFilter());
	}

	Source source = SAXUtil.createFilteredSource(is, filters.toArray(new XMLFilter[filters.size()]));

	PMML pmml = (PMML)unmarshaller.unmarshal(source);

	Visitor locatorHandler = (locatable ? new LocatorTransformer() : new LocatorNullifier());

	locatorHandler.applyTo(pmml);

	if(visitors != null && !visitors.isEmpty()){
		visitors.applyTo(pmml);
	}

	Model model = PMMLUtil.findModel(pmml, modelName);

	setPMML(pmml);
	setModel(model);

	return this;
}
 
Example #12
Source File: Example.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public Unmarshaller createUnmarshaller() throws JAXBException {
	return JAXBUtil.createUnmarshaller();
}
 
Example #13
Source File: Example.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public Marshaller createMarshaller() throws JAXBException {
	return JAXBUtil.createMarshaller();
}
 
Example #14
Source File: Openscoring.java    From openscoring with GNU Affero General Public License v3.0 4 votes vote down vote up
static
private LoadingModelEvaluatorBuilder createLoadingModelEvaluatorBuilder(Config config){
	Config modelEvaluatorBuilderConfig = config.getConfig("modelEvaluatorBuilder");

	LoadingModelEvaluatorBuilder modelEvaluatorBuilder = new LoadingModelEvaluatorBuilder();

	Class<? extends ModelEvaluatorFactory> modelEvaluatorFactoryClazz = loadClass(ModelEvaluatorFactory.class, modelEvaluatorBuilderConfig);
	modelEvaluatorBuilder.setModelEvaluatorFactory(newInstance(modelEvaluatorFactoryClazz));

	Class<? extends ValueFactoryFactory> valueFactoryFactoryClazz = loadClass(ValueFactoryFactory.class, modelEvaluatorBuilderConfig);
	modelEvaluatorBuilder.setValueFactoryFactory(newInstance(valueFactoryFactoryClazz));

	modelEvaluatorBuilder.setOutputFilter(OutputFilters.KEEP_FINAL_RESULTS);

	// Jackson does not support the JSON serialization of <code>null</code> map keys
	ResultMapper resultMapper = new ResultMapper(){

		private FieldName defaultTargetName = FieldName.create(ModelResponse.DEFAULT_TARGET_NAME);


		@Override
		public FieldName apply(FieldName name){

			// A "phantom" default target field
			if(name == null){
				return this.defaultTargetName;
			}

			return name;
		}
	};

	modelEvaluatorBuilder.setResultMapper(resultMapper);

	boolean validate = modelEvaluatorBuilderConfig.getBoolean("validate");

	if(validate){
		Schema schema;

		try {
			schema = JAXBUtil.getSchema();
		} catch(SAXException | IOException e){
			throw new RuntimeException(e);
		}

		modelEvaluatorBuilder
			.setSchema(schema)
			.setValidationEventHandler(new SimpleValidationEventHandler());
	}

	boolean locatable = modelEvaluatorBuilderConfig.getBoolean("locatable");

	modelEvaluatorBuilder.setLocatable(locatable);

	VisitorBattery visitors = new VisitorBattery();

	List<String> visitorClassNames = modelEvaluatorBuilderConfig.getStringList("visitorClasses");
	for(String visitorClassName : visitorClassNames){
		Class<?> clazz = loadClass(Object.class, visitorClassName);

		if((Visitor.class).isAssignableFrom(clazz)){
			Class<? extends Visitor> visitorClazz = clazz.asSubclass(Visitor.class);

			visitors.add(visitorClazz);
		} else

		if((VisitorBattery.class).isAssignableFrom(clazz)){
			Class<? extends VisitorBattery> visitorBatteryClazz = clazz.asSubclass(VisitorBattery.class);

			VisitorBattery visitorBattery = newInstance(visitorBatteryClazz);

			visitors.addAll(visitorBattery);
		} else

		{
			throw new IllegalArgumentException(new ClassCastException(clazz.toString()));
		}
	}

	modelEvaluatorBuilder.setVisitors(visitors);

	return modelEvaluatorBuilder;
}
 
Example #15
Source File: NodeTest.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
static
private Object clone(Object object) throws Exception {
	ByteArrayOutputStream os = new ByteArrayOutputStream();

	JAXBUtil.marshal(object, new StreamResult(os));

	byte[] buffer = os.toByteArray();

	ByteArrayInputStream is = new ByteArrayInputStream(buffer);

	return JAXBUtil.unmarshal(new StreamSource(is));
}