List of usage examples for org.w3c.dom.ls LSSerializer write
public boolean write(Node nodeArg, LSOutput destination) throws LSException;
LSSerializer
interface. From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileT.java
@Override public Document extendSignatures(Document document, Document originalData, SignatureParameters parameters) throws IOException { InputStream input = document.openStream(); if (this.tspSource == null) { throw new ConfigurationException(MSG.CONFIGURE_TSP_SERVER); }//ww w.j a va2 s.c o m try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse(input); NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (signatureNodeList.getLength() == 0) { throw new RuntimeException( "Impossible to perform the extension of the signature, the document is not signed."); } for (int i = 0; i < signatureNodeList.getLength(); i++) { Element signatureEl = (Element) signatureNodeList.item(i); extendSignatureTag(signatureEl, originalData, parameters.getSignatureFormat()); } DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); LSOutput output = impl.createLSOutput(); output.setByteStream(buffer); writer.write(doc, output); return new InMemoryDocument(buffer.toByteArray()); } catch (ParserConfigurationException ex) { throw new RuntimeException(ex); } catch (SAXException e) { throw new IOException("Cannot parse document", e); } catch (ClassCastException e) { throw new IOException("Cannot save document", e); } catch (ClassNotFoundException e) { throw new IOException("Cannot save document", e); } catch (InstantiationException e) { throw new IOException("Cannot save document", e); } catch (IllegalAccessException e) { throw new IOException("Cannot save document", e); } finally { if (input != null) { input.close(); } } }
From source file:com.redhat.plugin.eap6.AbstractEAP6Mojo.java
protected void writeXmlFile(final Document doc, final File workDirectory, final String fileName) throws MojoFailureException { final File destinationFile = new File(workDirectory, fileName); try {/* w w w .j a va2 s. c o m*/ final FileOutputStream ostream = new FileOutputStream(destinationFile); final DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation(); final LSSerializer lsSerializer = domImplementation.createLSSerializer(); lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); final LSOutput lsOutput = domImplementation.createLSOutput(); lsOutput.setByteStream(ostream); lsSerializer.write(doc, lsOutput); ostream.close(); refreshEclipse(destinationFile); } catch (final Exception e) { throw new MojoFailureException("Cannot write output file", e); } }
From source file:eu.semaine.util.XMLTool.java
/** * Document type to String format conversion * @param document//from w w w . j av a 2s. c o m * @return * @throws Exception * @throws FileNotFoundException */ public static String document2String(Document document) throws SystemConfigurationException { LSSerializer serializer; DOMImplementationLS domImplLS; try { DOMImplementation implementation = DOMImplementationRegistry.newInstance() .getDOMImplementation("XML 3.0"); domImplLS = (DOMImplementationLS) implementation.getFeature("LS", "3.0"); serializer = domImplLS.createLSSerializer(); DOMConfiguration config = serializer.getDomConfig(); config.setParameter("format-pretty-print", Boolean.TRUE); //config.setParameter("canonical-form", Boolean.TRUE); } catch (Exception e) { throw new SystemConfigurationException("Problem instantiating XML serializer code", e); } LSOutput output = domImplLS.createLSOutput(); output.setEncoding("UTF-8"); StringWriter buf = new StringWriter(); output.setCharacterStream(buf); serializer.write(document, output); return buf.toString(); }
From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileT.java
@Override public Document extendSignature(Object signatureId, Document document, Document originalData, SignatureParameters parameters) throws IOException { InputStream input = document.openStream(); if (this.tspSource == null) { throw new ConfigurationException(MSG.CONFIGURE_TSP_SERVER); }/*from ww w .jav a2 s . com*/ try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse(input); NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (signatureNodeList.getLength() == 0) { throw new RuntimeException( "Impossible to perform the extension of the signature, the document is not signed."); } for (int i = 0; i < signatureNodeList.getLength(); i++) { Element signatureEl = (Element) signatureNodeList.item(i); String sid = signatureEl.getAttribute("Id"); if (signatureId.equals(sid)) { extendSignatureTag(signatureEl, originalData, parameters.getSignatureFormat()); } } DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); LSOutput output = impl.createLSOutput(); output.setByteStream(buffer); writer.write(doc, output); return new InMemoryDocument(buffer.toByteArray()); } catch (ParserConfigurationException ex) { throw new RuntimeException(ex); } catch (SAXException e) { throw new IOException("Cannot parse document", e); } catch (ClassCastException e) { throw new IOException("Cannot save document", e); } catch (ClassNotFoundException e) { throw new IOException("Cannot save document", e); } catch (InstantiationException e) { throw new IOException("Cannot save document", e); } catch (IllegalAccessException e) { throw new IOException("Cannot save document", e); } finally { if (input != null) { input.close(); } } }
From source file:com.redhat.plugin.eap6.AbstractEAP6Mojo.java
/** * method to convert Document to String/*ww w .ja v a 2 s.c o m*/ * * @param doc * @return */ protected String getStringFromDocument(final Document doc) { try { final StringWriter writer = new StringWriter(); final DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation(); final LSSerializer lsSerializer = domImplementation.createLSSerializer(); lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); final LSOutput lsOutput = domImplementation.createLSOutput(); lsOutput.setCharacterStream(writer); lsSerializer.write(doc, lsOutput); return writer.toString(); } catch (final LSException ex) { getLog().error(ex); return null; } }
From source file:com.commander4j.thread.AutoLabellerThread.java
public void run() { logger.debug("AutoLabeller Thread running"); setSessionID(JUnique.getUniqueID()); JDBUser user = new JDBUser(getHostID(), getSessionID()); user.setUserId("interface"); user.setPassword("interface"); user.setLoginPassword("interface"); Common.userList.addUser(getSessionID(), user); Common.sd.setData(getSessionID(), "silentExceptions", "Yes", true); Boolean dbconnected = false;/*from w w w. j a va2 s.c om*/ if (Common.hostList.getHost(hostID).isConnected(sessionID) == false) { dbconnected = Common.hostList.getHost(hostID).connect(sessionID, hostID); } else { dbconnected = true; } if (dbconnected) { JDBViewAutoLabellerPrinter alp = new JDBViewAutoLabellerPrinter(getHostID(), getSessionID()); LinkedList<JDBViewAutoLabellerPrinter> autolabellerList = new LinkedList<JDBViewAutoLabellerPrinter>(); int noOfMessages = 0; while (true) { JWait.milliSec(500); if (allDone) { if (dbconnected) { Common.hostList.getHost(hostID).disconnect(getSessionID()); } return; } autolabellerList.clear(); autolabellerList = alp.getModifiedPrinterLines(); noOfMessages = autolabellerList.size(); if (noOfMessages > 0) { for (int x = 0; x < noOfMessages; x++) { JWait.milliSec(100); JDBViewAutoLabellerPrinter autolabview = autolabellerList.get(x); messageProcessedOK = true; messageError = ""; if (autolabview.getPrinterObj().isEnabled()) { logger.debug("Line =" + autolabview.getAutoLabellerObj().getLine()); logger.debug("Line Description =" + autolabview.getAutoLabellerObj().getDescription()); logger.debug("Printer ID =" + autolabview.getPrinterObj().getPrinterID()); logger.debug("Printer Enabled =" + autolabview.getPrinterObj().isEnabled()); logger.debug("Export Path =" + autolabview.getPrinterObj().getExportRealPath()); logger.debug("Export Enabled =" + autolabview.getPrinterObj().isExportEnabled()); logger.debug("Export Format =" + autolabview.getPrinterObj().getExportFormat()); logger.debug("Direct Print =" + autolabview.getPrinterObj().isDirectPrintEnabled()); logger.debug("Printer Type =" + autolabview.getPrinterObj().getPrinterType()); logger.debug("Printer IP =" + autolabview.getPrinterObj().getIPAddress()); logger.debug("Printer Port =" + autolabview.getPrinterObj().getPort()); logger.debug("Process Order =" + autolabview.getLabelDataObj().getProcessOrder()); logger.debug("Material =" + autolabview.getLabelDataObj().getMaterial()); logger.debug("Module ID =" + autolabview.getModuleObj().getModuleId()); logger.debug("Module Type =" + autolabview.getModuleObj().getType()); if (autolabview.getPrinterObj().isExportEnabled()) { String exportPath = JUtility.replaceNullStringwithBlank( JUtility.formatPath(autolabview.getPrinterObj().getExportRealPath())); if (exportPath.equals("") == false) { if (exportPath.substring(exportPath.length() - 1) .equals(File.separator) == false) { exportPath = exportPath + File.separator; } } else { exportPath = Common.interface_output_path + "Auto Labeller" + File.separator; } String exportFilename = exportPath + JUtility.removePathSeparators(autolabview.getAutoLabellerObj().getLine()) + "_" + JUtility.removePathSeparators(autolabview.getPrinterObj().getPrinterID()) + "." + autolabview.getPrinterObj().getExportFormat(); String exportFilenameTemp = exportFilename + ".out"; logger.debug("Export Filename =" + exportFilename); /* ================CSV================ */ if (autolabview.getPrinterObj().getExportFormat().equals("CSV")) { try { PreparedStatement stmt = null; ResultSet rs; String labelType = autolabview.getLabelDataObj().getLabelType(); stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID()) .prepareStatement( Common.hostList.getHost(getHostID()).getSqlstatements() .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties" + "_" + labelType)); stmt.setString(1, autolabview.getAutoLabellerObj().getLine()); stmt.setString(2, autolabview.getPrinterObj().getPrinterID()); stmt.setFetchSize(50); rs = stmt.executeQuery(); logger.debug("Writing CSV"); CSVWriter writer = new CSVWriter(new FileWriter(exportFilenameTemp), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); writer.writeAll(rs, true); rs.close(); stmt.close(); writer.close(); File fromFile = new File(exportFilenameTemp); File toFile = new File(exportFilename); FileUtils.deleteQuietly(toFile); FileUtils.moveFile(fromFile, toFile); fromFile = null; toFile = null; } catch (Exception e) { messageProcessedOK = false; messageError = e.getMessage(); } } /* ================XML================ */ if (autolabview.getPrinterObj().getExportFormat().equals("XML")) { try { PreparedStatement stmt = null; ResultSet rs; stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID()) .prepareStatement(Common.hostList.getHost(getHostID()) .getSqlstatements() .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties")); stmt.setString(1, autolabview.getAutoLabellerObj().getLine()); stmt.setString(2, autolabview.getPrinterObj().getPrinterID()); stmt.setFetchSize(50); rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int colCount = rsmd.getColumnCount(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element message = (Element) document.createElement("message"); Element hostUniqueID = addElement(document, "hostRef", Common.hostList.getHost(getHostID()).getUniqueID()); message.appendChild(hostUniqueID); Element messageRef = addElement(document, "messageRef", autolabview.getAutoLabellerObj().getUniqueID()); message.appendChild(messageRef); Element messageType = addElement(document, "interfaceType", "Auto Labeller Data"); message.appendChild(messageType); Element messageInformation = addElement(document, "messageInformation", "Unique ID=" + autolabview.getAutoLabellerObj().getUniqueID()); message.appendChild(messageInformation); Element messageDirection = addElement(document, "interfaceDirection", "Output"); message.appendChild(messageDirection); Element messageDate = addElement(document, "messageDate", JUtility.getISOTimeStampStringFormat(JUtility.getSQLDateTime())); message.appendChild(messageDate); if (rs.first()) { Element labelData = (Element) document.createElement("LabelData"); Element row = document.createElement("Row"); labelData.appendChild(row); for (int i = 1; i <= colCount; i++) { String columnName = rsmd.getColumnName(i); Object value = rs.getObject(i); Element node = document.createElement(columnName); node.appendChild(document.createTextNode(value.toString())); row.appendChild(node); } message.appendChild(labelData); document.appendChild(message); JXMLDocument xmld = new JXMLDocument(); xmld.setDocument(document); // =============================== DOMImplementationLS DOMiLS = null; FileOutputStream FOS = null; // testing the support for DOM // Load and Save if ((document.getFeature("Core", "3.0") != null) && (document.getFeature("LS", "3.0") != null)) { DOMiLS = (DOMImplementationLS) (document.getImplementation()) .getFeature("LS", "3.0"); // get a LSOutput object LSOutput LSO = DOMiLS.createLSOutput(); FOS = new FileOutputStream(exportFilename); LSO.setByteStream((OutputStream) FOS); // get a LSSerializer object LSSerializer LSS = DOMiLS.createLSSerializer(); // do the serialization LSS.write(document, LSO); FOS.close(); } // =============================== } rs.close(); stmt.close(); } catch (Exception e) { messageError = e.getMessage(); } } if (autolabview.getPrinterObj().getExportFormat().equals("LQF")) { } } if (autolabview.getPrinterObj().isDirectPrintEnabled()) { } } if (messageProcessedOK == true) { autolabview.getAutoLabellerObj().setModified(false); autolabview.getAutoLabellerObj().update(); } else { logger.debug(messageError); } autolabview = null; } } } } }
From source file:edu.wfu.inotado.helper.MarshalHelper.java
/** * Pretty-Prints the XML/*from w w w . j a va 2 s.c o m*/ * * @param xml * @return */ @SuppressWarnings("unused") private String prettyPrintXml(String xml) { DocumentBuilder documentBuilder; StringWriter stringWriter = new StringWriter(); try { documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputStream inputStream = new ByteArrayInputStream(xml.getBytes("UTF8")); Document document = documentBuilder.parse(inputStream); DOMImplementation domImplementation = document.getImplementation(); if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) { DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation.getFeature("LS", "3.0"); LSSerializer lsSerializer = domImplementationLS.createLSSerializer(); DOMConfiguration domConfiguration = lsSerializer.getDomConfig(); if (domConfiguration.canSetParameter("format-pretty-print", Boolean.TRUE)) { lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); LSOutput lsOutput = domImplementationLS.createLSOutput(); lsOutput.setEncoding("UTF-8"); lsOutput.setCharacterStream(stringWriter); lsSerializer.write(document, lsOutput); return stringWriter.toString(); } else { log.warn("DOMConfiguration 'format-pretty-print' parameter isn't settable."); } } else { log.warn("DOM 3.0 LS and/or DOM 2.0 Core not supported."); } } catch (ParserConfigurationException e) { log.error("Unable to parse xml: " + xml, e); } catch (UnsupportedEncodingException e) { log.error("Encoding unspported for xml: " + xml, e); } catch (SAXException e) { log.error("SAXException occurred: " + xml, e); } catch (IOException e) { log.error("IOException occurred:" + xml, e); } // return the input string if any error occurs return xml; }
From source file:com.xpn.xwiki.pdf.impl.PdfExportImpl.java
/** * Cleans up an HTML document, turning it into valid XHTML. * //www . j ava2 s .c o m * @param input the source HTML to process * @return the cleaned up source */ private String convertToStrictXHtml(String input) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Cleaning HTML: " + input); } try { // First step, Tidy the document StringWriter tidyOutput = new StringWriter(input.length()); this.tidy.parse(new StringReader(input), tidyOutput); // Tidy can't solve duplicate IDs, so it needs to be done manually DocumentBuilder docBuilder = dbFactory.newDocumentBuilder(); docBuilder.setEntityResolver(Utils.getComponent(EntityResolver.class)); String tidied = tidyOutput.toString().trim(); if (StringUtils.isEmpty(tidied)) { tidied = input.trim(); } Document doc = docBuilder.parse(new InputSource(new StringReader(tidied))); List<String> seenIDs = new ArrayList<String>(); this.cleanIDs(doc.getDocumentElement(), seenIDs); // Write back the fixed document to a String LSOutput output = lsImpl.createLSOutput(); StringWriter result = new StringWriter(); output.setCharacterStream(result); LSSerializer serializer = lsImpl.createLSSerializer(); serializer.setNewLine("\n"); output.setEncoding(doc.getXmlEncoding()); serializer.write(doc, output); return result.toString(); } catch (Exception ex) { LOGGER.warn("Failed to tidy document for export: " + ex.getMessage(), ex); return input; } }
From source file:edu.ur.ir.ir_export.service.DefaultContributorTypeExportService.java
/** * Create the xml file for the set of collections. * /* w ww . java 2s. co m*/ * @param xmlFile - file to write the xml to * @param contributor types - set of contributor types to export * * @throws IOException - if writing to the file fails. */ public void createXmlFile(File xmlFile, Collection<ContributorType> contributorTypes) throws IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; String path = FilenameUtils.getPath(xmlFile.getCanonicalPath()); if (!path.equals("")) { File pathOnly = new File(FilenameUtils.getFullPath(xmlFile.getCanonicalPath())); FileUtils.forceMkdir(pathOnly); } if (!xmlFile.exists()) { if (!xmlFile.createNewFile()) { throw new IllegalStateException("could not create file"); } } try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } DOMImplementation impl = builder.getDOMImplementation(); DOMImplementationLS domLs = (DOMImplementationLS) impl.getFeature("LS", "3.0"); LSSerializer serializer = domLs.createLSSerializer(); LSOutput lsOut = domLs.createLSOutput(); Document doc = impl.createDocument(null, "contributor_types", null); Element root = doc.getDocumentElement(); FileOutputStream fos; OutputStreamWriter outputStreamWriter; BufferedWriter writer; try { fos = new FileOutputStream(xmlFile); try { outputStreamWriter = new OutputStreamWriter(fos, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } writer = new BufferedWriter(outputStreamWriter); lsOut.setCharacterStream(writer); } catch (FileNotFoundException e) { throw new IllegalStateException(e); } // create XML for the child collections for (ContributorType ct : contributorTypes) { Element contributorType = doc.createElement("contributor_type"); this.addIdElement(contributorType, ct.getId().toString(), doc); this.addNameElement(contributorType, ct.getName(), doc); this.addDescription(contributorType, ct.getDescription(), doc); this.addSystemCode(contributorType, ct.getUniqueSystemCode(), doc); } serializer.write(root, lsOut); try { fos.close(); writer.close(); outputStreamWriter.close(); } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java
/** * Generate an xml file with the specified collections. * /*from ww w .j a v a2 s.com*/ * @see edu.ur.dspace.export.CollectionExporter#generateCollectionXMLFile(java.io.File, java.util.Collection) */ public Set<FileInfo> createXmlFile(File f, Collection<InstitutionalCollection> collections, boolean includeChildren) throws IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; Set<FileInfo> allPictures = new HashSet<FileInfo>(); String path = FilenameUtils.getPath(f.getCanonicalPath()); if (!path.equals("")) { File pathOnly = new File(FilenameUtils.getFullPath(f.getCanonicalPath())); FileUtils.forceMkdir(pathOnly); } if (!f.exists()) { if (!f.createNewFile()) { throw new IllegalStateException("could not create file"); } } try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } DOMImplementation impl = builder.getDOMImplementation(); DOMImplementationLS domLs = (DOMImplementationLS) impl.getFeature("LS", "3.0"); LSSerializer serializer = domLs.createLSSerializer(); LSOutput lsOut = domLs.createLSOutput(); Document doc = impl.createDocument(null, "institutionalCollections", null); Element root = doc.getDocumentElement(); FileOutputStream fos; OutputStreamWriter outputStreamWriter; BufferedWriter writer; try { fos = new FileOutputStream(f); try { outputStreamWriter = new OutputStreamWriter(fos, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } writer = new BufferedWriter(outputStreamWriter); lsOut.setCharacterStream(writer); } catch (FileNotFoundException e) { throw new IllegalStateException(e); } // create XML for the child collections for (InstitutionalCollection c : collections) { Element collection = doc.createElement("collection"); this.addIdElement(collection, c.getId().toString(), doc); this.addNameElement(collection, c.getName(), doc); this.addDescription(collection, c.getDescription(), doc); this.addCopyright(collection, c.getCopyright(), doc); if (c.getPrimaryPicture() != null) { this.addPrimaryImage(collection, c.getPrimaryPicture().getFileInfo().getNameWithExtension(), doc); allPictures.add(c.getPrimaryPicture().getFileInfo()); } Set<IrFile> pictures = c.getPictures(); if (pictures.size() > 0) { Element pics = doc.createElement("pictures"); for (IrFile irFile : pictures) { Element picture = doc.createElement("picture"); this.addImage(picture, irFile.getFileInfo().getNameWithExtension(), doc); pics.appendChild(picture); allPictures.add(irFile.getFileInfo()); } collection.appendChild(pics); } if (c.getLinks().size() > 0) { Element links = doc.createElement("links"); for (InstitutionalCollectionLink l : c.getLinks()) { this.addLink(links, l, doc); } collection.appendChild(links); } if (includeChildren) { for (InstitutionalCollection child : c.getChildren()) { addChild(child, collection, doc, allPictures); } } root.appendChild(collection); } serializer.write(root, lsOut); try { fos.close(); writer.close(); outputStreamWriter.close(); } catch (Exception e) { throw new IllegalStateException(e); } return allPictures; }