List of usage examples for javax.xml.stream XMLStreamReader next
public int next() throws XMLStreamException;
From source file:net.sf.jabref.importer.fileformat.MedlineImporter.java
@Override public ParserResult importDatabase(BufferedReader reader) throws IOException { Objects.requireNonNull(reader); List<BibEntry> bibItems = new ArrayList<>(); try {/*from www .j a v a 2s . c o m*/ JAXBContext context = JAXBContext.newInstance("net.sf.jabref.importer.fileformat.medline"); XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory(); XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader); //go to the root element while (!xmlStreamReader.isStartElement()) { xmlStreamReader.next(); } Unmarshaller unmarshaller = context.createUnmarshaller(); Object unmarshalledObject = unmarshaller.unmarshal(xmlStreamReader); //check whether we have an article set, an article, a book article or a book article set if (unmarshalledObject instanceof PubmedArticleSet) { PubmedArticleSet articleSet = (PubmedArticleSet) unmarshalledObject; for (Object article : articleSet.getPubmedArticleOrPubmedBookArticle()) { if (article instanceof PubmedArticle) { PubmedArticle currentArticle = (PubmedArticle) article; parseArticle(currentArticle, bibItems); } if (article instanceof PubmedBookArticle) { PubmedBookArticle currentArticle = (PubmedBookArticle) article; parseBookArticle(currentArticle, bibItems); } } } else if (unmarshalledObject instanceof PubmedArticle) { PubmedArticle article = (PubmedArticle) unmarshalledObject; parseArticle(article, bibItems); } else if (unmarshalledObject instanceof PubmedBookArticle) { PubmedBookArticle currentArticle = (PubmedBookArticle) unmarshalledObject; parseBookArticle(currentArticle, bibItems); } else { PubmedBookArticleSet bookArticleSet = (PubmedBookArticleSet) unmarshalledObject; for (PubmedBookArticle bookArticle : bookArticleSet.getPubmedBookArticle()) { parseBookArticle(bookArticle, bibItems); } } } catch (JAXBException | XMLStreamException e) { LOGGER.debug("could not parse document", e); return ParserResult.fromErrorMessage(e.getLocalizedMessage()); } return new ParserResult(bibItems); }
From source file:edu.indiana.d2i.htrc.portal.HTRCPersistenceAPIClient.java
private AlgorithmDetailsBean parseAlgorithmDetailBean(InputStream stream) throws XMLStreamException { AlgorithmDetailsBean res = new AlgorithmDetailsBean(); XMLStreamReader parser = factory.createXMLStreamReader(stream); List<AlgorithmDetailsBean.Parameter> parameters = new ArrayList<AlgorithmDetailsBean.Parameter>(); List<String> authors = new ArrayList<String>(); while (parser.hasNext()) { int event = parser.next(); if (event == XMLStreamConstants.START_ELEMENT) { if (parser.hasName()) { // only parse the info tag! if (parser.getLocalName().equals(AlgorithmDetailsBean.NAME)) { res.setName(parser.getElementText()); } else if (parser.getLocalName().equals(AlgorithmDetailsBean.VERSION)) { res.setVersion(parser.getElementText()); } else if (parser.getLocalName().equals(AlgorithmDetailsBean.DESCRIPTION)) { res.setDescription(parser.getElementText()); } else if (parser.getLocalName().equals(AlgorithmDetailsBean.SUPPORTURL)) { res.setSupportUrl(parser.getElementText()); } else if (parser.getLocalName().equals(AlgorithmDetailsBean.PARAMETER)) { AlgorithmDetailsBean.Parameter parameter = new AlgorithmDetailsBean.Parameter(); int count = parser.getAttributeCount(); for (int i = 0; i < count; i++) { if (parser.getAttributeLocalName(i).equals("required")) parameter.setRequired(Boolean.valueOf(parser.getAttributeValue(i))); if (parser.getAttributeLocalName(i).equals("type")) parameter.setType(parser.getAttributeValue(i)); if (parser.getAttributeLocalName(i).equals("name")) parameter.setName(parser.getAttributeValue(i)); if (parser.getAttributeLocalName(i).equals("defaultValue")) parameter.setDefaultValue(parser.getAttributeValue(i)); if (parser.getAttributeLocalName(i).equals("validation")) parameter.setValidation(parser.getAttributeValue(i)); if (parser.getAttributeLocalName(i).equals("validationError")) parameter.setValidationError(parser.getAttributeValue(i)); if (parser.getAttributeLocalName(i).equals("readOnly")) parameter.setReadOnly(Boolean.parseBoolean(parser.getAttributeValue(i))); }//ww w. j ava 2 s . c om parser.nextTag(); if (parser.getLocalName().equals("label")) parameter.setLabel(parser.getElementText()); parser.nextTag(); if (parser.getLocalName().equals("description")) parameter.setDescription(parser.getElementText()); parameters.add(parameter); } else if (parser.getLocalName().equals(AlgorithmDetailsBean.AUTHOR)) { int count = parser.getAttributeCount(); for (int i = 0; i < count; i++) { if (parser.getAttributeLocalName(i).equals("name")) authors.add(parser.getAttributeValue(i)); } } } } } res.setParameters(parameters); res.setAuthors(authors); return res; }
From source file:net.sf.jabref.logic.importer.fileformat.MedlineImporter.java
@Override public ParserResult importDatabase(BufferedReader reader) throws IOException { Objects.requireNonNull(reader); List<BibEntry> bibItems = new ArrayList<>(); try {/*from ww w . ja v a 2 s. co m*/ JAXBContext context = JAXBContext.newInstance("net.sf.jabref.logic.importer.fileformat.medline"); XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory(); XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader); //go to the root element while (!xmlStreamReader.isStartElement()) { xmlStreamReader.next(); } Unmarshaller unmarshaller = context.createUnmarshaller(); Object unmarshalledObject = unmarshaller.unmarshal(xmlStreamReader); //check whether we have an article set, an article, a book article or a book article set if (unmarshalledObject instanceof PubmedArticleSet) { PubmedArticleSet articleSet = (PubmedArticleSet) unmarshalledObject; for (Object article : articleSet.getPubmedArticleOrPubmedBookArticle()) { if (article instanceof PubmedArticle) { PubmedArticle currentArticle = (PubmedArticle) article; parseArticle(currentArticle, bibItems); } if (article instanceof PubmedBookArticle) { PubmedBookArticle currentArticle = (PubmedBookArticle) article; parseBookArticle(currentArticle, bibItems); } } } else if (unmarshalledObject instanceof PubmedArticle) { PubmedArticle article = (PubmedArticle) unmarshalledObject; parseArticle(article, bibItems); } else if (unmarshalledObject instanceof PubmedBookArticle) { PubmedBookArticle currentArticle = (PubmedBookArticle) unmarshalledObject; parseBookArticle(currentArticle, bibItems); } else { PubmedBookArticleSet bookArticleSet = (PubmedBookArticleSet) unmarshalledObject; for (PubmedBookArticle bookArticle : bookArticleSet.getPubmedBookArticle()) { parseBookArticle(bookArticle, bibItems); } } } catch (JAXBException | XMLStreamException e) { LOGGER.debug("could not parse document", e); return ParserResult.fromErrorMessage(e.getLocalizedMessage()); } return new ParserResult(bibItems); }
From source file:de.uzk.hki.da.cb.CreatePremisAction.java
/** * Accepts a premis.xml file and creates a new xml file for each jhove section * /*from w ww . ja v a2 s .c o m*/ * @author Thomas Kleinke * Extract jhove data. * * @param premisFilePath the premis file path * @param outputFolder the output folder * @throws XMLStreamException the xML stream exception */ public void extractJhoveData(String premisFilePath, String outputFolder) throws XMLStreamException { outputFolder += "/premis_output/"; FileInputStream inputStream = null; try { inputStream = new FileInputStream(premisFilePath); } catch (FileNotFoundException e) { throw new RuntimeException("Couldn't find file " + premisFilePath, e); } XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader streamReader = inputFactory.createXMLStreamReader(inputStream); boolean textElement = false; boolean jhoveSection = false; boolean objectIdentifierValue = false; int tab = 0; String fileId = ""; while (streamReader.hasNext()) { int event = streamReader.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: if (streamReader.getLocalName().equals("jhove")) { jhoveSection = true; String outputFilePath = outputFolder + fileId.replace('/', '_').replace('.', '_') + ".xml"; if (!new File(outputFolder).exists()) new File(outputFolder).mkdirs(); writer = startNewDocument(outputFilePath); } if (streamReader.getLocalName().equals("objectIdentifierValue")) objectIdentifierValue = true; if (jhoveSection) { writer.writeDTD("\n"); indent(tab); tab++; String prefix = streamReader.getPrefix(); if (prefix != null && !prefix.equals("")) { writer.setPrefix(prefix, streamReader.getNamespaceURI()); writer.writeStartElement(streamReader.getNamespaceURI(), streamReader.getLocalName()); } else writer.writeStartElement(streamReader.getLocalName()); for (int i = 0; i < streamReader.getNamespaceCount(); i++) writer.writeNamespace(streamReader.getNamespacePrefix(i), streamReader.getNamespaceURI(i)); for (int i = 0; i < streamReader.getAttributeCount(); i++) { QName qname = streamReader.getAttributeName(i); String attributeName = qname.getLocalPart(); String attributePrefix = qname.getPrefix(); if (attributePrefix != null && !attributePrefix.equals("")) attributeName = attributePrefix + ":" + attributeName; writer.writeAttribute(attributeName, streamReader.getAttributeValue(i)); } } break; case XMLStreamConstants.CHARACTERS: if (objectIdentifierValue) { fileId = streamReader.getText(); objectIdentifierValue = false; } if (jhoveSection && !streamReader.isWhiteSpace()) { writer.writeCharacters(streamReader.getText()); textElement = true; } break; case XMLStreamConstants.END_ELEMENT: if (jhoveSection) { tab--; if (!textElement) { writer.writeDTD("\n"); indent(tab); } writer.writeEndElement(); textElement = false; if (streamReader.getLocalName().equals("jhove")) { jhoveSection = false; finalizeDocument(); } } break; case XMLStreamConstants.END_DOCUMENT: streamReader.close(); try { inputStream.close(); } catch (IOException e) { throw new RuntimeException("Failed to close input stream", e); } break; default: break; } } }
From source file:net.bulletin.pdi.xero.step.support.XMLChunkerImpl.java
private String pullNextXmlChunkFromTopElementOnStack(XMLChunkerState data) throws KettleException { Stack<String> elementStack = data.getElementStack(); XMLStreamReader xmlStreamReader = data.getXmlStreamReader(); int elementStackDepthOnEntry = elementStack.size(); StringWriter stringWriter = new StringWriter(); try {/* w w w .ja va 2 s.c om*/ XMLStreamWriter xmlStreamWriter = data.getXmlOutputFactory().createXMLStreamWriter(stringWriter); xmlStreamWriter.writeStartDocument(CharEncoding.UTF_8, "1.0"); // put the current element on because presumably it's the open element for the one // that is being looked for. XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter); while (xmlStreamReader.hasNext() & elementStack.size() >= elementStackDepthOnEntry) { switch (xmlStreamReader.next()) { case XMLStreamConstants.END_DOCUMENT: break; // handled below explicitly. case XMLStreamConstants.END_ELEMENT: elementStack.pop(); XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter); break; case XMLStreamConstants.START_ELEMENT: elementStack.push(xmlStreamReader.getLocalName()); XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter); break; default: XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter); break; } } xmlStreamWriter.writeEndDocument(); xmlStreamWriter.close(); } catch (Exception e) { throw new KettleException("unable to process a chunk of the xero xml stream", e); } return stringWriter.toString(); }
From source file:com.pocketsoap.salesforce.soap.ChatterClient.java
private <T> T makeSoapRequest(String serverUrl, RequestEntity req, ResponseParser<T> respParser) throws XMLStreamException, IOException { PostMethod post = new PostMethod(serverUrl); post.addRequestHeader("SOAPAction", "\"\""); post.setRequestEntity(req);/*from ww w .jav a 2s . c o m*/ HttpClient http = new HttpClient(); int sc = http.executeMethod(post); if (sc != 200 && sc != 500) throw new IOException("request to " + serverUrl + " returned unexpected HTTP status code of " + sc + ", check configuration."); XMLInputFactory f = XMLInputFactory.newInstance(); f.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); XMLStreamReader rdr = f.createXMLStreamReader(post.getResponseBodyAsStream()); rdr.require(XMLStreamReader.START_DOCUMENT, null, null); rdr.nextTag(); rdr.require(XMLStreamReader.START_ELEMENT, SOAP_NS, "Envelope"); rdr.nextTag(); // TODO, should handle a Header appearing in the response. rdr.require(XMLStreamReader.START_ELEMENT, SOAP_NS, "Body"); rdr.nextTag(); if (rdr.getLocalName().equals("Fault")) { throw handleSoapFault(rdr); } try { T response = respParser.parse(rdr); while (rdr.hasNext()) rdr.next(); return response; } finally { try { rdr.close(); } finally { post.releaseConnection(); } } }
From source file:hudson.plugins.report.jck.parsers.JtregReportParser.java
/** * Test status of testcase is determined from its child tags( <skipped>, <failure>, <error> ). * If it doesn't contain any of these tags, test is considered passed. If it contains both failure and error tags, * test status is set to error.//from ww w. j a va 2s. c om */ private JtregBackwardCompatibileTest parseTestcase(XMLStreamReader in) throws Exception { final String testName = findAttributeValue(in, "name"); final String className = findAttributeValue(in, "classname"); TestStatus status = TestStatus.PASSED; String failureOutput = ""; String stdOutput = ""; String sysErrOutput = ""; String message = ""; StringBuilder errOutput = new StringBuilder(); while (in.hasNext()) { int event = in.next(); if (event == START_ELEMENT && FAILURE.equals(in.getLocalName())) { final String lEmessage = findAttributeValue(in, "message"); if (lEmessage != null) { message = lEmessage; } failureOutput = captureCharacters(in, FAILURE); if (status != TestStatus.ERROR) { status = TestStatus.FAILED; } continue; } if (event == START_ELEMENT && SYSTEMOUT.equals(in.getLocalName())) { stdOutput = captureCharacters(in, SYSTEMOUT); continue; } if (event == START_ELEMENT && SYSTEMERR.equals(in.getLocalName())) { sysErrOutput = captureCharacters(in, SYSTEMERR); continue; } if (event == START_ELEMENT && SKIPPED.equals(in.getLocalName())) { status = TestStatus.NOT_RUN; continue; } if (event == START_ELEMENT && ERROR.equals(in.getLocalName())) { status = TestStatus.ERROR; errOutput.append(captureCharacters(in, ERROR)).append('\n'); continue; } if (event == END_ELEMENT && TESTCASE.equals(in.getLocalName())) { break; } } //order imortant! see revalidateTests List<TestOutput> outputs = Arrays.asList(new TestOutput(SYSTEMOUT, stdOutput), new TestOutput(SYSTEMERR, sysErrOutput)); return new JtregBackwardCompatibileTest(className, status, message, outputs, testName, failureOutput, errOutput.toString()); }
From source file:com.microsoft.alm.plugin.context.soap.CatalogServiceImpl.java
/** * Advances the {@link XMLStreamReader} until it has read the end of the * current element. Useful when an element is encountered while reading a * stream, and it should be skipped.//from w w w . j a va 2 s .c o m * * @param reader the stream reader to read from (not null). */ private static void readUntilElementEnd(final XMLStreamReader reader) throws XMLStreamException { int event = reader.getEventType(); /* * Start element depth at 1, increment when an element is started (not * including the element that we start with), decrement when an element * is ended, and when it goes to 0 we've read the end of the original * reader's element. */ int elementDepth = 1; boolean firstTime = true; while (true) { switch (event) { case XMLStreamConstants.START_ELEMENT: /* * Don't increment depth the first time through, because the * caller opened the element. */ if (firstTime) { firstTime = false; } else { elementDepth++; } break; case XMLStreamConstants.END_ELEMENT: elementDepth--; if (elementDepth < 1) { /* * We just read the end element for the original * element. */ return; } break; default: /* * Things like characters, comments, attributes, etc. Ignore * them all. */ } event = reader.next(); } }
From source file:com.liferay.portal.util.LocalizationImpl.java
private void _copyNonExempt(XMLStreamReader xmlStreamReader, XMLStreamWriter xmlStreamWriter, String exemptLanguageId, String defaultLanguageId, boolean cdata) throws XMLStreamException { while (xmlStreamReader.hasNext()) { int event = xmlStreamReader.next(); if (event == XMLStreamConstants.START_ELEMENT) { String languageId = xmlStreamReader.getAttributeValue(null, _LANGUAGE_ID); if (Validator.isNull(languageId)) { languageId = defaultLanguageId; }//from w ww . j a v a 2s . c om if (!languageId.equals(exemptLanguageId)) { xmlStreamWriter.writeStartElement(xmlStreamReader.getLocalName()); xmlStreamWriter.writeAttribute(_LANGUAGE_ID, languageId); while (xmlStreamReader.hasNext()) { event = xmlStreamReader.next(); if ((event == XMLStreamConstants.CHARACTERS) || (event == XMLStreamConstants.CDATA)) { String text = xmlStreamReader.getText(); if (cdata) { xmlStreamWriter.writeCData(text); } else { xmlStreamWriter.writeCharacters(xmlStreamReader.getText()); } break; } else if (event == XMLStreamConstants.END_ELEMENT) { break; } } xmlStreamWriter.writeEndElement(); } } else if (event == XMLStreamConstants.END_DOCUMENT) { break; } } }
From source file:com.microsoft.windowsazure.storage.table.TableParser.java
/** * Reserved for internal use. Parses the operation response as an entity. Parses the result returned in the * specified stream in AtomPub format into a {@link TableResult} containing an entity of the specified class type * projected using the specified resolver. * /* w ww .j a va 2 s . co m*/ * @param xmlr * An <code>XMLStreamReader</code> on the input stream. * @param clazzType * The class type <code>T</code> implementing {@link TableEntity} for the entity returned. Set to * <code>null</code> to ignore the returned entity and copy only response properties into the * {@link TableResult} object. * @param resolver * An {@link EntityResolver} instance to project the entity into an instance of type <code>R</code>. Set * to <code>null</code> to return the entity as an instance of the class type <code>T</code>. * @param opContext * An {@link OperationContext} object used to track the execution of the operation. * @return * A {@link TableResult} containing the parsed entity result of the operation. * * @throws XMLStreamException * if an error occurs while accessing the stream. * @throws ParseException * if an error occurs while parsing the stream. * @throws InstantiationException * if an error occurs while constructing the result. * @throws IllegalAccessException * if an error occurs in reflection while parsing the result. * @throws StorageException * if a storage service error occurs. */ private static <T extends TableEntity, R> TableResult parseAtomEntity(final XMLStreamReader xmlr, final Class<T> clazzType, final EntityResolver<R> resolver, final OperationContext opContext) throws XMLStreamException, ParseException, InstantiationException, IllegalAccessException, StorageException { int eventType = xmlr.getEventType(); final TableResult res = new TableResult(); xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.ENTRY); String etag = StringEscapeUtils.unescapeHtml4( xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.ETAG)); res.setEtag(etag); while (xmlr.hasNext()) { eventType = xmlr.next(); if (eventType == XMLStreamConstants.CHARACTERS) { xmlr.getText(); continue; } final String name = xmlr.getName().toString(); if (eventType == XMLStreamConstants.START_ELEMENT) { if (name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.ID)) { Utility.readElementFromXMLReader(xmlr, ODataConstants.ID); } else if (name .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) { // Do read properties if (resolver == null && clazzType == null) { return res; } else { res.setProperties(readAtomProperties(xmlr, opContext)); break; } } } } // Move to end Content eventType = xmlr.next(); if (eventType == XMLStreamConstants.CHARACTERS) { eventType = xmlr.next(); } xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.CONTENT); eventType = xmlr.next(); if (eventType == XMLStreamConstants.CHARACTERS) { eventType = xmlr.next(); } xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.ENTRY); String rowKey = null; String partitionKey = null; Date timestamp = null; // Remove core properties from map and set individually EntityProperty tempProp = res.getProperties().remove(TableConstants.PARTITION_KEY); if (tempProp != null) { partitionKey = tempProp.getValueAsString(); } tempProp = res.getProperties().remove(TableConstants.ROW_KEY); if (tempProp != null) { rowKey = tempProp.getValueAsString(); } tempProp = res.getProperties().remove(TableConstants.TIMESTAMP); if (tempProp != null) { timestamp = tempProp.getValueAsDate(); } if (resolver != null) { // Call resolver res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, res.getProperties(), res.getEtag())); } else if (clazzType != null) { // Generate new entity and return final T entity = clazzType.newInstance(); entity.setEtag(res.getEtag()); entity.setPartitionKey(partitionKey); entity.setRowKey(rowKey); entity.setTimestamp(timestamp); entity.readEntity(res.getProperties(), opContext); res.setResult(entity); } return res; }