List of usage examples for javax.xml.stream XMLInputFactory createXMLEventReader
public abstract XMLEventReader createXMLEventReader(java.io.InputStream stream) throws XMLStreamException;
From source file:log4JToXml.xmlToProperties.XmlToLog4jConverterImpl.java
private void addDTDDeclaration(String filename) throws XMLStreamException { XMLEventFactory eventFactory = XMLEventFactory.newInstance(); XMLEvent dtd = eventFactory/*from w w w.ja v a 2s .c om*/ .createDTD("<!DOCTYPE log4j:configuration SYSTEM \"" + tempDTD.getAbsolutePath() + "\">"); XMLInputFactory inFactory = XMLInputFactory.newInstance(); XMLOutputFactory outFactory = XMLOutputFactory.newInstance(); XMLEventReader reader = inFactory.createXMLEventReader(new StreamSource(filename)); reader = new DTDReplacer(reader, dtd); XMLEventWriter writer = outFactory.createXMLEventWriter(documentStream); writer.add(reader); writer.flush(); writer.close(); }
From source file:ca.uhn.fhir.util.XmlUtil.java
public static XMLEventReader createXmlReader(Reader reader) throws FactoryConfigurationError, XMLStreamException { throwUnitTestExceptionIfConfiguredToDoSo(); XMLInputFactory inputFactory = getOrCreateInputFactory(); // Now.. create the reader and return it XMLEventReader er = inputFactory.createXMLEventReader(reader); return er;//from w ww. ja v a 2s .co m }
From source file:org.castor.jaxb.CastorUnmarshallerTest.java
/** * Tests the {@link CastorUnmarshaller#unmarshal(XMLEventReader, Class)} method when declared type is null. <p/> * {@link IllegalArgumentException} is expected. * * @throws Exception if any error occurs during test *///from w w w . ja va 2 s.co m @Test(expected = IllegalArgumentException.class) public void testUnmarshalXMLEventReaderJAXBElementNull2() throws Exception { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(new StringReader(INPUT_XML)); unmarshaller.unmarshal(xmlEventReader, null); }
From source file:org.castor.jaxb.CastorUnmarshallerTest.java
/** * Tests the {@link CastorUnmarshaller#unmarshal(XMLEventReader)} method. * * @throws Exception if any error occurs during test *///from w w w . j a v a 2s .co m @Test public void testUnmarshalXMLEventReader() throws Exception { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(new StringReader(INPUT_XML)); Entity entity = (Entity) unmarshaller.unmarshal(xmlEventReader); testEntity(entity); }
From source file:org.castor.jaxb.CastorUnmarshallerTest.java
/** * Tests the {@link CastorUnmarshaller#unmarshal(XMLEventReader, Class)} method. * * @throws Exception if any error occurs during test *///from w w w . j a v a 2 s . co m @Test public void testUnmarshalXMLEventReaderJAXBElement() throws Exception { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(new StringReader(INPUT_XML)); JAXBElement<Entity> entity = unmarshaller.unmarshal(xmlEventReader, Entity.class); testJAXBElement(entity); }
From source file:json_to_xml_1.java
public int execute(String args[]) throws ProgramTerminationException { this.getInfoMessages().clear(); if (args.length < 2) { throw constructTermination("messageArgumentsMissing", null, getI10nString("messageArgumentsMissingUsage") + "\n\tjson_to_xml_1 " + getI10nString("messageParameterList") + "\n"); }/*from ww w.j ava2 s.co m*/ File resultInfoFile = new File(args[1]); try { resultInfoFile = resultInfoFile.getCanonicalFile(); } catch (SecurityException ex) { throw constructTermination("messageResultInfoFileCantGetCanonicalPath", ex, null, resultInfoFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageResultInfoFileCantGetCanonicalPath", ex, null, resultInfoFile.getAbsolutePath()); } if (resultInfoFile.exists() == true) { if (resultInfoFile.isFile() == true) { if (resultInfoFile.canWrite() != true) { throw constructTermination("messageResultInfoFileIsntWritable", null, null, resultInfoFile.getAbsolutePath()); } } else { throw constructTermination("messageResultInfoPathIsntAFile", null, null, resultInfoFile.getAbsolutePath()); } } json_to_xml_1.resultInfoFile = resultInfoFile; File jobFile = new File(args[0]); try { jobFile = jobFile.getCanonicalFile(); } catch (SecurityException ex) { throw constructTermination("messageJobFileCantGetCanonicalPath", ex, null, jobFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageJobFileCantGetCanonicalPath", ex, null, jobFile.getAbsolutePath()); } if (jobFile.exists() != true) { throw constructTermination("messageJobFileDoesntExist", null, null, jobFile.getAbsolutePath()); } if (jobFile.isFile() != true) { throw constructTermination("messageJobPathIsntAFile", null, null, jobFile.getAbsolutePath()); } if (jobFile.canRead() != true) { throw constructTermination("messageJobFileIsntReadable", null, null, jobFile.getAbsolutePath()); } System.out.println("json_to_xml_1: " + getI10nStringFormatted("messageCallDetails", jobFile.getAbsolutePath(), resultInfoFile.getAbsolutePath())); File inputFile = null; File outputFile = null; try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); InputStream in = new FileInputStream(jobFile); XMLEventReader eventReader = inputFactory.createXMLEventReader(in); while (eventReader.hasNext() == true) { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement() == true) { String tagName = event.asStartElement().getName().getLocalPart(); if (tagName.equals("json-input-file") == true) { StartElement inputFileElement = event.asStartElement(); Attribute pathAttribute = inputFileElement.getAttributeByName(new QName("path")); if (pathAttribute == null) { throw constructTermination("messageJobFileEntryIsMissingAnAttribute", null, null, jobFile.getAbsolutePath(), tagName, "path"); } String inputFilePath = pathAttribute.getValue(); if (inputFilePath.isEmpty() == true) { throw constructTermination("messageJobFileAttributeValueIsEmpty", null, null, jobFile.getAbsolutePath(), tagName, "path"); } inputFile = new File(inputFilePath); if (inputFile.isAbsolute() != true) { inputFile = new File( jobFile.getAbsoluteFile().getParent() + File.separator + inputFilePath); } try { inputFile = inputFile.getCanonicalFile(); } catch (SecurityException ex) { throw constructTermination("messageInputFileCantGetCanonicalPath", ex, null, new File(inputFilePath).getAbsolutePath(), jobFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageInputFileCantGetCanonicalPath", ex, null, new File(inputFilePath).getAbsolutePath(), jobFile.getAbsolutePath()); } if (inputFile.exists() != true) { throw constructTermination("messageInputFileDoesntExist", null, null, inputFile.getAbsolutePath(), jobFile.getAbsolutePath()); } if (inputFile.isFile() != true) { throw constructTermination("messageInputPathIsntAFile", null, null, inputFile.getAbsolutePath(), jobFile.getAbsolutePath()); } if (inputFile.canRead() != true) { throw constructTermination("messageInputFileIsntReadable", null, null, inputFile.getAbsolutePath(), jobFile.getAbsolutePath()); } } else if (tagName.equals("xml-output-file") == true) { StartElement outputFileElement = event.asStartElement(); Attribute pathAttribute = outputFileElement.getAttributeByName(new QName("path")); if (pathAttribute == null) { throw constructTermination("messageJobFileEntryIsMissingAnAttribute", null, null, jobFile.getAbsolutePath(), tagName, "path"); } String outputFilePath = pathAttribute.getValue(); if (outputFilePath.isEmpty() == true) { throw constructTermination("messageJobFileAttributeValueIsEmpty", null, null, jobFile.getAbsolutePath(), tagName, "path"); } outputFile = new File(outputFilePath); if (outputFile.isAbsolute() != true) { outputFile = new File( jobFile.getAbsoluteFile().getParent() + File.separator + outputFilePath); } try { outputFile = outputFile.getCanonicalFile(); } catch (SecurityException ex) { throw constructTermination("messageOutputFileCantGetCanonicalPath", ex, null, new File(outputFilePath).getAbsolutePath(), jobFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageOutputFileCantGetCanonicalPath", ex, null, new File(outputFilePath).getAbsolutePath(), jobFile.getAbsolutePath()); } if (outputFile.exists() == true) { if (outputFile.isFile() == true) { if (outputFile.canWrite() != true) { throw constructTermination("messageOutputFileIsntWritable", null, null, outputFile.getAbsolutePath()); } } else { throw constructTermination("messageOutputPathIsntAFile", null, null, outputFile.getAbsolutePath()); } } } } } } catch (XMLStreamException ex) { throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath()); } catch (SecurityException ex) { throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath()); } if (inputFile == null) { throw constructTermination("messageJobFileNoInputFile", null, null, jobFile.getAbsolutePath()); } if (outputFile == null) { throw constructTermination("messageJobFileNoOutputFile", null, null, jobFile.getAbsolutePath()); } StringBuilder stringBuilder = new StringBuilder(); try { JSONObject json = new JSONObject(new JSONTokener(new BufferedReader(new FileReader(inputFile)))); stringBuilder.append(XML.toString(json)); } catch (Exception ex) { throw constructTermination("messageConversionError", ex, null, inputFile.getAbsolutePath()); } try { BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.write( "<!-- This file was created by json_to_xml_1, which is free software licensed under the GNU Affero General Public License 3 or any later version (see https://github.com/publishing-systems/digital_publishing_workflow_tools/ and http://www.publishing-systems.org). -->\n"); writer.write(stringBuilder.toString()); writer.flush(); writer.close(); } catch (FileNotFoundException ex) { throw constructTermination("messageOutputFileWritingError", ex, null, outputFile.getAbsolutePath()); } catch (UnsupportedEncodingException ex) { throw constructTermination("messageOutputFileWritingError", ex, null, outputFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageOutputFileWritingError", ex, null, outputFile.getAbsolutePath()); } return 0; }
From source file:microsoft.exchange.webservices.data.core.EwsXmlReader.java
/** * Initializes the XML reader.//from w w w. j a v a 2 s. co m * * @param stream the stream * @return An XML reader to use. * @throws Exception on error */ protected XMLEventReader initializeXmlReader(InputStream stream) throws Exception { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); return inputFactory.createXMLEventReader(stream); }
From source file:com.evolveum.polygon.connector.hcm.DocumentProcessing.java
public Map<String, Object> parseXMLData(HcmConnectorConfiguration conf, ResultsHandler handler, Map<String, Object> schemaAttributeMap, Filter query) { XMLInputFactory factory = XMLInputFactory.newInstance(); try {// w ww.j a v a2 s.c om String uidAttributeName = conf.getUidAttribute(); String primariId = conf.getPrimaryId(); String startName = ""; String value = null; StringBuilder assignmentXMLBuilder = null; List<String> builderList = new ArrayList<String>(); Integer nOfIterations = 0; Boolean isSubjectToQuery = false; Boolean isAssigment = false; Boolean evaluateAttr = true; Boolean specificAttributeQuery = false; XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(conf.getFilePath())); List<String> dictionary = populateDictionary(FIRSTFLAG); if (!attrsToGet.isEmpty()) { attrsToGet.add(uidAttributeName); attrsToGet.add(primariId); specificAttributeQuery = true; evaluateAttr = false; LOGGER.ok("The uid and primary id were added to the queried attribute list"); schemaAttributeMap = modifySchemaAttributeMap(schemaAttributeMap); } while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); Integer code = event.getEventType(); if (code == XMLStreamConstants.START_ELEMENT) { StartElement startElement = event.asStartElement(); startName = startElement.getName().getLocalPart(); if (!evaluateAttr && attrsToGet.contains(startName)) { evaluateAttr = true; } if (!elementIsEmployeeData) { if (startName.equals(EMPLOYEES)) { if (dictionary.contains(nOfIterations.toString())) { LOGGER.ok("The defined number of iterations has been hit: {0}", nOfIterations.toString()); break; } else { startName = ""; elementIsEmployeeData = true; nOfIterations++; } } } else if (evaluateAttr) { if (!isAssigment) { if (!ASSIGNMENTTAG.equals(startName)) { } else { assignmentXMLBuilder = new StringBuilder(); isAssigment = true; } } else { builderList = processAssignment(startName, null, START, builderList); } if (multiValuedAttributesList.contains(startName)) { elementIsMultiValued = true; } } } else if (elementIsEmployeeData) { if (code == XMLStreamConstants.CHARACTERS && evaluateAttr) { Characters characters = event.asCharacters(); if (!characters.isWhiteSpace()) { StringBuilder valueBuilder; if (value != null) { valueBuilder = new StringBuilder(value).append("") .append(characters.getData().toString()); } else { valueBuilder = new StringBuilder(characters.getData().toString()); } value = valueBuilder.toString(); // value = StringEscapeUtils.escapeXml10(value); // LOGGER.info("The attribute value for: {0} is // {1}", startName, value); } } else if (code == XMLStreamConstants.END_ELEMENT) { EndElement endElement = event.asEndElement(); String endName = endElement.getName().getLocalPart(); isSubjectToQuery = checkFilter(endName, value, query, uidAttributeName); if (!isSubjectToQuery) { attributeMap.clear(); elementIsEmployeeData = false; value = null; endName = EMPLOYEES; } if (endName.equals(EMPLOYEES)) { attributeMap = handleEmployeeData(attributeMap, schemaAttributeMap, handler, uidAttributeName, primariId); elementIsEmployeeData = false; } else if (evaluateAttr) { if (endName.equals(startName)) { if (value != null) { if (!isAssigment) { if (!elementIsMultiValued) { attributeMap.put(startName, value); } else { multiValuedAttributeBuffer.put(startName, value); } } else { value = StringEscapeUtils.escapeXml10(value); builderList = processAssignment(endName, value, VALUE, builderList); builderList = processAssignment(endName, null, END, builderList); } // LOGGER.info("Attribute name: {0} and the // Attribute value: {1}", endName, value); value = null; } } else { if (endName.equals(ASSIGNMENTTAG)) { builderList = processAssignment(endName, null, CLOSE, builderList); // if (assigmentIsActive) { for (String records : builderList) { assignmentXMLBuilder.append(records); } attributeMap.put(ASSIGNMENTTAG, assignmentXMLBuilder.toString()); // } else { // } builderList = new ArrayList<String>(); // assigmentIsActive = false; isAssigment = false; } else if (multiValuedAttributesList.contains(endName)) { processMultiValuedAttributes(multiValuedAttributeBuffer); } } } if (specificAttributeQuery && evaluateAttr) { evaluateAttr = false; } } } else if (code == XMLStreamConstants.END_DOCUMENT) { handleBufferedData(uidAttributeName, primariId, handler); } } } catch (FileNotFoundException e) { StringBuilder errorBuilder = new StringBuilder("File not found at the specified path.") .append(e.getLocalizedMessage()); LOGGER.error("File not found at the specified path: {0}", e); throw new ConnectorIOException(errorBuilder.toString()); } catch (XMLStreamException e) { LOGGER.error("Unexpected processing error while parsing the .xml document : {0}", e); StringBuilder errorBuilder = new StringBuilder( "Unexpected processing error while parsing the .xml document. ") .append(e.getLocalizedMessage()); throw new ConnectorIOException(errorBuilder.toString()); } return attributeMap; }
From source file:microsoft.exchange.webservices.data.core.EwsXmlReader.java
public XMLEventReader readSubtree() throws XMLStreamException, FileNotFoundException, ServiceXmlDeserializationException { if (!this.isStartElement()) { throw new ServiceXmlDeserializationException("The current position is not the start of an element."); }/*from w ww .j a v a 2 s .c o m*/ XMLEventReader eventReader = null; InputStream in = null; XMLEvent startEvent = this.presentEvent; XMLEvent event = startEvent; StringBuilder str = new StringBuilder(); str.append(startEvent); do { event = this.xmlReader.nextEvent(); str.append(event); } while (!checkEndElement(startEvent, event)); try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); try { in = new ByteArrayInputStream(str.toString().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { LOG.error(e); } eventReader = inputFactory.createXMLEventReader(in); } catch (Exception e) { LOG.error(e); } return eventReader; }
From source file:com.logiware.accounting.domain.EdiInvoice.java
private void createEcuLineInvoice(File file) throws Exception { InputStream inputStream = null; XMLEventReader eventReader = null; try {/*from ww w .j a v a2 s. c o m*/ XMLInputFactory inputFactory = XMLInputFactory.newInstance(); inputStream = new FileInputStream(file); eventReader = inputFactory.createXMLEventReader(inputStream); while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); if ("Header".equalsIgnoreCase(startElement.getName().toString())) { isHeader = true; elements.add("Header"); } else if ("Body".equalsIgnoreCase(startElement.getName().toString())) { isBody = true; elements.add("Body"); } else if (isBody && "Information".equalsIgnoreCase(startElement.getName().toString())) { isInformation = true; elements.add("Information"); } else if (isBody && !isInformation && "Details".equalsIgnoreCase(startElement.getName().toString())) { isDetails = true; elements.add("Details"); } else if (isBody && !isInformation && !isDetails && "Summary".equalsIgnoreCase(startElement.getName().toString())) { isSummary = true; elements.add("Summary"); } else if (null == elementType) { setElementType(startElement); } else if (null != elementType && null == characterType) { setCharacterType(startElement); } } else if (event.isCharacters()) { setValue(event.asCharacters()); } else if (event.isEndElement()) { EndElement endElement = event.asEndElement(); if (null != characterType && null != elementType) { removeCharacterType(); } else if (null != elementType) { removeElementType(endElement); } else if (isSummary && "Summary".equalsIgnoreCase(endElement.getName().toString())) { isSummary = false; } else if (isDetails && "Details".equalsIgnoreCase(endElement.getName().toString())) { isDetails = false; } else if (isBody && "Information".equalsIgnoreCase(endElement.getName().toString())) { isInformation = false; } else if ("Body".equalsIgnoreCase(endElement.getName().toString())) { isBody = false; } else if ("Header".equalsIgnoreCase(endElement.getName().toString())) { isHeader = false; } } } this.company = Company.ECU_LINE; status = new EdiInvoiceDAO().getStatus(vendorNumber, invoiceNumber); if (!elements.contains("Header")) { throw new AccountingException("Bad File. <Header> element missing"); } else if (!elements.contains("Body")) { throw new AccountingException("Bad File. <Body> missing"); } else if (!elements.contains("Information")) { throw new AccountingException("Bad File. <Information> element under <Body> missing"); } else if (!elements.contains("Details")) { throw new AccountingException("Bad File. <Details> element under <Body> missing"); } else if (!elements.contains("Summary")) { throw new AccountingException("Bad File. <Summary> element under <Body> missing"); } else if (!elements.contains("Applicationreference")) { throw new AccountingException("Bad File. <Applicationreference> element under <Header> missing"); } else if (!elements.contains("Reference")) { throw new AccountingException("Bad File. <Reference> element under <Header> missing"); } else if (!elements.contains("Sender")) { throw new AccountingException("Bad File. <Sender> element under <Header> missing"); } else if (!elements.contains("Code")) { throw new AccountingException("Bad File. <Code> element under <Sender> of <Header> missing"); } else if (!elements.contains("Invoice")) { throw new AccountingException( "Bad File. <Invoice> element under <Information> element of <Body> missing"); } else if (!elements.contains("RelatedReferences")) { throw new AccountingException( "Bad File. <RelatedReferences> element under <Information> element of <Body> missing"); } else if (!elements.contains("BY")) { throw new AccountingException( "Bad File. <Parties Qualifier=\"BY\"> under <Information> element of <Body> missing"); } else if (!elements.contains("SU")) { throw new AccountingException( "Bad File. <Parties Qualifier=\"SU\"> under <Information> element of <Body> missing"); } else if (!elements.contains("PaymentTerms")) { throw new AccountingException( "Bad File. <PaymentTerms> element under <Information> element of <Body> missing"); } else if (!elements.contains("ShipmentInformation")) { throw new AccountingException( "Bad File. <ShipmentInformation> element under <Information> element of <Body> missing"); } else if (!elements.contains("Detail")) { throw new AccountingException( "Bad File. <Detail> element under <Details> element of <Body> missing"); } else if (!elements.contains("TotalMonetaryAmount")) { throw new AccountingException( "Bad File. <TotalMonetaryAmount> element under <Summary> element of <Body> missing"); } else if (!elements.contains("TotalMonetaryAmountGroupByVAT")) { throw new AccountingException( "Bad File. <TotalMonetaryAmountGroupByVAT> element under <Summary> element of <Body> missing"); } } catch (Exception e) { throw e; } finally { if (null != eventReader) { eventReader.close(); } if (null != inputStream) { inputStream.close(); } } }