/** * Pretty prints a node. * * @param doc The document the node comes from. * @param node The node that should be pretty printed. * @param prefix The prefix the node should get. */ private static void prettyPrint(Document doc, Node node, String prefix) { String childPrefix = prefix + " "; // Add the indenting to the children NodeList childList = node.getChildNodes(); boolean hasChildren = false; for (int i = childList.getLength() - 1; i >= 0; i--) { Node child = childList.item(i); boolean isNormalNode = (!child.getNodeName().startsWith("#")); if (isNormalNode) { // Add the indenting to this node Node textNode = doc.createTextNode(childPrefix); node.insertBefore(textNode, child); // pretty print the child's children prettyPrint(doc, child, childPrefix); hasChildren = true; } } // Add the indenting to the end tag if (hasChildren) { Node textNode = doc.createTextNode(prefix); node.appendChild(textNode); } }
public void renderTo(ClassDoc classDoc, Element parent) { Document document = parent.getOwnerDocument(); Element title = document.createElement("title"); parent.appendChild(title); title.appendChild(document.createTextNode(classDoc.getSimpleName())); Element list = document.createElement("segmentedlist"); parent.appendChild(list); Element segtitle = document.createElement("segtitle"); list.appendChild(segtitle); segtitle.appendChild(document.createTextNode("API Documentation")); Element listItem = document.createElement("seglistitem"); list.appendChild(listItem); Element seg = document.createElement("seg"); listItem.appendChild(seg); Element apilink = document.createElement("apilink"); seg.appendChild(apilink); apilink.setAttribute("class", classDoc.getName()); apilink.setAttribute("style", classDoc.getStyle()); warningsRenderer.renderTo(classDoc, "class", parent); for (Element element : classDoc.getComment()) { parent.appendChild(document.importNode(element, true)); } NodeList otherContent = classDoc.getClassSection().getChildNodes(); for (int i = 0; i < otherContent.getLength(); i++) { Node child = otherContent.item(i); if (child instanceof Element && !((Element) child).getTagName().equals("section")) { parent.appendChild(document.importNode(child, true)); } } }
/** * Add attachement element for the javadoc artifact if present. * * <pre> * <attach file="${basedir}/target/my-project-1.0-javadoc.jar" * type="jar" * classifier="javadoc"/> * </pre> * * @param el element to add the attachment to. * @param ba The bundle archive to add a source artifact for. * @param prefix Whitespace to add before the new element. */ private void addJavadocAttachment(final Element el, final BundleArchive ba, final String prefix) { String javadocPath = ba.file.getAbsolutePath(); // Remove ".jar" suffix. javadocPath = javadocPath.substring(0, javadocPath.length() - 4); javadocPath = javadocPath + "-javadoc.jar"; final File javadocFile = new File(javadocPath); if (javadocFile.exists()) { final Document doc = el.getOwnerDocument(); final String prefix1 = prefix + " "; final String prefix2 = prefix1 + " "; final Element javadocAttachment = doc.createElement("javadoc-attachment"); el.appendChild(doc.createTextNode("\n" + prefix1)); el.appendChild(javadocAttachment); el.appendChild(doc.createTextNode("\n" + prefix)); final Element attach = doc.createElement("attach"); javadocAttachment.appendChild(doc.createTextNode("\n" + prefix2)); javadocAttachment.appendChild(attach); javadocAttachment.appendChild(doc.createTextNode("\n" + prefix1)); attach.setAttribute("file", javadocPath); attach.setAttribute("type", "jar"); attach.setAttribute("classifier", "javadoc"); } }
public String writePermutationInformation( String strongName, Set<BindingProperty> bindingProperties, Set<String> files) throws XMLPermutationProviderException { Document document = createDocument(); Element permutationNode = document.createElement(PERMUTATION_NODE); document.appendChild(permutationNode); permutationNode.setAttribute(PERMUTATION_NAME, strongName); // create and append variables node Element variablesNode = document.createElement("variables"); permutationNode.appendChild(variablesNode); // write out all variables for (BindingProperty prop : bindingProperties) { Element varNode = document.createElement(prop.getName()); varNode.appendChild(document.createTextNode(prop.getValue())); variablesNode.appendChild(varNode); } // create file node Element filesNode = document.createElement("files"); permutationNode.appendChild(filesNode); // write out all files for (String string : files) { Element fileNode = document.createElement("file"); fileNode.appendChild(document.createTextNode(string)); filesNode.appendChild(fileNode); } return transformDocumentToString(document); }
/** * Print out report of .jars found in a classpath. * * <p>Takes the information encoded from a checkPathForJars() call and dumps it out to our * PrintWriter. * * @param container Node to append our report to * @param factory Document providing createElement, etc. services * @param v Vector of Hashtables of .jar file info * @param desc description to print out in header * @return false if OK, true if any .jars were reported as having errors * @see #checkPathForJars(String, String[]) */ protected boolean appendFoundJars(Node container, Document factory, Vector v, String desc) { if ((null == v) || (v.size() < 1)) return false; boolean errors = false; for (int i = 0; i < v.size(); i++) { Hashtable subhash = (Hashtable) v.elementAt(i); for (Enumeration keys = subhash.keys(); keys.hasMoreElements(); /* no increment portion */ ) { Object key = keys.nextElement(); try { String keyStr = (String) key; if (keyStr.startsWith(ERROR)) { errors = true; } Element node = factory.createElement("foundJar"); node.setAttribute("name", keyStr.substring(0, keyStr.indexOf("-"))); node.setAttribute("desc", keyStr.substring(keyStr.indexOf("-") + 1)); node.appendChild(factory.createTextNode((String) subhash.get(keyStr))); container.appendChild(node); } catch (Exception e) { errors = true; Element node = factory.createElement("foundJar"); node.appendChild( factory.createTextNode(ERROR + " Reading " + key + " threw: " + e.toString())); container.appendChild(node); } } } return errors; }
/** * A helper method that adds extra XML. * * <p>This includes a test name, time (in ms), message, and stack trace, when present. Example: * * <pre> * <testresult name="failed_test" time="200"> * <message>Reason for test failure</message> * <stacktrace>Stacktrace here</stacktrace> * </testresult> * </pre> * * @param testCase The test case summary containing one or more tests. * @param testEl The XML element object for the <test> tag, in which extra information tags will * be added. */ @VisibleForTesting static void addExtraXmlInfo(TestCaseSummary testCase, Element testEl) { Document doc = testEl.getOwnerDocument(); // Loop through the test case and extract test data. for (TestResultSummary testResult : testCase.getTestResults()) { // Extract the test name and time. String name = Strings.nullToEmpty(testResult.getTestName()); String time = Long.toString(testResult.getTime()); // Create the tag: <testresult name="..." time="..."> Element testResultEl = doc.createElement("testresult"); testResultEl.setAttribute("name", name); testResultEl.setAttribute("time", time); testEl.appendChild(testResultEl); // Create the tag: <message>(Error message here)</message> Element messageEl = doc.createElement("message"); String message = Strings.nullToEmpty(testResult.getMessage()); messageEl.appendChild(doc.createTextNode(message)); testResultEl.appendChild(messageEl); // Create the tag: <stacktrace>(Stacktrace here)</stacktrace> Element stacktraceEl = doc.createElement("stacktrace"); String stacktrace = Strings.nullToEmpty(testResult.getStacktrace()); stacktraceEl.appendChild(doc.createTextNode(stacktrace)); testResultEl.appendChild(stacktraceEl); } }
/** * This method exports the single pattern decision instance to the XML. It MUST be called by an * XML exporter, as this will not have a complete header. * * @param ratDoc The ratDoc generated by the XML exporter * @return the SAX representation of the object. */ public Element toXML(Document ratDoc) { Element decisionE; RationaleDB db = RationaleDB.getHandle(); // Now, add pattern to doc String entryID = db.getRef(this); if (entryID == null) { entryID = db.addPatternDecisionRef(this); } decisionE = ratDoc.createElement("DR:patternDecision"); decisionE.setAttribute("rid", entryID); decisionE.setAttribute("name", name); decisionE.setAttribute("type", type.toString()); decisionE.setAttribute("phase", devPhase.toString()); decisionE.setAttribute("status", status.toString()); // decisionE.setAttribute("artifact", artifact); Element descE = ratDoc.createElement("description"); Text descText = ratDoc.createTextNode(description); descE.appendChild(descText); decisionE.appendChild(descE); // Add child pattern references... Iterator<Pattern> cpi = candidatePatterns.iterator(); while (cpi.hasNext()) { Pattern cur = cpi.next(); Element curE = ratDoc.createElement("refChildPattern"); Text curText = ratDoc.createTextNode("p" + new Integer(cur.getID()).toString()); curE.appendChild(curText); decisionE.appendChild(curE); } return decisionE; }
/** * Add attachement element for the source artifact if present. * * <pre> * <attach file="${basedir}/target/my-project-1.0-sources.jar" * type="jar" * classifier="sources"> * </pre> * * @param el element to add the attachment to. * @param ba The bundle archive to add a source artifact for. * @param prefix Whitespace to add before the new element. */ private void addSourceAttachment(final Element el, final BundleArchive ba, final String prefix) { String sourcePath = ba.file.getAbsolutePath(); // Remove ".jar" suffix. sourcePath = sourcePath.substring(0, sourcePath.length() - 4); sourcePath = sourcePath + "-source.jar"; final File sourceFile = new File(sourcePath); if (sourceFile.exists()) { final Document doc = el.getOwnerDocument(); final String prefix1 = prefix + " "; final String prefix2 = prefix1 + " "; final Element sourceAttachment = doc.createElement("source-attachment"); el.appendChild(doc.createTextNode("\n" + prefix1)); el.appendChild(sourceAttachment); el.appendChild(doc.createTextNode("\n" + prefix)); final Element attach = doc.createElement("attach"); sourceAttachment.appendChild(doc.createTextNode("\n" + prefix2)); sourceAttachment.appendChild(attach); sourceAttachment.appendChild(doc.createTextNode("\n" + prefix1)); attach.setAttribute("file", sourcePath); attach.setAttribute("type", "jar"); attach.setAttribute("classifier", "sources"); } }
public Document export(Document doc, Element root, Customer cus, List<CardBean> cards) { Element customer = doc.createElement("Kunde"); root.appendChild(customer); Attr cusNum = doc.createAttribute("Kundennummer"); cusNum.setValue(cus.getCustomernumber()); customer.setAttributeNode(cusNum); Element cusName = doc.createElement("Name"); cusName.appendChild(doc.createTextNode(cus.getName())); customer.appendChild(cusName); Iterator<CardBean> it = cards.iterator(); while (it.hasNext()) { CardBean card = it.next(); Element cusCard = doc.createElement("Karte"); customer.appendChild(cusCard); Attr cardNum = doc.createAttribute("Kartennummer"); cardNum.setValue(card.getCardNumber()); cusCard.setAttributeNode(cardNum); Element telFirst = doc.createElement("Telefonnummer"); telFirst.appendChild(doc.createTextNode(card.getPhoneString())); cusCard.appendChild(telFirst); } return doc; }
protected void getAlbumsElements(Document doc, GalleryAlbums gallery) { Element galleryNameElement = doc.createElement("galleryName"); galleryNameElement.appendChild(doc.createTextNode(gallery.getGalleryName())); Element homePageElement = doc.createElement("homePage"); homePageElement.appendChild(doc.createTextNode(gallery.getGalleryHomePage())); Element root = doc.getDocumentElement(); root.appendChild(galleryNameElement); root.appendChild(homePageElement); Element albumsElement = doc.createElement("albums"); AlbumBean[] albums = gallery.getAllAlbums(); for (AlbumBean album : albums) { Element albumElement = doc.createElement("album"); albumElement.setAttribute("img", album.getImgThumbnail()); albumElement.setAttribute("folderName", album.getFolderName()); albumElement.setAttribute("name", album.getName()); albumElement.setAttribute("tags", album.getTagsInOneLine()); albumsElement.appendChild(albumElement); } root.appendChild(albumsElement); }
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) throws MarshalException { Document ownerDoc = DOMUtils.getOwnerDocument(parent); Element pdElem = DOMUtils.createElement(ownerDoc, "PGPData", XMLSignature.XMLNS, dsPrefix); // create and append PGPKeyID element if (keyId != null) { Element keyIdElem = DOMUtils.createElement(ownerDoc, "PGPKeyID", XMLSignature.XMLNS, dsPrefix); keyIdElem.appendChild(ownerDoc.createTextNode(Base64.encode(keyId))); pdElem.appendChild(keyIdElem); } // create and append PGPKeyPacket element if (keyPacket != null) { Element keyPktElem = DOMUtils.createElement(ownerDoc, "PGPKeyPacket", XMLSignature.XMLNS, dsPrefix); keyPktElem.appendChild(ownerDoc.createTextNode(Base64.encode(keyPacket))); pdElem.appendChild(keyPktElem); } // create and append any elements for (int i = 0, size = externalElements.size(); i < size; i++) { DOMUtils.appendChild( pdElem, ((javax.xml.crypto.dom.DOMStructure) externalElements.get(i)).getNode()); } parent.appendChild(pdElem); }
private void createXML(String user, String pass, String name, String amount) { try { File _file = new File("Customer.xml"); DocumentBuilderFactory _dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder _db = _dbf.newDocumentBuilder(); Document _doc = _db.parse(_file); Element _root = _doc.getDocumentElement(); Element _nodeCustomer = _doc.createElement("Customer"); _root.appendChild(_nodeCustomer); Element _nodeCustomerID = _doc.createElement("CusID"); _nodeCustomerID.appendChild(_doc.createTextNode(user)); _nodeCustomer.appendChild(_nodeCustomerID); Element _nodeCustomerPass = _doc.createElement("CusPass"); _nodeCustomerPass.appendChild(_doc.createTextNode(pass)); _nodeCustomer.appendChild(_nodeCustomerPass); Element _nodeCustomerName = _doc.createElement("CusName"); _nodeCustomerName.appendChild(_doc.createTextNode(name)); _nodeCustomer.appendChild(_nodeCustomerName); Element _nodeCustomerAmount = _doc.createElement("Amount"); _nodeCustomerAmount.appendChild(_doc.createTextNode(amount)); _nodeCustomer.appendChild(_nodeCustomerAmount); createFile(_file, _doc); } catch (Exception e) { e.printStackTrace(); } }
/** * Converts transaction to XML DOM corresponding to OFX Statement transaction and returns the * element node for the transaction. The Unique ID of the account is needed in order to properly * export double entry transactions * * @param doc XML document to which transaction should be added * @param accountUID Unique Identifier of the account which called the method. * @return Element in DOM corresponding to transaction */ public Element toOfx(Document doc, String accountUID) { Element transactionNode = doc.createElement("STMTTRN"); Element type = doc.createElement("TRNTYPE"); type.appendChild(doc.createTextNode(mType.toString())); transactionNode.appendChild(type); Element datePosted = doc.createElement("DTPOSTED"); datePosted.appendChild(doc.createTextNode(OfxExporter.getOfxFormattedTime(mTimestamp))); transactionNode.appendChild(datePosted); Element dateUser = doc.createElement("DTUSER"); dateUser.appendChild(doc.createTextNode(OfxExporter.getOfxFormattedTime(mTimestamp))); transactionNode.appendChild(dateUser); Element amount = doc.createElement("TRNAMT"); amount.appendChild(doc.createTextNode(mAmount.toPlainString())); transactionNode.appendChild(amount); Element transID = doc.createElement("FITID"); transID.appendChild(doc.createTextNode(mTransactionUID)); transactionNode.appendChild(transID); Element name = doc.createElement("NAME"); name.appendChild(doc.createTextNode(mName)); transactionNode.appendChild(name); if (mDescription != null && mDescription.length() > 0) { Element memo = doc.createElement("MEMO"); memo.appendChild(doc.createTextNode(mDescription)); transactionNode.appendChild(memo); } if (mDoubleEntryAccountUID != null && mDoubleEntryAccountUID.length() > 0) { Element bankId = doc.createElement("BANKID"); bankId.appendChild(doc.createTextNode(OfxExporter.APP_ID)); // select the proper account as the double account String doubleAccountUID = mDoubleEntryAccountUID.equals(accountUID) ? mAccountUID : mDoubleEntryAccountUID; Element acctId = doc.createElement("ACCTID"); acctId.appendChild(doc.createTextNode(doubleAccountUID)); Element accttype = doc.createElement("ACCTTYPE"); AccountsDbAdapter acctDbAdapter = new AccountsDbAdapter(GnuCashApplication.getAppContext()); OfxAccountType ofxAccountType = Account.convertToOfxAccountType(acctDbAdapter.getAccountType(doubleAccountUID)); accttype.appendChild(doc.createTextNode(ofxAccountType.toString())); acctDbAdapter.close(); Element bankAccountTo = doc.createElement("BANKACCTTO"); bankAccountTo.appendChild(bankId); bankAccountTo.appendChild(acctId); bankAccountTo.appendChild(accttype); transactionNode.appendChild(bankAccountTo); } return transactionNode; }
public static void bindDictionaryToElement(Dictionary dict, Document doc, Element element) { for (Map.Entry<String, Object> entry : dict) { String k = entry.getKey(); Object v = entry.getValue(); Element key = doc.createElement("key"); key.appendChild(doc.createTextNode(k)); element.appendChild(key); if (v instanceof String) { Element value = doc.createElement("string"); value.appendChild(doc.createTextNode(v.toString())); element.appendChild(value); } else if (v instanceof Integer) { Element value = doc.createElement("integer"); value.appendChild(doc.createTextNode(((Integer) v).toString())); element.appendChild(value); } else if (v instanceof Boolean) { Element value = doc.createElement("boolean"); value.appendChild(doc.createTextNode(((Boolean) v).toString())); element.appendChild(value); } else if (v instanceof List<?>) { Element value = doc.createElement("list"); ListParser.bindListToElement((List<Object>) v, doc, value); element.appendChild(value); } else if (v instanceof Dictionary) { Element value = doc.createElement("dict"); bindDictionaryToElement((Dictionary) v, doc, value); element.appendChild(value); } } }
/** * Creates an Element(or Node in XML in Document d) for single component * * @param x the component for which Element will be created * @param d Where the element will be added * @return the Element(for XML) created from component x */ private Element createCmpEle(component x, Document d) { Element cmp_el = d.createElement("comp"); cmp_el.setAttribute("id", String.valueOf(x.getId())); Element type_el = d.createElement("comp_type_id"); Text type_txt = d.createTextNode(String.valueOf(x.getType().getId())); type_el.appendChild(type_txt); cmp_el.appendChild(type_el); Element pkg_el = d.createElement("pkg_name"); Text pkg_txt = d.createTextNode(x.getType().getType_pkg_name()); pkg_el.appendChild(pkg_txt); cmp_el.appendChild(pkg_el); Element pos_el = d.createElement("position"); Element x_el = d.createElement("x"); Text x_txt = d.createTextNode(String.valueOf(x.getPosition().x)); x_el.appendChild(x_txt); pos_el.appendChild(x_el); Element y_el = d.createElement("y"); Text y_txt = d.createTextNode(String.valueOf(x.getPosition().y)); y_el.appendChild(y_txt); pos_el.appendChild(y_el); cmp_el.appendChild(pos_el); return cmp_el; }
/** * Exports a <code>GetRecordById</code> instance to a <code>GetRecordByIdDocument</code>. * * @param request * @return DOM representation of the <code>GetRecordById</code> * @throws XMLException if XML template could not be loaded */ public static GetRecordByIdDocument export(GetRecordById request) throws XMLException { GetRecordByIdDocument getRecordByIdDoc = new GetRecordByIdDocument(); try { getRecordByIdDoc.createEmptyDocument(); } catch (Exception e) { throw new XMLException(e.getMessage()); } Element rootElement = getRecordByIdDoc.getRootElement(); Document doc = rootElement.getOwnerDocument(); // 'version'-attribute rootElement.setAttribute("version", request.getVersion()); String[] ids = request.getIds(); for (int i = 0; i < ids.length; i++) { Element idElement = doc.createElementNS(CSWNS.toString(), "csw:Id"); idElement.appendChild(doc.createTextNode(ids[i])); rootElement.appendChild(idElement); } String elementSetName = request.getElementSetName(); if (elementSetName != null) { Element esnElement = doc.createElementNS(CSWNS.toString(), "csw:ElementSetName"); esnElement.appendChild(doc.createTextNode(elementSetName)); rootElement.appendChild(esnElement); } return getRecordByIdDoc; }
private void napraviXml(DocumentBuilder DOMParser) throws TransformerConfigurationException, TransformerException { Document doc = DOMParser.newDocument(); Element kluboviElement = doc.createElement("Klubovi"); for (Klub klub : sviKlubovi) { Element klubElement = doc.createElement("Klub"); Element imeElement = doc.createElement("Ime"); imeElement.appendChild(doc.createTextNode(klub.getIme())); Element gradElement = doc.createElement("Grad"); gradElement.appendChild(doc.createTextNode(klub.getGrad())); Element ProracunElement = doc.createElement("Proracun"); ProracunElement.appendChild(doc.createTextNode(klub.getProracun() + "")); Element predsjednikElement = doc.createElement("Predsjednik"); predsjednikElement.appendChild(doc.createTextNode(klub.getPredsjednik())); klubElement.appendChild(imeElement); klubElement.appendChild(gradElement); klubElement.appendChild(ProracunElement); klubElement.appendChild(predsjednikElement); kluboviElement.appendChild(klubElement); } doc.appendChild(kluboviElement); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer newTransformer = transFactory.newTransformer(); StreamResult file = new StreamResult("klubovi.xml"); newTransformer.transform(new DOMSource(doc), file); }
private void store_data(Location loc) { Element trkpt = gpx_document.createElement("trkpt"); Attr longitude = gpx_document.createAttribute("lon"); Attr latitude = gpx_document.createAttribute("lat"); longitude.setValue(Double.toString(currentLongitude)); latitude.setValue(Double.toString(currentLatitude)); trkpt.setAttributeNode(longitude); trkpt.setAttributeNode(latitude); Element elevation = gpx_document.createElement("ele"); String altitude = Double.toString(loc.getAltitude()); elevation.appendChild(gpx_document.createTextNode(altitude)); trkpt.appendChild(elevation); Element timestamp = gpx_document.createElement("time"); String time = Long.toString(loc.getTime()); timestamp.appendChild(gpx_document.createTextNode(time)); trkpt.appendChild(timestamp); Element type = gpx_document.createElement("type"); String difficulty = currentDifficulty.getDifficulty(); type.appendChild(gpx_document.createTextNode(difficulty)); trkpt.appendChild(type); trackSegment.appendChild(trkpt); update_screen_info(altitude, difficulty); }
@Get("xml") public Representation toXml() { try { DomRepresentation representation = new DomRepresentation(MediaType.TEXT_XML); // Generate a DOM document representing the item. Document d = representation.getDocument(); Element eltItem = d.createElement("item"); d.appendChild(eltItem); Element eltName = d.createElement("name"); eltName.appendChild(d.createTextNode(item.getName())); eltItem.appendChild(eltName); Element eltDescription = d.createElement("description"); eltDescription.appendChild(d.createTextNode(item.getDescription())); eltItem.appendChild(eltDescription); d.normalizeDocument(); // Returns the XML representation of this document. return representation; } catch (IOException e) { e.printStackTrace(); } return null; }
private void readColumnValue( Document doc, Map<String, String> xmlFieldXPaths, String columnName, Object value, ReportResultData reportData, int index, Element node) throws XPathExpressionException { if ("RESULTXML".equalsIgnoreCase(columnName) || "PROCESSINGRESULT".equalsIgnoreCase(columnName)) { Document columnValueAsDoc = parseXML((String) reportData.getColumnValue().get(index)); if (xmlFieldXPaths.containsKey(columnName.toLowerCase())) { String xpathEvaluationResult = XMLConverter.getNodeTextContentByXPath( columnValueAsDoc, xmlFieldXPaths.get(columnName)); // don't store null values but empty strings instead, to ensure // proper display on client side if (xpathEvaluationResult == null) { xpathEvaluationResult = ""; } node.appendChild(doc.createTextNode(xpathEvaluationResult)); } else { appendXMLStructureToNode(node, columnValueAsDoc); } } else { node.appendChild(doc.createTextNode(value.toString())); } }
public String addUser(String login, String password) { try { File file = new File(ServerSettings.STATISTICS_ROOT + File.separator + type + ".xml"); if (!file.exists()) { return "File doesn't exists: " + file.getAbsolutePath(); } Map<String, String> map = readUsersFromFile(); if (map == null) { return "Impossible to read xml file: " + file.getAbsolutePath(); } if (map.containsKey(login)) { return "User already exists"; } Document document = ResponseUtils.getXmlDocument(file); if (document == null) { return "Impossible to read xml file: " + file.getAbsolutePath(); } NodeList nodeList = document.getElementsByTagName("users"); Node newNode = document.createElement("user"); newNode.appendChild(document.createElement("login")); newNode.appendChild(document.createTextNode(login)); newNode.appendChild(document.createElement("password")); try { password = generateMD5(password); } catch (NoSuchAlgorithmException e) { ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer( e, SessionInfo.TypeOfRequest.AUTHORIZATION.name(), "ldap: " + login); return "Impossible to generate MD5"; } catch (UnsupportedEncodingException e) { ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer( e, SessionInfo.TypeOfRequest.AUTHORIZATION.name(), "ldap: " + login); return "Impossible to read password in UTF-8"; } newNode.appendChild(document.createTextNode(password)); nodeList.item(0).appendChild(newNode); NodeList list = document.getElementsByTagName("users"); Node node = list.item(0); DOMSource source = new DOMSource(node); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); FileWriter writer = new FileWriter(file); StreamResult result = new StreamResult(writer); transformer.transform(source, result); writer.close(); return "User was added"; } catch (Throwable e) { ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer( e, SessionInfo.TypeOfRequest.ANALYZE_LOG.name(), ""); return "Unknown error: User wasn't added"; } }
public static void main(String[] args) { // TODO Auto-generated method stub try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // Создание корневого элемента Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("company"); doc.appendChild(rootElement); // дочерние элементы Element staff = doc.createElement("Staff"); rootElement.appendChild(staff); // добавление аттрибутов Attr attr = doc.createAttribute("id"); attr.setValue("1"); staff.setAttributeNode(attr); // другой способ // staff.setAttribute("id", "1"); Element firstname = doc.createElement("firstname"); firstname.appendChild(doc.createTextNode("yong")); staff.appendChild(firstname); Element lastname = doc.createElement("lastname"); lastname.appendChild(doc.createTextNode("mook kim")); staff.appendChild(lastname); Element nickname = doc.createElement("nickname"); nickname.appendChild(doc.createTextNode("mkyong")); staff.appendChild(nickname); Element salary = doc.createElement("salary"); salary.appendChild(doc.createTextNode("100000")); staff.appendChild(salary); // Запись контента в xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("Export.xml")); transformer.transform(source, result); System.out.println("File saved!"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } ModifyXMLFile mxf = new ModifyXMLFile(); mxf.ModifyFile(); }
public void saveCurrentRoute(View view) { if (GPS_captureStarted) { Log.w("Saving Route", "Can't Save, tracking not paused"); return; } Element metadata = gpx_document.createElement("metadata"); Element filename = gpx_document.createElement("name"); Element author = gpx_document.createElement("author"); Element trackName = gpx_document.createElement("name"); String fn = "TestFile"; String tn = "TestTrack"; String auth = "Username"; filename.appendChild(gpx_document.createTextNode(fn)); author.appendChild(gpx_document.createTextNode(auth)); trackName.appendChild(gpx_document.createTextNode(tn)); track.appendChild(trackName); metadata.appendChild(filename); metadata.appendChild(author); rootElement.appendChild(metadata); try { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnected(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMSource source = new DOMSource(gpx_document); StreamResult result; if (isConnected) { result = new StreamResult(new StringWriter()); transformer.transform(source, result); String gpx = result.getWriter().toString(); Request.send_GPX(gpx); } else { FileOutputStream stream = openFileOutput(fn + ".gpx", MODE_PRIVATE); result = new StreamResult(stream); transformer.transform(source, result); Log.i("writing file", "success"); filesToSync.put(fn + ".gpx", true); } } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** * Creates a DOM representation (fullfilling musicXML dtd) of the specified tune. * * @param tune A tune. * @return A DOM representation (fullfilling musicXML dtd) of the specified tune. */ public Document createMusicXmlDOM(Tune tune) { Document doc = null; try { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element root = doc.createElement(SCORE_PARTWISE_TAG); doc.appendChild(root); doc.setXmlVersion("1.0"); root.setAttribute("version", "2.0"); Element movementNumberEl = doc.createElement(MOVEMENT_NUMBER_TAG); root.appendChild(movementNumberEl); Element movementTitleEl = doc.createElement(MOVEMENT_TITLE_TAG); if (tune.getTitles().length > 0) movementTitleEl.appendChild(doc.createTextNode(tune.getTitles()[0])); root.appendChild(movementTitleEl); Element identificationEl = doc.createElement(IDENTIFICATION_TAG); Element encodingEl = doc.createElement(ENCODING_TAG); Element softwareEl = doc.createElement(SOFTWARE_TAG); softwareEl.appendChild(doc.createTextNode("ABC4J")); encodingEl.appendChild(softwareEl); Element encodingDateEl = doc.createElement(ENCODING_DATE_TAG); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); encodingDateEl.appendChild(doc.createTextNode(sdf.format(new Date()))); encodingEl.appendChild(encodingDateEl); identificationEl.appendChild(encodingEl); root.appendChild(identificationEl); Element partListEl = doc.createElement(PART_LIST_TAG); Element scorePartEl = doc.createElement(SCORE_PART_TAG); scorePartEl.setAttribute(ID_ATTRIBUTE, "P1"); Element partNameEl = doc.createElement(PART_NAME_TAG); Element partEl = doc.createElement(PART_TAG); partEl.setAttribute(ID_ATTRIBUTE, "P1"); // partNameEl.appendChild(doc.createTextNode(tune.getTitles()[0])); scorePartEl.appendChild(partNameEl); partListEl.appendChild(scorePartEl); root.appendChild(partListEl); root.appendChild(partEl); // Music music = tune.getMusic(); convert(doc, tune.getMusic(), partEl); /* * int measureNb = tune.getMusic().countMeasures(); for (int i=1; * i<=measureNb; i++) { Measure meas = * tune.getMusic().getMeasure(i); partEl.appendChild(convert(doc, * meas, i)); } */ } catch (Exception e) { e.printStackTrace(); } return doc; }
/** * Generate source different count elements * * @param sourceDiffFile The source differences * @param root Root element where the generated element will be placed */ private void generateSourceDifferenceCount(DiffFile sourceDiffFile, Element root) { int removedLinesCount = 0, addedLinesCount = 0; for (Delta sourceDiff : sourceDiffFile.getChanges()) { if (sourceDiff.getType() == TYPE.CHANGE) { removedLinesCount += sourceDiff.getOriginal().size(); addedLinesCount += sourceDiff.getRevised().size(); } else if (sourceDiff.getType() == TYPE.DELETE) { removedLinesCount += sourceDiff.getOriginal().size(); } else if (sourceDiff.getType() == TYPE.INSERT) { addedLinesCount += sourceDiff.getRevised().size(); } } int totalLinesChangedCount = sourceDiffFile.getRevisedLineCount() - sourceDiffFile.getOriginalLineCount(); double totalPercentage = 100.0; if (sourceDiffFile.getOriginalLineCount() > 0) { totalPercentage = Math.round( (double) totalLinesChangedCount / (double) sourceDiffFile.getOriginalLineCount() * (double) 10000) / (double) 100; } root.setAttribute("sizeChange", totalLinesChangedCount + " (" + totalPercentage + "%)"); if (removedLinesCount > 0) { Element removedLines = doc.createElement("removedLineCount"); double percentage = Math.round( (double) removedLinesCount / (double) sourceDiffFile.getOriginalLineCount() * (double) 10000) / (double) 100; removedLines.appendChild(doc.createTextNode(removedLinesCount + " (" + percentage + "%)")); root.appendChild(removedLines); } if (addedLinesCount > 0) { Element addedLines = doc.createElement("addedLineCount"); double percentage = 100.0; if (sourceDiffFile.getOriginalLineCount() > 0) { percentage = Math.round( (double) addedLinesCount / (double) sourceDiffFile.getOriginalLineCount() * (double) 10000) / (double) 100; } addedLines.appendChild(doc.createTextNode(addedLinesCount + " (" + percentage + "%)")); root.appendChild(addedLines); } }
public static void main(String argv[]) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("company"); doc.appendChild(rootElement); // staff elements Element staff = doc.createElement("Staff"); rootElement.appendChild(staff); // set attribute to staff element Attr attr = doc.createAttribute("id"); attr.setValue("1"); staff.setAttributeNode(attr); // shorten way // staff.setAttribute("id", "1"); // firstname elements Element firstname = doc.createElement("firstname"); firstname.appendChild(doc.createTextNode("yong")); staff.appendChild(firstname); // lastname elements Element lastname = doc.createElement("lastname"); lastname.appendChild(doc.createTextNode("mook kim")); staff.appendChild(lastname); // nickname elements Element nickname = doc.createElement("nickname"); nickname.appendChild(doc.createTextNode("mkyong")); staff.appendChild(nickname); // salary elements Element salary = doc.createElement("salary"); salary.appendChild(doc.createTextNode("100000")); staff.appendChild(salary); // 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(".\\file.xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } }
protected Node convert(Document doc, TimeSignature signature) { Element timeEl = doc.createElement(TIME_TAG); Element beatsEl = doc.createElement(BEATS_TAG); Element beatTypeEl = doc.createElement(BEAT_TYPE_TAG); beatsEl.appendChild(doc.createTextNode(Integer.toString(signature.getNumerator()))); beatTypeEl.appendChild(doc.createTextNode(Integer.toString(signature.getDenominator()))); timeEl.appendChild(beatsEl); timeEl.appendChild(beatTypeEl); return timeEl; }
/** * Carries out preprocessing that makes JEuclid handle the document better. * * @param doc Document */ static void preprocessForJEuclid(Document doc) { // underbrace and overbrace NodeList list = doc.getElementsByTagName("mo"); for (int i = 0; i < list.getLength(); i++) { Element mo = (Element) list.item(i); String parentName = ((Element) mo.getParentNode()).getTagName(); if (parentName == null) { continue; } if (parentName.equals("munder") && isTextChild(mo, "\ufe38")) { mo.setAttribute("stretchy", "true"); mo.removeChild(mo.getFirstChild()); mo.appendChild(doc.createTextNode("\u23df")); } else if (parentName.equals("mover") && isTextChild(mo, "\ufe37")) { mo.setAttribute("stretchy", "true"); mo.removeChild(mo.getFirstChild()); mo.appendChild(doc.createTextNode("\u23de")); } } // menclose for long division doesn't allow enough top padding. Oh, and // <mpadded> isn't implemented. And there isn't enough padding to left of // the bar either. Solve by adding an <mover> with just an <mspace> over# // the longdiv, contained within an mrow that adds a <mspace> before it. list = doc.getElementsByTagName("menclose"); for (int i = 0; i < list.getLength(); i++) { Element menclose = (Element) list.item(i); // Only for longdiv if (!"longdiv".equals(menclose.getAttribute("notation"))) { continue; } Element mrow = doc.createElementNS(WebMathsService.NS, "mrow"); Element mover = doc.createElementNS(WebMathsService.NS, "mover"); Element mspace = doc.createElementNS(WebMathsService.NS, "mspace"); Element mspaceW = doc.createElementNS(WebMathsService.NS, "mspace"); boolean previousElement = false; for (Node previous = menclose.getPreviousSibling(); previous != null; previous = previous.getPreviousSibling()) { if (previous.getNodeType() == Node.ELEMENT_NODE) { previousElement = true; break; } } if (previousElement) { mspaceW.setAttribute("width", "4px"); } menclose.getParentNode().insertBefore(mrow, menclose); menclose.getParentNode().removeChild(menclose); mrow.appendChild(mspaceW); mrow.appendChild(mover); mover.appendChild(menclose); mover.appendChild(mspace); } }
protected String createStringToBeSaved() { Component[] components = this.handler.getDrawPanel().getComponents(); List<GridElement> entities = new ArrayList<GridElement>(); for (int i = 0; i < components.length; i++) { if (components[i] instanceof GridElement) entities.add((GridElement) components[i]); } DocumentBuilder db = null; String returnString = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); Element root = doc.createElement("diagram"); root.setAttribute("program", Program.PROGRAM_NAME.toLowerCase()); root.setAttribute("version", String.valueOf(Program.VERSION)); doc.appendChild(root); // save helptext String helptext = this.handler.getHelpText(); if (!helptext.equals(Constants.DEFAULT_HELPTEXT)) { Element help = doc.createElement("help_text"); help.appendChild(doc.createTextNode(helptext)); root.appendChild(help); } // save zoom Element zoom = doc.createElement("zoom_level"); zoom.appendChild(doc.createTextNode(String.valueOf(this.handler.getGridSize()))); root.appendChild(zoom); // save elements (group = null = rootlayer) this.createXMLOutputDoc(doc, entities, root, null); // output the stuff... DOMSource source = new DOMSource(doc); StringWriter stringWriter = new StringWriter(); StreamResult result = new StreamResult(stringWriter); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(source, result); returnString = stringWriter.toString(); } catch (Exception e) { log.error("Error saving XML.", e); } return returnString; }
@Override public Element getSOAPHeaders(Object portObject) { String securityToken = getSecurityToken(); // Exit if no security token found if (securityToken == null) { if (LOG.isDebugEnabled()) { LOG.debug("securityToken is null"); } return null; } // Set time SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); long created = System.currentTimeMillis(); long expires = created + 24 * 60 * 60 * 1000; // 24 hours // Create the SOAP WSSecurity header try { Document document = XMLUtils.newDomDocument(); Element wsseSecurityElement = document.createElementNS(WSSE_NAMESPACE, "Security"); Element wsuTimestampElement = document.createElementNS(WSU_NAMESPACE, "Timestamp"); wsseSecurityElement.appendChild(wsuTimestampElement); Element tsCreatedElement = document.createElementNS(WSU_NAMESPACE, "Created"); tsCreatedElement.appendChild(document.createTextNode(sdf.format(created))); wsuTimestampElement.appendChild(tsCreatedElement); Element tsExpiresElement = document.createElementNS(WSU_NAMESPACE, "Expires"); tsExpiresElement.appendChild(document.createTextNode(sdf.format(expires))); wsuTimestampElement.appendChild(tsExpiresElement); // Add the BinarySecurityToken (contains the LTPAv2 token) Element wsseBinarySecurityTokenElement = document.createElementNS(WSSE_NAMESPACE, "BinarySecurityToken"); wsseBinarySecurityTokenElement.setAttribute("xmlns:wsu", WSU_NAMESPACE); wsseBinarySecurityTokenElement.setAttribute( "xmlns:wsst", "http://www.ibm.com/websphere/appserver/tokentype"); wsseBinarySecurityTokenElement.setAttribute("wsu:Id", "ltpa_20"); wsseBinarySecurityTokenElement.setAttribute("ValueType", "wsst:LTPAv2"); wsseBinarySecurityTokenElement.appendChild(document.createTextNode(securityToken)); // Append BinarySecurityToken to Security section wsseSecurityElement.appendChild(wsseBinarySecurityTokenElement); return wsseSecurityElement; } catch (ParserConfigurationException e) { // shouldn't happen... throw new CmisRuntimeException("Could not build SOAP header: " + e.getMessage(), e); } }