List of usage examples for org.dom4j.io XMLWriter close
public void close() throws IOException
From source file:org.snipsnap.util.XMLSnipRepair.java
License:Open Source License
public static void repair(File input, File output, File webAppDir) { System.err.println("STEP 1: parsing input file ..."); Document document = null;/* w w w .j a va 2 s. c o m*/ try { document = load(input); } catch (Exception e) { System.err.println("Unable to read input document: " + e); System.err.println( "This is usually the case for illegal XML characters, please manually edit the file and remove them."); System.exit(0); } System.err.println("STEP 2: checking SnipSpace consistency ..."); Document repaired = repair(document, webAppDir); System.err.println("STEP 3: writing output file ..."); OutputFormat outputFormat = new OutputFormat(); outputFormat.setEncoding("UTF-8"); outputFormat.setNewlines(true); try { XMLWriter xmlWriter = new XMLWriter( null == output ? System.out : (OutputStream) new FileOutputStream(output)); xmlWriter.write(repaired); xmlWriter.flush(); xmlWriter.close(); } catch (Exception e) { System.err.println("Error: unable to write data: " + e); } System.err.println("Finished."); }
From source file:org.springbyexample.enterprise.solr.CatalogItemMarshaller.java
License:Apache License
/** * Implementation of <code>Marshaller</code>. *//*w w w .jav a 2s . c o m*/ @SuppressWarnings("unchecked") public void marshal(Object bean, Result result) throws XmlMappingException, IOException { List<CatalogItem> lCatalogItems = (List<CatalogItem>) bean; OutputStream out = null; XMLWriter writer = null; if (result instanceof StreamResult) { try { out = ((StreamResult) result).getOutputStream(); Document document = DocumentHelper.createDocument(); Element root = document.addElement(ADD_ELEMENT_NAME); for (CatalogItem item : lCatalogItems) { Element doc = root.addElement(DOC_ELEMENT_NAME); doc.addElement(FIELD_ELEMENT_NAME).addAttribute(FIELD_ELEMENT_NAME_ATTRIBUTE, "id") .addText(item.getId()); doc.addElement(FIELD_ELEMENT_NAME).addAttribute(FIELD_ELEMENT_NAME_ATTRIBUTE, "manu") .addText(item.getManufacturer()); doc.addElement(FIELD_ELEMENT_NAME) .addAttribute(FIELD_ELEMENT_NAME_ATTRIBUTE, FIELD_ELEMENT_NAME_ATTRIBUTE) .addText(item.getName()); doc.addElement(FIELD_ELEMENT_NAME).addAttribute(FIELD_ELEMENT_NAME_ATTRIBUTE, "price") .addText(new Float(item.getPrice()).toString()); doc.addElement(FIELD_ELEMENT_NAME).addAttribute(FIELD_ELEMENT_NAME_ATTRIBUTE, "inStock") .addText(BooleanUtils.toStringTrueFalse(item.isInStock())); doc.addElement(FIELD_ELEMENT_NAME).addAttribute(FIELD_ELEMENT_NAME_ATTRIBUTE, "popularity") .addText(new Integer(item.getPopularity()).toString()); } writer = new XMLWriter(out); writer.write(document); } finally { try { writer.close(); } catch (Exception e) { } IOUtils.closeQuietly(out); } } logger.debug("Marshalled bean of size {}.", lCatalogItems.size()); }
From source file:org.talend.componentdesigner.manager.ComponentFolderManager.java
License:Open Source License
/** * DOC slanglois Comment method "writeXMLContent". * /*from ww w .jav a2s .c o m*/ * @param iFile * @param document * @param enCode * @throws CoreException */ private void writeXMLContent(IFile iFile, Document document, String enCode) throws CoreException { PrintWriter pw = null; XMLWriter writer = null; byte[] byteArray = null; // get xml content as inputstream TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = null; try { transformer = tf.newTransformer(); } catch (TransformerConfigurationException e1) { // e1.printStackTrace(); org.talend.componentdesigner.exception.ExceptionHandler.process(e1); } DOMSource source = new DOMSource(document); transformer.setOutputProperty(OutputKeys.ENCODING, enCode); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ ByteArrayOutputStream sw = new ByteArrayOutputStream(); pw = new PrintWriter(sw); StreamResult result = new StreamResult(pw); try { transformer.transform(source, result); } catch (TransformerException e1) { // e1.printStackTrace(); org.talend.componentdesigner.exception.ExceptionHandler.process(e1); } try { sw.flush(); } catch (IOException e1) { // e1.printStackTrace(); org.talend.componentdesigner.exception.ExceptionHandler.process(e1); } finally { if (pw != null) { pw.close(); } } byteArray = sw.toByteArray(); // format the xml content SAXReader saxReader = new SAXReader(); org.dom4j.Document dom4jDocument = null; try { dom4jDocument = saxReader.read(new ByteArrayInputStream(byteArray)); } catch (DocumentException e1) { // e1.printStackTrace(); org.talend.componentdesigner.exception.ExceptionHandler.process(e1); } /** format the output like the webBrowser */ OutputFormat format = OutputFormat.createPrettyPrint(); /** give the xml encoding */ format.setEncoding(enCode); sw = new ByteArrayOutputStream(); try { writer = new XMLWriter(sw, format); } catch (UnsupportedEncodingException e1) { // e1.printStackTrace(); org.talend.componentdesigner.exception.ExceptionHandler.process(e1); } try { writer.write(dom4jDocument); writer.flush(); } catch (IOException e1) { // e1.printStackTrace(); org.talend.componentdesigner.exception.ExceptionHandler.process(e1); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // e.printStackTrace(); org.talend.componentdesigner.exception.ExceptionHandler.process(e); } } } byteArray = sw.toByteArray(); // write content iFile.setContents(new ByteArrayInputStream(byteArray), true, false, null); }
From source file:org.talend.componentdesigner.util.XMLUtil.java
License:Open Source License
/** * format the exist xml file.//from w w w .j a v a2s .co m * * @param filename * @return */ public static int formatXMLFile(String filename, String enCode) { int returnValue = 0; try { SAXReader saxReader = new SAXReader(); org.dom4j.Document document = saxReader.read(new File(filename)); XMLWriter writer = null; /** format the output like the webBrowser */ OutputFormat format = OutputFormat.createPrettyPrint(); /** give the xml encoding */ format.setEncoding(enCode); writer = new XMLWriter(new FileWriter(new File(filename)), format); writer.write(document); writer.close(); /** succes will retun 1 */ returnValue = 1; } catch (Exception ex) { // ex.printStackTrace(); org.talend.componentdesigner.exception.ExceptionHandler.process(ex); } return returnValue; }
From source file:org.talend.core.model.genhtml.XMLHandler.java
License:Open Source License
/** * Generates xml file base on inputted path, file path and an instance of <code>Document</code> * //from ww w.ja v a 2 s .co m * @param tempFolderPath * @param filePath * @param document */ public static void generateXMLFile(String tempFolderPath, String filePath, Document document) { XMLWriter output = null; FileOutputStream out = null; Writer writer = null; try { // OutputFormat format = OutputFormat.createPrettyPrint(); out = new java.io.FileOutputStream(filePath); writer = new OutputStreamWriter(out, "UTF-8"); //$NON-NLS-1$ OutputFormat format = OutputFormat.createPrettyPrint(); output = new XMLWriter(writer, format) { /* * (non-Javadoc) * * @see org.dom4j.io.XMLWriter#writeDeclaration() */ @Override protected void writeDeclaration() throws IOException { OutputFormat formatTmp = this.getOutputFormat(); String encoding = formatTmp.getEncoding(); // Only print of declaration is not suppressed if (!formatTmp.isSuppressDeclaration()) { // Assume 1.0 version if (encoding.equals("UTF8")) { //$NON-NLS-1$ writer.write("<?xml version=\"1.1\""); //$NON-NLS-1$ if (!formatTmp.isOmitEncoding()) { writer.write(" encoding=\"UTF-8\""); //$NON-NLS-1$ } writer.write("?>"); //$NON-NLS-1$ } else { writer.write("<?xml version=\"1.1\""); //$NON-NLS-1$ if (!formatTmp.isOmitEncoding()) { writer.write(" encoding=\"" + encoding + "\""); //$NON-NLS-1$ //$NON-NLS-2$ } writer.write("?>"); //$NON-NLS-1$ } if (formatTmp.isNewLineAfterDeclaration()) { println(); } } } }; output.setMaximumAllowedCharacter(127); output.write(document); output.flush(); } catch (Exception e) { ExceptionHandler.process(e); } finally { if (output != null) { try { output.close(); } catch (Exception e) { ExceptionHandler.process(e); } } if (writer != null) { try { writer.close(); } catch (Exception e) { ExceptionHandler.process(e); } } if (out != null) { try { out.close(); } catch (Exception e) { ExceptionHandler.process(e); } } } }
From source file:org.talend.core.nexus.MavenResolverCreator.java
License:Open Source License
public String setupMavenWithNexus(String url, String userName, String password, String repId) { // return the repository id configured in the settings.xml String repositoryIdToReture = repId; try {//from ww w. ja va2 s. co m if (url == null || userName == null || password == null) { throw new MavenSetupException("Please specifiy a nexus url to setup"); } String userConfigPath = System.getProperty("user.home") + "/.m2/settings.xml"; boolean modified = true; String nexusUrl = url.trim(); URL settingsUrl = getSettingsFileUrl(); Document document = new SAXReader(false).read(new File(settingsUrl.getPath())); Element root = document.getRootElement(); Element profiles = getOrCreateElement(root, "profiles"); Element activeProf = getOrCreateElement(root, "activeProfiles"); List<String> activeProfileIds = getSubElementValues(activeProf, "activeProfile"); Element servers = getOrCreateElement(root, "servers"); Set<String> existingProIds = new HashSet<String>(); Set<String> existingRepIds = new HashSet<String>(); if (profiles != null) { Iterator profileIter = profiles.elementIterator("profile"); String profileId = null; String repositoryId = null; boolean found = false; while (profileIter.hasNext()) { Element profile = (Element) profileIter.next(); Element pIdElement = profile.element("id"); if (pIdElement != null) { profileId = pIdElement.getText(); } Element repositories = profile.element("repositories"); if (repositories != null) { Iterator repIter = repositories.elementIterator("repository"); while (repIter.hasNext()) { Element repository = (Element) repIter.next(); Element repIdElement = repository.element("id"); if (repIdElement != null) { repositoryId = repIdElement.getText(); existingRepIds.add(repositoryId); } Element urlElement = repository.element("url"); if (urlElement != null) { String repUrl = urlElement.getText().trim(); if (nexusUrl.equals(repUrl)) { repositoryIdToReture = repositoryId; found = true; modified = false; break; } } } } } if (found) { // recheck active profile if (!activeProfileIds.contains(profileId)) { addElement(activeProf, "activeProfile", profileId); } } else { // create profile repositoryIdToReture = createProfile(profiles, servers, activeProf, existingProIds, existingRepIds, url, userName, password, repId); } } if (modified) { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); XMLWriter writer = null; try { writer = new XMLWriter(new FileWriter(userConfigPath), format); writer.write(document); writer.close(); } catch (IOException e) { ExceptionHandler.process(e); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { ExceptionHandler.process(e); } } } } } catch (Exception e) { ExceptionHandler.process(e); } return repositoryIdToReture; }
From source file:org.talend.mdm.webapp.base.server.util.XmlUtil.java
License:Open Source License
public static void write(Document document, String filePath, String printMode, String encoding) throws IOException { OutputFormat format;//w w w . j a v a 2s .c o m if (printMode.toLowerCase().equals("pretty")) { //$NON-NLS-1$ // Pretty print the document format = OutputFormat.createPrettyPrint(); } else if (printMode.toLowerCase().equals("compact")) { //$NON-NLS-1$ // Compact format format = OutputFormat.createCompactFormat(); } else { format = null; } format.setEncoding(encoding); // lets write to a file XMLWriter writer = new XMLWriter(new FileOutputStream(filePath), format); writer.write(document); writer.close(); if (logger.isDebugEnabled()) { logger.debug("New xml file has bean exported on " + filePath); //$NON-NLS-1$ } }
From source file:org.talend.repository.ui.wizards.exportjob.scriptsmanager.JobJavaScriptsManager.java
License:Open Source License
protected void saveXmlDocoment(Document document, File outputFile) throws IOException { XMLWriter output = null; try {//w ww. ja va 2 s . c om output = new XMLWriter(new FileWriter(outputFile), OutputFormat.createPrettyPrint()); output.write(document); } finally { output.close(); } }
From source file:org.talend.repository.ui.wizards.exportjob.scriptsmanager.JobJavaScriptsWSManager.java
License:Open Source License
/** * DOC x Comment method "genWebInfoForder". * // ww w . j a va 2s . com * @param list */ private void editWSDDFile(ProcessItem processItem) { String projectName = getCorrespondingProjectName(processItem); String selectedProcessVersion = processItem.getProperty().getVersion(); if (!isMultiNodes() && this.getSelectedJobVersion() != null) { selectedProcessVersion = this.getSelectedJobVersion(); } String jobFolderName = JavaResourcesHelper.getJobFolderName(escapeFileNameSpace(processItem), selectedProcessVersion); String deployFileName = getTmpFolder() + PATH_SEPARATOR + projectName + PATH_SEPARATOR + jobFolderName + PATH_SEPARATOR + "deploy.wsdd"; //$NON-NLS-1$ String serverConfigFile = getTmpFolder() + PATH_SEPARATOR + "server-config.wsdd"; //$NON-NLS-1$ File deployFile = new File(deployFileName); if (!deployFile.exists()) { log.error(org.talend.repository.i18n.Messages.getString("JobJavaScriptsWSManager.errorMessage")); //$NON-NLS-1$ return; } // edit the server-config.wsdd file try { File wsddFile = new File(serverConfigFile); BufferedReader reader = new BufferedReader(new FileReader(wsddFile)); SAXReader saxReader = new SAXReader(); Document doc = saxReader.read(reader); BufferedReader wsdlreader = new BufferedReader(new FileReader(deployFile)); SAXReader wsdlsaxReader = new SAXReader(); Document wsdldoc = wsdlsaxReader.read(wsdlreader); Element wsdlroot = wsdldoc.getRootElement(); Element element = wsdlroot.element("service"); //$NON-NLS-1$ List<Element> elements = element.elements("arrayMapping"); //$NON-NLS-1$ for (Element item : elements) { Attribute attribute = item.attribute("qname"); //$NON-NLS-1$ item.remove(attribute); attribute.setValue(attribute.getValue().replaceFirst(">", "")); //$NON-NLS-1$ //$NON-NLS-2$ item.add(attribute); } Element root = doc.getRootElement(); List<Node> content = root.content(); for (int i = 0; i < content.size(); i++) { Node n = content.get(i); if (n instanceof Element) { if (n.getName().equals("transport")) { //$NON-NLS-1$ content.add(i - 1, element); break; } } } BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(serverConfigFile), "UTF-8")); //$NON-NLS-1$ OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter output = new XMLWriter(writer, format); output.write(doc); output.flush(); output.close(); } catch (Exception e) { ExceptionHandler.process(e); } }
From source file:org.talend.updates.runtime.nexus.component.ComponentIndexManager.java
License:Open Source License
public boolean createIndexFile(File indexFile, List<ComponentIndexBean> newIndexList) throws IOException { if (newIndexList == null || newIndexList.isEmpty() || indexFile == null) { return false; }//from w w w .jav a 2 s. c om XMLWriter xmlWriter = null; boolean created = false; try { // write to index final DocumentFactory docFactory = DocumentFactory.getInstance(); final Element components = docFactory.createElement(ELEM_COMPONENTS); Document newDoc = docFactory.createDocument(components); for (ComponentIndexBean b : newIndexList) { final Element elem = createXmlElement(b); if (elem != null) { components.add(elem); } } // 4 spaces OutputFormat format = new OutputFormat(); format.setEncoding("UTF-8"); //$NON-NLS-1$ format.setIndentSize(4); format.setNewlines(true); xmlWriter = new XMLWriter(new FileOutputStream(indexFile), format); xmlWriter.write(newDoc); created = true; return true; } finally { if (xmlWriter != null) { try { xmlWriter.close(); } catch (IOException e) { // } } if (!created && indexFile.exists()) { indexFile.delete(); // remove the wrong file. } } }