List of usage examples for org.jdom2 Document Document
public Document(List<? extends Content> content)
Document
, with the supplied list of content, and a DocType
declaration only if the content contains a DocType instance. From source file:codigoFonte.Sistema.java
public boolean removeUser(User u) { File file = new File("Sistema.xml"); Document newDocument = null;/*from w w w . j a v a 2 s . c o m*/ Element root = null; Element user = null; boolean success = false; if (file.exists()) { SAXBuilder builder = new SAXBuilder(); try { newDocument = builder.build(file); } catch (JDOMException ex) { Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex); } root = newDocument.getRootElement(); } else { root = new Element("sistema"); newDocument = new Document(root); } List<Element> listusers = root.getChildren("user"); for (Element e : listusers) { if (e.getAttributeValue("matrcula").equals(u.getMatricula()) && e.getChildren("livro").size() == 0) { root.removeContent(e); XMLOutputter out = new XMLOutputter(); try { FileWriter arquivo = new FileWriter(file); out.output(newDocument, arquivo); } catch (IOException ex) { Logger.getLogger(Sistema.class.getName()).log(Level.SEVERE, null, ex); } success = true; return success; } } return success; }
From source file:codigoFonte.Sistema.java
public boolean autentica(User u) { File file = new File("Sistema.xml"); Document newDocument = null;/*from w w w .j a v a 2 s . co m*/ Element root = null; boolean autenticado = false; if (file.exists()) { SAXBuilder builder = new SAXBuilder(); try { newDocument = builder.build(file); } catch (JDOMException ex) { Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex); } root = newDocument.getRootElement(); } else { root = new Element("sistema"); newDocument = new Document(root); } User user = null; List<Element> listusers = root.getChildren(); for (Element e : listusers) { if (e.getAttributeValue("matrcula").equals(u.getMatricula()) && e.getAttributeValue("senha").equals(u.getPassword())) { autenticado = true; return autenticado; } } return autenticado; }
From source file:codigoFonte.Sistema.java
public boolean autenticaAdmin(String username, String password) { File file = new File("Sistema.xml"); Document newDocument = null;//from w w w. j a va2 s .c o m Element root = null; boolean autenticado = false; if (file.exists()) { SAXBuilder builder = new SAXBuilder(); try { newDocument = builder.build(file); } catch (JDOMException ex) { Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex); } root = newDocument.getRootElement(); } else { root = new Element("sistema"); newDocument = new Document(root); } if (root.getAttributeValue("username").equals(username) && root.getAttributeValue("password").equals(password)) { autenticado = true; return autenticado; } return autenticado; }
From source file:com.astronomy.project.Project.java
/** * Save project as XML file//from www . java2 s . com * @param file XML file * @throws FileNotFoundException File not found error * @throws IOException IO error * @throws NullPointerException Null pointer error */ public void toXML(File file) throws FileNotFoundException, IOException, NullPointerException { Element estudioElemento = new Element("estudio"); Document doc = new Document(estudioElemento); estudioElemento.setAttribute("nombre", name); Element aa = new Element("alineamientos"); estudioElemento.addContent(aa); for (int i = 0; i < data.size(); i++) { Alignment ali = (Alignment) data.get(i); aa.addContent(ali.getXMLElement()); } XMLOutputter xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); FileOutputStream out = null; try { xmlOutput.output(doc, out = new FileOutputStream(file)); } finally { out.close(); } }
From source file:com.c4om.autoconf.ulysses.extra.svinchangesetgenerator.SVINChangesetGenerator.java
License:Apache License
/** * This method generates a changeset document, which describes what nodes * must be added and replaced. It generates it from the SVRLInterpreter * report passed at constructor./*from w w w .ja v a 2 s . c om*/ * * @param pathToConfiguration path to the runtime configuration. * * @param reportDocument the report document (objective solution description). * * @return The generated changeset document. * * @throws JDOMException * If there are problems at JDOM2 XML parsings * @throws IOException * I/O problems * @throws SaxonApiException * problems with Saxon API while transforming metamodel * suggestions into partial autocomplete nodes * @throws ParserConfigurationException * problems with javax.xml APIs while transforming metamodel * suggestions into partial autocomplete nodes */ public Document getSingleChangesetDocument(String pathToConfiguration, Document reportDocument) throws JDOMException, IOException, SaxonApiException, ParserConfigurationException { Element resultRoot = new Element("changeset", AutoconfXMLConstants.NAMESPACE_SVINAPPLIER); resultRoot.addNamespaceDeclaration(NAMESPACE_AUTOCONF_METADATA); // To // prevent // several // "xmlns:*****" // attributes // to // appear // everywhere Document result = new Document(resultRoot); Element reportElement = reportDocument.getRootElement(); for (Element currentDiscrepancyElement : reportElement.getChildren()) { boolean isCreate = false; Element interestingPathsElement = currentDiscrepancyElement.getChild("interestingPaths", NAMESPACE_SVRL_INTERPETER_REPORT); String searchPathText = interestingPathsElement.getAttributeValue("search-path"); String basePathText = interestingPathsElement.getAttributeValue("base-path"); String keySubpathText = interestingPathsElement.getAttributeValue("key-subpath"); // First, we look for a path to search the element where discrepancy // took place (if it exists) String[] docAndPath; String searchPathInternal; if (searchPathText == null) { docAndPath = divideDocAndPath(basePathText); searchPathInternal = docAndPath[1] + "[" + keySubpathText + "]"; } else { docAndPath = divideDocAndPath(searchPathText); searchPathInternal = docAndPath[1]; } if (!documentCache.containsKey(docAndPath[0])) { documentCache.put(docAndPath[0], loadJDOMDocumentFromFile(new File(pathToConfiguration + "/" + docAndPath[0]))); } Document currentDoc = documentCache.get(docAndPath[0]); List<Element> discordingElementAtDocList = performJAXENXPath(searchPathInternal, currentDoc, Filters.element(), xpathNamespaces); if (discordingElementAtDocList.size() == 0) { isCreate = true; } if (isCreate) { Element nodeToCreate = currentDiscrepancyElement .getChild("suggestedPartialNode", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0) .clone(); //Sometimes, svinrep namespace is declared here (it is not clear why). We must remove it. nodeToCreate.removeNamespaceDeclaration(NAMESPACE_SVRL_INTERPETER_REPORT); boolean thereAreMetamodelSuggestions = currentDiscrepancyElement .getChild("metamodelSuggestions", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren() .size() > 0; if (thereAreMetamodelSuggestions) { Element metamodelSuggestionUntransformed = currentDiscrepancyElement .getChild("metamodelSuggestions", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0) .clone(); Document suggestionMiniDocument = new Document(metamodelSuggestionUntransformed); Document suggestionMiniDocumentTransformed = performXSLT(suggestionMiniDocument, xsltTransformMetamodelDocument); Element metamodelSuggestion = suggestionMiniDocumentTransformed.getRootElement(); Attribute metadataAttribute = new Attribute("autogen-from", "metamodel", NAMESPACE_AUTOCONF_METADATA); mixTreesRecursive(metamodelSuggestion, nodeToCreate, metadataAttribute, NAMESPACE_AUTOCONF_METADATA.getURI()); } else { Attribute mayNeedManualCompletion = new Attribute("may-need-completion", "true", NAMESPACE_AUTOCONF_METADATA); nodeToCreate.setAttribute(mayNeedManualCompletion); } Element createNodeElement = new Element("add-node", AutoconfXMLConstants.NAMESPACE_SVINAPPLIER); final String REGEXP_TO_GET_PARENT_PATH = "(.+)(/[^\\[\\]/]+(\\[.+\\])?)$"; Pattern patternToGetParentPath = Pattern.compile(REGEXP_TO_GET_PARENT_PATH); Matcher matcherToGetParentPath = patternToGetParentPath.matcher(searchPathInternal); matcherToGetParentPath.matches(); String pathToParent = matcherToGetParentPath.group(1); Attribute pathToParentAttr = new Attribute("underParentAtPath", pathToParent); Attribute documentToChangeAttr = new Attribute("atResource", docAndPath[0]); createNodeElement.setAttribute(documentToChangeAttr); createNodeElement.setAttribute(pathToParentAttr); createNodeElement.addContent(nodeToCreate); resultRoot.addContent(createNodeElement); } else { for (int i = 0; i < discordingElementAtDocList.size(); i++) { Element nodeToModify = currentDiscrepancyElement .getChild("suggestedPartialNode", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0) .clone(); //Sometimes, svinrep namespace is declared here (it is not clear why). We must remove it. nodeToModify.removeNamespaceDeclaration(NAMESPACE_SVRL_INTERPETER_REPORT); Element discordingElementAtDoc = discordingElementAtDocList.get(i); mixTreesRecursive(discordingElementAtDoc, nodeToModify, null, NAMESPACE_AUTOCONF_METADATA.getURI()); Element replaceNodeElement = new Element("replace-node", AutoconfXMLConstants.NAMESPACE_SVINAPPLIER); Attribute pathToElementAttr = new Attribute("atPath", generateAttributeBasedPath(discordingElementAtDoc)); Attribute documentToChangeAttr = new Attribute("atResource", docAndPath[0]); replaceNodeElement.setAttribute(documentToChangeAttr); replaceNodeElement.setAttribute(pathToElementAttr); replaceNodeElement.addContent(nodeToModify); resultRoot.addContent(replaceNodeElement); } } } return result; }
From source file:com.c4om.autoconf.ulysses.extra.svrlinterpreter.SVRLInterpreterProcessor.java
License:Apache License
/** * Method that actually performs the process * @param intermediateResults a list of intermediate results. * @return the resulting report/*ww w. j a v a2s . co m*/ * @throws SaxonApiException if a XQuery query fails. * @throws IOException required by internal methods, but it will never be thrown (normally) * @throws JDOMException if there are problems at XML Parsing */ public Document process(List<List<String>> intermediateResults) throws SaxonApiException, JDOMException, IOException { SAXBuilder builder = new SAXBuilder(); Element rootElement = new Element("report", NAMESPACE_SVRL_INTERPETER_REPORT); Document result = new Document(rootElement); Map<String, List<Element>> queryCache = performXPathMetamodelSuggestionQueries( listOfListsToSingleList(intermediateResults, 0)); for (int i = 0; i < intermediateResults.size(); i++) { List<String> intermediateResult = intermediateResults.get(i); Element currentDiscrepancyElement = new Element("discrepancy", NAMESPACE_SVRL_INTERPETER_REPORT); rootElement.addContent(currentDiscrepancyElement); String partialNodeString = saxonQuery(intermediateResult.get(1)); Reader partialNodeStringReader = new StringReader(partialNodeString); Document partialNodeDoc = builder.build(partialNodeStringReader); Element partialNode = partialNodeDoc.getRootElement().detach(); Element currentInterestingPathsElement = new Element("interestingPaths", NAMESPACE_SVRL_INTERPETER_REPORT); moveAndRemoveNSOfAttr(partialNode, currentInterestingPathsElement, "mandatory-path", NAMESPACE_SVRL_INTERPETER_REPORT); moveAndRemoveNSOfAttr(partialNode, currentInterestingPathsElement, "base-path", NAMESPACE_SVRL_INTERPETER_REPORT); moveAndRemoveNSOfAttr(partialNode, currentInterestingPathsElement, "key-subpath", NAMESPACE_SVRL_INTERPETER_REPORT); moveAndRemoveNSOfAttr(partialNode, currentInterestingPathsElement, "search-path", NAMESPACE_SVRL_INTERPETER_REPORT); currentDiscrepancyElement.addContent(currentInterestingPathsElement); Element currentSuggestedPartialNodeElement = new Element("suggestedPartialNode", NAMESPACE_SVRL_INTERPETER_REPORT); currentDiscrepancyElement.addContent(currentSuggestedPartialNodeElement); currentSuggestedPartialNodeElement.addContent(partialNode); Element currentMetamodelSuggestionsElement = new Element("metamodelSuggestions", NAMESPACE_SVRL_INTERPETER_REPORT); currentDiscrepancyElement.addContent(currentMetamodelSuggestionsElement); List<Element> queryResults = queryCache.get(intermediateResult.get(0)); for (Element queryResult : queryResults) { currentMetamodelSuggestionsElement.addContent(queryResult.clone()); } } return result; }
From source file:com.c4om.autoconf.ulysses.extra.svrlmultipathinterpreter.SVRLMultipathInterpreterMain.java
License:Apache License
/** * This method performs the actual svrl interpretation process (which constitutes the objective solving process). * @param svrlDocument the SVRL document (i.e. the objective description) * @return the svrl interpreter report (i.e. the objective solution) * @throws JDOMException if there are XML problems * @throws IOException if there are I/O problems. *//*from w ww . java 2 s . c o m*/ public Document interpret(Document svrlDocument) throws JDOMException, IOException { Element resultRootElement = new Element("report", AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT); Document result = new Document(resultRootElement); List<String> pathsListRepeated = getPathsFromDocument(svrlDocument); PathGroupsGenerator pathGroupsGenerator = new PathGroupsGenerator(); List<PathGroup> pathGroups = pathGroupsGenerator.getPathGroups(pathsListRepeated); PartialNodeGenerator partialNodeGenerator = new PartialNodeGenerator(this.xpathNamespaces, this.pathToConfiguration, this.pathToMetamodel, this.metamodelAttributesPrefix); for (PathGroup pathGroup : pathGroups) { Element currentDiscrepancyElement = new Element("discrepancy", AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT); Element currentInterestingPathsElement = new Element("interestingPaths", AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT); // '/.[text()=something]' tokens should not be used to look for elements at the metamodel and/or search paths, as text DOES NOT identify elements according to our convention. String fixedBasePath = pathGroup.getBasePath().replaceAll("\\]/\\.\\[(?<bracketContent>[^\\]]+)\\]$", "]"); currentInterestingPathsElement.setAttribute("search-path", "doc('" + pathGroup.getDocumentPath() + "')" + fixedBasePath); currentDiscrepancyElement.addContent(currentInterestingPathsElement); Element suggestedPartialNodeElement = new Element("suggestedPartialNode", AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT); currentDiscrepancyElement.addContent(suggestedPartialNodeElement); Element partialNode = partialNodeGenerator.generatePartialNode(pathGroup); suggestedPartialNodeElement.addContent(partialNode); File metamodelDocFile = new File(pathGroup.getDocumentPath()); if (!metamodelDocFile.isAbsolute()) { metamodelDocFile = new File(this.pathToMetamodel, pathGroup.getDocumentPath()); } List<Element> metamodelSuggestedNodeList; try { Document metamodelDoc = documentCache.get(metamodelDocFile.getAbsolutePath()); if (metamodelDoc == null) { metamodelDoc = loadJDOMDocumentFromFile(metamodelDocFile); documentCache.put(metamodelDocFile.getAbsolutePath(), metamodelDoc); } metamodelSuggestedNodeList = performJAXENXPath(fixedBasePath, metamodelDoc); } catch (IOException e) { metamodelSuggestedNodeList = Collections.emptyList(); } Element metamodelSuggestionsElement = new Element("metamodelSuggestions", AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT); for (Element metamodelSuggestedNode : metamodelSuggestedNodeList) { metamodelSuggestionsElement.addContent(metamodelSuggestedNode.clone()); } currentDiscrepancyElement.addContent(metamodelSuggestionsElement); resultRootElement.addContent(currentDiscrepancyElement); } return result; }
From source file:com.collir24.policyextractor.Extract.java
License:Apache License
private static Document buildDocument(List<ModulePermissions> modulePermissions) { Element modulePolicy = new Element("modulePolicy"); for (ModulePermissions mps : modulePermissions) { Element module = new Element("module"); module.setAttribute("name", mps.getModuleName()); Set<String> policySet = new HashSet<String>(); for (ModulePermission mp : mps.getPermissions()) { Element permRequired = new Element("permRequired"); permRequired.setAttribute("line", Integer.toString(mp.getLine())); permRequired.setAttribute("className", mp.getClassName()); for (String s : mp.getPolicy()) { Element perm = new Element("perm"); perm.setText(s);/* w ww . ja va 2 s.c o m*/ permRequired.addContent(perm); } module.addContent(permRequired); // TODO: say what caused the permission to be required - see key policySet.addAll(mp.getPolicy()); } CDATA policyData = new CDATA(generatePolicy(policySet)); module.addContent(policyData); modulePolicy.addContent(module); } return new Document(modulePolicy); }
From source file:com.dexterapps.android.translator.TranslateAndSaveAndroid.java
License:Apache License
private void generateXMLForCountry(String countryCode, List<String> translatedText, ArrayList<AndroidStringMapping> stringXmlDOM, HashMap<String, Integer> baseStringResourcesMapping, String outPutFolder) {/*w w w . j a v a 2 s. co m*/ Element resources = new Element("resources"); Document doc = new Document(resources); //System.out.println("Generating XML"); //int totalNumberOfStrings = 0; for (int i = 0; i < stringXmlDOM.size(); i++) { AndroidStringMapping stringMapping = stringXmlDOM.get(i); if (stringMapping.getType().equalsIgnoreCase("string")) { Element string = new Element("string"); string.setAttribute(new Attribute("name", stringMapping.getAttributeName())); //To get the attribute value, use the hasmap and then string array int translatedTextIndex = baseStringResourcesMapping.get(stringMapping.getAttributeValue()); string.setText(translatedText.get(translatedTextIndex)); //Add element to root doc.getRootElement().addContent(string); } else if (stringMapping.getType().equalsIgnoreCase("string-array")) { Element stringArray = new Element("string-array"); stringArray.setAttribute(new Attribute("name", stringMapping.getAttributeName())); //Since this is String array it will have a list of string items, get the list of string items ArrayList<String> stringArrayItems = (ArrayList<String>) stringMapping.getAttributeValue(); for (int j = 0; j < stringArrayItems.size(); j++) { int translatedTextIndex = baseStringResourcesMapping.get(stringArrayItems.get(j)); stringArray.addContent(new Element("item").setText(translatedText.get(translatedTextIndex))); } //Add element to root doc.getRootElement().addContent(stringArray); } else { Element stringArray = new Element("plurals"); stringArray.setAttribute(new Attribute("name", stringMapping.getAttributeName())); //Since this is plurals it will have a list of string items with values, get the list of string items ArrayList<AndroidStringPlurals> stringPluralItems = (ArrayList<AndroidStringPlurals>) stringMapping .getAttributeValue(); for (int j = 0; j < stringPluralItems.size(); j++) { int translatedTextIndex = baseStringResourcesMapping .get(stringPluralItems.get(j).getAttributeValue()); Element pluralItem = new Element("item"); pluralItem.setAttribute("quantity", stringPluralItems.get(j).getAttributeName()); pluralItem.setText(translatedText.get(translatedTextIndex)); stringArray.addContent(pluralItem); } //Add element to root doc.getRootElement().addContent(stringArray); } } // new XMLOutputter().output(doc, System.out); XMLOutputter xmlOutput = new XMLOutputter(); try { // System.out.println("Saving File"); Format format = Format.getPrettyFormat(); format.setEncoding("UTF-8"); xmlOutput.setFormat(format); File file = new File(outPutFolder + "/values-" + countryCode); if (!file.exists()) { file.mkdir(); } file = new File(outPutFolder + "/values-" + countryCode + "/strings.xml"); FileOutputStream fop = new FileOutputStream(file); xmlOutput.output(doc, fop); System.out.println("Translation Successful !!"); // System.out.println("File Saved!"); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.facebook.buck.ide.intellij.projectview.ProjectView.java
License:Apache License
private static Document newDocument(Element root) { return new Document(root); }