Search in sources :

Example 16 with XmlElement

use of eu.esdihumboldt.hale.io.xsd.model.XmlElement in project hale by halestudio.

the class StreamGmlWriter method write.

/**
 * Write the given instances to an {@link XMLStreamWriter}.<br>
 * <br>
 * Use {@link #createWriter(OutputStream, IOReporter)} to create a properly
 * configured writer for this method.
 *
 * @param instances the instance collection
 * @param writer the writer to write the instances to
 * @param reporter the reporter
 * @param progress the progress
 * @see #createWriter(OutputStream, IOReporter)
 */
protected void write(InstanceCollection instances, PrefixAwareStreamWriter writer, ProgressIndicator progress, IOReporter reporter) {
    this.writer = writer;
    try {
        final SubtaskProgressIndicator sub = new SubtaskProgressIndicator(progress) {

            @Override
            protected String getCombinedTaskName(String taskName, String subtaskName) {
                return taskName + " (" + subtaskName + ")";
            }
        };
        progress = sub;
        progress.begin(getTaskName(), instances.size());
        XmlElement container = findDefaultContainter(targetIndex, reporter);
        TypeDefinition containerDefinition = (container == null) ? (null) : (container.getType());
        QName containerName = (container == null) ? (null) : (container.getName());
        if (containerDefinition == null) {
            XmlElement containerElement = getConfiguredContainerElement(this, getXMLIndex());
            if (containerElement != null) {
                containerDefinition = containerElement.getType();
                containerName = containerElement.getName();
                container = containerElement;
            } else {
                // this is the last option, so we can throw a specific error
                throw new IllegalStateException("Configured container element not found");
            }
        }
        if (containerDefinition == null || containerName == null) {
            throw new IllegalStateException("No root element/container found");
        }
        /*
			 * Add schema for container to validation schemas, if the namespace
			 * differs from the main namespace or additional schemas.
			 * 
			 * Needed for validation based on schemaLocation attribute.
			 */
        if (container != null && !containerName.getNamespaceURI().equals(targetIndex.getNamespace()) && !additionalSchemas.containsKey(containerName.getNamespaceURI())) {
            try {
                final URI containerSchemaLoc = stripFragment(container.getLocation());
                if (containerSchemaLoc != null) {
                    addValidationSchema(containerName.getNamespaceURI(), new Locatable() {

                        @Override
                        public URI getLocation() {
                            return containerSchemaLoc;
                        }
                    }, null);
                }
            } catch (Exception e) {
                reporter.error("Could not determine location of container definition", e);
            }
        }
        // additional schema namespace prefixes
        for (Entry<String, String> schemaNs : additionalSchemaPrefixes.entrySet()) {
            GmlWriterUtil.addNamespace(writer, schemaNs.getKey(), schemaNs.getValue());
        }
        writer.writeStartDocument();
        if (documentWrapper != null) {
            documentWrapper.startWrap(writer, reporter);
        }
        GmlWriterUtil.writeStartElement(writer, containerName);
        // generate mandatory id attribute (for feature collection)
        String containerId = getParameter(PARAM_CONTAINER_ID).as(String.class);
        GmlWriterUtil.writeID(writer, containerDefinition, null, false, containerId);
        // write schema locations
        StringBuffer locations = new StringBuffer();
        String noNamespaceLocation = null;
        if (targetIndex.getNamespace() != null && !targetIndex.getNamespace().isEmpty()) {
            locations.append(targetIndex.getNamespace());
            // $NON-NLS-1$
            locations.append(" ");
            locations.append(targetIndex.getLocation().toString());
        } else {
            noNamespaceLocation = targetIndex.getLocation().toString();
        }
        for (Entry<String, Locatable> schema : additionalSchemas.entrySet()) {
            if (schema.getKey() != null && !schema.getKey().isEmpty()) {
                if (locations.length() > 0) {
                    // $NON-NLS-1$
                    locations.append(" ");
                }
                locations.append(schema.getKey());
                // $NON-NLS-1$
                locations.append(" ");
                locations.append(schema.getValue().getLocation().toString());
            } else {
                noNamespaceLocation = schema.getValue().getLocation().toString();
            }
        }
        if (locations.length() > 0) {
            // $NON-NLS-1$
            writer.writeAttribute(SCHEMA_INSTANCE_NS, "schemaLocation", locations.toString());
        }
        if (noNamespaceLocation != null) {
            // $NON-NLS-1$
            writer.writeAttribute(// $NON-NLS-1$
            SCHEMA_INSTANCE_NS, // $NON-NLS-1$
            "noNamespaceSchemaLocation", noNamespaceLocation);
        }
        writeAdditionalElements(writer, containerDefinition, reporter);
        // write the instances
        ResourceIterator<Instance> itInstance = instances.iterator();
        try {
            Map<TypeDefinition, DefinitionPath> paths = new HashMap<TypeDefinition, DefinitionPath>();
            long lastUpdate = 0;
            int count = 0;
            Descent lastDescent = null;
            while (itInstance.hasNext() && !progress.isCanceled()) {
                Instance instance = itInstance.next();
                TypeDefinition type = instance.getDefinition();
                /*
					 * Skip all objects that are no features when writing to a
					 * GML feature collection.
					 */
                boolean skip = useFeatureCollection && !GmlWriterUtil.isFeatureType(type);
                if (skip) {
                    progress.advance(1);
                    continue;
                }
                // get stored definition path for the type
                DefinitionPath defPath;
                if (paths.containsKey(type)) {
                    // get the stored path, may be null
                    defPath = paths.get(type);
                } else {
                    // determine a valid definition path in the container
                    defPath = findMemberAttribute(containerDefinition, containerName, type);
                    // store path (may be null)
                    paths.put(type, defPath);
                }
                if (defPath != null) {
                    // write the feature
                    lastDescent = Descent.descend(writer, defPath, lastDescent, false);
                    writeMember(instance, type, reporter);
                } else {
                    reporter.warn(new IOMessageImpl(MessageFormat.format("No compatible member attribute for type {0} found in root element {1}, one instance was skipped", type.getDisplayName(), containerName.getLocalPart()), null));
                }
                progress.advance(1);
                count++;
                long now = System.currentTimeMillis();
                // only update every 100 milliseconds
                if (now - lastUpdate > 100 || !itInstance.hasNext()) {
                    lastUpdate = now;
                    sub.subTask(String.valueOf(count) + " instances");
                }
            }
            if (lastDescent != null) {
                lastDescent.close();
            }
        } finally {
            itInstance.close();
        }
        // FeatureCollection
        writer.writeEndElement();
        if (documentWrapper != null) {
            documentWrapper.endWrap(writer, reporter);
        }
        writer.writeEndDocument();
        writer.close();
        reporter.setSuccess(reporter.getErrors().isEmpty());
    } catch (Exception e) {
        reporter.error(new IOMessageImpl(e.getLocalizedMessage(), e));
        reporter.setSuccess(false);
    } finally {
        progress.end();
    }
}
Also used : Instance(eu.esdihumboldt.hale.common.instance.model.Instance) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) IOMessageImpl(eu.esdihumboldt.hale.common.core.io.report.impl.IOMessageImpl) SubtaskProgressIndicator(eu.esdihumboldt.hale.common.core.io.impl.SubtaskProgressIndicator) URI(java.net.URI) IOProviderConfigurationException(eu.esdihumboldt.hale.common.core.io.IOProviderConfigurationException) XMLStreamException(javax.xml.stream.XMLStreamException) MismatchedDimensionException(org.opengis.geometry.MismatchedDimensionException) IOException(java.io.IOException) FactoryException(org.opengis.referencing.FactoryException) URISyntaxException(java.net.URISyntaxException) TransformException(org.opengis.referencing.operation.TransformException) Point(org.locationtech.jts.geom.Point) TypeDefinition(eu.esdihumboldt.hale.common.schema.model.TypeDefinition) XmlElement(eu.esdihumboldt.hale.io.xsd.model.XmlElement) DefinitionPath(eu.esdihumboldt.hale.io.gml.writer.internal.geometry.DefinitionPath) Descent(eu.esdihumboldt.hale.io.gml.writer.internal.geometry.Descent) Locatable(eu.esdihumboldt.hale.common.core.io.supplier.Locatable)

