List of usage examples for javax.xml.parsers DocumentBuilder getDOMImplementation
public abstract DOMImplementation getDOMImplementation();
From source file:org.openremote.beehive.configuration.www.UsersAPI.java
private File createControllerXmlFile(java.nio.file.Path temporaryFolder, Account account) { File controllerXmlFile = new File(temporaryFolder.toFile(), "controller.xml"); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); try {/*w w w . j av a2 s . c o m*/ documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); DOMImplementation domImplementation = documentBuilder.getDOMImplementation(); Document document = domImplementation.createDocument(OPENREMOTE_NAMESPACE, "openremote", null); document.getDocumentElement().setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation", "http://www.openremote.org http://www.openremote.org/schemas/controller.xsd"); Element componentsElement = document.createElementNS(OPENREMOTE_NAMESPACE, "components"); document.getDocumentElement().appendChild(componentsElement); writeSensors(document, document.getDocumentElement(), account, findHighestCommandId(account)); writeCommands(document, document.getDocumentElement(), account); writeConfig(document, document.getDocumentElement(), account); // Document is fully built, validate against schema before writing to file URL xsdResource = UsersAPI.class.getResource(CONTROLLER_XSD_PATH); if (xsdResource == null) { log.error("Cannot find XSD schema ''{0}''. Disabling validation...", CONTROLLER_XSD_PATH); } else { String language = XMLConstants.W3C_XML_SCHEMA_NS_URI; SchemaFactory factory = SchemaFactory.newInstance(language); Schema schema = factory.newSchema(xsdResource); Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); } Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Result output = new StreamResult(controllerXmlFile); Source input = new DOMSource(document); transformer.transform(input, output); } catch (ParserConfigurationException e) { log.error("Error generating controller.xml file", e); throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR); } catch (TransformerConfigurationException e) { log.error("Error generating controller.xml file", e); throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR); } catch (TransformerException e) { log.error("Error generating controller.xml file", e); throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR); } catch (SAXException e) { log.error("Error generating controller.xml file", e); throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR); } catch (IOException e) { log.error("Error generating controller.xml file", e); throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR); } return controllerXmlFile; }
From source file:edu.ur.ir.ir_import.service.DefaultCollectionImportService.java
/** * Load the dspace collection information from the xml file. * @throws DuplicateNameException // w ww . j a v a 2 s . c o m * * @see edu.ur.dspace.load.CollectionImporter#getCollections(java.io.File) */ private void getCollections(File communityXmlFile, Repository repo, ZipFile zip) throws IOException, DuplicateNameException { if (log.isDebugEnabled()) { log.debug("get collections"); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } DOMImplementation impl = builder.getDOMImplementation(); DOMImplementationLS domLs = (DOMImplementationLS) impl.getFeature("LS", "3.0"); LSInput lsIn = domLs.createLSInput(); LSParser parser = domLs.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); lsIn.setEncoding("UTF-8"); FileInputStream fileInputStream; try { fileInputStream = new FileInputStream(communityXmlFile); } catch (FileNotFoundException e) { throw new IllegalStateException(e); } InputStreamReader inputStreamReader; try { inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } lsIn.setCharacterStream(inputStreamReader); Document doc = parser.parse(lsIn); Element root = doc.getDocumentElement(); NodeList nodeList = root.getChildNodes(); log.debug("node list length = " + nodeList.getLength()); for (int index = 0; index < nodeList.getLength(); index++) { Node child = nodeList.item(index); importCollection(child, repo, zip); } }
From source file:br.org.indt.mobisus.common.ResultWriter.java
public void write() throws ParserConfigurationException, Exception { logger.info("creatint result file in " + resultPath); Document xmldoc = null;//from w w w. java2s . c o m DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); DOMImplementation impl = builder.getDOMImplementation(); Element answerElement = null; Element categoryElement = null; Element text = null; Element title = null; Element lat = null; Element lon = null; Element other = null; Node titleText = null; Node nodeStr = null; xmldoc = impl.createDocument(null, "result", null); Element root = xmldoc.getDocumentElement(); root.setAttribute("r_id", result.getResultId()); root.setAttribute("s_id", result.getSurveyId()); root.setAttribute("u_id", result.getUserId()); root.setAttribute("time", result.getTime()); if (result.getLatitude() != null) { lat = xmldoc.createElementNS(null, "latitude"); titleText = xmldoc.createTextNode(result.getLatitude()); lat.appendChild(titleText); root.appendChild(lat); } if (result.getLongitude() != null) { lon = xmldoc.createElementNS(null, "longitude"); titleText = xmldoc.createTextNode(result.getLongitude()); lon.appendChild(titleText); root.appendChild(lon); } title = xmldoc.createElementNS(null, "title"); titleText = xmldoc.createTextNode(""); title.appendChild(titleText); root.appendChild(title); TreeMap<Integer, Category> categories = survey.getCategories(); Iterator<Category> iteratorCat = categories.values().iterator(); while (iteratorCat.hasNext()) { Category category = iteratorCat.next(); categoryElement = xmldoc.createElementNS(null, "category"); categoryElement.setAttribute("name", category.getName()); categoryElement.setAttribute("id", String.valueOf(category.getId())); root.appendChild(categoryElement); Integer categoryId = new Integer(category.getId()); Vector<Field> questions = category.getFields(); for (Field question : questions) { answerElement = xmldoc.createElementNS(null, "answer"); answerElement.setAttributeNS(null, "type", question.getXmlType()); answerElement.setAttributeNS(null, "id", String.valueOf(question.getId())); answerElement.setAttributeNS(null, "visited", "false"); Field answer = result.getCategories().get(categoryId).getFieldById(question.getId()); if (question.getFieldType() == FieldType.CHOICE) { ArrayList<Item> items = answer.getChoice().getItems(); for (Item item : items) { if (item.getOtr() == null || item.getOtr().equals("0")) { nodeStr = xmldoc.createTextNode("" + item.getIndex()); text = xmldoc.createElementNS(null, question.getElementName()); text.appendChild(nodeStr); answerElement.appendChild(text); categoryElement.appendChild(answerElement); } else { nodeStr = xmldoc.createTextNode(item.getValue()); other = xmldoc.createElementNS(null, "other"); other.setAttributeNS(null, "index", "" + item.getIndex()); other.appendChild(nodeStr); answerElement.appendChild(other); categoryElement.appendChild(answerElement); } } } else { nodeStr = xmldoc.createTextNode((answer.getValue() == null ? "" : answer.getValue())); text = xmldoc.createElementNS(null, question.getElementName()); text.appendChild(nodeStr); answerElement.appendChild(text); categoryElement.appendChild(answerElement); } if ((question.getCategoryId() == survey.getDisplayCategory()) && (question.getId() == survey.getDisplayQuestion())) { (root.getElementsByTagName("title")).item(0).setTextContent(answer.getValue()); } } } ResultDeploy resultDeploy = new ResultDeploy(xmldoc, getNextResultFile()); resultDeploy.deploy(resultPath); }
From source file:edu.ur.ir.ir_export.service.DefaultContributorTypeExportService.java
/** * Create the xml file for the set of collections. * /*from www. j av a2s .c o 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:be.docarch.odt2braille.PEF.java
/** * Converts the flat .odt filt to a .pef file according to the braille settings. * * This function/*from w w w . j a v a2s . c om*/ * <ul> * <li>uses {@link ODT} to convert the .odt file to multiple DAISY-like xml files,</li> * <li>uses {@link LiblouisXML} to translate these files into braille, and</li> * <li>recombines these braille files into one single .pef file.</li> * </ul> * * First, the document <i>body</i> is processed and split in volumes, then the <i>page ranges</i> are calculated * and finally the <i>preliminary pages</i> of each volume are processed and inserted at the right places. * The checker checks the DAISY-like files and the volume lengths. * */ public boolean makePEF() throws IOException, ParserConfigurationException, TransformerException, InterruptedException, SAXException, ConversionException, LiblouisXMLException, Exception { logger.entering("PEF", "makePEF"); Configuration settings = odt.getConfiguration(); Element[] volumeElements; Element sectionElement; File bodyFile = null; File brailleFile = null; File preliminaryFile = null; List<Volume> volumes = manager.getVolumes(); String volumeInfo = capitalizeFirstLetter( ResourceBundle.getBundle(L10N, settings.mainLocale).getString("in")) + " " + volumes.size() + " " + ResourceBundle.getBundle(L10N, settings.mainLocale) .getString((volumes.size() > 1) ? "volumes" : "volume") + "\n@title\n@pages"; volumeElements = new Element[volumes.size()]; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setValidating(false); docFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); DOMImplementation impl = docBuilder.getDOMImplementation(); Document document = impl.createDocument(pefNS, "pef", null); Element root = document.getDocumentElement(); root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", pefNS); root.setAttributeNS(null, "version", "2008-1"); Element headElement = document.createElementNS(pefNS, "head"); Element metaElement = document.createElementNS(pefNS, "meta"); metaElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dc", "http://purl.org/dc/elements/1.1/"); Element dcElement = document.createElementNS("http://purl.org/dc/elements/1.1/", "dc:identifier"); dcElement.appendChild(document.createTextNode(Integer.toHexString((int) (Math.random() * 1000000)) + " " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format((new Date())))); metaElement.appendChild(dcElement); dcElement = document.createElementNS("http://purl.org/dc/elements/1.1/", "dc:format"); dcElement.appendChild(document.createTextNode("application/x-pef+xml")); metaElement.appendChild(dcElement); headElement.appendChild(metaElement); root.appendChild(headElement); int columns = pefSettings.getColumns(); int rows = pefSettings.getRows(); boolean duplex = pefSettings.getDuplex(); int rowgap = pefSettings.getEightDots() ? 1 : 0; int beginPage = settings.getBeginningBraillePageNumber(); if (statusIndicator != null) { statusIndicator.start(); statusIndicator.setSteps(volumes.size()); statusIndicator.setStatus(ResourceBundle.getBundle(L10N, statusIndicator.getPreferredLocale()) .getString("statusIndicatorStep")); } for (int volumeCount = 0; volumeCount < volumes.size(); volumeCount++) { volumeElements[volumeCount] = document.createElementNS(pefNS, "volume"); volumeElements[volumeCount].setAttributeNS(null, "cols", String.valueOf(columns)); volumeElements[volumeCount].setAttributeNS(null, "rows", String.valueOf(rows + (int) Math.ceil(((rows - 1) * rowgap) / 4d))); volumeElements[volumeCount].setAttributeNS(null, "rowgap", String.valueOf(rowgap)); volumeElements[volumeCount].setAttributeNS(null, "duplex", duplex ? "true" : "false"); Volume volume = volumes.get(volumeCount); // Body section logger.info("Processing volume " + (volumeCount + 1) + " : " + volume.getTitle()); if (!(volume instanceof PreliminaryVolume)) { bodyFile = File.createTempFile(TMP_NAME, ".daisy.body." + (volumeCount + 1) + ".xml", TMP_DIR); bodyFile.deleteOnExit(); brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR); brailleFile.deleteOnExit(); odt.getBodyMatter(bodyFile, volume); liblouisXML.configure(bodyFile, brailleFile, false, beginPage); liblouisXML.run(); // Read pages sectionElement = document.createElementNS(pefNS, "section"); int pageCount = addPagesToSection(document, sectionElement, brailleFile, rows, columns, -1); volumeElements[volumeCount].appendChild(sectionElement); // Checker if (checker != null) { checker.checkDaisyFile(bodyFile); } // Braille page range volume.setBraillePagesStart(beginPage); volume.setNumberOfBraillePages(pageCount); beginPage += pageCount; // Print page range if (volume.getFrontMatter() && settings.getVolumeInfoEnabled()) { extractPrintPageRange(bodyFile, volume, settings); } } // Special symbols list if (volume.getSpecialSymbolListEnabled()) { extractSpecialSymbols(bodyFile, volume, volumeCount, settings); } // Preliminary section if (volume.getFrontMatter() || volume.getTableOfContent() || volume.getTranscribersNotesPageEnabled() || volume.getSpecialSymbolListEnabled()) { preliminaryFile = File.createTempFile(TMP_NAME, ".daisy.front." + (volumeCount + 1) + ".xml", TMP_DIR); preliminaryFile.deleteOnExit(); brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR); brailleFile.deleteOnExit(); odt.getFrontMatter(preliminaryFile, volume, volumeInfo); liblouisXML.configure(preliminaryFile, brailleFile, true, volume.getTableOfContent() ? volume.getFirstBraillePage() : 1); liblouisXML.run(); // Page range int pageCount = countPages(brailleFile, volume); volume.setNumberOfPreliminaryPages(pageCount); // Translate again with updated volume info and without volume separator marks brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR); brailleFile.deleteOnExit(); odt.getFrontMatter(preliminaryFile, volume, volumeInfo); liblouisXML.configure(preliminaryFile, brailleFile, false, volume.getTableOfContent() ? volume.getFirstBraillePage() : 1); liblouisXML.run(); // Read pages sectionElement = document.createElementNS(pefNS, "section"); addPagesToSection(document, sectionElement, brailleFile, rows, columns, pageCount); volumeElements[volumeCount].insertBefore(sectionElement, volumeElements[volumeCount].getFirstChild()); // Checker if (checker != null) { checker.checkDaisyFile(preliminaryFile); } } if (statusIndicator != null) { statusIndicator.increment(); } } if (checker != null) { checker.checkVolumes(volumes); } Element bodyElement = document.createElementNS(pefNS, "body"); for (int volumeCount = 0; volumeCount < volumes.size(); volumeCount++) { bodyElement.appendChild(volumeElements[volumeCount]); } root.appendChild(bodyElement); document.insertBefore((ProcessingInstruction) document.createProcessingInstruction("xml-stylesheet", "type='text/css' href='pef.css'"), document.getFirstChild()); OdtUtils.saveDOM(document, pefFile); logger.exiting("PEF", "makePEF"); if (!validatePEF(pefFile)) { return false; } return true; }
From source file:com.collabnet.tracker.core.PTrackerWebServicesClient.java
private Document createNewXMLDocument(String namespace, String qualifiedTagName) { DocumentBuilderFactory dbf;// = DocumentBuilderFactory.newInstance(); DocumentBuilder db; Document doc = null;/* ww w .ja v a2s . c o m*/ try { dbf = DocumentBuilderFactory.newInstance(); db = dbf.newDocumentBuilder(); DOMImplementation di = db.getDOMImplementation(); doc = di.createDocument(namespace, qualifiedTagName, null); } catch (ParserConfigurationException e) { log(e, "could not create document"); } return doc; }
From source file:DOMProcessor.java
/** Adds a new element to the root of the DOM. * @param name Name of the new element//from w ww . j a v a 2 s. c om * @return New element in the DOM. */ public Node addElement(String name) { if (dom == null) { // Create a DocumentBuilder using the DocumentBuilderFactory. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; indent = 0; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { System.err.println("Problem finding an XML parser:\n" + e); return null; } dom = db.getDOMImplementation().createDocument(null, name, null); return dom.getDocumentElement(); } return addElement(name, null, dom.getDocumentElement()); }
From source file:de.mpg.escidoc.services.exportmanager.Export.java
/** * Parses <code>itemList</code> XML to <code>org.w3c.dom.Document</code>. * //from w w w .ja v a 2 s . c o m * @param itemList * @return <code>org.w3c.dom.Document</code> * @throws ExportManagerException */ private Document parseDocument(String itemList) throws ExportManagerException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder parser; try { parser = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new ExportManagerException("Cannot create DocumentBuilder:", e); } // Check for the traversal module DOMImplementation impl = parser.getDOMImplementation(); if (!impl.hasFeature("traversal", "2.0")) { throw new ExportManagerException("A DOM implementation that supports traversal is required."); } Document doc; try { doc = parser.parse(new ByteArrayInputStream(itemList.getBytes())); } catch (Exception e) { throw new ExportManagerException("Cannot parse itemList to w3c document"); } return doc; }
From source file:nl.b3p.kaartenbalie.service.requesthandler.WMSRequestHandler.java
private Document createKBDescribeLayerResponse(DataWrapper dw, List<DescribeLayerData> describeLayerData) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false);/* w w w .j ava 2 s. co m*/ dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); DOMImplementation di = db.getDOMImplementation(); // <!DOCTYPE WMS_DescribeLayerResponse SYSTEM "http://schemas.opengis.net/wms/1.1.1/WMS_DescribeLayerResponse.dtd"> // [ <WMS_DescribeLayerResponse version="1.1.1" > (...) </WMS_DescribeLayerResponse>] DocumentType dt = di.createDocumentType("WMS_DescribeLayerResponse", null, CallWMSServlet.DESCRIBELAYER_DTD); Document dom = di.createDocument(null, "WMS_DescribeLayerResponse", dt); Element rootElement = dom.getDocumentElement(); rootElement.setAttribute("version", "1.1.1"); //describeLayer version in kbconfig? String spAbbrUrl = dw.getOgcrequest().getServiceProviderName(); String personalUrl = this.user.getPersonalURL(dw.getRequest(), spAbbrUrl); Integer[] orgIds = this.user.getOrganizationIds(); WFSProviderDAO wfsProviderDao = new WFSProviderDAO(); String[] validLayerNames = wfsProviderDao.getAuthorizedFeatureTypeNames(orgIds, null, false); //it is not possible to use getSeviceProviderURLS because that will call getValidObjects implementation of WMSRequestHandler //therefore build spInfo here in loop //also, B3PLayering is not relevant here, because describeLayer should not be subject to pricing List spInfo = new ArrayList(); for (String name : validLayerNames) { SpLayerSummary layerInfo = wfsProviderDao.getAuthorizedFeatureTypeSummary(name, orgIds, false); if (layerInfo == null) { continue; } spInfo.add(layerInfo); } for (DescribeLayerData resp : describeLayerData) { for (LayerDescription descr : resp.getDescribeLayerResponse().getLayerDescs()) { Element layerDescriptionElement = dom.createElement("LayerDescription"); if (spAbbrUrl != null && !spAbbrUrl.equals("")) { layerDescriptionElement.setAttribute("name", descr.getName()); } else { layerDescriptionElement.setAttribute("name", OGCCommunication.attachSp(resp.getWmsPrefix(), descr.getName())); } descr.getOwsURL(); //additional info should only be returned for WMS layer that has corresponding WFS type that is served by Kaartenbalie String wfsPrefix = getAuthorizedWFSPrefix(spInfo, descr); if (wfsPrefix != null) { layerDescriptionElement.setAttribute("wfs", personalUrl); layerDescriptionElement.setAttribute("owsType", descr.getOwsType()); layerDescriptionElement.setAttribute("owsURL", personalUrl); Element queryElement = dom.createElement("Query"); queryElement.setAttribute("typeName", OGCCommunication.attachSp(wfsPrefix, descr.getName())); layerDescriptionElement.appendChild(queryElement); } rootElement.appendChild(layerDescriptionElement); } } return dom; }
From source file:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java
/** * Generate an xml file with the specified collections. * /* ww w. j a v a2s.c o m*/ * @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; }