List of usage examples for org.w3c.dom Document createTextNode
public Text createTextNode(String data);
Text
node given the specified string. From source file:Interface.MainJFrame.java
private void btnXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXMLActionPerformed // TODO add your handling code here: try {/*w ww . ja va 2 s.c om*/ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("Employees"); doc.appendChild(rootElement); // staff elements String empTitle = txtEmployeeType.getText().trim(); empTitle = empTitle.replace(" ", ""); Element staff = doc.createElement(empTitle); rootElement.appendChild(staff); // set attribute to staff element Attr attr = doc.createAttribute("ID"); attr.setValue(txtEmployeeID.getText().trim()); staff.setAttributeNode(attr); // shorten way // staff.setAttribute("id", "1"); // FullName elements Element FulllName = doc.createElement("FulllName"); FulllName.appendChild(doc.createTextNode(txtFullName.getText().trim())); staff.appendChild(FulllName); // Phone elements Element Phone = doc.createElement("PhoneNumber"); Phone.appendChild(doc.createTextNode(txtPhoneNumber.getText().trim())); staff.appendChild(Phone); // Address elements Element Address = doc.createElement("Address"); Address.appendChild(doc.createTextNode(txtAddress.getText().trim())); staff.appendChild(Address); // Title elements Element Title = doc.createElement("Tile"); Title.appendChild(doc.createTextNode(txtEmployeeType.getText().trim())); staff.appendChild(Title); // PayCategory elements Element PayCategory = doc.createElement("PayCategory"); PayCategory.appendChild(doc.createTextNode(txtPayCategory.getText().trim())); staff.appendChild(PayCategory); // Salary elements Element Salary = doc.createElement("Salary"); Salary.appendChild(doc.createTextNode(txtSalary.getText().trim())); staff.appendChild(Salary); // Hours elements String hours = txtHours.getText().trim(); if (txtHours.getText().equalsIgnoreCase("") || hours == null) { hours = "null"; } Element Hours = doc.createElement("Hours"); Hours.appendChild(doc.createTextNode(hours)); staff.appendChild(Hours); // Bonus elements Element Bonus = doc.createElement("Bonus"); Bonus.appendChild(doc.createTextNode(txtBonuses.getText().trim())); staff.appendChild(Bonus); // Total elements Element Total = doc.createElement("Total"); Total.appendChild(doc.createTextNode(txtTotal.getText().trim())); staff.appendChild(Total); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("XMLOutput")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } }
From source file:com.amalto.core.util.Util.java
public static void setUserProperty(Document user, String name, String value) throws Exception { if (name == null) { return;/*w w w .j a va2s .co m*/ } NodeList properties = Util.getNodeList(user, "//properties"); //$NON-NLS-1$ Element propertiesElement = null; if (properties == null || properties.getLength() == 0) { propertiesElement = user.createElement("properties"); //$NON-NLS-1$ user.getDocumentElement().appendChild(propertiesElement); } else { propertiesElement = (Element) properties.item(0); } NodeList props = Util.getNodeList(propertiesElement, "//property"); //$NON-NLS-1$ boolean propertyFound = false; if (props != null) { for (int i = 0; i < props.getLength(); i++) { Node node = props.item(i); if (name.equals(getFirstTextNode(node, "name"))) { //$NON-NLS-1$ propertyFound = true; if (getFirstTextNode(node, "value") == null) { //$NON-NLS-1$ getNodeList(node, "value").item(0).appendChild(user.createTextNode(value)); //$NON-NLS-1$ } else { getNodeList(node, "value").item(0).getFirstChild().setNodeValue(value); //$NON-NLS-1$ } } } } if (!propertyFound) { Element propertyElement = user.createElement("property"); //$NON-NLS-1$ propertiesElement.appendChild(propertyElement); Element nameElement = user.createElement("name"); //$NON-NLS-1$ nameElement.setTextContent(name); propertyElement.appendChild(nameElement); Element valueElement = user.createElement("value"); //$NON-NLS-1$ valueElement.setTextContent(value); propertyElement.appendChild(valueElement); } }
From source file:com.datatorrent.stram.client.DTConfiguration.java
public void writeToFile(File file, Scope scope, String comment) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); Date date = new Date(); Document doc; try {// www.ja va 2 s .co m doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); } catch (ParserConfigurationException ex) { throw new RuntimeException(ex); } Element rootElement = doc.createElement("configuration"); rootElement.appendChild( doc.createComment(" WARNING: Do not edit this file. Your changes will be overwritten. ")); rootElement.appendChild(doc.createComment(" Written by dtgateway on " + sdf.format(date))); rootElement.appendChild(doc.createComment(" " + comment + " ")); doc.appendChild(rootElement); for (Map.Entry<String, ValueEntry> entry : map.entrySet()) { ValueEntry valueEntry = entry.getValue(); if (scope == null || valueEntry.scope == scope) { Element property = doc.createElement("property"); rootElement.appendChild(property); Element name = doc.createElement("name"); name.appendChild(doc.createTextNode(entry.getKey())); property.appendChild(name); Element value = doc.createElement("value"); value.appendChild(doc.createTextNode(valueEntry.value)); property.appendChild(value); if (valueEntry.description != null) { Element description = doc.createElement("description"); description.appendChild(doc.createTextNode(valueEntry.description)); property.appendChild(description); } if (valueEntry.isFinal) { Element isFinal = doc.createElement("final"); isFinal.appendChild(doc.createTextNode("true")); property.appendChild(isFinal); } } } rootElement.appendChild( doc.createComment(" WARNING: Do not edit this file. Your changes will be overwritten. ")); // write the content into xml file DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(file); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(source, result); } catch (TransformerConfigurationException ex) { throw new RuntimeException(ex); } catch (TransformerException ex) { throw new IOException(ex); } }
From source file:com.centeractive.ws.builder.soap.XmlUtils.java
public static String createJdbcXmlResult(Statement statement) throws SQLException, ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document xmlDocumentResult = builder.newDocument(); Element resultsElement = xmlDocumentResult.createElement("Results"); xmlDocumentResult.appendChild(resultsElement); if (statement != null) { ResultSet resultSet = statement.getResultSet(); if (resultSet != null) { resultSet.setFetchSize(statement.getFetchSize()); xmlDocumentResult = addResultSetXmlPart(resultsElement, resultSet, xmlDocumentResult); while (statement.getMoreResults()) { xmlDocumentResult = addResultSetXmlPart(resultsElement, statement.getResultSet(), xmlDocumentResult); }/* ww w . jav a 2s .c o m*/ } else { Element errorElement = xmlDocumentResult.createElement("UpdateCount"); errorElement .appendChild(xmlDocumentResult.createTextNode(String.valueOf(statement.getUpdateCount()))); resultsElement.appendChild(errorElement); } } StringWriter out = new StringWriter(); OutputFormat outputFormat = new OutputFormat(xmlDocumentResult); outputFormat.setOmitComments(true); outputFormat.setOmitDocumentType(true); outputFormat.setOmitXMLDeclaration(true); // outputFormat.setLineSeparator( "\n" ); // add this line // // outputFormat.setPreserveSpace( true ); outputFormat.setIndent(3); outputFormat.setIndenting(true); try { XMLSerializer serializer = new XMLSerializer(new PrintWriter(out), outputFormat); serializer.asDOMSerializer(); serializer.serialize(xmlDocumentResult); } catch (IOException e) { throw new SoapBuilderException(e); } return out.toString(); }
From source file:com.zacwolf.commons.wbxcon.WBXCONorg.java
/** * Creates a new WebExConnect User Account.<br /> * <br />/*from ww w . ja v a 2 s .c o m*/ * cmd=execute<br /> * task=ProvisionUserComplete<br /> * * @param account a <code>WBXCONuser</code> object that represents a new user * @param password a String password to use as the initial password for the new account * @param sendWelcomeEmail a true/false flag that determine if WebEx should send the normal Welcome Email to the new user * @throws WBXCONexception */ final WBXCONuser.WBXCONUID restapiAccountCreate(final WBXCONuser account, final String pass, final boolean sendWelcomeEmail) throws WBXCONexception { final List<NameValuePair> params; try { final Document doc = account.marshallXML(); final Element orgID = doc.createElement("orgID"); orgID.appendChild(doc.createTextNode(this.orgID)); final Element ISProviderID = doc.createElement("ISProviderID"); ISProviderID.appendChild(doc.createTextNode("WBX")); final Element ISProviders = doc.createElement("ISProviders"); ISProviders.appendChild(ISProviderID); final Element password = doc.createElement("password"); password.appendChild(doc.createTextNode(pass)); final Node user = doc.getElementsByTagName("user").item(0); user.appendChild(orgID); user.appendChild(ISProviders); user.appendChild(password); if (!sendWelcomeEmail) { final Element isSendCPIPMail = doc.createElement("isSendCPIPMail"); isSendCPIPMail.appendChild(doc.createTextNode("false")); user.appendChild(isSendCPIPMail); } params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("cmd", "execute")); params.add(new BasicNameValuePair("task", "ProvisionUserComplete")); params.add(new BasicNameValuePair("xml", documentToXMLstring(user))); } catch (final Exception e) { throw new WBXCONexception(e); } return new WBXCONuser.WBXCONUID(documentGetTextContentByTagName(executeQueued(params), "userID")); }
From source file:org.shareok.data.sagedata.SageJournalDataProcessorAbstract.java
@Override /** /* w w w . j a v a 2s .c o m*/ * Convert the article data to dublin core xml metadata and save the the file * * @param String fileName : the root folder contains all the uploading article data */ public void exportXmlByJournalData(String fileName) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("dublin_core"); doc.appendChild(rootElement); // Add the type node: Element element = doc.createElement("dcvalue"); element.appendChild(doc.createTextNode("Research Article")); rootElement.appendChild(element); Attr attr = doc.createAttribute("element"); attr.setValue("type"); element.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); element.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); element.setAttributeNode(attr); // Add the abstract node: String abs = journalData.getAbstractText(); if (null != abs) { Element elementAbs = doc.createElement("dcvalue"); elementAbs.appendChild(doc.createTextNode(abs)); rootElement.appendChild(elementAbs); attr = doc.createAttribute("element"); attr.setValue("description"); elementAbs.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementAbs.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("abstract"); elementAbs.setAttributeNode(attr); } // Add the language node: String lang = journalData.getLanguage(); if (null != lang) { Element elementLang = doc.createElement("dcvalue"); elementLang.appendChild(doc.createTextNode(lang)); rootElement.appendChild(elementLang); attr = doc.createAttribute("element"); attr.setValue("language"); elementLang.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementLang.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("iso"); elementLang.setAttributeNode(attr); } // Add the title node: String tit = journalData.getTitle(); if (null != tit) { Element elementTitle = doc.createElement("dcvalue"); elementTitle.appendChild(doc.createTextNode(tit)); rootElement.appendChild(elementTitle); attr = doc.createAttribute("element"); attr.setValue("title"); elementTitle.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementTitle.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementTitle.setAttributeNode(attr); } // Add the available date node: // Element elementAvailable = doc.createElement("dcvalue"); // elementAvailable.appendChild(doc.createTextNode(getDateAvailable().toString())); // rootElement.appendChild(elementAvailable); // // attr = doc.createAttribute("element"); // attr.setValue("date"); // elementAvailable.setAttributeNode(attr); // // attr = doc.createAttribute("qualifier"); // attr.setValue("available"); // elementAvailable.setAttributeNode(attr); // Add the issued date node: Date issueDate = journalData.getDateIssued(); if (null != issueDate) { SimpleDateFormat format_issuedDate = new SimpleDateFormat("yyyy-MM-dd"); Element elementIssued = doc.createElement("dcvalue"); elementIssued.appendChild(doc.createTextNode(format_issuedDate.format(issueDate))); rootElement.appendChild(elementIssued); attr = doc.createAttribute("element"); attr.setValue("date"); elementIssued.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("issued"); elementIssued.setAttributeNode(attr); } // Add the author nodes: String[] authorSet = journalData.getAuthors(); if (null != authorSet && authorSet.length > 0) { for (String author : authorSet) { Element elementAuthor = doc.createElement("dcvalue"); elementAuthor.appendChild(doc.createTextNode(author)); rootElement.appendChild(elementAuthor); attr = doc.createAttribute("element"); attr.setValue("contributor"); elementAuthor.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("author"); elementAuthor.setAttributeNode(attr); } } // Add the acknowledgements node: String ack = journalData.getAcknowledgements(); if (null != ack) { Element elementAck = doc.createElement("dcvalue"); elementAck.appendChild(doc.createTextNode(ack)); rootElement.appendChild(elementAck); attr = doc.createAttribute("element"); attr.setValue("description"); elementAck.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementAck.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementAck.setAttributeNode(attr); } // Add the author contributions node: String contrib = journalData.getAuthorContributions(); if (null != contrib) { Element elementContribution = doc.createElement("dcvalue"); elementContribution.appendChild(doc.createTextNode(contrib)); rootElement.appendChild(elementContribution); attr = doc.createAttribute("element"); attr.setValue("description"); elementContribution.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementContribution.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementContribution.setAttributeNode(attr); } // Add the publisher node: String puber = journalData.getPublisher(); if (null != puber) { Element elementPublisher = doc.createElement("dcvalue"); elementPublisher.appendChild(doc.createTextNode(puber)); rootElement.appendChild(elementPublisher); attr = doc.createAttribute("element"); attr.setValue("publisher"); elementPublisher.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementPublisher.setAttributeNode(attr); } // Add the citation node: String cit = journalData.getCitation(); if (null != cit) { Element elementCitation = doc.createElement("dcvalue"); elementCitation.appendChild(doc.createTextNode(cit)); rootElement.appendChild(elementCitation); attr = doc.createAttribute("element"); attr.setValue("identifier"); elementCitation.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementCitation.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("citation"); elementCitation.setAttributeNode(attr); } // Add the rights node: String rit = journalData.getRights(); if (null != rit) { Element elementRights = doc.createElement("dcvalue"); elementRights.appendChild(doc.createTextNode(rit)); rootElement.appendChild(elementRights); attr = doc.createAttribute("element"); attr.setValue("rights"); elementRights.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementRights.setAttributeNode(attr); } // Add the rights URI node: String ritUri = journalData.getRightsUri(); if (null != ritUri) { Element elementRightsUri = doc.createElement("dcvalue"); elementRightsUri.appendChild(doc.createTextNode(ritUri)); rootElement.appendChild(elementRightsUri); attr = doc.createAttribute("element"); attr.setValue("rights"); elementRightsUri.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("uri"); elementRightsUri.setAttributeNode(attr); } // Add the rights requestable node: Element elementRightsRequestable = doc.createElement("dcvalue"); elementRightsRequestable .appendChild(doc.createTextNode(Boolean.toString(journalData.isRightsRequestable()))); rootElement.appendChild(elementRightsRequestable); attr = doc.createAttribute("element"); attr.setValue("rights"); elementRightsRequestable.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementRightsRequestable.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("requestable"); elementRightsRequestable.setAttributeNode(attr); // Add the is part of node: String partOf = journalData.getIsPartOfSeries(); if (null != partOf) { Element elementIsPartOf = doc.createElement("dcvalue"); elementIsPartOf.appendChild(doc.createTextNode(partOf)); rootElement.appendChild(elementIsPartOf); attr = doc.createAttribute("element"); attr.setValue("relation"); elementIsPartOf.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("ispartofseries"); elementIsPartOf.setAttributeNode(attr); } // Add the relation uri node: String reUri = journalData.getRelationUri(); if (null != reUri) { Element elementRelationUri = doc.createElement("dcvalue"); elementRelationUri.appendChild(doc.createTextNode(reUri)); rootElement.appendChild(elementRelationUri); attr = doc.createAttribute("element"); attr.setValue("relation"); elementRelationUri.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("uri"); elementRelationUri.setAttributeNode(attr); } // Add the subject nodes: String[] subjectSet = journalData.getSubjects(); if (null != subjectSet && subjectSet.length > 0) { for (String subject : subjectSet) { Element elementSubject = doc.createElement("dcvalue"); elementSubject.appendChild(doc.createTextNode(subject)); rootElement.appendChild(elementSubject); attr = doc.createAttribute("element"); attr.setValue("subject"); elementSubject.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementSubject.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementSubject.setAttributeNode(attr); } } // Add the peerReview node: String review = journalData.getPeerReview(); if (null != review) { Element elementPeerReview = doc.createElement("dcvalue"); elementPeerReview.appendChild(doc.createTextNode(review)); rootElement.appendChild(elementPeerReview); attr = doc.createAttribute("element"); attr.setValue("description"); elementPeerReview.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementPeerReview.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("peerreview"); elementPeerReview.setAttributeNode(attr); } // Add the peer review notes node: String peer = journalData.getPeerReviewNotes(); if (null != peer) { Element elementPeerReviewNotes = doc.createElement("dcvalue"); elementPeerReviewNotes.appendChild(doc.createTextNode(peer)); rootElement.appendChild(elementPeerReviewNotes); attr = doc.createAttribute("element"); attr.setValue("description"); elementPeerReviewNotes.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementPeerReviewNotes.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("peerreviewnotes"); elementPeerReviewNotes.setAttributeNode(attr); } // Add the doi node: String doi = journalData.getDoi(); if (null != doi) { Element elementDoi = doc.createElement("dcvalue"); elementDoi.appendChild(doc.createTextNode(doi)); rootElement.appendChild(elementDoi); attr = doc.createAttribute("element"); attr.setValue("identifier"); elementDoi.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementDoi.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("doi"); elementDoi.setAttributeNode(attr); } String folderPath = setOutputPath(fileName); String filePath = folderPath + "/dublin_core.xml"; TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(filePath)); transformer.transform(source, result); } catch (ParserConfigurationException | TransformerException pce) { pce.printStackTrace(); } catch (DOMException | BeansException e) { e.printStackTrace(); } }
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 ww. j av a 2 s. com * <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:org.shareok.data.plosdata.PlosData.java
/** * Generate the metadata xml file// w w w . jav a 2 s. c o m * @param fileName */ public void exportXmlByDoiData(String fileName) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("dublin_core"); doc.appendChild(rootElement); // Add the type node: Element element = doc.createElement("dcvalue"); element.appendChild(doc.createTextNode("Research Article")); rootElement.appendChild(element); Attr attr = doc.createAttribute("element"); attr.setValue("type"); element.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); element.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); element.setAttributeNode(attr); // Add the abstract node: String abs = getAbstractText(); if (null != abs) { Element elementAbs = doc.createElement("dcvalue"); elementAbs.appendChild(doc.createTextNode(abs)); rootElement.appendChild(elementAbs); attr = doc.createAttribute("element"); attr.setValue("description"); elementAbs.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementAbs.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("abstract"); elementAbs.setAttributeNode(attr); } // Add the language node: String lang = getLanguage(); if (null != lang) { Element elementLang = doc.createElement("dcvalue"); elementLang.appendChild(doc.createTextNode(lang)); rootElement.appendChild(elementLang); attr = doc.createAttribute("element"); attr.setValue("language"); elementLang.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementLang.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("iso"); elementLang.setAttributeNode(attr); } // Add the title node: String tit = getTitle(); if (null != tit) { Element elementTitle = doc.createElement("dcvalue"); elementTitle.appendChild(doc.createTextNode(tit)); rootElement.appendChild(elementTitle); attr = doc.createAttribute("element"); attr.setValue("title"); elementTitle.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementTitle.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementTitle.setAttributeNode(attr); } // Add the available date node: // Element elementAvailable = doc.createElement("dcvalue"); // elementAvailable.appendChild(doc.createTextNode(getDateAvailable().toString())); // rootElement.appendChild(elementAvailable); // // attr = doc.createAttribute("element"); // attr.setValue("date"); // elementAvailable.setAttributeNode(attr); // // attr = doc.createAttribute("qualifier"); // attr.setValue("available"); // elementAvailable.setAttributeNode(attr); // Add the issued date node: Date issueDate = getDateIssued(); if (null != issueDate) { SimpleDateFormat format_issuedDate = new SimpleDateFormat("yyyy-MM-dd"); Element elementIssued = doc.createElement("dcvalue"); elementIssued.appendChild(doc.createTextNode(format_issuedDate.format(issueDate))); rootElement.appendChild(elementIssued); attr = doc.createAttribute("element"); attr.setValue("date"); elementIssued.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("issued"); elementIssued.setAttributeNode(attr); } // Add the author nodes: String[] authorSet = getAuthors(); if (null != authorSet && authorSet.length > 0) { for (String author : authorSet) { Element elementAuthor = doc.createElement("dcvalue"); elementAuthor.appendChild(doc.createTextNode(author)); rootElement.appendChild(elementAuthor); attr = doc.createAttribute("element"); attr.setValue("contributor"); elementAuthor.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("author"); elementAuthor.setAttributeNode(attr); } } // Add the acknowledgements node: String ack = getAcknowledgements(); if (null != ack) { Element elementAck = doc.createElement("dcvalue"); elementAck.appendChild(doc.createTextNode(ack)); rootElement.appendChild(elementAck); attr = doc.createAttribute("element"); attr.setValue("description"); elementAck.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementAck.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementAck.setAttributeNode(attr); } // Add the author contributions node: String contrib = getAuthorContributions(); if (null != contrib) { Element elementContribution = doc.createElement("dcvalue"); elementContribution.appendChild(doc.createTextNode(contrib)); rootElement.appendChild(elementContribution); attr = doc.createAttribute("element"); attr.setValue("description"); elementContribution.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementContribution.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementContribution.setAttributeNode(attr); } // Add the publisher node: String puber = getPublisher(); if (null != puber) { Element elementPublisher = doc.createElement("dcvalue"); elementPublisher.appendChild(doc.createTextNode(puber)); rootElement.appendChild(elementPublisher); attr = doc.createAttribute("element"); attr.setValue("publisher"); elementPublisher.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementPublisher.setAttributeNode(attr); } // Add the citation node: String cit = getCitation(); if (null != cit) { Element elementCitation = doc.createElement("dcvalue"); elementCitation.appendChild(doc.createTextNode(cit)); rootElement.appendChild(elementCitation); attr = doc.createAttribute("element"); attr.setValue("identifier"); elementCitation.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementCitation.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("citation"); elementCitation.setAttributeNode(attr); } // Add the rights node: String rit = getRights(); if (null != rit) { Element elementRights = doc.createElement("dcvalue"); elementRights.appendChild(doc.createTextNode(rit)); rootElement.appendChild(elementRights); attr = doc.createAttribute("element"); attr.setValue("rights"); elementRights.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementRights.setAttributeNode(attr); } // Add the rights URI node: String ritUri = getRightsUri(); if (null != ritUri) { Element elementRightsUri = doc.createElement("dcvalue"); elementRightsUri.appendChild(doc.createTextNode(ritUri)); rootElement.appendChild(elementRightsUri); attr = doc.createAttribute("element"); attr.setValue("rights"); elementRightsUri.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("uri"); elementRightsUri.setAttributeNode(attr); } // Add the rights requestable node: Element elementRightsRequestable = doc.createElement("dcvalue"); elementRightsRequestable.appendChild(doc.createTextNode(Boolean.toString(isRightsRequestable()))); rootElement.appendChild(elementRightsRequestable); attr = doc.createAttribute("element"); attr.setValue("rights"); elementRightsRequestable.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementRightsRequestable.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("requestable"); elementRightsRequestable.setAttributeNode(attr); // Add the is part of node: String partOf = getIsPartOfSeries(); if (null != partOf) { Element elementIsPartOf = doc.createElement("dcvalue"); elementIsPartOf.appendChild(doc.createTextNode(partOf)); rootElement.appendChild(elementIsPartOf); attr = doc.createAttribute("element"); attr.setValue("relation"); elementIsPartOf.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("ispartofseries"); elementIsPartOf.setAttributeNode(attr); } // Add the relation uri node: String reUri = getRelationUri(); if (null != reUri) { Element elementRelationUri = doc.createElement("dcvalue"); elementRelationUri.appendChild(doc.createTextNode(reUri)); rootElement.appendChild(elementRelationUri); attr = doc.createAttribute("element"); attr.setValue("relation"); elementRelationUri.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("uri"); elementRelationUri.setAttributeNode(attr); } // Add the subject nodes: String[] subjectSet = getSubjects(); if (null != subjectSet && subjectSet.length > 0) { for (String subject : subjectSet) { Element elementSubject = doc.createElement("dcvalue"); elementSubject.appendChild(doc.createTextNode(subject)); rootElement.appendChild(elementSubject); attr = doc.createAttribute("element"); attr.setValue("subject"); elementSubject.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementSubject.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("none"); elementSubject.setAttributeNode(attr); } } // Add the peerReview node: String review = getPeerReview(); if (null != review) { Element elementPeerReview = doc.createElement("dcvalue"); elementPeerReview.appendChild(doc.createTextNode(review)); rootElement.appendChild(elementPeerReview); attr = doc.createAttribute("element"); attr.setValue("description"); elementPeerReview.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementPeerReview.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("peerreview"); elementPeerReview.setAttributeNode(attr); } // Add the peer review notes node: String peer = getPeerReviewNotes(); if (null != peer) { Element elementPeerReviewNotes = doc.createElement("dcvalue"); elementPeerReviewNotes.appendChild(doc.createTextNode(peer)); rootElement.appendChild(elementPeerReviewNotes); attr = doc.createAttribute("element"); attr.setValue("description"); elementPeerReviewNotes.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementPeerReviewNotes.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("peerreviewnotes"); elementPeerReviewNotes.setAttributeNode(attr); } // Add the doi node: String doi = getDoi(); if (null != doi) { Element elementDoi = doc.createElement("dcvalue"); elementDoi.appendChild(doc.createTextNode(doi)); rootElement.appendChild(elementDoi); attr = doc.createAttribute("element"); attr.setValue("identifier"); elementDoi.setAttributeNode(attr); attr = doc.createAttribute("language"); attr.setValue("en_US"); elementDoi.setAttributeNode(attr); attr = doc.createAttribute("qualifier"); attr.setValue("doi"); elementDoi.setAttributeNode(attr); } // Generate the xml file: TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(fileName)); transformer.transform(source, result); } catch (ParserConfigurationException | TransformerException pce) { pce.printStackTrace(); System.exit(0); } catch (DOMException | BeansException e) { e.printStackTrace(); System.exit(0); } }
From source file:com.microsoft.windowsazure.management.ManagementCertificateOperationsImpl.java
/** * The Create Management Certificate operation adds a certificate to the * list of management certificates. Management certificates, which are also * known as subscription certificates, authenticate clients attempting to * connect to resources associated with your Azure subscription. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj154123.aspx for * more information)/*from w ww. j a va2 s . co m*/ * * @param parameters Required. Parameters supplied to the Create Management * Certificate operation. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return A standard service response including an HTTP status code and * request ID. */ @Override public OperationResponse create(ManagementCertificateCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (parameters == null) { throw new NullPointerException("parameters"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/certificates"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2014-10-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element subscriptionCertificateElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "SubscriptionCertificate"); requestDoc.appendChild(subscriptionCertificateElement); if (parameters.getPublicKey() != null) { Element subscriptionCertificatePublicKeyElement = requestDoc.createElementNS( "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificatePublicKey"); subscriptionCertificatePublicKeyElement .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getPublicKey()))); subscriptionCertificateElement.appendChild(subscriptionCertificatePublicKeyElement); } if (parameters.getThumbprint() != null) { Element subscriptionCertificateThumbprintElement = requestDoc.createElementNS( "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateThumbprint"); subscriptionCertificateThumbprintElement .appendChild(requestDoc.createTextNode(parameters.getThumbprint())); subscriptionCertificateElement.appendChild(subscriptionCertificateThumbprintElement); } if (parameters.getData() != null) { Element subscriptionCertificateDataElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateData"); subscriptionCertificateDataElement .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getData()))); subscriptionCertificateElement.appendChild(subscriptionCertificateDataElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; // Deserialize Response result = new OperationResponse(); result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }