Search in sources :

Example 76 with Unmarshaller

use of javax.xml.bind.Unmarshaller in project opennms by OpenNMS.

the class JAXBTest method testMarshall.

/**
     * Test marshall.
     *
     * @throws Exception the exception
     */
@Test
public void testMarshall() throws Exception {
    final String expectedXML = "" + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<test-alarm>\n" + "    <id>23</id>\n" + "</test-alarm>\n" + "";
    TestNorthBoundAlarm nba = new TestNorthBoundAlarm();
    nba.setId("23");
    // Create a Marshaller
    JAXBContext context = JAXBContext.newInstance(TestNorthBoundAlarm.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    // save the output in a byte array
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    // marshall the output
    marshaller.marshal(nba, out);
    // verify its matches the expected results
    byte[] utf8 = out.toByteArray();
    String result = new String(utf8, StandardCharsets.UTF_8);
    assertXmlEquals(expectedXML, result);
    System.err.println(result);
    // unmarshall the generated XML
    //		URL xsd = getClass().getResource("/ncs-model.xsd");
    //		
    //		assertNotNull(xsd);
    //		
    //		SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    //		Schema schema = schemaFactory.newSchema(xsd);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    //		unmarshaller.setSchema(schema);
    Source source = new StreamSource(new ByteArrayInputStream(utf8));
    TestNorthBoundAlarm read = unmarshaller.unmarshal(source, TestNorthBoundAlarm.class).getValue();
    assertNotNull(read);
    // round trip back to XML and make sure we get the same thing
    ByteArrayOutputStream reout = new ByteArrayOutputStream();
    marshaller.marshal(read, reout);
    String roundTrip = new String(reout.toByteArray(), StandardCharsets.UTF_8);
    assertXmlEquals(expectedXML, roundTrip);
}
Also used : Marshaller(javax.xml.bind.Marshaller) ByteArrayInputStream(java.io.ByteArrayInputStream) StreamSource(javax.xml.transform.stream.StreamSource) JAXBContext(javax.xml.bind.JAXBContext) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Unmarshaller(javax.xml.bind.Unmarshaller) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) Test(org.junit.Test)

Example 77 with Unmarshaller

use of javax.xml.bind.Unmarshaller in project opennms by OpenNMS.

the class RrdtoolXportFetchStrategy method fetchMeasurements.

/**
     * {@inheritDoc}
     */
