Search in sources :

Example 21 with HierarchicalStreamReader

use of com.thoughtworks.xstream.io.HierarchicalStreamReader in project ddf by codice.

the class AbstractFeatureConverter method createMetacardFromFeature.

protected Metacard createMetacardFromFeature(HierarchicalStreamReader hreader, MetacardType metacardType) {
    StringWriter metadataWriter = new StringWriter();
    HierarchicalStreamReader reader = copyXml(hreader, metadataWriter);
    MetacardImpl mc = new MetacardImpl(metacardType);
    mc.setContentTypeName(metacardType.getName());
    while (reader.hasMoreChildren()) {
        reader.moveDown();
        String featureProperty = prefix + reader.getNodeName();
        AttributeDescriptor attributeDescriptor = metacardType.getAttributeDescriptor(featureProperty);
        //Check MetacardMapper for mappings of incoming values
        String mappedMetacardAttribute = null;
        if (metacardMapper != null) {
            LOGGER.debug("Looking up metacard attribute for feature property {} using metacard mapper", featureProperty);
            mappedMetacardAttribute = metacardMapper.getMetacardAttribute(featureProperty);
            LOGGER.debug("Found metacard attribute {} for feature property {}", mappedMetacardAttribute, featureProperty);
        }
        Serializable value = null;
        if (attributeDescriptor != null && (StringUtils.isNotBlank(reader.getValue()) || BasicTypes.GEO_TYPE.getAttributeFormat().equals(attributeDescriptor.getType().getAttributeFormat()) || BasicTypes.DATE_TYPE.getAttributeFormat().equals(attributeDescriptor.getType().getAttributeFormat()))) {
            if (StringUtils.isNotBlank(mappedMetacardAttribute)) {
                if (StringUtils.equals(mappedMetacardAttribute, Core.RESOURCE_SIZE)) {
                    String sizeBeforeConversion = reader.getValue();
                    String bytes = convertToBytes(reader, metacardMapper.getDataUnit());
                    if (StringUtils.isNotBlank(bytes)) {
                        LOGGER.debug("Setting mapped metacard attribute {} with value {}", mappedMetacardAttribute, bytes);
                        mc.setAttribute(mappedMetacardAttribute, bytes);
                    }
                    if (StringUtils.isNotBlank(sizeBeforeConversion)) {
                        LOGGER.debug("Setting metacard attribute {} with value {}", featureProperty, sizeBeforeConversion);
                        mc.setAttribute(featureProperty, sizeBeforeConversion);
                    }
                } else {
                    value = getValueForMetacardAttribute(attributeDescriptor.getType().getAttributeFormat(), reader);
                    if (value != null) {
                        LOGGER.debug("Setting mapped metacard attribute {} with value {}", mappedMetacardAttribute, value);
                        mc.setAttribute(mappedMetacardAttribute, value);
                        mc.setAttribute(featureProperty, value);
                    }
                }
            } else {
                value = getValueForMetacardAttribute(attributeDescriptor.getType().getAttributeFormat(), reader);
                if (value != null) {
                    LOGGER.debug("Setting metacard attribute {} with value {}", featureProperty, value);
                    mc.setAttribute(featureProperty, value);
                }
            }
            if (BasicTypes.GEO_TYPE.getAttributeFormat().equals(attributeDescriptor.getType().getAttributeFormat())) {
                mc.setLocation((String) value);
            }
            // populate that field as well
            if (isBasicMetacardAttribute(reader.getNodeName())) {
                LOGGER.debug("Setting metacard basic attribute: {} = {}", reader.getNodeName(), value);
                mc.setAttribute(reader.getNodeName(), value);
            }
        }
        reader.moveUp();
    }
    mc.setMetadata(metadataWriter.toString());
    try {
        if (metacardType instanceof FeatureMetacardType) {
            URI namespaceUri = new URI(((FeatureMetacardType) metacardType).getNamespaceURI());
            mc.setTargetNamespace(namespaceUri);
        }
    } catch (URISyntaxException e) {
        LOGGER.debug("Error setting target namespace uri on metacard.", e);
    }
    return mc;
}
Also used : Serializable(java.io.Serializable) StringWriter(java.io.StringWriter) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) AttributeDescriptor(ddf.catalog.data.AttributeDescriptor) URISyntaxException(java.net.URISyntaxException) FeatureMetacardType(org.codice.ddf.spatial.ogc.wfs.catalog.common.FeatureMetacardType) URI(java.net.URI) MetacardImpl(ddf.catalog.data.impl.MetacardImpl)

