Search in sources :

Example 11 with XMLStreamException

use of javax.xml.stream.XMLStreamException in project GCViewer by chewiebug.

the class DataReaderIBM_J9_R28 method read.

@Override
public GCModel read() throws IOException {
    GCModel model = new GCModel();
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLEventReader eventReader = factory.createXMLEventReader(in);
        GCEvent currentGcEvent = null;
        String eventNameStart = null;
        while (eventReader.hasNext()) {
            try {
                XMLEvent event = eventReader.nextEvent();
                if (event.isStartElement()) {
                    StartElement startElement = event.asStartElement();
                    switch(startElement.getName().getLocalPart()) {
                        case VERBOSEGC:
                            handleVerboseGC(startElement);
                            break;
                        case INITIALIZED:
                            handleInitialized(eventReader);
                            break;
                        case EXCLUSIVE_START:
                            currentGcEvent = handleExclusiveStart(startElement);
                            break;
                        case SYS_START:
                            assert eventNameStart == null : "eventNameStart was expected to be null, but was " + eventNameStart;
                            eventNameStart = handleSysStart(eventReader, startElement);
                            break;
                        case AF_START:
                            assert eventNameStart == null : "eventNameStart was expected to be null, but was " + eventNameStart;
                            eventNameStart = handleAfStart(eventReader, startElement);
                            break;
                        case GC_START:
                            handleGcStart(eventReader, startElement, currentGcEvent, eventNameStart);
                            break;
                        case GC_END:
                            if (currentGcEvent.getTypeAsString() != null) {
                                handleGcEnd(eventReader, currentGcEvent);
                            }
                            break;
                        case EXCLUSIVE_END:
                            handleExclusiveEnd(startElement, currentGcEvent);
                            if (currentGcEvent.getExtendedType() == null) {
                                if (getLogger().isLoggable(Level.FINE))
                                    getLogger().fine("event at " + in.getLineNumber() + " doesn't contain any information, the parser can handle");
                            } else {
                                model.add(currentGcEvent);
                            }
                            currentGcEvent = null;
                            eventNameStart = null;
                            break;
                    }
                }
            } catch (Exception e) {
                if (e instanceof XMLStreamException) {
                    throw e;
                }
                if (getLogger().isLoggable(Level.WARNING))
                    getLogger().warning("line " + in.getLineNumber() + ": " + e.toString());
                if (getLogger().isLoggable(Level.FINE))
                    getLogger().log(Level.FINE, "line " + in.getLineNumber() + ": " + e.getMessage(), e);
            }
        }
    } catch (XMLStreamException e) {
        if (getLogger().isLoggable(Level.WARNING))
            getLogger().warning("line " + in.getLineNumber() + ": " + e.toString());
        if (getLogger().isLoggable(Level.FINE))
            getLogger().log(Level.FINE, "line " + in.getLineNumber() + ": " + e.getMessage(), e);
    } finally {
        if (getLogger().isLoggable(Level.INFO))
            getLogger().info("Done reading.");
    }
    return model;
}
Also used : StartElement(javax.xml.stream.events.StartElement) XMLStreamException(javax.xml.stream.XMLStreamException) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) AbstractGCEvent(com.tagtraum.perf.gcviewer.model.AbstractGCEvent) GCEvent(com.tagtraum.perf.gcviewer.model.GCEvent) GCModel(com.tagtraum.perf.gcviewer.model.GCModel) XMLInputFactory(javax.xml.stream.XMLInputFactory) IOException(java.io.IOException) DateTimeParseException(java.time.format.DateTimeParseException) XMLStreamException(javax.xml.stream.XMLStreamException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 12 with XMLStreamException

use of javax.xml.stream.XMLStreamException in project elasticsearch by elastic.

the class Ec2DiscoveryClusterFormationTests method startHttpd.

/**
     * Creates mock EC2 endpoint providing the list of started nodes to the DescribeInstances API call
     */
@BeforeClass
public static void startHttpd() throws Exception {
    logDir = createTempDir();
    httpServer = MockHttpServer.createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0);
    httpServer.createContext("/", (s) -> {
        Headers headers = s.getResponseHeaders();
        headers.add("Content-Type", "text/xml; charset=UTF-8");
        String action = null;
        for (NameValuePair parse : URLEncodedUtils.parse(IOUtils.toString(s.getRequestBody()), StandardCharsets.UTF_8)) {
            if ("Action".equals(parse.getName())) {
                action = parse.getValue();
                break;
            }
        }
        assertThat(action, equalTo("DescribeInstances"));
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
        xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
        StringWriter out = new StringWriter();
        XMLStreamWriter sw;
        try {
            sw = xmlOutputFactory.createXMLStreamWriter(out);
            sw.writeStartDocument();
            String namespace = "http://ec2.amazonaws.com/doc/2013-02-01/";
            sw.setDefaultNamespace(namespace);
            sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "DescribeInstancesResponse", namespace);
            {
                sw.writeStartElement("requestId");
                sw.writeCharacters(UUID.randomUUID().toString());
                sw.writeEndElement();
                sw.writeStartElement("reservationSet");
                {
                    Path[] files = FileSystemUtils.files(logDir);
                    for (int i = 0; i < files.length; i++) {
                        Path resolve = files[i].resolve("transport.ports");
                        if (Files.exists(resolve)) {
                            List<String> addresses = Files.readAllLines(resolve);
                            Collections.shuffle(addresses, random());
                            sw.writeStartElement("item");
                            {
                                sw.writeStartElement("reservationId");
                                sw.writeCharacters(UUID.randomUUID().toString());
                                sw.writeEndElement();
                                sw.writeStartElement("instancesSet");
                                {
                                    sw.writeStartElement("item");
                                    {
                                        sw.writeStartElement("instanceId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();
                                        sw.writeStartElement("imageId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();
                                        sw.writeStartElement("instanceState");
                                        {
                                            sw.writeStartElement("code");
                                            sw.writeCharacters("16");
                                            sw.writeEndElement();
                                            sw.writeStartElement("name");
                                            sw.writeCharacters("running");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();
                                        sw.writeStartElement("privateDnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();
                                        sw.writeStartElement("dnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();
                                        sw.writeStartElement("instanceType");
                                        sw.writeCharacters("m1.medium");
                                        sw.writeEndElement();
                                        sw.writeStartElement("placement");
                                        {
                                            sw.writeStartElement("availabilityZone");
                                            sw.writeCharacters("use-east-1e");
                                            sw.writeEndElement();
                                            sw.writeEmptyElement("groupName");
                                            sw.writeStartElement("tenancy");
                                            sw.writeCharacters("default");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();
                                        sw.writeStartElement("privateIpAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();
                                        sw.writeStartElement("ipAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();
                                }
                                sw.writeEndElement();
                            }
                            sw.writeEndElement();
                        }
                    }
                }
                sw.writeEndElement();
            }
            sw.writeEndElement();
            sw.writeEndDocument();
            sw.flush();
            final byte[] responseAsBytes = out.toString().getBytes(StandardCharsets.UTF_8);
            s.sendResponseHeaders(200, responseAsBytes.length);
            OutputStream responseBody = s.getResponseBody();
            responseBody.write(responseAsBytes);
            responseBody.close();
        } catch (XMLStreamException e) {
            Loggers.getLogger(Ec2DiscoveryClusterFormationTests.class).error("Failed serializing XML", e);
            throw new RuntimeException(e);
        }
    });
    httpServer.start();
}
Also used : Path(java.nio.file.Path) NameValuePair(org.apache.http.NameValuePair) XMLOutputFactory(javax.xml.stream.XMLOutputFactory) InetSocketAddress(java.net.InetSocketAddress) Headers(com.sun.net.httpserver.Headers) OutputStream(java.io.OutputStream) StringWriter(java.io.StringWriter) XMLStreamException(javax.xml.stream.XMLStreamException) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) BeforeClass(org.junit.BeforeClass)

Example 13 with XMLStreamException

use of javax.xml.stream.XMLStreamException in project OpenRefine by OpenRefine.

the class XmlImporter method descendElement.

private static final JSONObject descendElement(XMLStreamReader parser, PreviewParsingState state) {
    JSONObject result = new JSONObject();
    {
        String name = parser.getLocalName();
        JSONUtilities.safePut(result, "n", name);
        String prefix = parser.getPrefix();
        if (prefix != null) {
            JSONUtilities.safePut(result, "p", prefix);
        }
        String nsUri = parser.getNamespaceURI();
        if (nsUri != null) {
            JSONUtilities.safePut(result, "uri", nsUri);
        }
    }
    int namespaceCount = parser.getNamespaceCount();
    if (namespaceCount > 0) {
        JSONArray namespaces = new JSONArray();
        JSONUtilities.safePut(result, "ns", namespaces);
        for (int i = 0; i < namespaceCount; i++) {
            JSONObject namespace = new JSONObject();
            JSONUtilities.append(namespaces, namespace);
            JSONUtilities.safePut(namespace, "p", parser.getNamespacePrefix(i));
            JSONUtilities.safePut(namespace, "uri", parser.getNamespaceURI(i));
        }
    }
    int attributeCount = parser.getAttributeCount();
    if (attributeCount > 0) {
        JSONArray attributes = new JSONArray();
        JSONUtilities.safePut(result, "a", attributes);
        for (int i = 0; i < attributeCount; i++) {
            JSONObject attribute = new JSONObject();
            JSONUtilities.append(attributes, attribute);
            JSONUtilities.safePut(attribute, "n", parser.getAttributeLocalName(i));
            JSONUtilities.safePut(attribute, "v", parser.getAttributeValue(i));
            String prefix = parser.getAttributePrefix(i);
            if (prefix != null) {
                JSONUtilities.safePut(attribute, "p", prefix);
            }
        }
    }
    JSONArray children = new JSONArray();
    try {
        while (parser.hasNext() && state.tokenCount < PREVIEW_PARSING_LIMIT) {
            int tokenType = parser.next();
            state.tokenCount++;
            if (tokenType == XMLStreamConstants.END_ELEMENT) {
                break;
            } else if (tokenType == XMLStreamConstants.START_ELEMENT) {
                JSONObject childElement = descendElement(parser, state);
                if (childElement != null) {
                    JSONUtilities.append(children, childElement);
                }
            } else if (tokenType == XMLStreamConstants.CHARACTERS || tokenType == XMLStreamConstants.CDATA || tokenType == XMLStreamConstants.SPACE) {
                JSONObject childElement = new JSONObject();
                JSONUtilities.safePut(childElement, "t", parser.getText());
                JSONUtilities.append(children, childElement);
            } else {
            // ignore everything else
            }
        }
    } catch (XMLStreamException e) {
        logger.error("Error generating parser UI initialization data for XML file", e);
    }
    if (children.length() > 0) {
        JSONUtilities.safePut(result, "c", children);
    }
    return result;
}
Also used : JSONObject(org.json.JSONObject) XMLStreamException(javax.xml.stream.XMLStreamException) JSONArray(org.json.JSONArray)

Example 14 with XMLStreamException

use of javax.xml.stream.XMLStreamException in project OpenRefine by OpenRefine.

the class XmlImporter method wrapPrefixRemovingInputStream.

private static final InputStream wrapPrefixRemovingInputStream(InputStream inputStream) throws XMLStreamException, IOException {
    PushbackInputStream pis = new PushbackInputStream(inputStream);
    int b;
    int count = 0;
    while (count < 100 && (b = pis.read()) >= 0) {
        if (++count > 100) {
            throw new XMLStreamException("File starts with too much non-XML content to skip over");
        } else if (b == '<') {
            pis.unread(b);
            break;
        }
    }
    return pis;
}
Also used : XMLStreamException(javax.xml.stream.XMLStreamException) PushbackInputStream(java.io.PushbackInputStream)

Example 15 with XMLStreamException

use of javax.xml.stream.XMLStreamException in project OpenRefine by OpenRefine.

the class XmlImporter method createParserUIInitializationData.

@Override
public JSONObject createParserUIInitializationData(ImportingJob job, List<JSONObject> fileRecords, String format) {
    JSONObject options = super.createParserUIInitializationData(job, fileRecords, format);
    try {
        if (fileRecords.size() > 0) {
            JSONObject firstFileRecord = fileRecords.get(0);
            File file = ImportingUtilities.getFile(job, firstFileRecord);
            InputStream is = new FileInputStream(file);
            try {
                XMLStreamReader parser = createXMLStreamReader(is);
                PreviewParsingState state = new PreviewParsingState();
                while (parser.hasNext() && state.tokenCount < PREVIEW_PARSING_LIMIT) {
                    int tokenType = parser.next();
                    state.tokenCount++;
                    if (tokenType == XMLStreamConstants.START_ELEMENT) {
                        JSONObject rootElement = descendElement(parser, state);
                        if (rootElement != null) {
                            JSONUtilities.safePut(options, "dom", rootElement);
                            break;
                        }
                    } else {
                    // ignore everything else
                    }
                }
            } catch (XMLStreamException e) {
                logger.warn("Error generating parser UI initialization data for XML file", e);
            } finally {
                is.close();
            }
        }
    } catch (IOException e) {
        logger.error("Error generating parser UI initialization data for XML file", e);
    }
    return options;
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) JSONObject(org.json.JSONObject) XMLStreamException(javax.xml.stream.XMLStreamException) PushbackInputStream(java.io.PushbackInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Aggregations

XMLStreamException (javax.xml.stream.XMLStreamException)274 IOException (java.io.IOException)75 XMLStreamReader (javax.xml.stream.XMLStreamReader)74 XMLInputFactory (javax.xml.stream.XMLInputFactory)60 InputStream (java.io.InputStream)43 XMLStreamWriter (javax.xml.stream.XMLStreamWriter)34 XMLEvent (javax.xml.stream.events.XMLEvent)24 StringReader (java.io.StringReader)22 JAXBException (javax.xml.bind.JAXBException)22 XMLEventReader (javax.xml.stream.XMLEventReader)19 ModelNode (org.jboss.dmr.ModelNode)18 ArrayList (java.util.ArrayList)16 XMLExtendedStreamReader (org.jboss.staxmapper.XMLExtendedStreamReader)15 ModelElement (org.wildfly.extension.picketlink.common.model.ModelElement)15 SAXException (org.xml.sax.SAXException)15 ByteArrayInputStream (java.io.ByteArrayInputStream)14 XMLOutputFactory (javax.xml.stream.XMLOutputFactory)14 StringWriter (java.io.StringWriter)12 Unmarshaller (javax.xml.bind.Unmarshaller)11 Characters (javax.xml.stream.events.Characters)11