Example 17 with XmlElement

use of eu.esdihumboldt.hale.io.xsd.model.XmlElement in project hale by halestudio.

the class TypeDefinitionXmlElementsSection method refresh.

/**
 * @see AbstractPropertySection#refresh()
 */
@Override
public void refresh() {
    if (composite != null)
        composite.dispose();
    Collection<? extends XmlElement> elements = getDefinition().getConstraint(XmlElements.class).getElements();
    int size = elements.size();
    XmlElement[] elm = elements.toArray(new XmlElement[size]);
    textarray = new Text[size];
    super.createControls(parent, aTabbedPropertySheetPage);
    composite = getWidgetFactory().createFlatFormComposite(parent);
    FormData data;
    // $NON-NLS-1$
    text = getWidgetFactory().createText(composite, "");
    text.setEditable(false);
    data = new FormData();
    data.left = new FormAttachment(0, STANDARD_LABEL_WIDTH);
    data.right = new FormAttachment(100, 0);
    data.top = new FormAttachment(0, ITabbedPropertyConstants.VSPACE);
    text.setLayoutData(data);
    // $NON-NLS-1$
    CLabel namespaceLabel = getWidgetFactory().createCLabel(composite, "XML-Elements:");
    data = new FormData();
    data.left = new FormAttachment(0, 0);
    data.right = new FormAttachment(text, 10);
    data.top = new FormAttachment(text, 0, SWT.CENTER);
    namespaceLabel.setLayoutData(data);
    text.setText(elm[0].getName().toString());
    textarray[0] = text;
    for (int pos = 1; pos < size; pos++) {
        // $NON-NLS-1$
        text = getWidgetFactory().createText(composite, "");
        text.setEditable(false);
        data = new FormData();
        data.left = new FormAttachment(0, STANDARD_LABEL_WIDTH);
        data.right = new FormAttachment(100, 0);
        data.top = new FormAttachment(textarray[pos - 1], ITabbedPropertyConstants.VSPACE);
        text.setLayoutData(data);
        // $NON-NLS-1$
        namespaceLabel = getWidgetFactory().createCLabel(composite, "");
        data = new FormData();
        data.left = new FormAttachment(0, 0);
        data.right = new FormAttachment(text, 10);
        data.top = new FormAttachment(text, 0, SWT.CENTER);
        namespaceLabel.setLayoutData(data);
        text.setText(elm[pos].getName().getNamespaceURI().toString());
        textarray[pos] = text;
    }
    parent.layout();
    parent.getParent().layout();
}
Also used : FormData(org.eclipse.swt.layout.FormData) CLabel(org.eclipse.swt.custom.CLabel) XmlElements(eu.esdihumboldt.hale.io.xsd.constraint.XmlElements) XmlElement(eu.esdihumboldt.hale.io.xsd.model.XmlElement) FormAttachment(org.eclipse.swt.layout.FormAttachment)

Example 18 with XmlElement

use of eu.esdihumboldt.hale.io.xsd.model.XmlElement in project hale by halestudio.

the class XmlSchemaReaderTest method testRead_shiporder_types.

/**
 * Test reading a simple XML schema that uses several custom named types
 *
 * @throws Exception if reading the schema fails
 */
@Test
public void testRead_shiporder_types() throws Exception {
    URI location = getClass().getResource("/testdata/shiporder/shiporder-types.xsd").toURI();
    LocatableInputSupplier<? extends InputStream> input = new DefaultInputSupplier(location);
    XmlIndex schema = (XmlIndex) readSchema(input);
    String ns = "http://www.example.com";
    assertEquals(ns, schema.getNamespace());
    // shiporder element
    Collection<XmlElement> elements = getElementsWithNS(ns, schema.getElements().values());
    assertEquals(1, elements.size());
    XmlElement shiporder = elements.iterator().next();
    testShiporderStructure(shiporder, ns);
}
Also used : DefaultInputSupplier(eu.esdihumboldt.hale.common.core.io.supplier.DefaultInputSupplier) XmlIndex(eu.esdihumboldt.hale.io.xsd.model.XmlIndex) XmlElement(eu.esdihumboldt.hale.io.xsd.model.XmlElement) URI(java.net.URI) Test(org.junit.Test)

Example 19 with XmlElement

use of eu.esdihumboldt.hale.io.xsd.model.XmlElement in project hale by halestudio.

the class XmlSchemaReaderTest method testRead_definitive_substitution.

/**
 * Test reading a simple XML schema containing substitution groups.
 *
 * @throws Exception if reading the schema fails
 */