Example 22 with HierarchicalStreamReader

use of com.thoughtworks.xstream.io.HierarchicalStreamReader in project spatial-portal by AtlasOfLivingAustralia.

the class MapComposer method loadUserSession.

public void loadUserSession(String sessionid) {
    onClick$removeAllLayers();
    Scanner scanner = null;
    try {
        String sfld = getSettingsSupplementary().getProperty(StringConstants.ANALYSIS_OUTPUT_DIR) + "session/" + sessionid;
        File sessfolder = new File(sfld);
        if (!sessfolder.exists()) {
            showMessage("Session information does not exist. Please provide a valid session id");
            return;
        }
        scanner = new Scanner(new File(sfld + "/details.txt"));
        // first grab the zoom level and bounding box
        String[] mapdetails = scanner.nextLine().split(",");
        BoundingBox bb = new BoundingBox();
        bb.setMinLongitude(Float.parseFloat(mapdetails[1]));
        bb.setMinLatitude(Float.parseFloat(mapdetails[2]));
        bb.setMaxLongitude(Float.parseFloat(mapdetails[3]));
        bb.setMaxLatitude(Float.parseFloat(mapdetails[4]));
        openLayersJavascript.setAdditionalScript(openLayersJavascript.zoomToBoundingBox(bb, true));
        String[] scatterplotNames = null;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.startsWith("scatterplotNames")) {
                scatterplotNames = line.substring(17).split("___");
            }
        }
        ArrayUtils.reverse(scatterplotNames);
        // ignore fields not found
        XStream xstream = new XStream(new DomDriver()) {

            protected MapperWrapper wrapMapper(MapperWrapper next) {
                return new MapperWrapper(next) {

                    public boolean shouldSerializeMember(Class definedIn, String fieldName) {
                        if (definedIn == Object.class || !super.shouldSerializeMember(definedIn, fieldName))
                            System.out.println("faled to read: " + definedIn + ", " + fieldName);
                        return definedIn != Object.class ? super.shouldSerializeMember(definedIn, fieldName) : false;
                    }
                };
            }

            @Override
            public Object unmarshal(HierarchicalStreamReader reader) {
                Object o = super.unmarshal(reader);
                if (o instanceof BiocacheQuery)
                    ((BiocacheQuery) o).getFullQ(false);
                return o;
            }

            @Override
            public Object unmarshal(HierarchicalStreamReader reader, Object root) {
                Object o = super.unmarshal(reader, root);
                if (o instanceof BiocacheQuery)
                    ((BiocacheQuery) o).getFullQ(false);
                return o;
            }

            @Override
            public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) {
                Object o = super.unmarshal(reader, root, dataHolder);
                if (o instanceof BiocacheQuery)
                    ((BiocacheQuery) o).getFullQ(false);
                return o;
            }
        };
        PersistenceStrategy strategy = new FilePersistenceStrategy(new File(sfld), xstream);
        List list = new XmlArrayList(strategy);
        ListIterator it = list.listIterator(list.size());
        int scatterplotIndex = 0;
        while (it.hasPrevious()) {
            Object o = it.previous();
            MapLayer ml = null;
            if (o instanceof MapLayer) {
                ml = (MapLayer) o;
                LOGGER.debug("Loading " + ml.getName() + " -> " + ml.isDisplayed());
                addUserDefinedLayerToMenu(ml, false);
            } else if (o instanceof ScatterplotDataDTO) {
                ScatterplotDataDTO spdata = (ScatterplotDataDTO) o;
                loadScatterplot(spdata, "My Scatterplot " + scatterplotIndex++);
            }
            if (ml != null) {
                addUserDefinedLayerToMenu(ml, true);
            }
        }
    } catch (Exception e) {
        try {
            File f = new File("/data/sessions/" + sessionid + ".txt");
            PrintWriter pw = new PrintWriter(f);
            e.printStackTrace(pw);
            pw.close();
        } catch (Exception ex) {
        }
        LOGGER.error("Unable to load session data", e);
        showMessage("Unable to load session data");
    } finally {
        if (scanner != null) {
            scanner.close();
        }
        try {
            File f = new File("/data/sessions/ok/" + sessionid + ".txt");
            FileUtils.writeStringToFile(f, "ok");
        } catch (Exception ex) {
        }
    }
}
Also used : ScatterplotDataDTO(au.org.ala.spatial.dto.ScatterplotDataDTO) XStream(com.thoughtworks.xstream.XStream) HasMapLayer(au.org.emii.portal.menu.HasMapLayer) MapLayer(au.org.emii.portal.menu.MapLayer) XmlArrayList(com.thoughtworks.xstream.persistence.XmlArrayList) ParseException(org.json.simple.parser.ParseException) PersistenceStrategy(com.thoughtworks.xstream.persistence.PersistenceStrategy) FilePersistenceStrategy(com.thoughtworks.xstream.persistence.FilePersistenceStrategy) DomDriver(com.thoughtworks.xstream.io.xml.DomDriver) MapperWrapper(com.thoughtworks.xstream.mapper.MapperWrapper) DataHolder(com.thoughtworks.xstream.converters.DataHolder) BoundingBox(au.org.emii.portal.value.BoundingBox) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) JSONObject(org.json.simple.JSONObject) LegendObject(au.org.ala.legend.LegendObject) XmlArrayList(com.thoughtworks.xstream.persistence.XmlArrayList) List(java.util.List) FilePersistenceStrategy(com.thoughtworks.xstream.persistence.FilePersistenceStrategy)

