List of usage examples for org.w3c.dom Document setXmlVersion
public void setXmlVersion(String xmlVersion) throws DOMException;
From source file:org.gephi.desktop.preview.PresetUtils.java
public void savePreset(PreviewPreset preset) { int exist = -1; for (int i = 0; i < presets.size(); i++) { PreviewPreset p = presets.get(i); if (p.getName().equals(preset.getName())) { exist = i;// w w w. j a v a2 s . c o m break; } } if (exist == -1) { addPreset(preset); } else { presets.set(exist, preset); } try { //Create file if dont exist FileObject folder = FileUtil.getConfigFile("previewpresets"); if (folder == null) { folder = FileUtil.getConfigRoot().createFolder("previewpresets"); } String filename = DigestUtils.sha1Hex(preset.getName());//Safe filename FileObject presetFile = folder.getFileObject(filename, "xml"); if (presetFile == null) { presetFile = folder.createData(filename, "xml"); } //Create doc DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); final Document document = documentBuilder.newDocument(); document.setXmlVersion("1.0"); document.setXmlStandalone(true); //Write doc writeXML(document, preset); //Write XML file try (OutputStream outputStream = presetFile.getOutputStream()) { Source source = new DOMSource(document); Result result = new StreamResult(outputStream); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(source, result); } } catch (Exception ex) { Exceptions.printStackTrace(ex); } }
From source file:org.mapsforge.directions.TurnByTurnDescriptionToString.java
/** * Creates a KML (Keyhole markup language) version of the directions. * /* w w w . j a va 2 s. c om*/ * @return a KML string * @throws ParserConfigurationException * if the DOM can't be built * @throws TransformerConfigurationException * if turning the DOM into a string fails * @throws TransformerException * if turning the DOM into a string fails * @throws TransformerFactoryConfigurationError * if turning the DOM into a string fails */ public String toKML() throws ParserConfigurationException, TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError { // This creates a new DOM Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); // And let's get this started dom.setXmlVersion("1.0"); dom.setXmlStandalone(true); Element kml = dom.createElement("kml"); dom.appendChild(kml); kml.setAttribute("xmlns", "http://www.opengis.net/kml/2.2"); Element document = dom.createElement("Document"); kml.appendChild(document); Element name = dom.createElement("name"); name.setTextContent( "MapsForge directions from " + streets.firstElement().name + " to " + streets.lastElement().name); document.appendChild(name); Element style = dom.createElement("Style"); style.setAttribute("id", "MapsForgeStyle"); document.appendChild(style); Element lineStyle = dom.createElement("LineStyle"); style.appendChild(lineStyle); Element color = dom.createElement("color"); color.setTextContent("ff0000ff"); lineStyle.appendChild(color); Element width = dom.createElement("width"); width.setTextContent("3"); lineStyle.appendChild(width); for (TurnByTurnStreet street : streets) { Element placemark = dom.createElement("Placemark"); document.appendChild(placemark); Element placemarkName = dom.createElement("name"); placemarkName.setTextContent(street.name); placemark.appendChild(placemarkName); Element lineString = dom.createElement("LineString"); placemark.appendChild(lineString); Element coordinates = dom.createElement("coordinates"); lineString.appendChild(coordinates); String coordinatesContent = ""; for (GeoCoordinate c : street.points) { coordinatesContent += c.getLongitude() + "," + c.getLatitude() + " "; } coordinatesContent = coordinatesContent.substring(0, coordinatesContent.length() - 1); // remove last space coordinates.setTextContent(coordinatesContent); Element extendedData = dom.createElement("ExtendedData"); placemark.appendChild(extendedData); Element length = dom.createElement("Length"); extendedData.appendChild(length); length.setTextContent(Double.toString(street.length)); Element angle = dom.createElement("AngleToPreviousStreet"); extendedData.appendChild(angle); angle.setTextContent(Double.toString(street.angleFromStreetLastStreet)); Element styleUrl = dom.createElement("styleUrl"); placemark.appendChild(styleUrl); styleUrl.setTextContent("#MapsForgeStyle"); } // This is for turning the DOM object into a proper StringWriter StringWriter stringWriter = new StringWriter(); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(dom), new StreamResult(stringWriter)); return stringWriter.getBuffer().toString(); }
From source file:org.mapsforge.directions.TurnByTurnDescriptionToString.java
/** * Creates a GPX (GPS Exchange Format) version of the directions. * /*from ww w.j a v a 2 s. co m*/ * @return a KML string * @throws ParserConfigurationException * if the DOM can't be built * @throws TransformerConfigurationException * if turning the DOM into a string fails * @throws TransformerException * if turning the DOM into a string fails * @throws TransformerFactoryConfigurationError * if turning the DOM into a string fails */ public String toGPX() throws ParserConfigurationException, TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError { // This creates a new DOM Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); // And let's get this started dom.setXmlVersion("1.0"); dom.setXmlStandalone(true); Element gpx = dom.createElement("gpx"); dom.appendChild(gpx); gpx.setAttribute("version", "1.1"); gpx.setAttribute("xmlns", "http://www.topografix.com/GPX/1/1"); gpx.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); gpx.setAttribute("xmlns:mf", "http://tom.mapsforge.de"); gpx.setAttribute("xsi:schemaLocation", "http://www.topografix.com/GPX/1/1 http://www.topografix.com/gpx/1/1/gpx.xsd"); gpx.setAttribute("creator", "tom.mapsforge.de"); Element metadata = dom.createElement("metadata"); gpx.appendChild(metadata); Element name = dom.createElement("name"); name.setTextContent( "MapsForge directions from " + streets.firstElement().name + " to " + streets.lastElement().name); metadata.appendChild(name); for (TurnByTurnStreet street : streets) { Element trk = dom.createElement("trk"); gpx.appendChild(trk); Element trkName = dom.createElement("name"); trkName.setTextContent(street.name); trk.appendChild(trkName); Element trkseg = dom.createElement("trkseg"); trk.appendChild(trkseg); for (GeoCoordinate c : street.points) { Element trkpt = dom.createElement("trkpt"); trkseg.appendChild(trkpt); trkpt.setAttribute("lat", Double.toString(c.getLatitude())); trkpt.setAttribute("lon", Double.toString(c.getLongitude())); } Element extensions = dom.createElement("extensions"); trkseg.appendChild(extensions); Element length = dom.createElement("mf:Length"); extensions.appendChild(length); length.setTextContent(Double.toString(street.length)); Element angle = dom.createElement("mf:AngleToPreviousStreet"); extensions.appendChild(angle); angle.setTextContent(Double.toString(street.angleFromStreetLastStreet)); } // This is for turning the DOM object into a proper StringWriter StringWriter stringWriter = new StringWriter(); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(dom), new StreamResult(stringWriter)); return stringWriter.getBuffer().toString(); }
From source file:org.massyframework.modules.utils.SunJdkModuleExporter.java
public Document genericDocument(String rtJar) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // ???//w w w . ja v a 2s .c o m factory.setNamespaceAware(true); // ?? factory.setValidating(true); Document result = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); result = builder.newDocument(); //XML result.setXmlVersion("1.0"); Element root = result.createElement("module"); root.setAttribute("xmlns", "urn:jboss:module:1.5"); root.setAttribute("name", "sun.jdk"); result.appendChild(root); Element dependencies = result.createElement("dependencies"); root.appendChild(dependencies); Element system = result.createElement("system"); system.setAttribute("export", "true"); dependencies.appendChild(system); Element paths = result.createElement("paths"); system.appendChild(paths); List<String> packageNames = this.getSunJdkPackageNames(rtJar); for (String packageName : packageNames) { Element path = result.createElement("path"); path.setAttribute("name", packageName); paths.appendChild(path); } } catch (Exception e) { e.printStackTrace(); } return result; }
From source file:org.parelon.pskc.XmlManager.java
public void convertXml(String fileIn, String fileOut) throws FileNotFoundException, SAXException, IOException, InvalidKeyException, Base64DecodingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, UnsupportedEncodingException, ParserConfigurationException, DecoderException, Exception { ArrayList<OtpSeed> seeds = new ArrayList<OtpSeed>(); /**/* w w w . j ava 2s. c o m*/ * Parserizzazione XML */ FileInputStream fileToConvert = new FileInputStream(fileIn); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document parsedXml = builder.parse(fileToConvert); fileToConvert.close(); if (parsedXml.hasChildNodes()) { int validSerials = 0; NodeList keyPackages = parsedXml.getElementsByTagName("KeyPackage"); for (int i = 0; i < keyPackages.getLength(); i++) { Node keyPackageNode = keyPackages.item(i); /** * Parse PSKC node structure */ String serialNo = ((Element) keyPackageNode).getElementsByTagName("SerialNo").item(0) .getTextContent(); if (validateSerial(serialNo)) { validSerials++; OtpSeed validSeed = new OtpSeed(); validSeed.setSerialNo(serialNo); validSeed.setCryptoId(String.format("KR-%06d", validSerials)); validSeed.setIssuer(issuer); validSeed.setKeyId(String.format("%08d", validSerials)); validSeed.setManufacturer(manufactuer); NodeList tempNode = ((Element) keyPackageNode).getElementsByTagName("xenc:CipherValue"); if (tempNode != null && tempNode.getLength() != 0) { validSeed.setCipherValue(((Element) tempNode.item(0)).getTextContent()); } seeds.add(validSeed); } } } /** * Creazione del nuovo XML */ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); doc.setXmlVersion("1.0"); Element keyContainer = doc.createElement("KeyContainer"); doc.appendChild(keyContainer); keyContainer.setAttribute("xmlns", "urn:ietf:params:xml:ns:keyprov:pskc"); keyContainer.setAttribute("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#"); keyContainer.setAttribute("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#"); keyContainer.setAttribute("Version", "1.0"); keyContainer.setAttribute("ID", "KC0001"); /** * Key Name */ Element encryptionKey = doc.createElement("EncryptionKey"); keyContainer.appendChild(encryptionKey); Element ds_keyName = doc.createElement("ds:KeyName"); encryptionKey.appendChild(ds_keyName); ds_keyName.setTextContent(this.preSharedKeyName); /** * MAC Method */ Element macMethod = doc.createElement("MACMethod"); keyContainer.appendChild(macMethod); macMethod.setAttribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#hmac-sha1"); /** * Mac Key */ Element macKey = doc.createElement("MACKey"); macMethod.appendChild(macKey); /** * EncryptionMethod */ Element encryptionMethod = doc.createElement("xenc:EncryptionMethod"); macKey.appendChild(encryptionMethod); encryptionMethod.setAttribute("Algorithm", "http://www.w3.org/2001/04/xmlenc#aes128-cbc"); /** * xenc:CipherData */ Element xenc_CipherData = doc.createElement("xenc:CipherData"); macKey.appendChild(xenc_CipherData); /** * xenc:CipherValue */ Element xenc_CipherValue = doc.createElement("xenc:CipherValue"); xenc_CipherData.appendChild(xenc_CipherValue); /** * Passo 1: Criptare la MAC Key */ String macSignature = Base64.encode(crypto.getAesCipheredMacKey()); xenc_CipherValue.setTextContent(macSignature); for (OtpSeed seed : seeds) { /** * Passo 2: Convertire il dato criptato */ byte[] reCipheredSecretBytes = crypto.convertRsaToAes(seed.getCipherValue()); seed.setCipherValue(Base64.encode(reCipheredSecretBytes)); /** * Passo 3: Firmare il dato criptato */ byte[] secretSignatureBytes = crypto.signCipheredSecret(reCipheredSecretBytes); seed.setValueMac(Base64.encode(secretSignatureBytes)); /** * KeyPackage */ Element keyPackageElement = doc.createElement("KeyPackage"); keyContainer.appendChild(keyPackageElement); /** * DeviceInfo */ Element deviceInfoElement = doc.createElement("DeviceInfo"); keyPackageElement.appendChild(deviceInfoElement); /** * Manufactuer */ Element manufactuerElement = doc.createElement("Manufactuer"); manufactuerElement.setTextContent(seed.getManufacturer()); deviceInfoElement.appendChild(manufactuerElement); /** * SerialNo */ Element serialNoElement = doc.createElement("SerialNo"); serialNoElement.setTextContent(seed.getSerialNo()); deviceInfoElement.appendChild(serialNoElement); /** * CryptoModuleInfo */ Element cryptoModuleInfoElement = doc.createElement("CryptoModuleInfo"); keyPackageElement.appendChild(cryptoModuleInfoElement); /** * ID */ Element idElement = doc.createElement("ID"); idElement.setTextContent(seed.getCryptoId()); cryptoModuleInfoElement.appendChild(idElement); /** * Key */ Element keyElement = doc.createElement("Key"); keyPackageElement.appendChild(keyElement); keyElement.setAttribute("Id", seed.getKeyId()); if (seed.getType().equals("TOTP")) { keyElement.setAttribute("Algorithm", "urn:ietf:params:xml:ns:keyprov:pskc:totp"); } else if (seed.getType().equals("HOTP")) { keyElement.setAttribute("Algorithm", "urn:ietf:params:xml:ns:keyprov:pskc:hotp"); } else { throw new Exception("OTP type not supported"); } /** * Issuer */ Element issuerElement = doc.createElement("Issuer"); issuerElement.setTextContent(seed.getIssuer()); keyElement.appendChild(issuerElement); /** * AlgorithmParameters */ Element algorithmParametersElement = doc.createElement("AlgorithmParameters"); keyElement.appendChild(algorithmParametersElement); /** * ResponseFormat */ Element responseFormatElement = doc.createElement("ResponseFormat"); algorithmParametersElement.appendChild(responseFormatElement); responseFormatElement.setAttribute("Length", seed.getLength()); responseFormatElement.setAttribute("Encoding", seed.getEncoding()); /** * Data */ Element dataElement = doc.createElement("Data"); keyElement.appendChild(dataElement); /** * Secret */ Element secretElement = doc.createElement("Secret"); dataElement.appendChild(secretElement); /** * EncryptedValue */ Element encryptedValueElement = doc.createElement("EncryptedValue"); secretElement.appendChild(encryptedValueElement); /** * xenc:EncryptionMethod */ Element encryptionMethodElement = doc.createElement("xenc:EncryptionMethod"); encryptedValueElement.appendChild(encryptionMethodElement); encryptionMethodElement.setAttribute("Algorithm", "http://www.w3.org/2001/04/xmlenc#aes128-cbc"); /** * xenc:CipherData */ Element cipherDataElement = doc.createElement("xenc:CipherData"); encryptedValueElement.appendChild(cipherDataElement); /** * xenc:CipherValue */ Element cipherValueElement = doc.createElement("xenc:CipherValue"); cipherValueElement.setTextContent(seed.getCipherValue()); cipherDataElement.appendChild(cipherValueElement); /** * ValueMAC */ Element valueMACElement = doc.createElement("ValueMAC"); valueMACElement.setTextContent(seed.getValueMac()); secretElement.appendChild(valueMACElement); /** * Counter */ Element counterElement = doc.createElement("Counter"); dataElement.appendChild(counterElement); /** * PlainValue */ Element counterPlainValueElement = doc.createElement("PlainValue"); counterPlainValueElement.setTextContent(seed.getCounter()); counterElement.appendChild(counterPlainValueElement); /** * TimeInterval */ Element timeIntervalElement = doc.createElement("TimeInterval"); dataElement.appendChild(timeIntervalElement); /** * PlainValue */ Element timeIntervalPlainValueElement = doc.createElement("PlainValue"); timeIntervalPlainValueElement.setTextContent(seed.getTimeInterval()); timeIntervalElement.appendChild(timeIntervalPlainValueElement); /** * Time */ Element timeElement = doc.createElement("Time"); dataElement.appendChild(timeElement); /** * PlainValue */ Element timePlainValueElement = doc.createElement("PlainValue"); timePlainValueElement.setTextContent(seed.getTime()); timeElement.appendChild(timePlainValueElement); } doc.normalizeDocument(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(fileOut)); transformer.transform(source, result); }
From source file:org.rdswicthboard.utils.rdf.oai.App.java
public static void main(String[] args) { // create the command line parser CommandLineParser parser = new DefaultParser(); // create the Options Options options = new Options(); options.addOption("i", PROPERTY_INPUT_FILE, true, "input RDF file"); options.addOption("o", PROPERTY_OUTPUT_FILE, true, "output OAI-PMH XML file (default is " + DEFAULT_OUTPUT_FILE + ")"); options.addOption("c", PROPERTY_CONFIG_FILE, true, "configuration file (" + PROPERTIES_FILE + ")"); options.addOption("s", PROPERTY_SET_SPEC, true, "set spec value (default is " + DEFAULT_SET_SPEC + ")"); options.addOption("I", PROPERTY_INPUT_ENCODING, true, "input file encoding (default is " + DEFAULT_ENCODING + ")"); options.addOption("O", PROPERTY_OUTPUT_ENCODING, true, "output file encoding (default is " + DEFAULT_ENCODING + ")"); options.addOption("f", PROPERTY_FORMAT_OUTPUT, false, "format output encoding"); options.addOption("h", PROPERTY_HELP, false, "print this message"); try {/*from w w w . j a v a2 s .c om*/ // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption(PROPERTY_HELP)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar rdf2oai-[verion].jar [PARAMETERS] [INPUT FILE] [OUTPUT FILE]", options); System.exit(0); } // variables to store program properties CompositeConfiguration config = new CompositeConfiguration(); config.setProperty(PROPERTY_OUTPUT_FILE, DEFAULT_OUTPUT_FILE); config.setProperty(PROPERTY_INPUT_ENCODING, DEFAULT_ENCODING); config.setProperty(PROPERTY_OUTPUT_ENCODING, DEFAULT_ENCODING); config.setProperty(PROPERTY_SET_SPEC, DEFAULT_SET_SPEC); config.setProperty(PROPERTY_FORMAT_OUTPUT, DEFAULT_FORMAT_OUTPUT); // check if arguments has input file properties if (line.hasOption(PROPERTY_CONFIG_FILE)) { // if it does, load the specified configuration file Path defaultConfig = Paths.get(line.getOptionValue(PROPERTY_CONFIG_FILE)); if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) { config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile())); } else throw new Exception("Invalid configuration file: " + defaultConfig.toString()); } else { // if it not, try to load default configurationfile Path defaultConfig = Paths.get(PROPERTIES_FILE); if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) { config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile())); } } // check if arguments has input file if (line.hasOption(PROPERTY_INPUT_FILE)) config.setProperty(PROPERTY_INPUT_FILE, line.getOptionValue(PROPERTY_INPUT_FILE)); // check if arguments has output file if (line.hasOption(PROPERTY_OUTPUT_FILE)) config.setProperty(PROPERTY_OUTPUT_FILE, line.getOptionValue(PROPERTY_OUTPUT_FILE)); // check if arguments has set spec name if (line.hasOption(PROPERTY_SET_SPEC)) config.setProperty(PROPERTY_SET_SPEC, line.getOptionValue(PROPERTY_SET_SPEC)); // check if arguments has input encoding if (line.hasOption(PROPERTY_INPUT_ENCODING)) config.setProperty(PROPERTY_INPUT_ENCODING, line.getOptionValue(PROPERTY_INPUT_ENCODING)); // check if arguments has output encoding if (line.hasOption(PROPERTY_OUTPUT_ENCODING)) config.setProperty(PROPERTY_OUTPUT_ENCODING, line.getOptionValue(PROPERTY_OUTPUT_ENCODING)); // check if arguments has output encoding if (line.hasOption(PROPERTY_FORMAT_OUTPUT)) config.setProperty(PROPERTY_FORMAT_OUTPUT, "yes"); // check if arguments has input file without a key if (line.getArgs().length > 0) { config.setProperty(PROPERTY_INPUT_FILE, line.getArgs()[0]); // check if arguments has output file without a key if (line.getArgs().length > 1) { config.setProperty(PROPERTY_OUTPUT_FILE, line.getArgs()[1]); // check if there is too many arguments if (line.getArgs().length > 2) throw new Exception("Too many arguments"); } } // The program has default output file, but input file must be presented if (!config.containsKey(PROPERTY_INPUT_FILE)) throw new Exception("Please specify input file"); // extract input file String inputFile = config.getString(PROPERTY_INPUT_FILE); // extract output file String outputFile = config.getString(PROPERTY_OUTPUT_FILE); // extract set spec String setSpecName = config.getString(PROPERTY_SET_SPEC); // extract encoding String inputEncoding = config.getString(PROPERTY_INPUT_ENCODING); String outputEncoding = config.getString(PROPERTY_OUTPUT_ENCODING); boolean formatOutput = config.getBoolean(PROPERTY_FORMAT_OUTPUT); // test if source is an regular file and it is readable Path source = Paths.get(inputFile); if (!Files.isRegularFile(source)) throw new Exception("The input file: " + source.toString() + " is not an regular file"); if (!Files.isReadable(source)) throw new Exception("The input file: " + source.toString() + " is not readable"); Path target = Paths.get(outputFile); if (Files.exists(target)) { if (!Files.isRegularFile(target)) throw new Exception("The output file: " + target.toString() + " is not an regular file"); if (!Files.isWritable(target)) throw new Exception("The output file: " + target.toString() + " is not writable"); } // create and setup document builder factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // create new document builder DocumentBuilder builder = factory.newDocumentBuilder(); // create oai document Document oai = builder.newDocument(); // set document version oai.setXmlVersion("1.0"); oai.setXmlStandalone(true); // create root OAI-PMH element Element oaiPmh = oai.createElement("OAI-PMH"); // set document namespaces oaiPmh.setAttribute("xmlns", "http://www.openarchives.org/OAI/2.0/"); oaiPmh.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); oaiPmh.setAttribute("xsi:schemaLocation", "http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd"); // append root node oai.appendChild(oaiPmh); // create responseDate element Element responseDate = oai.createElement("responseDate"); // create simple date format DateFormat dateFormat = new SimpleDateFormat(TIME_FORMAT); // generate date String date = dateFormat.format(new Date()); // set current date and time responseDate.setTextContent(date); oaiPmh.appendChild(responseDate); Element listRecords = oai.createElement("ListRecords"); oaiPmh.appendChild(listRecords); // create xpath factory XPathFactory xPathfactory = XPathFactory.newInstance(); // create namespace context NamespaceContext namespaceContext = new NamespaceContext() { public String getNamespaceURI(String prefix) { if (prefix.equals("rdf")) return RDF_NAMESPACE; else if (prefix.equals("rns")) return RNF_NAMESPACE; else return null; } @Override public Iterator<?> getPrefixes(String val) { throw new IllegalAccessError("Not implemented!"); } @Override public String getPrefix(String uri) { throw new IllegalAccessError("Not implemented!"); } }; // create xpath object XPath xpath = xPathfactory.newXPath(); // set namespace contex xpath.setNamespaceContext(namespaceContext); // create XPath expressions XPathExpression idExpr = xpath.compile("/rdf:RDF/rns:Researcher/@rdf:about"); XPathExpression emptyExpr = xpath.compile("//text()[normalize-space(.) = '']"); // create RegEx patterns Pattern pattern = Pattern.compile( "<\\?xml\\s+version=\"[\\d\\.]+\"\\s*\\?>\\s*<\\s*rdf:RDF[^>]*>[\\s\\S]*?<\\s*\\/\\s*rdf:RDF\\s*>"); // read file into a string String content = new String(Files.readAllBytes(source), inputEncoding); Matcher matcher = pattern.matcher(content); // process all records while (matcher.find()) { // convert string to input stream ByteArrayInputStream input = new ByteArrayInputStream( matcher.group().getBytes(StandardCharsets.UTF_8.toString())); // parse the xml document Document doc = builder.parse(input); // remove all spaces NodeList emptyNodes = (NodeList) emptyExpr.evaluate(doc, XPathConstants.NODESET); // Remove each empty text node from document. for (int i = 0; i < emptyNodes.getLength(); i++) { Node emptyTextNode = emptyNodes.item(i); emptyTextNode.getParentNode().removeChild(emptyTextNode); } // obtain researcher id String id = (String) idExpr.evaluate(doc, XPathConstants.STRING); if (StringUtils.isEmpty(id)) throw new Exception("The record identifier can not be empty"); // create record element Element record = oai.createElement("record"); listRecords.appendChild(record); // create header element Element header = oai.createElement("header"); record.appendChild(header); // create identifier element Element identifier = oai.createElement("identifier"); identifier.setTextContent(id); header.appendChild(identifier); // create datestamp element Element datestamp = oai.createElement("datestamp"); datestamp.setTextContent(date); header.appendChild(datestamp); // create set spec element if it exists if (!StringUtils.isEmpty(setSpecName)) { Element setSpec = oai.createElement("setSpec"); setSpec.setTextContent(setSpecName); header.appendChild(setSpec); } // create metadata element Element metadata = oai.createElement("metadata"); record.appendChild(metadata); // import the record metadata.appendChild(oai.importNode(doc.getDocumentElement(), true)); } // create transformer factory TransformerFactory transformerFactory = TransformerFactory.newInstance(); // create transformer Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding); if (formatOutput) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } else transformer.setOutputProperty(OutputKeys.INDENT, "no"); // create dom source DOMSource oaiSource = new DOMSource(oai); // create stream result StreamResult result = new StreamResult(target.toFile()); // stream xml to file transformer.transform(oaiSource, result); // optional stream xml to console for testing //StreamResult consoleResult = new StreamResult(System.out); //transformer.transform(oaiSource, consoleResult); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); //e.printStackTrace(); System.exit(1); } }
From source file:org.xwoot.wikiContentManager.XWikiSwizzleClient.XwikiSwizzleClient.java
public static Document toXmlStatic(String pageId, String href, Map<String, String> pageMap) throws WikiContentManagerException { if (pageMap == null) { return null; }/*from w w w .j a va 2 s . c om*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new WikiContentManagerException(e); } Document document = builder.newDocument(); // Proprits du DOM document.setXmlVersion("1.0"); document.setXmlStandalone(true); // Cration de l'arborescence du DOM Element racine = document.createElement(XML_NODE_NAME_XWIKIPAGE); racine.setAttribute(XML_ATTRIBUTE_NAME_XWIKIPAGEID, pageId); racine.setAttribute(XML_ATTRIBUTE_NAME_HREF, href); Element entries = document.createElement(XML_NODE_NAME_ENTRIES); Iterator i = pageMap.entrySet().iterator(); Element entry = null; Element key = null; Element value = null; while (i.hasNext()) { Entry k = (Entry) i.next(); entry = document.createElement(XML_NODE_NAME_ENTRY); key = document.createElement(XML_NODE_NAME_ENTRY_KEY); key.appendChild(document.createTextNode((String) k.getKey())); entry.appendChild(key); value = document.createElement(XML_NODE_NAME_ENTRY_VALUE); value.appendChild(document.createTextNode((String) k.getValue())); entry.appendChild(value); entries.appendChild(entry); } racine.appendChild(entries); document.appendChild(racine); document.normalizeDocument(); return document; }
From source file:org.xwoot.wikiContentManager.XWikiSwizzleClient.XwikiSwizzleClient.java
public static Document PageListToXmlStatic(String pagesHRef, List<String> list) throws WikiContentManagerException { if (list != null) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder;// w w w.j a va 2s . c om try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new WikiContentManagerException(e); } Document document = builder.newDocument(); // Proprits du DOM document.setXmlVersion("1.0"); document.setXmlStandalone(true); // Cration de l'arborescence du DOM Element racine = document.createElement(WikiContentManager.XML_NODE_NAME_XWIKIPAGELIST); racine.setAttribute(WikiContentManager.XML_ATTRIBUTE_NAME_LISTSIZE, String.valueOf(list.size())); Iterator i = list.iterator(); Element page = null; while (i.hasNext()) { String k = (String) i.next(); page = document.createElement(WikiContentManager.XML_NODE_NAME_XWIKIPAGE); page.setAttribute(WikiContentManager.XML_ATTRIBUTE_NAME_XWIKIPAGEID, k); page.setAttribute(WikiContentManager.XML_ATTRIBUTE_NAME_HREF, pagesHRef + "/" + k); racine.appendChild(page); } document.appendChild(racine); document.normalizeDocument(); return document; } return null; }