List of usage examples for javax.xml.stream XMLEventReader hasNext
@Override public boolean hasNext();
From source file:com.aionengine.gameserver.dataholders.loadingutils.XmlMerger.java
/** * Read all {@link javax.xml.stream.events.XMLEvent}'s from specified file and write them onto the {@link javax.xml.stream.XMLEventWriter} * * @param file File to import/* www .j a va 2 s. c o m*/ * @param skipRoot Skip-root flag * @param writer Destenation writer * @throws XMLStreamException On event reading/writing error. * @throws FileNotFoundException if the reading file does not exist, * is a directory rather than a regular file, * or for some other reason cannot be opened for * reading. */ private void importFile(File file, boolean skipRoot, XMLEventWriter writer, Properties metadata) throws XMLStreamException, IOException { logger.debug("Appending file " + file); metadata.setProperty(file.getPath(), makeHash(file)); XMLEventReader reader = null; try { reader = inputFactory.createXMLEventReader(new FileReader(file)); QName firstTagQName = null; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); // skip start and end of document. if (event.isStartDocument() || event.isEndDocument()) continue; // skip all comments. if (event instanceof Comment) continue; // skip white-spaces and all ignoreable white-spaces. if (event.isCharacters()) { if (event.asCharacters().isWhiteSpace() || event.asCharacters().isIgnorableWhiteSpace()) continue; } // modify root-tag of imported file. if (firstTagQName == null && event.isStartElement()) { firstTagQName = event.asStartElement().getName(); if (skipRoot) { continue; } else { StartElement old = event.asStartElement(); event = eventFactory.createStartElement(old.getName(), old.getAttributes(), null); } } // if root was skipped - skip root end too. if (event.isEndElement() && skipRoot && event.asEndElement().getName().equals(firstTagQName)) continue; // finally - write tag writer.add(event); } } finally { if (reader != null) try { reader.close(); } catch (Exception ignored) { } } }
From source file:sapience.injectors.stax.inject.StringBasedStaxStreamInjector.java
/** * The actual injection procedure/*from w w w . j a va2s . co m*/ * @param in the input stream where the XML is coming from (will be closed in the end) * @param out the output stream where we write the annotated XML into (remains open) * @param refs a list of references * @throws IOException */ public void inject(InputStream in, OutputStream out, List<Reference> refs) throws IOException { StringBuilder pb; String characters = null; NamespaceContext context = null; int marked; current_path = new Stack<String>(); current_path.push("//"); try { XMLEventReader r = inFac.createXMLEventReader(in); XMLEventWriter w = outFac.createXMLEventWriter(out); XMLStreamWriter ws = outFac.createXMLStreamWriter(System.out); while (r.hasNext()) { XMLEvent e = r.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_ELEMENT: StartElement se = (StartElement) e; context = se.getNamespaceContext(); if (elementReferences == null) { // process the namespaces in the references this.prepareReferences(refs, context); } // store location col = e.getLocation().getColumnNumber(); // add to current xpath current_path.add(generator.asXPathString((StartElement) e)); //XPathHelper.addCurrentElementToStack(current_path, se); // check if the current xpath is in our list of attribute references if (attributeReferences.size() > 0) { for (int i = 0; i < refs.size(); i++) { Stack<String> stack = attributeReferences.get(refs.get(i)); if (matcher.matches(current_path, stack, true, context)) { // yes, let's inject the reference (only valid for attributes here) this.handleAttribute(w, refs.get(i)); attributeReferences.remove(refs.get(i)); refs.remove(i); } } } w.add(e); break; case XMLEvent.END_ELEMENT: // before removing from stack, we check if the current path with added characters is a match (which means we have to add a new element now) if (characters != null) this.current_path.push(characters); if (elementReferences.size() > 0) { for (int i = 0; i < refs.size(); i++) { Stack<String> stack = elementReferences.get(refs.get(i)); if (matcher.matches(current_path, stack, true, context)) { // yes, let's inject the reference (only valid for attributes here) this.interceptingElement = refs.get(i); elementReferences.remove(refs.get(i)); refs.remove(i); } } } if (characters != null) { // clean up this.current_path.pop(); characters = null; } this.current_path.pop(); w.add(e); // if the intercepting is not null, the preceding element was a match, hence we inject some xml before writing a new element if (this.interceptingElement != null) { w.add(eventFac.createSpace("\n")); writeElementIntoStream(w, interceptingElement); } break; case XMLEvent.CHARACTERS: characters = generator.asXPathString((Characters) e); w.add(e); break; default: w.add(e); break; } } } catch (XPathExpressionException e) { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, "Not a valid XPath", e); } throw new IOException(e); } catch (XMLStreamException e) { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, "Failed to inject. Reason: " + e.getLocalizedMessage(), e); } throw new IOException(e); } finally { in.close(); } }
From source file:com.aionemu.gameserver.dataholders.loadingutils.XmlMerger.java
/** * Read all {@link javax.xml.stream.events.XMLEvent}'s from specified file * and write them onto the {@link javax.xml.stream.XMLEventWriter} * * @param file File to import/*w ww . j a v a 2 s . c o m*/ * @param skipRoot Skip-root flag * @param writer Destenation writer * @throws XMLStreamException On event reading/writing error. * @throws FileNotFoundException if the reading file does not exist, is a * directory rather than a regular file, or for some other reason cannot be * opened for reading. */ private void importFile(File file, boolean skipRoot, XMLEventWriter writer, Properties metadata) throws XMLStreamException, IOException { logger.debug("Appending file " + file); metadata.setProperty(file.getPath(), makeHash(file)); XMLEventReader reader = null; try { reader = inputFactory.createXMLEventReader(new FileReader(file)); QName firstTagQName = null; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); // skip start and end of document. if (event.isStartDocument() || event.isEndDocument()) { continue; } // skip all comments. if (event instanceof Comment) { continue; } // skip white-spaces and all ignoreable white-spaces. if (event.isCharacters()) { if (event.asCharacters().isWhiteSpace() || event.asCharacters().isIgnorableWhiteSpace()) { continue; } } // modify root-tag of imported file. if (firstTagQName == null && event.isStartElement()) { firstTagQName = event.asStartElement().getName(); if (skipRoot) { continue; } else { StartElement old = event.asStartElement(); event = eventFactory.createStartElement(old.getName(), old.getAttributes(), null); } } // if root was skipped - skip root end too. if (event.isEndElement() && skipRoot && event.asEndElement().getName().equals(firstTagQName)) { continue; } // finally - write tag writer.add(event); } } finally { if (reader != null) { try { reader.close(); } catch (Exception ignored) { } } } }
From source file:act.installer.pubchem.PubchemParser.java
/** * Incrementally parses a stream of XML events from a PubChem file, extracting the next available PC-Compound entry * as a Chemical object./*www . j a v a2s .com*/ * @param eventReader The xml event reader we are parsing the XML from * @return The constructed chemical * @throws XMLStreamException * @throws XPathExpressionException */ public Chemical extractNextChemicalFromXMLStream(XMLEventReader eventReader) throws XMLStreamException, JaxenException { Document bufferDoc = null; Element currentElement = null; StringBuilder textBuffer = null; /* With help from * http://stackoverflow.com/questions/7998733/loading-local-chunks-in-dom-while-parsing-a-large-xml-file-in-sax-java */ while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); switch (event.getEventType()) { case XMLStreamConstants.START_ELEMENT: String eventName = event.asStartElement().getName().getLocalPart(); if (COMPOUND_DOC_TAG.equals(eventName)) { // Create a new document if we've found the start of a compound object. bufferDoc = documentBuilder.newDocument(); currentElement = bufferDoc.createElement(eventName); bufferDoc.appendChild(currentElement); } else if (currentElement != null) { // Wait until we've found a compound entry to start slurping up data. // Create a new child element and push down the current pointer when we find a new node. Element newElement = bufferDoc.createElement(eventName); currentElement.appendChild(newElement); currentElement = newElement; } // If we aren't in a PC-Compound tree, we just let the elements pass by. break; case XMLStreamConstants.CHARACTERS: if (currentElement == null) { // Ignore this event if we're not in a PC-Compound tree. continue; } Characters chars = event.asCharacters(); // Ignore only whitespace strings, which just inflate the size of the DOM. Text coalescing makes this safe. if (chars.isWhiteSpace()) { continue; } // Rely on the XMLEventStream to coalesce consecutive text events. Text textNode = bufferDoc.createTextNode(chars.getData()); currentElement.appendChild(textNode); break; case XMLStreamConstants.END_ELEMENT: if (currentElement == null) { // Ignore this event if we're not in a PC-Compound tree. continue; } eventName = event.asEndElement().getName().getLocalPart(); Node parentNode = currentElement.getParentNode(); if (parentNode instanceof Element) { currentElement = (Element) parentNode; } else if (parentNode instanceof Document && eventName.equals(COMPOUND_DOC_TAG)) { // We're back at the top of the node stack! Convert the buffered document into a Chemical. PubchemEntry entry = extractPCCompoundFeatures(bufferDoc); if (entry != null) { return entry.asChemical(); } else { // Skip this entry if we can't process it correctly by resetting the world and continuing on. bufferDoc = null; currentElement = null; } } else { // This should not happen, but is here as a sanity check. throw new RuntimeException(String.format("Parent of XML element %s is of type %d, not Element", currentElement.getTagName(), parentNode.getNodeType())); } break; // TODO: do we care about attributes or other XML structures? } } // Return null when we run out of chemicals, just like readLine(). return null; }
From source file:sapience.injectors.stax.inject.ModelBasedStaxStreamInjector.java
/** * If the reference is more then a simple attribute, we have to add new XML (subtree) to the stream. We transform * the reference into an InputStream and invoke another SAX parsing process for it. But the parsed events are added * to the main XMLEventWriter. /*from w ww. ja v a 2s . c om*/ * * @param w * @param string * @throws XMLStreamException * @throws XMLStreamException */ private void createEventsForElement(XMLEventWriter w, Reference ref) throws XMLStreamException { XMLEventReader r = null; try { StringBuilder target = new StringBuilder(ref.getTarget().toString()); NamespaceContext c = w.getNamespaceContext(); ByteArrayInputStream bais = new ByteArrayInputStream(target.toString().getBytes()); getXMLInputFactory().setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); r = getXMLInputFactory().createXMLEventReader(bais); while (r.hasNext()) { XMLEvent e = r.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_DOCUMENT: break; case XMLEvent.END_DOCUMENT: break; default: w.add(e); break; } } } finally { ; if (r != null) r.close(); } }
From source file:com.aionengine.gameserver.dataholders.loadingutils.XmlMerger.java
/** * This method processes the source file, replacing all of * the 'import' tags by the data from the relevant files. * * @throws XMLStreamException on event writing error. * @throws IOException if the destination file exists but is a directory rather than * a regular file, does not exist but cannot be created, * or cannot be opened for any other reason *//*from w ww .j a va2 s.c o m*/ private void doUpdate() throws XMLStreamException, IOException { XMLEventReader reader = null; XMLEventWriter writer = null; Properties metadata = new Properties(); try { writer = outputFactory.createXMLEventWriter(new BufferedWriter(new FileWriter(destFile, false))); reader = inputFactory.createXMLEventReader(new FileReader(sourceFile)); while (reader.hasNext()) { final XMLEvent xmlEvent = reader.nextEvent(); if (xmlEvent.isStartElement() && isImportQName(xmlEvent.asStartElement().getName())) { processImportElement(xmlEvent.asStartElement(), writer, metadata); continue; } if (xmlEvent.isEndElement() && isImportQName(xmlEvent.asEndElement().getName())) continue; if (xmlEvent instanceof Comment)// skip comments. continue; if (xmlEvent.isCharacters())// skip whitespaces. if (xmlEvent.asCharacters().isWhiteSpace() || xmlEvent.asCharacters().isIgnorableWhiteSpace())// skip whitespaces. continue; writer.add(xmlEvent); if (xmlEvent.isStartDocument()) { writer.add(eventFactory.createComment("\nThis file is machine-generated. DO NOT MODIFY IT!\n")); } } storeFileModifications(metadata, metaDataFile); } finally { if (writer != null) try { writer.close(); } catch (Exception ignored) { } if (reader != null) try { reader.close(); } catch (Exception ignored) { } } }
From source file:com.aionemu.gameserver.dataholders.loadingutils.XmlMerger.java
/** * This method processes the source file, replacing all of the 'import' tags * by the data from the relevant files.//from w ww . j a v a2 s. c om * * @throws XMLStreamException on event writing error. * @throws IOException if the destination file exists but is a directory * rather than a regular file, does not exist but cannot be created, or * cannot be opened for any other reason */ private void doUpdate() throws XMLStreamException, IOException { XMLEventReader reader = null; XMLEventWriter writer = null; Properties metadata = new Properties(); try { writer = outputFactory.createXMLEventWriter(new BufferedWriter(new FileWriter(destFile, false))); reader = inputFactory.createXMLEventReader(new FileReader(sourceFile)); while (reader.hasNext()) { final XMLEvent xmlEvent = reader.nextEvent(); if (xmlEvent.isStartElement() && isImportQName(xmlEvent.asStartElement().getName())) { processImportElement(xmlEvent.asStartElement(), writer, metadata); continue; } if (xmlEvent.isEndElement() && isImportQName(xmlEvent.asEndElement().getName())) { continue; } if (xmlEvent instanceof Comment)// skip comments. { continue; } if (xmlEvent.isCharacters())// skip whitespaces. { if (xmlEvent.asCharacters().isWhiteSpace() || xmlEvent.asCharacters().isIgnorableWhiteSpace())// skip // whitespaces. { continue; } } writer.add(xmlEvent); if (xmlEvent.isStartDocument()) { writer.add(eventFactory.createComment("\nThis file is machine-generated. DO NOT MODIFY IT!\n")); } } storeFileModifications(metadata, metaDataFile); } finally { if (writer != null) { try { writer.close(); } catch (Exception ignored) { } } if (reader != null) { try { reader.close(); } catch (Exception ignored) { } } } }
From source file:eu.peppol.document.PayloadParserTest.java
/** * Takes a file holding an SBD/SBDH with an ASiC archive in base64 as payload and extracts the ASiC archive in binary format, while * calculating the message digest./*from w w w .j av a2s . c o m*/ * * @throws Exception */ @Test public void parseSampleSbdWithAsic() throws Exception { InputStream resourceAsStream = PayloadParserTest.class.getClassLoader() .getResourceAsStream("sample-sbd-with-asic.xml"); assertNotNull(resourceAsStream); Path xmlFile = Files.createTempFile("unit-test", ".xml"); XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(resourceAsStream, "UTF-8"); FileOutputStream outputStream = new FileOutputStream(xmlFile.toFile()); XMLEventWriter xmlEventWriter = XMLOutputFactory.newInstance().createXMLEventWriter(outputStream, "UTF-8"); Path asicFile = Files.createTempFile("unit-test", ".asice"); OutputStream asicOutputStream = Files.newOutputStream(asicFile); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); DigestOutputStream digestOutputStream = new DigestOutputStream(asicOutputStream, messageDigest); Base64OutputStream base64OutputStream = new Base64OutputStream(digestOutputStream, false); boolean insideAsicElement = false; while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = xmlEventReader.nextEvent(); switch (xmlEvent.getEventType()) { case XMLEvent.START_ELEMENT: String localPart = xmlEvent.asStartElement().getName().getLocalPart(); if ("asic".equals(localPart)) { insideAsicElement = true; } break; case XMLEvent.END_ELEMENT: localPart = xmlEvent.asEndElement().getName().getLocalPart(); if ("asic".equals(localPart)) { insideAsicElement = false; } break; case XMLEvent.CHARACTERS: // Whenever we are inside the ASiC XML element, spit // out the base64 encoded data into the base64 decoding output stream. if (insideAsicElement) { Characters characters = xmlEvent.asCharacters(); base64OutputStream.write(characters.getData().getBytes("UTF-8")); } break; } xmlEventWriter.add(xmlEvent); } asicOutputStream.close(); outputStream.close(); log.debug("Wrote xml output to: " + xmlFile); log.debug("Wrote ASiC to:" + asicFile); log.debug("Digest: " + new String(Base64.getEncoder().encode(messageDigest.digest()))); }
From source file:de.dfki.km.leech.parser.wikipedia.WikipediaDumpParser.java
public MultiValueHashMap<String, String> getPageTitle2Redirects(InputStream sWikipediaDump) throws FileNotFoundException, XMLStreamException { // <text xml:space="preserve">#REDIRECT [[Autopoiesis]]</text> // <text xml:space="preserve">#REDIRECT:[[Hans Leo Haler]]</text> // <text xml:space="preserve">#redirect [[Weier Hai]]</text> // #weiterleitung // <page> // <title>Autopoiesis</title> Logger.getLogger(WikipediaDumpParser.class.getName()).info("will collect redirects from wikipedia dump..."); MultiValueHashMap<String, String> hsPageTitle2Redirects = new MultiValueBalancedTreeMap<String, String>(); String strCurrentTitle = ""; XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(sWikipediaDump, "Utf-8"); int iTitlesRead = 0; while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = xmlEventReader.nextEvent(); if (!xmlEvent.isStartElement()) continue; // wenn wir einen Title haben, dann merken wir uns den, falls wir ihn brauchen if (xmlEvent.asStartElement().getName().getLocalPart().equals("title")) { strCurrentTitle = readNextCharEventsText(xmlEventReader); iTitlesRead++;/*from w w w . ja v a 2 s. c om*/ if (iTitlesRead % 200000 == 0) Logger.getLogger(WikipediaDumpParser.class.getName()) .info("read doc #" + StringUtils.beautifyNumber(iTitlesRead)); continue; } if (!xmlEvent.asStartElement().getName().getLocalPart().equals("text")) continue; // jetzt haben wir ein text-tag. Wir schauen, ob jetzt ein redirect kommt // entweder kommt ein charEvent oder ein EndEvent. Leere Texte gibts wohl auch XMLEvent nextEvent = xmlEventReader.peek(); if (!nextEvent.isCharacters()) continue; String strCharEventData = readNextCharEventsText(xmlEventReader); if (strCharEventData == null) continue; strCharEventData = strCharEventData.trim(); boolean bRedirect = false; if (strCharEventData.length() >= 9 && strCharEventData.substring(0, 9).equalsIgnoreCase("#redirect")) bRedirect = true; if (!bRedirect && strCharEventData.length() >= 8 && strCharEventData.substring(0, 8).equalsIgnoreCase("redirect") && !strCharEventData.contains("\n")) bRedirect = true; if (!bRedirect && strCharEventData.length() >= 14 && strCharEventData.substring(0, 14).equalsIgnoreCase("#weiterleitung")) bRedirect = true; if (!bRedirect && strCharEventData.length() >= 13 && strCharEventData.substring(0, 13).equalsIgnoreCase("weiterleitung") && !strCharEventData.contains("\n")) bRedirect = true; if (!bRedirect) continue; // wir haben einen redirect - der wird in unsere Datenstruktur eingetragen int iStart = strCharEventData.indexOf("[["); int iEnd = strCharEventData.indexOf("]]"); if (iStart < 0 || iEnd < 0) continue; if (iEnd <= iStart) continue; if ((iStart + 2) > strCharEventData.length() || iEnd > strCharEventData.length()) continue; String strRedirectTarget = strCharEventData.substring(iStart + 2, iEnd).trim(); hsPageTitle2Redirects.add(strRedirectTarget, strCurrentTitle); // if("Venceslav Konstantinov".equalsIgnoreCase(strCurrentTitle) || "Venceslav Konstantinov".equalsIgnoreCase(strRedirectTarget)) // System.out.println("redirect found: (" + hsPageTitle2Redirects.keySize() + ") " + strCurrentTitle + " => '" + strRedirectTarget + "'"); } Logger.getLogger(WikipediaDumpParser.class.getName()) .info("Redirects found: " + StringUtils.beautifyNumber(hsPageTitle2Redirects.valueSize())); return hsPageTitle2Redirects; }
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 w w w.j a v a 2s. 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; }