Example 23 with HierarchicalStreamReader

use of com.thoughtworks.xstream.io.HierarchicalStreamReader in project camel by apache.

the class MapOfMapsConverterTest method readerFor.

HierarchicalStreamReader readerFor(final String xml) throws XmlPullParserException, IOException {
    parser.setInput(new StringReader(xml));
    final XppDom dom = XppDom.build(parser);
    final HierarchicalStreamReader reader = new XppDomReader(dom);
    return reader;
}
Also used : XppDom(com.thoughtworks.xstream.io.xml.xppdom.XppDom) StringReader(java.io.StringReader) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) XppDomReader(com.thoughtworks.xstream.io.xml.XppDomReader)

Example 24 with HierarchicalStreamReader

use of com.thoughtworks.xstream.io.HierarchicalStreamReader in project ddf by codice.

the class TestCswRecordConverter method testUnmarshalWriteNamespaces.

@Test
public void testUnmarshalWriteNamespaces() throws IOException, SAXException, XmlPullParserException {
    XStream xstream = new XStream(new XppDriver());
    xstream.registerConverter(converter);
    xstream.alias("Record", MetacardImpl.class);
    xstream.alias("csw:Record", MetacardImpl.class);
    InputStream is = IOUtils.toInputStream(getRecordNoNamespaceDeclaration());
    HierarchicalStreamReader reader = new XppReader(new InputStreamReader(is), XmlPullParserFactory.newInstance().newPullParser());
    DataHolder args = xstream.newDataHolder();
    Map<String, String> namespaces = new HashMap<>();
    namespaces.put(CswConstants.XMLNS + CswConstants.NAMESPACE_DELIMITER + CswConstants.CSW_NAMESPACE_PREFIX, CswConstants.CSW_OUTPUT_SCHEMA);
    namespaces.put(CswConstants.XMLNS + CswConstants.NAMESPACE_DELIMITER + CswConstants.DUBLIN_CORE_NAMESPACE_PREFIX, CswConstants.DUBLIN_CORE_SCHEMA);
    namespaces.put(CswConstants.XMLNS + CswConstants.NAMESPACE_DELIMITER + CswConstants.DUBLIN_CORE_TERMS_NAMESPACE_PREFIX, CswConstants.DUBLIN_CORE_TERMS_SCHEMA);
    namespaces.put(CswConstants.XMLNS + CswConstants.NAMESPACE_DELIMITER + CswConstants.OWS_NAMESPACE_PREFIX, CswConstants.OWS_NAMESPACE);
    args.put(CswConstants.NAMESPACE_DECLARATIONS, namespaces);
    Metacard mc = (Metacard) xstream.unmarshal(reader, null, args);
    Metacard expectedMetacard = getTestMetacard();
    assertThat(mc, notNullValue());
    assertThat(mc.getContentTypeName(), is(mc.getContentTypeName()));
    assertThat(mc.getCreatedDate(), is(expectedMetacard.getCreatedDate()));
    assertThat(mc.getEffectiveDate(), is(expectedMetacard.getEffectiveDate()));
    assertThat(mc.getId(), is(expectedMetacard.getId()));
    assertThat(mc.getModifiedDate(), is(expectedMetacard.getModifiedDate()));
    assertThat(mc.getTitle(), is(expectedMetacard.getTitle()));
    assertThat(mc.getResourceURI(), is(expectedMetacard.getResourceURI()));
    XMLUnit.setIgnoreWhitespace(true);
    assertXMLEqual(mc.getMetadata(), getControlRecord());
}
Also used : Metacard(ddf.catalog.data.Metacard) InputStreamReader(java.io.InputStreamReader) XppDriver(com.thoughtworks.xstream.io.xml.XppDriver) HashMap(java.util.HashMap) XStream(com.thoughtworks.xstream.XStream) InputStream(java.io.InputStream) XppReader(com.thoughtworks.xstream.io.xml.XppReader) DataHolder(com.thoughtworks.xstream.converters.DataHolder) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) Matchers.containsString(org.hamcrest.Matchers.containsString) Test(org.junit.Test)