@Override
protected FetchResults fetchMeasurements(long start, long end, long step, int maxrows, Map<Source, String> rrdsBySource, Map<String, Object> constants) throws RrdException {
    String rrdBinary = System.getProperty("rrd.binary");
    if (rrdBinary == null) {
        throw new RrdException("No RRD binary is set.");
    }
    final long startInSeconds = (long) Math.floor(start / 1000);
    final long endInSeconds = (long) Math.floor(end / 1000);
    long stepInSeconds = (long) Math.floor(step / 1000);
    // The step must be strictly positive
    if (stepInSeconds <= 0) {
        stepInSeconds = 1;
    }
    final CommandLine cmdLine = new CommandLine(rrdBinary);
    cmdLine.addArgument("xport");
    cmdLine.addArgument("--step");
    cmdLine.addArgument("" + stepInSeconds);
    cmdLine.addArgument("--start");
    cmdLine.addArgument("" + startInSeconds);
    cmdLine.addArgument("--end");
    cmdLine.addArgument("" + endInSeconds);
    if (maxrows > 0) {
        cmdLine.addArgument("--maxrows");
        cmdLine.addArgument("" + maxrows);
    }
    // Use labels without spaces when executing the xport command
    // These are mapped back to the requested labels in the response
    final Map<String, String> labelMap = Maps.newHashMap();
    int k = 0;
    for (final Map.Entry<Source, String> entry : rrdsBySource.entrySet()) {
        final Source source = entry.getKey();
        final String rrdFile = entry.getValue();
        final String tempLabel = Integer.toString(++k);
        labelMap.put(tempLabel, source.getLabel());
        cmdLine.addArgument(String.format("DEF:%s=%s:%s:%s", tempLabel, Utils.escapeColons(rrdFile), Utils.escapeColons(source.getEffectiveDataSource()), source.getAggregation()));
        cmdLine.addArgument(String.format("XPORT:%s:%s", tempLabel, tempLabel));
    }
    // Use commons-exec to execute rrdtool
    final DefaultExecutor executor = new DefaultExecutor();
    // Capture stdout/stderr
    final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    final ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, null));
    // Fail if we get a non-zero exit code
    executor.setExitValue(0);
    // Fail if the process takes too long
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(XPORT_TIMEOUT_MS);
    executor.setWatchdog(watchdog);
    // Export
    RrdXport rrdXport;
    try {
        LOG.debug("Executing: {}", cmdLine);
        executor.execute(cmdLine);
        final XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        final SAXSource source = new SAXSource(xmlReader, new InputSource(new StringReader(stdout.toString())));
        final JAXBContext jc = JAXBContext.newInstance(RrdXport.class);
        final Unmarshaller u = jc.createUnmarshaller();
        rrdXport = (RrdXport) u.unmarshal(source);
    } catch (IOException e) {
        throw new RrdException("An error occured while executing '" + StringUtils.join(cmdLine.toStrings(), " ") + "' with stderr: " + stderr.toString(), e);
    } catch (SAXException | JAXBException e) {
        throw new RrdException("The output generated by 'rrdtool xport' could not be parsed.", e);
    }
    final int numRows = rrdXport.getRows().size();
    final int numColumns = rrdXport.getMeta().getLegends().size();
    final long xportStartInMs = rrdXport.getMeta().getStart() * 1000;
    final long xportStepInMs = rrdXport.getMeta().getStep() * 1000;
    final long[] timestamps = new long[numRows];
    final double[][] values = new double[numColumns][numRows];
    // Convert rows to columns
    int i = 0;
    for (final XRow row : rrdXport.getRows()) {
        // Derive the timestamp from the start and step since newer versions
        // of rrdtool no longer include it as part of the rows
        timestamps[i] = xportStartInMs + xportStepInMs * i;
        for (int j = 0; j < numColumns; j++) {
            if (row.getValues() == null) {
                // NMS-7710: Avoid NPEs, in certain cases the list of values may be null
                throw new RrdException("The output generated by 'rrdtool xport' was not recognized. Try upgrading your rrdtool binaries.");
            }
            values[j][i] = row.getValues().get(j);
        }
        i++;
    }
    // Map the columns by label
    // The legend entries are in the same order as the column values
    final Map<String, double[]> columns = Maps.newHashMapWithExpectedSize(numColumns);
    i = 0;
    for (String label : rrdXport.getMeta().getLegends()) {
        columns.put(labelMap.get(label), values[i++]);
    }
    return new FetchResults(timestamps, columns, xportStepInMs, constants);
}
Also used : InputSource(org.xml.sax.InputSource) JAXBContext(javax.xml.bind.JAXBContext) XRow(org.opennms.netmgt.rrd.model.XRow) RrdXport(org.opennms.netmgt.rrd.model.RrdXport) InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) Source(org.opennms.netmgt.measurements.model.Source) SAXException(org.xml.sax.SAXException) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) FetchResults(org.opennms.netmgt.measurements.api.FetchResults) StringReader(java.io.StringReader) RrdException(org.jrobin.core.RrdException) Unmarshaller(javax.xml.bind.Unmarshaller) XMLReader(org.xml.sax.XMLReader) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog) JAXBException(javax.xml.bind.JAXBException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) CommandLine(org.apache.commons.exec.CommandLine) SAXSource(javax.xml.transform.sax.SAXSource) Map(java.util.Map)

Example 78 with Unmarshaller

use of javax.xml.bind.Unmarshaller in project opennms by OpenNMS.

the class HypericAckProcessor method parseHypericAlerts.

/**
     * <p>parseHypericAlerts</p>
     *
     * @param reader a {@link java.io.Reader} object.
     * @return a {@link java.util.List} object.
     * @throws javax.xml.bind.JAXBException if any.
     * @throws javax.xml.stream.XMLStreamException if any.
     */
public static List<HypericAlertStatus> parseHypericAlerts(Reader reader) throws JAXBException, XMLStreamException {
    List<HypericAlertStatus> retval = new ArrayList<HypericAlertStatus>();
    // Instantiate a JAXB context to parse the alert status
    JAXBContext context = JAXBContext.newInstance(new Class[] { HypericAlertStatuses.class, HypericAlertStatus.class });
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    XMLEventReader xmler = xmlif.createXMLEventReader(reader);
    EventFilter filter = new EventFilter() {

        @Override
        public boolean accept(XMLEvent event) {
            return event.isStartElement();
        }
    };
    XMLEventReader xmlfer = xmlif.createFilteredReader(xmler, filter);
    // Read up until the beginning of the root element
    StartElement startElement = (StartElement) xmlfer.nextEvent();
    // Fetch the root element name for {@link HypericAlertStatus} objects
    String rootElementName = context.createJAXBIntrospector().getElementName(new HypericAlertStatuses()).getLocalPart();
    if (rootElementName.equals(startElement.getName().getLocalPart())) {
        Unmarshaller unmarshaller = context.createUnmarshaller();
        // Use StAX to pull parse the incoming alert statuses
        while (xmlfer.peek() != null) {
            Object object = unmarshaller.unmarshal(xmler);
            if (object instanceof HypericAlertStatus) {
                HypericAlertStatus alertStatus = (HypericAlertStatus) object;
                retval.add(alertStatus);
            }
        }
    } else {
        // Try to pull in the HTTP response to give the user a better idea of what went wrong
        StringBuffer errorContent = new StringBuffer();
        LineNumberReader lineReader = new LineNumberReader(reader);
        try {
            String line;
            while (true) {
                line = lineReader.readLine();
                if (line == null) {
                    break;
                } else {
                    errorContent.append(line.trim());
                }
            }
        } catch (IOException e) {
            errorContent.append("Exception while trying to print out message content: " + e.getMessage());
        }
        // Throw an exception and include the erroneous HTTP response in the exception text
        throw new JAXBException("Found wrong root element in Hyperic XML document, expected: \"" + rootElementName + "\", found \"" + startElement.getName().getLocalPart() + "\"\n" + errorContent.toString());
    }
    return retval;
}
Also used : JAXBException(javax.xml.bind.JAXBException) ArrayList(java.util.ArrayList) JAXBContext(javax.xml.bind.JAXBContext) IOException(java.io.IOException) EventFilter(javax.xml.stream.EventFilter) LineNumberReader(java.io.LineNumberReader) StartElement(javax.xml.stream.events.StartElement) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) Unmarshaller(javax.xml.bind.Unmarshaller) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 79 with Unmarshaller

