use of eu.esdihumboldt.hale.common.instance.model.impl.DefaultInstance in project hale by halestudio.
the class FunctionExecutor method processValue.
/**
* Processes the given value. Does not handle {@link MultiValue}!
*
* @param cellLog the transformation log
* @param function the property function
* @param value the value to process
* @param node the target node
* @return the processed value
*/
private Object processValue(TransformationLog cellLog, PropertyTransformation<?> function, Object value, TargetNode node) {
if (function.allowAutomatedResultConversion()) {
if (!(value instanceof Group)) {
// convert value for target
try {
value = convert(value, toPropertyEntityDefinition(node.getEntityDefinition()));
} catch (Throwable e) {
// ignore, but create error
cellLog.error(cellLog.createMessage("Conversion according to target property failed, using value as is.", e));
}
} else {
// TODO any conversion necessary/possible
}
} else {
// unwrap value
if (value instanceof Value) {
value = ((Value) value).getValue();
}
}
/*
* If the value is no group, but it should be one, create an instance
* wrapping the value
*/
TypeDefinition propertyType = toPropertyEntityDefinition(node.getEntityDefinition()).getDefinition().getPropertyType();
if (!(value instanceof Group) && !propertyType.getChildren().isEmpty()) {
MutableInstance instance = new DefaultInstance(propertyType, null);
instance.setValue(value);
value = instance;
}
return value;
}
use of eu.esdihumboldt.hale.common.instance.model.impl.DefaultInstance in project hale by halestudio.
the class InstanceBuilder method getValue.
/**
* Get the value for a target node.
*
* @param node the target node
* @param typeLog the type transformation log
* @return the value or {@link NoObject#NONE} representing no value
*/
private Object getValue(TargetNode node, TransformationLog typeLog) {
if (node.getChildren(true).isEmpty()) {
// simple leaf
if (node.isDefined()) {
// XXX this is done in FunctionExecutor
return node.getResult();
} else {
return NoObject.NONE;
}
}
boolean isProperty = node.getDefinition().asProperty() != null;
boolean isGroup = node.getDefinition().asGroup() != null;
if (isProperty && node.isDefined()) {
// it's a property and we have a value/values
Object nodeValue = node.getResult();
if (!(nodeValue instanceof MultiValue)) {
// pack single value into multivalue
MultiValue nodeMultiValue = new MultiValue();
nodeMultiValue.add(nodeValue);
nodeValue = nodeMultiValue;
}
MultiValue nodeMultiValue = (MultiValue) nodeValue;
if (!nodeMultiValue.isEmpty()) {
// Create n instances
MultiValue resultMultiValue = new MultiValue(nodeMultiValue.size());
for (Object value : nodeMultiValue) {
// the value may have been wrapped in an Instance
if (value instanceof Instance) {
value = ((Instance) value).getValue();
}
MutableInstance instance = new DefaultInstance(node.getDefinition().asProperty().getPropertyType(), null);
instance.setValue(value);
// XXX since this is the same for all instances maybe do
// this on a dummy and only copy properties for each?
// XXX MultiValue w/ target node children => strange results
populateGroup(instance, node, typeLog);
resultMultiValue.add(instance);
}
return resultMultiValue;
}
// if nodeMultiValue is empty fall through to below
// it the instance could still have children even without a value
}
// it's a property or group with no value
MutableGroup group;
if (isGroup) {
group = new DefaultGroup(node.getDefinition().asGroup());
} else if (isProperty) {
group = new DefaultInstance(node.getDefinition().asProperty().getPropertyType(), null);
} else {
throw new IllegalStateException("Illegal child definition");
}
// populate with children
if (populateGroup(group, node, typeLog)) {
return group;
} else {
return NoObject.NONE;
}
}
use of eu.esdihumboldt.hale.common.instance.model.impl.DefaultInstance in project hale by halestudio.
the class InstanceValidator method validateChildren.
/**
* Validates the given property values (their values - as instances - and/or
* group children).
*
* @param properties the array of existing properties, may be null
* @param childDef their definition
* @param reporter the reporter to report to
* @param type the top level type
* @param path the current property path
* @param onlyCheckExistingChildren whether to only validate existing
* children (in case of a choice) or not
* @param reference the instance reference
* @param context the instance validation context
* @param entity the entity definition related to the property values or
* <code>null</code>
*/
private void validateChildren(Object[] properties, ChildDefinition<?> childDef, InstanceValidationReporter reporter, QName type, List<QName> path, boolean onlyCheckExistingChildren, InstanceReference reference, InstanceValidationContext context, @Nullable EntityDefinition entity) {
if (properties != null && properties.length > 0) {
for (Object property : properties) {
if (property instanceof Instance) {
validateInstance((Instance) property, reporter, type, path, onlyCheckExistingChildren, reference, context, childDef, entity);
} else if (property instanceof Group) {
validateGroupChildren((Group) property, reporter, type, path, onlyCheckExistingChildren, reference, context, childDef, entity);
} else {
if (childDef.asGroup() != null)
reporter.warn(new DefaultInstanceValidationMessage(reference, type, new ArrayList<QName>(path), "Wrong group", "A property is no group"));
else if (childDef.asProperty() != null) {
if (!skipValidation(childDef.asProperty().getPropertyType(), property)) {
// don't skip property
// wrap value in dummy instance for type validation
MutableInstance instance = new DefaultInstance(childDef.asProperty().getPropertyType(), null);
instance.setValue(property);
validateInstance(instance, reporter, type, path, onlyCheckExistingChildren, reference, context, childDef, entity);
}
}
}
}
} else {
/*
* Special case: No property value, but a combination of minimum
* cardinality greater than zero and NillableFlag is set. Then there
* can be sub-properties that are required.
*
* Applicable for XML (simple) types with mandatory attributes.
*/
if (childDef.asProperty() != null && childDef.asProperty().getConstraint(Cardinality.class).getMinOccurs() > 0 && childDef.asProperty().getConstraint(NillableFlag.class).isEnabled() && childDef.asProperty().getPropertyType().getConstraint(HasValueFlag.class).isEnabled() && !childDef.asProperty().getPropertyType().getChildren().isEmpty()) {
// collect XML attribute children
List<ChildDefinition<?>> attributes = new ArrayList<ChildDefinition<?>>();
for (ChildDefinition<?> child : childDef.asProperty().getPropertyType().getChildren()) {
if (child.asProperty() != null && child.asProperty().getConstraint(XmlAttributeFlag.class).isEnabled()) {
attributes.add(child);
}
}
if (!attributes.isEmpty()) {
// create an empty dummy instance
Instance instance = new DefaultInstance(childDef.asProperty().getPropertyType(), null);
validateGroupChildren(instance, attributes, reporter, type, path, onlyCheckExistingChildren, reference, context, entity);
}
}
}
}
use of eu.esdihumboldt.hale.common.instance.model.impl.DefaultInstance in project hale by halestudio.
the class StreamGmlHelper method parseInstance.
/**
* Parses an instance with the given type from the given XML stream reader.
*
* @param reader the XML stream reader, the current event must be the start
* element of the instance
* @param type the definition of the instance type
* @param indexInStream the index of the instance in the stream or
* <code>null</code>
* @param strict if associating elements with properties should be done
* strictly according to the schema, otherwise a fall-back is
* used trying to populate values also on invalid property paths
* @param srsDimension the dimension of the instance or <code>null</code>
* @param crsProvider CRS provider in case no CRS is specified, may be
* <code>null</code>
* @param parentType the type of the topmost instance
* @param propertyPath the property path down from the topmost instance, may
* be <code>null</code>
* @param allowNull if a <code>null</code> result is allowed
* @param ignoreNamespaces if parsing of the XML instances should allow
* types and properties with namespaces that differ from those
* defined in the schema
* @param ioProvider the I/O Provider to get value
* @param crs The <code>CRSDefinition</code> to use for geometries
* @return the parsed instance, may be <code>null</code> if allowNull is
* <code>true</code>
* @throws XMLStreamException if parsing the instance failed
*/
public static Instance parseInstance(XMLStreamReader reader, TypeDefinition type, Integer indexInStream, boolean strict, AtomicInteger srsDimension, CRSProvider crsProvider, TypeDefinition parentType, List<QName> propertyPath, boolean allowNull, boolean ignoreNamespaces, IOProvider ioProvider, CRSDefinition crs) throws XMLStreamException {
if (srsDimension == null) {
// Initialize srsDimension here w/ dummy value to be passed down
// when parsing the instance. That way "srsDimension" attributes
// at the coordinate level (e.g. "pos", "posList" etc.) can be
// evaluated and its valued passed back up to the level where
// the geometry object is created.
srsDimension = new AtomicInteger(-1);
}
checkState(reader.getEventType() == XMLStreamConstants.START_ELEMENT);
if (propertyPath == null) {
propertyPath = Collections.emptyList();
}
String dim = reader.getAttributeValue(null, "srsDimension");
if (dim != null) {
srsDimension.set(Integer.parseInt(dim));
}
// extract additional settings from I/O provider
boolean suppressParsingGeometry = ioProvider.getParameter(StreamGmlReader.PARAM_SUPPRESS_PARSE_GEOMETRY).as(Boolean.class, false);
MutableInstance instance;
if (indexInStream == null) {
// not necessary to associate data set
instance = new DefaultInstance(type, null);
} else {
instance = new StreamGmlInstance(type, indexInStream);
}
// If the current instance has an srsName attribute, try to resolve the
// corresponding CRS and pass it down the hierarchy and use it for
// nested geometries that don't have their own srsName.
CRSDefinition lastCrs = crs;
String srsName = reader.getAttributeValue(null, "srsName");
if (srsName != null) {
lastCrs = CodeDefinition.tryResolve(srsName);
if (lastCrs == null && crsProvider != null) {
// In case the srsName value could not be resolved to a CRS, try
// to resolve the CRS via the crsProvider.
CRSDefinition unresolvedCrs = new CodeDefinition(srsName);
CRSDefinition resolvedCrs = crsProvider.getCRS(parentType, propertyPath, unresolvedCrs);
// unresolvedCrs unchanged
if (resolvedCrs != null && !resolvedCrs.equals(unresolvedCrs)) {
lastCrs = resolvedCrs;
}
}
// If the provided CRS could not be resolved, it will be ignored
// here silently, so that use cases that don't need the CRS will not
// fail.
}
boolean mixed = type.getConstraint(XmlMixedFlag.class).isEnabled();
if (!mixed) {
// mixed types are treated special (see else)
// check if xsi:nil attribute is there and set to true
String nilString = reader.getAttributeValue(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil");
boolean isNil = nilString != null && "true".equalsIgnoreCase(nilString);
// instance properties
parseProperties(reader, instance, strict, srsDimension, crsProvider, lastCrs, parentType, propertyPath, false, ignoreNamespaces, ioProvider);
// nil instance w/o properties
if (allowNull && isNil && Iterables.isEmpty(instance.getPropertyNames())) {
// no value should be created
/*
* XXX returning null here then results in problems during
* adding other properties to the parent group, as mandatory
* elements are expected to appear, and it will warn about
* possible invalid data loaded
*/
// return null;
}
// instance value
if (!hasElements(type)) {
/*
* Value can only be determined if there are no documents,
* because otherwise elements have already been processed in
* parseProperties and we are already past END_ELEMENT.
*/
if (type.getConstraint(HasValueFlag.class).isEnabled()) {
// try to get text value
String value = reader.getElementText();
if (!isNil && value != null) {
instance.setValue(convertSimple(type, value));
}
}
}
} else {
/*
* XXX For a mixed type currently ignore elements and parse only
* attributes and text.
*/
// instance properties (attributes only)
parseProperties(reader, instance, strict, srsDimension, crsProvider, lastCrs, parentType, propertyPath, true, ignoreNamespaces, ioProvider);
// combined text
String value = readText(reader);
if (value != null) {
instance.setValue(convertSimple(type, value));
}
}
// augmented value XXX should this be an else if?
if (!suppressParsingGeometry && type.getConstraint(AugmentedValueFlag.class).isEnabled()) {
// add geometry as a GeometryProperty value where applicable
GeometryFactory geomFactory = type.getConstraint(GeometryFactory.class);
Object geomValue = null;
// the default value for the srsDimension
int defaultValue = 2;
try {
if (srsDimension.get() != -1) {
geomValue = geomFactory.createGeometry(instance, srsDimension.get(), ioProvider);
} else {
// srsDimension is not set
geomValue = geomFactory.createGeometry(instance, defaultValue, ioProvider);
}
} catch (Exception e) {
/*
* Catch IllegalArgumentException that e.g. occurs if a linear
* ring has to few points. NullPointerExceptions may occur
* because an internal geometry could not be created.
*
* XXX a problem is that these messages will not appear in the
* report
*/
log.error("Error creating geometry", e);
}
if (geomValue != null && crsProvider != null && propertyPath != null) {
// check if CRS are set, and if not, try determining them using
// the CRS provider
Collection<?> values;
if (geomValue instanceof Collection) {
values = (Collection<?>) geomValue;
} else {
values = Collections.singleton(geomValue);
}
List<Object> resultVals = new ArrayList<Object>();
for (Object value : values) {
if (value instanceof Geometry || (value instanceof GeometryProperty<?> && ((GeometryProperty<?>) value).getCRSDefinition() == null)) {
if (lastCrs == null) {
lastCrs = crsProvider.getCRS(parentType, propertyPath, lastCrs);
}
if (lastCrs != null) {
Geometry geom = (value instanceof Geometry) ? ((Geometry) value) : (((GeometryProperty<?>) value).getGeometry());
resultVals.add(new DefaultGeometryProperty<Geometry>(lastCrs, geom));
continue;
}
}
resultVals.add(value);
}
if (resultVals.size() == 1) {
geomValue = resultVals.get(0);
} else {
geomValue = resultVals;
}
}
if (geomValue != null) {
instance.setValue(geomValue);
}
}
return instance;
}
use of eu.esdihumboldt.hale.common.instance.model.impl.DefaultInstance in project hale by halestudio.
the class GroovyJoinPage method validate.
@Override
protected boolean validate(String document) {
ParameterValue param = CellUtil.getFirstParameter(getWizard().getUnfinishedCell(), JoinFunction.PARAMETER_JOIN);
JoinParameter joinParameter = param.as(JoinParameter.class);
// check Join parameter
if (joinParameter == null) {
// setValidationError("Missing join configuration");
return false;
} else {
String error = joinParameter.validate();
if (!setValidationError(error)) {
return false;
}
}
// target type
Type targetType = (Type) CellUtil.getFirstEntity(getWizard().getUnfinishedCell().getTarget());
if (targetType == null) {
// not yet selected (NewRelationWizard)
return false;
}
/*
* FIXME use JoinParameter to fake joined instances!
*
* XXX for now just base instance
*/
TypeEntityDefinition sourceType = joinParameter.getTypes().get(0);
InstanceBuilder builder = new InstanceBuilder(false);
Instance instance = getTestValues().get(sourceType);
if (instance == null) {
// use an empty instance as input for the script
instance = new DefaultInstance(sourceType.getDefinition(), DataSet.SOURCE);
}
FamilyInstance source = new FamilyInstanceImpl(instance);
// prepare binding
Cell cell = getWizard().getUnfinishedCell();
CellLog log = new CellLog(new DefaultTransformationReporter("dummy", false), cell);
ExecutionContext context = new DummyExecutionContext(HaleUI.getServiceProvider());
Binding binding = GroovyRetype.createBinding(source, cell, builder, log, context, targetType.getDefinition().getDefinition());
GroovyService service = HaleUI.getServiceProvider().getService(GroovyService.class);
Script script = null;
try {
script = service.parseScript(document, binding);
GroovyUtil.evaluateAll(script, builder, targetType.getDefinition().getDefinition(), service, log);
} catch (final Exception e) {
return handleValidationResult(script, e);
}
return handleValidationResult(script, null);
}
Aggregations