Example 25 with HierarchicalStreamReader

use of com.thoughtworks.xstream.io.HierarchicalStreamReader in project ddf by codice.

the class GmdTransformer method handleTransform.

private Metacard handleTransform(InputStream inputStream, String id) throws CatalogTransformerException {
    String xml;
    XstreamPathValueTracker pathValueTracker;
    try (TemporaryFileBackedOutputStream temporaryFileBackedOutputStream = new TemporaryFileBackedOutputStream()) {
        IOUtils.copy(inputStream, temporaryFileBackedOutputStream);
        byteArray = temporaryFileBackedOutputStream.asByteSource();
        try (InputStream xmlSourceInputStream = getSourceInputStream()) {
            xml = IOUtils.toString(xmlSourceInputStream);
        }
        argumentHolder.put(XstreamPathConverter.PATH_KEY, buildPaths());
        XMLStreamReader streamReader = xmlFactory.createXMLStreamReader(new StringReader(xml));
        HierarchicalStreamReader reader = new StaxReader(new QNameMap(), streamReader);
        pathValueTracker = (XstreamPathValueTracker) xstream.unmarshal(reader, null, argumentHolder);
        Metacard metacard = toMetacard(pathValueTracker, id);
        metacard.setAttribute(new AttributeImpl(Core.METADATA, xml));
        return metacard;
    } catch (XStreamException | XMLStreamException | IOException e) {
        throw new CatalogTransformerException(TRANSFORM_EXCEPTION_MSG, e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
Also used : StaxReader(com.thoughtworks.xstream.io.xml.StaxReader) XMLStreamReader(javax.xml.stream.XMLStreamReader) TemporaryFileBackedOutputStream(org.codice.ddf.platform.util.TemporaryFileBackedOutputStream) InputStream(java.io.InputStream) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) XstreamPathValueTracker(org.codice.ddf.spatial.ogc.csw.catalog.converter.XstreamPathValueTracker) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) IOException(java.io.IOException) Metacard(ddf.catalog.data.Metacard) XStreamException(com.thoughtworks.xstream.XStreamException) XMLStreamException(javax.xml.stream.XMLStreamException) StringReader(java.io.StringReader) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) QNameMap(com.thoughtworks.xstream.io.xml.QNameMap)

Aggregations

HierarchicalStreamReader (com.thoughtworks.xstream.io.HierarchicalStreamReader)34 Test (org.junit.Test)28 DomReader (com.thoughtworks.xstream.io.xml.DomReader)13 DocumentBuilder (javax.xml.parsers.DocumentBuilder)13 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)13 Document (org.w3c.dom.Document)13 StringReader (java.io.StringReader)11 UnmarshallingContext (com.thoughtworks.xstream.converters.UnmarshallingContext)8 InputStream (java.io.InputStream)8 TreeUnmarshaller (com.thoughtworks.xstream.core.TreeUnmarshaller)7 WstxDriver (com.thoughtworks.xstream.io.xml.WstxDriver)6 XppReader (com.thoughtworks.xstream.io.xml.XppReader)6 HashMap (java.util.HashMap)6 XStream (com.thoughtworks.xstream.XStream)5 Metacard (ddf.catalog.data.Metacard)5 Serializable (java.io.Serializable)5 DataHolder (com.thoughtworks.xstream.converters.DataHolder)4 QNameMap (com.thoughtworks.xstream.io.xml.QNameMap)4 StaxReader (com.thoughtworks.xstream.io.xml.StaxReader)4 IOException (java.io.IOException)4