use of javax.xml.bind.Unmarshaller in project opennms by OpenNMS.

the class DnsRequisitionUrlConnectionIT method dwoUrlAsResourceUsingNonMatchingExpression.

@Test
@JUnitDNSServer(port = 9153, zones = { @DNSZone(name = "example.com", entries = { @DNSEntry(hostname = "www", address = "72.14.204.99"), @DNSEntry(hostname = "monkey", address = "72.14.204.99") }) })
public void dwoUrlAsResourceUsingNonMatchingExpression() throws IOException, JAXBException {
    String urlString = "dns://localhost:9153/example.com/?expression=Local.*";
    Resource resource = new UrlResource(urlString);
    Assert.assertEquals(urlString, resource.getURL().toString());
    Requisition req = null;
    Assert.assertNotNull(resource);
    InputStream resourceStream = resource.getInputStream();
    JAXBContext context = JAXBContext.newInstance(Requisition.class);
    Unmarshaller um = context.createUnmarshaller();
    um.setSchema(null);
    req = (Requisition) um.unmarshal(resourceStream);
    Assert.assertEquals(0, req.getNodeCount());
    resourceStream.close();
}
Also used : UrlResource(org.springframework.core.io.UrlResource) InputStream(java.io.InputStream) UrlResource(org.springframework.core.io.UrlResource) Resource(org.springframework.core.io.Resource) JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller) Requisition(org.opennms.netmgt.provision.persist.requisition.Requisition) JUnitDNSServer(org.opennms.core.test.dns.annotations.JUnitDNSServer) Test(org.junit.Test)

Example 80 with Unmarshaller

use of javax.xml.bind.Unmarshaller in project opennms by OpenNMS.

the class DnsRequisitionUrlConnectionIT method dwoUrlAsResource.

@Test
@JUnitDNSServer(port = 9153, zones = { @DNSZone(name = "example.com", entries = { @DNSEntry(hostname = "www", address = "72.14.204.99") }) })
public void dwoUrlAsResource() throws IOException, JAXBException {
    Resource resource = new UrlResource(TEST_URL);
    Assert.assertEquals(TEST_URL, resource.getURL().toString());
    Requisition req = null;
    Assert.assertNotNull(resource);
    InputStream resourceStream = resource.getInputStream();
    JAXBContext context = JAXBContext.newInstance(Requisition.class);
    Unmarshaller um = context.createUnmarshaller();
    um.setSchema(null);
    req = (Requisition) um.unmarshal(resourceStream);
    Assert.assertEquals("should have 2 A records: 1 for example.com, and 1 for www.example.com", 2, req.getNodeCount());
    resourceStream.close();
}
Also used : UrlResource(org.springframework.core.io.UrlResource) InputStream(java.io.InputStream) UrlResource(org.springframework.core.io.UrlResource) Resource(org.springframework.core.io.Resource) JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller) Requisition(org.opennms.netmgt.provision.persist.requisition.Requisition) JUnitDNSServer(org.opennms.core.test.dns.annotations.JUnitDNSServer) Test(org.junit.Test)

Aggregations

Unmarshaller (javax.xml.bind.Unmarshaller)292 JAXBContext (javax.xml.bind.JAXBContext)240 JAXBException (javax.xml.bind.JAXBException)97 InputStream (java.io.InputStream)91 Test (org.junit.Test)79 StringReader (java.io.StringReader)40 BaseTest (org.orcid.core.BaseTest)39 V2Convertible (org.orcid.core.version.V2Convertible)39 File (java.io.File)33 InputSource (org.xml.sax.InputSource)22 IOException (java.io.IOException)21 JAXBElement (javax.xml.bind.JAXBElement)18 Marshaller (javax.xml.bind.Marshaller)18 ByteArrayInputStream (java.io.ByteArrayInputStream)17 SAXSource (javax.xml.transform.sax.SAXSource)17 SAXParserFactory (javax.xml.parsers.SAXParserFactory)13 XMLInputFactory (javax.xml.stream.XMLInputFactory)13 XMLStreamException (javax.xml.stream.XMLStreamException)13 XMLStreamReader (javax.xml.stream.XMLStreamReader)13 Schema (javax.xml.validation.Schema)13