List of usage examples for javax.xml.parsers DocumentBuilder getDOMImplementation
public abstract DOMImplementation getDOMImplementation();
From source file:com.CodeSeance.JSeance.CodeGenXML.DependencyTracking.DependencyManager.java
public void commit() { try {// w w w .j a v a 2 s . c om // Build the XML representation DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); DOMImplementation domImplementation = documentBuilder.getDOMImplementation(); Document document = domImplementation.createDocument(null, "JSeanceDependencies", null); Element rootNode = document.getDocumentElement(); for (String fileName : templateDependencies.keySet()) { Element templateChild = templateDependencies.get(fileName).serialize(document); rootNode.appendChild(templateChild); } // Write the XML Document DOMSource domSource = new DOMSource(document); StreamResult streamResult = new StreamResult(dependencyFile); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); } catch (Exception ex) { // Wrap Exception with RuntimeException since caller won't be able to handle it throw new RuntimeException( "Unexpected Exception while building dependencies document: " + ex.getClass(), ex); } }
From source file:eu.apenet.dpt.standalone.gui.hgcreation.LevelTreeActions.java
public File createXML(TreeModel model, HashMap<String, String> paramMap, String countryCode, String globalIdentifier) { CLevelTreeObject obj = (CLevelTreeObject) ((DefaultMutableTreeNode) model.getRoot()).getUserObject(); try {// ww w. j av a2 s . co m DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); DOMImplementation domImplementation = builder.getDOMImplementation(); Document doc = domImplementation.createDocument(null, null, null); Element root = createArchdesc(doc, model, model.getRoot(), paramMap, obj.getId(), obj.getName()); doc.appendChild(root); TransformerFactory tf = TransformerFactory.newInstance(); Transformer output = tf.newTransformer(); output.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes"); output.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes"); output.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); output.transform(new DOMSource(doc.getFirstChild()), new StreamResult(new File(Utilities.TEMP_DIR + ".hg_creation.xml"))); File outputFile = new File(Utilities.TEMP_DIR + "temp_HG.xml"); File finalFile = new File( Utilities.TEMP_DIR + "Holdings_Guide_" + globalIdentifier + "_" + obj.getId() + ".xml"); finalFile.deleteOnExit(); FileUtils.writeStringToFile(outputFile, HoldingsGuideCreationUtils.eadDeclaration(obj.getName(), obj.getId(), countryCode, globalIdentifier, DataPreparationToolGUI.VERSION_NB), "UTF-8"); fileUtil.writeToFile(fileUtil.readFileAsString_linebreak(Utilities.TEMP_DIR + ".hg_creation.xml"), Utilities.TEMP_DIR + outputFile.getName(), true); fileUtil.writeToFile(HoldingsGuideCreationUtils.endDeclaration(), Utilities.TEMP_DIR + outputFile.getName(), true); TransformationTool.createTransformation(fileUtil.readFileAsInputStream(outputFile), finalFile, Utilities.BEFORE_XSL_FILE, null, true, true, null, true, null); outputFile.delete(); return finalFile; } catch (Exception e) { LOG.error("Error", e); } return null; }
From source file:de.ingrid.interfaces.csw.server.cswt.impl.GenericServerCSWT.java
private Document createErrorResponse(CSWTransactionResult result) throws ParserConfigurationException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true);/*from w w w . j a v a2 s .c o m*/ DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); DOMImplementation domImpl = docBuilder.getDOMImplementation(); Document doc = domImpl.createDocument(RESPONSE_NAMESPACE, "ows:ExceptionReport", null); // create summary Element exception = doc.createElementNS(RESPONSE_NAMESPACE, "ows:Exception"); exception.setAttribute("exceptionCode", "NoApplicableCode"); doc.getDocumentElement().appendChild(exception); exception.appendChild(doc.createElementNS(RESPONSE_NAMESPACE, "ows:ExceptionText")) .appendChild(doc.createTextNode("Cannot process transaction: " + result.getErrorMessage())); return doc; }
From source file:de.ingrid.interfaces.csw.server.cswt.impl.GenericServerCSWT.java
private Document createSummaryResponse(CSWTransactionResult result) throws ParserConfigurationException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true);/* w w w. j a v a 2 s . c o m*/ DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); DOMImplementation domImpl = docBuilder.getDOMImplementation(); Document doc = domImpl.createDocument(RESPONSE_NAMESPACE, "csw:TransactionResponse", null); // create summary Element summary = doc.createElementNS(RESPONSE_NAMESPACE, "csw:TransactionSummary"); summary.setAttribute("requestId", result.getRequestId()); doc.getDocumentElement().appendChild(summary); int inserts = result.getNumberOfInserts(); summary.appendChild(doc.createElementNS(RESPONSE_NAMESPACE, "totalInserted")) .appendChild(doc.createTextNode(String.valueOf(inserts))); int updates = result.getNumberOfUpdates(); summary.appendChild(doc.createElementNS(RESPONSE_NAMESPACE, "totalUpdated")) .appendChild(doc.createTextNode(String.valueOf(updates))); int deletes = result.getNumberOfDeletes(); summary.appendChild(doc.createElementNS(RESPONSE_NAMESPACE, "totalDeleted")) .appendChild(doc.createTextNode(String.valueOf(deletes))); // add insert results // if (inserts > 0) { // Element insertResult = doc.createElementNS(RESPONSE_NAMESPACE, "csw:InsertResult"); // doc.getDocumentElement().appendChild(insertResult); // for (ActionResult curResult : result.getInsertResults()) { // List<CSWRecord> records = curResult.getRecords(); // if (records.size() > 0) { // Node recordNode = records.get(0).getDocument().getFirstChild(); // Action action = curResult.getAction(); // String handle = action.getHandle(); // if (handle != null && recordNode instanceof Element) { // ((Element)recordNode).setAttribute("handle", handle); // } // doc.adoptNode(recordNode); // insertResult.appendChild(recordNode); // } // } // } return doc; }
From source file:net.sourceforge.eclipsetrader.core.internal.TradingSystemRepository.java
void saveTradingSystems() { try {/*from w w w . j a v a 2 s. com*/ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.getDOMImplementation().createDocument(null, "data", null); //$NON-NLS-1$ Element root = document.getDocumentElement(); root.setAttribute("nextId", String.valueOf(tsNextId)); //$NON-NLS-1$ root.setAttribute("nextGroupId", String.valueOf(tsGroupNextId)); //$NON-NLS-1$ for (Iterator iter = tsGroupMap.values().iterator(); iter.hasNext();) { TradingSystemGroup group = (TradingSystemGroup) iter.next(); if (group.getParent() == null) saveGroup(group, document, root); } for (Iterator iter = tsMap.values().iterator(); iter.hasNext();) { TradingSystem system = (TradingSystem) iter.next(); if (system.getGroup() == null) saveSystem(system, document, root); } repository.saveDocument(document, "", "ts.xml"); //$NON-NLS-1$ //$NON-NLS-2$ } catch (Exception e) { logger.error(e.toString(), e); } }
From source file:org.apache.camel.component.cm.CMSenderOneMessageImpl.java
private String createXml(final CMMessage message) { try {//from w w w.j a va2 s . co m final ByteArrayOutputStream xml = new ByteArrayOutputStream(); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // Get the DocumentBuilder final DocumentBuilder docBuilder = factory.newDocumentBuilder(); // Create blank DOM Document final DOMImplementation impl = docBuilder.getDOMImplementation(); final Document doc = impl.createDocument(null, "MESSAGES", null); // ROOT Element es MESSAGES final Element root = doc.getDocumentElement(); // AUTHENTICATION element final Element authenticationElement = doc.createElement("AUTHENTICATION"); final Element productTokenElement = doc.createElement("PRODUCTTOKEN"); authenticationElement.appendChild(productTokenElement); final Text productTokenValue = doc.createTextNode("" + productToken); productTokenElement.appendChild(productTokenValue); root.appendChild(authenticationElement); // MSG Element final Element msgElement = doc.createElement("MSG"); root.appendChild(msgElement); // <FROM>VALUE</FROM> final Element fromElement = doc.createElement("FROM"); fromElement.appendChild(doc.createTextNode(message.getSender())); msgElement.appendChild(fromElement); // <BODY>VALUE</BODY> final Element bodyElement = doc.createElement("BODY"); bodyElement.appendChild(doc.createTextNode(message.getMessage())); msgElement.appendChild(bodyElement); // <TO>VALUE</TO> final Element toElement = doc.createElement("TO"); toElement.appendChild(doc.createTextNode(message.getPhoneNumber())); msgElement.appendChild(toElement); // <DCS>VALUE</DCS> - if UNICODE - messageOut.isGSM338Enc // false if (message.isUnicode()) { final Element dcsElement = doc.createElement("DCS"); dcsElement.appendChild(doc.createTextNode("8")); msgElement.appendChild(dcsElement); } // <REFERENCE>VALUE</REFERENCE> -Alfanum final String id = message.getIdAsString(); if (id != null && !id.isEmpty()) { final Element refElement = doc.createElement("REFERENCE"); refElement.appendChild(doc.createTextNode("" + message.getIdAsString())); msgElement.appendChild(refElement); } // <MINIMUMNUMBEROFMESSAGEPARTS>1</MINIMUMNUMBEROFMESSAGEPARTS> // <MAXIMUMNUMBEROFMESSAGEPARTS>8</MAXIMUMNUMBEROFMESSAGEPARTS> if (message.isMultipart()) { final Element minMessagePartsElement = doc.createElement("MINIMUMNUMBEROFMESSAGEPARTS"); minMessagePartsElement.appendChild(doc.createTextNode("1")); msgElement.appendChild(minMessagePartsElement); final Element maxMessagePartsElement = doc.createElement("MAXIMUMNUMBEROFMESSAGEPARTS"); maxMessagePartsElement.appendChild(doc.createTextNode(Integer.toString(message.getMultiparts()))); msgElement.appendChild(maxMessagePartsElement); } // Creatate XML as String final Transformer aTransformer = TransformerFactory.newInstance().newTransformer(); aTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); final Source src = new DOMSource(doc); final Result dest = new StreamResult(xml); aTransformer.transform(src, dest); return xml.toString(); } catch (final TransformerException e) { LOG.error("Cant serialize CMMessage {}: ", message, e); throw new XMLConstructionException(e); } catch (final ParserConfigurationException e) { LOG.error("Cant serialize CMMessage {}: ", message, e); throw new XMLConstructionException(e); } }
From source file:de.ingrid.interfaces.csw.server.impl.GenericServer.java
@Override public Document process(GetRecordByIdRequest request) throws CSWException { try {// w ww . j a v a 2s . c o m CSWQuery query = request.getQuery(); CSWRecordResults result = this.searcher.search(query); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); DOMImplementation domImpl = docBuilder.getDOMImplementation(); Document doc = domImpl.createDocument(RESPONSE_NAMESPACE, "csw:GetRecordByIdResponse", null); if (result.getResults() != null) { Element rootElement = doc.getDocumentElement(); for (CSWRecord record : result.getResults()) { Node recordNode = record.getDocument().getFirstChild(); doc.adoptNode(recordNode); rootElement.appendChild(recordNode); } } return doc; } catch (CSWException ex) { log.error("An error occured processing GetRecordByIdRequest", ex); throw ex; } catch (Exception ex) { log.error("An error occured processing GetRecordByIdRequest", ex); throw new CSWException("An error occured processing GetRecordByIdRequest"); } }
From source file:de.ingrid.interfaces.csw.server.impl.GenericServer.java
@Override public Document process(GetRecordsRequest request) throws CSWException { try {/*from ww w.ja v a 2s . co m*/ CSWQuery query = request.getQuery(); CSWRecordResults result = this.searcher.search(query); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); DOMImplementation domImpl = docBuilder.getDOMImplementation(); Document doc = domImpl.createDocument(RESPONSE_NAMESPACE, "csw:GetRecordsResponse", null); Element searchStatus = doc.createElementNS(RESPONSE_NAMESPACE, "csw:SearchStatus"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("ThreeLetterISO8601TimeZone")); searchStatus.setAttribute("timestamp", df.format(new Date())); doc.getDocumentElement().appendChild(searchStatus); Element searchResults = doc.createElementNS(RESPONSE_NAMESPACE, "csw:SearchResults"); searchResults.setAttribute("elementSet", request.getQuery().getElementSetName().name().toLowerCase()); searchResults.setAttribute("numberOfRecordsMatched", String.valueOf(result.getTotalHits())); searchResults.setAttribute("numberOfRecordsReturned", String.valueOf((result.getResults() == null) ? 0 : result.getResults().size())); int nextRecord = query.getStartPosition() + ((result.getResults() == null) ? 0 : result.getResults().size()); if (nextRecord > result.getTotalHits()) { nextRecord = 0; } searchResults.setAttribute("nextRecord", String.valueOf(nextRecord)); doc.getDocumentElement().appendChild(searchResults); if (query.getResultType() == ResultType.RESULTS && result.getResults() != null) { for (CSWRecord record : result.getResults()) { Node recordNode = record.getDocument().getFirstChild(); doc.adoptNode(recordNode); searchResults.appendChild(recordNode); } } return doc; } catch (CSWException ex) { log.error("An error occured processing GetRecordsRequest", ex); throw ex; } catch (Exception ex) { log.error("An error occured processing GetRecordsRequest", ex); throw new CSWException("An error occured processing GetRecordsRequest"); } }
From source file:net.sourceforge.eclipsetrader.ats.Repository.java
public void save() { try {/*from w w w. ja v a 2 s. c o m*/ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.getDOMImplementation().createDocument(null, "data", null); Element root = document.getDocumentElement(); root.setAttribute("nextId", String.valueOf(nextId)); for (Iterator iter = systems.iterator(); iter.hasNext();) { TradingSystem system = (TradingSystem) iter.next(); Element element = document.createElement("system"); element.setAttribute("id", String.valueOf(system.getId())); Element node = document.createElement("name"); node.appendChild(document.createTextNode(system.getName())); element.appendChild(node); if (system.getAccount().getId() != null) { node = document.createElement("account"); node.appendChild(document.createTextNode(String.valueOf(system.getAccount().getId()))); element.appendChild(node); } node = document.createElement("tradingProvider"); node.appendChild(document.createTextNode(system.getTradingProviderId())); element.appendChild(node); if (system.getMoneyManager() != null) { node = document.createElement("moneyManager"); saveComponent(system.getMoneyManager(), document, node); element.appendChild(node); } for (Iterator paramIter = system.getParams().keySet().iterator(); paramIter.hasNext();) { String key = (String) paramIter.next(); node = document.createElement("param"); node.setAttribute("key", key); node.setAttribute("value", (String) system.getParams().get(key)); element.appendChild(node); } for (Iterator iter2 = system.getStrategies().iterator(); iter2.hasNext();) saveStrategy((Strategy) iter2.next(), document, element); root.appendChild(element); } saveDocument(document, "", "systems.xml"); } catch (Exception e) { log.error(e.toString(), e); } }
From source file:net.sourceforge.eclipsetrader.core.CurrencyConverter.java
private void save() { try {//ww w.j a va 2 s . c o m DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.getDOMImplementation().createDocument(null, "data", null); //$NON-NLS-1$ Element root = document.getDocumentElement(); for (Iterator iter = currencies.iterator(); iter.hasNext();) { Element node = document.createElement("currency"); //$NON-NLS-1$ node.appendChild(document.createTextNode((String) iter.next())); root.appendChild(node); } for (Iterator iter = map.keySet().iterator(); iter.hasNext();) { String symbol = (String) iter.next(); Element node = document.createElement("conversion"); //$NON-NLS-1$ node.setAttribute("symbol", symbol); //$NON-NLS-1$ node.setAttribute("ratio", String.valueOf(map.get(symbol))); //$NON-NLS-1$ saveHistory(node, symbol); root.appendChild(node); } TransformerFactory factory = TransformerFactory.newInstance(); try { factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$ } catch (Exception e) { } Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$ DOMSource source = new DOMSource(document); File file = new File(Platform.getLocation().toFile(), "currencies.xml"); //$NON-NLS-1$ BufferedWriter out = new BufferedWriter(new FileWriter(file)); StreamResult result = new StreamResult(out); transformer.transform(source, result); out.flush(); out.close(); } catch (Exception e) { logger.error(e, e); } }