Search in sources :

Example 1 with DataHolder

use of com.thoughtworks.xstream.converters.DataHolder in project ddf by codice.

the class TestCswRecordConverter method testUnmarshalCswRecordWithProductAndThumbnail.

@Test
public void testUnmarshalCswRecordWithProductAndThumbnail() throws URISyntaxException, IOException, JAXBException, ParserConfigurationException, SAXException {
    XStream xstream = new XStream(new WstxDriver());
    xstream.registerConverter(converter);
    InputStream is = TestCswRecordConverter.class.getResourceAsStream("/Csw_Record.xml");
    // get the URL to the thumbnail image and stick it in the xml string
    // this makes the test filesystem independent
    URL thumbnail = TestCswRecordConverter.class.getResource("/ddf_globe.png");
    String xml = null;
    if (thumbnail != null) {
        StringWriter writer = new StringWriter();
        IOUtils.copy(is, writer);
        xml = writer.toString();
        xml = xml.replace(THUMBNAIL_URL, thumbnail.toString());
    }
    xstream.alias("csw:Record", MetacardImpl.class);
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(IOUtils.toInputStream(xml));
    HierarchicalStreamReader reader = new DomReader(doc);
    DataHolder holder = xstream.newDataHolder();
    Metacard mc = (Metacard) xstream.unmarshal(reader, null, holder);
    assertThat(mc, notNullValue());
    String productUrl = "http://example.com/product.pdf";
    assertThat(mc.getAttribute(Core.RESOURCE_URI).getValue(), is(productUrl));
    assertThat(mc.getThumbnail(), is(getThumbnailByteArray(thumbnail)));
}
Also used : WstxDriver(com.thoughtworks.xstream.io.xml.WstxDriver) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) DomReader(com.thoughtworks.xstream.io.xml.DomReader) XStream(com.thoughtworks.xstream.XStream) InputStream(java.io.InputStream) Matchers.containsString(org.hamcrest.Matchers.containsString) Document(org.w3c.dom.Document) URL(java.net.URL) Metacard(ddf.catalog.data.Metacard) StringWriter(java.io.StringWriter) DocumentBuilder(javax.xml.parsers.DocumentBuilder) DataHolder(com.thoughtworks.xstream.converters.DataHolder) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) Test(org.junit.Test)

Example 2 with DataHolder

use of com.thoughtworks.xstream.converters.DataHolder in project ddf by codice.

the class TestCswRecordConverter method testUnmarshalSingleCswRecordToMetacardContentTypeMapsToFormat.

@Test
public void testUnmarshalSingleCswRecordToMetacardContentTypeMapsToFormat() throws ParserConfigurationException, IOException, SAXException {
    XStream xstream = new XStream(new WstxDriver());
    xstream.registerConverter(converter);
    xstream.alias("csw:Record", MetacardImpl.class);
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(TestCswRecordConverter.class.getResource("/Csw_Record.xml").getPath());
    HierarchicalStreamReader reader = new DomReader(doc);
    DataHolder holder = xstream.newDataHolder();
    Metacard mc = (Metacard) xstream.unmarshal(reader, null, holder);
    assertThat(mc, notNullValue());
    assertThat(mc.getContentTypeName(), is("IMAGE-PRODUCT"));
    assertThat(mc.getAttribute(Media.FORMAT).getValue(), is("PDF"));
}
Also used : WstxDriver(com.thoughtworks.xstream.io.xml.WstxDriver) Metacard(ddf.catalog.data.Metacard) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) DomReader(com.thoughtworks.xstream.io.xml.DomReader) DocumentBuilder(javax.xml.parsers.DocumentBuilder) XStream(com.thoughtworks.xstream.XStream) DataHolder(com.thoughtworks.xstream.converters.DataHolder) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) Document(org.w3c.dom.Document) Test(org.junit.Test)

Example 3 with DataHolder

use of com.thoughtworks.xstream.converters.DataHolder in project jmeter by apache.

the class SaveService method saveSampleResult.

/**
 * Save a sampleResult to an XML output file using XStream.
 *
 * @param evt sampleResult wrapped in a sampleEvent
 * @param writer output stream which must be created using {@link #getFileEncoding(String)}
 * @throws IOException when writing data to output fails
 */
// Used by ResultCollector.sampleOccurred(SampleEvent event)
public static synchronized void saveSampleResult(SampleEvent evt, Writer writer) throws IOException {
    DataHolder dh = JTLSAVER.newDataHolder();
    dh.put(SAMPLE_EVENT_OBJECT, evt);
    // Don't know why there is no method for this in the XStream class
    try {
        JTLSAVER.marshal(evt.getResult(), new XppDriver().createWriter(writer), dh);
    } catch (RuntimeException e) {
        throw new IllegalArgumentException("Failed marshalling:" + (evt.getResult() != null ? showDebuggingInfo(evt.getResult()) : "null"), e);
    }
    writer.write('\n');
}
Also used : XppDriver(com.thoughtworks.xstream.io.xml.XppDriver) DataHolder(com.thoughtworks.xstream.converters.DataHolder)

Example 4 with DataHolder

use of com.thoughtworks.xstream.converters.DataHolder 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 5 with DataHolder

use of com.thoughtworks.xstream.converters.DataHolder 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)

Aggregations

DataHolder (com.thoughtworks.xstream.converters.DataHolder)9 XStream (com.thoughtworks.xstream.XStream)7 HierarchicalStreamReader (com.thoughtworks.xstream.io.HierarchicalStreamReader)7 Metacard (ddf.catalog.data.Metacard)6 Test (org.junit.Test)6 DomReader (com.thoughtworks.xstream.io.xml.DomReader)4 WstxDriver (com.thoughtworks.xstream.io.xml.WstxDriver)4 XppDriver (com.thoughtworks.xstream.io.xml.XppDriver)4 InputStream (java.io.InputStream)4 DocumentBuilder (javax.xml.parsers.DocumentBuilder)4 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)4 Matchers.containsString (org.hamcrest.Matchers.containsString)4 Document (org.w3c.dom.Document)4 InputStreamReader (java.io.InputStreamReader)3 XppReader (com.thoughtworks.xstream.io.xml.XppReader)2 StringWriter (java.io.StringWriter)2 URL (java.net.URL)2 HashMap (java.util.HashMap)2 LegendObject (au.org.ala.legend.LegendObject)1 ScatterplotDataDTO (au.org.ala.spatial.dto.ScatterplotDataDTO)1