@Test
public void testRead_definitive_substitution() throws Exception {
    URI location = getClass().getResource("/testdata/definitive/substgroups.xsd").toURI();
    LocatableInputSupplier<? extends InputStream> input = new DefaultInputSupplier(location);
    XmlIndex schema = (XmlIndex) readSchema(input);
    // shirt element
    XmlElement shirt = schema.getElements().get(new QName("shirt"));
    assertNotNull(shirt);
    assertEquals(new QName("product"), shirt.getSubstitutionGroup());
// TODO extend
}
Also used : DefaultInputSupplier(eu.esdihumboldt.hale.common.core.io.supplier.DefaultInputSupplier) QName(javax.xml.namespace.QName) XmlIndex(eu.esdihumboldt.hale.io.xsd.model.XmlIndex) XmlElement(eu.esdihumboldt.hale.io.xsd.model.XmlElement) URI(java.net.URI) Test(org.junit.Test)

Example 20 with XmlElement

use of eu.esdihumboldt.hale.io.xsd.model.XmlElement in project hale by halestudio.

the class CustomTypeContentHelper method applyElementsMode.

private static void applyElementsMode(PropertyDefinition propDef, DefinitionGroup propParent, CustomTypeContent config, XmlIndex index) {
    // build new property type based on config
    DefaultTypeDefinition type = new DefaultTypeDefinition(new QName(propDef.getIdentifier(), "customElementsContentType"), false);
    type.setConstraint(MappableFlag.DISABLED);
    DefaultGroupPropertyDefinition choice = new DefaultGroupPropertyDefinition(new QName(propDef.getIdentifier(), "customElementsContentChoice"), type, false);
    choice.setConstraint(new DisplayName("elements"));
    choice.setConstraint(ChoiceFlag.ENABLED);
    choice.setConstraint(Cardinality.CC_ANY_NUMBER);
    for (QName elementName : config.getElements()) {
        XmlElement element = index.getElements().get(elementName);
        if (element != null) {
            DefaultPropertyDefinition elementProp = new DefaultPropertyDefinition(elementName, choice, element.getType());
            elementProp.setConstraint(Cardinality.CC_EXACTLY_ONCE);
            elementProp.setConstraint(NillableFlag.DISABLED);
        } else {
            log.error("Element {} could not be found when creating custom type content", elementName);
        }
    }
    replaceTypeForProperty(propDef, propParent, type);
}
Also used : DefaultTypeDefinition(eu.esdihumboldt.hale.common.schema.model.impl.DefaultTypeDefinition) DefaultPropertyDefinition(eu.esdihumboldt.hale.common.schema.model.impl.DefaultPropertyDefinition) DefaultGroupPropertyDefinition(eu.esdihumboldt.hale.common.schema.model.impl.DefaultGroupPropertyDefinition) QName(javax.xml.namespace.QName) DisplayName(eu.esdihumboldt.hale.common.schema.model.constraint.DisplayName) XmlElement(eu.esdihumboldt.hale.io.xsd.model.XmlElement)

Aggregations

XmlElement (eu.esdihumboldt.hale.io.xsd.model.XmlElement)37 QName (javax.xml.namespace.QName)23 XmlIndex (eu.esdihumboldt.hale.io.xsd.model.XmlIndex)16 TypeDefinition (eu.esdihumboldt.hale.common.schema.model.TypeDefinition)14 XmlElements (eu.esdihumboldt.hale.io.xsd.constraint.XmlElements)12 DefaultInputSupplier (eu.esdihumboldt.hale.common.core.io.supplier.DefaultInputSupplier)11 URI (java.net.URI)11 Test (org.junit.Test)9 HashSet (java.util.HashSet)7 IOMessageImpl (eu.esdihumboldt.hale.common.core.io.report.impl.IOMessageImpl)6 IOProviderConfigurationException (eu.esdihumboldt.hale.common.core.io.IOProviderConfigurationException)4 SchemaSpace (eu.esdihumboldt.hale.common.schema.model.SchemaSpace)4 IOException (java.io.IOException)4 XMLStreamException (javax.xml.stream.XMLStreamException)4 Instance (eu.esdihumboldt.hale.common.instance.model.Instance)3 PropertyDefinition (eu.esdihumboldt.hale.common.schema.model.PropertyDefinition)3 DefaultPropertyDefinition (eu.esdihumboldt.hale.common.schema.model.impl.DefaultPropertyDefinition)3 DefaultTypeDefinition (eu.esdihumboldt.hale.common.schema.model.impl.DefaultTypeDefinition)3 File (java.io.File)3 ValueList (eu.esdihumboldt.hale.common.core.io.ValueList)2