List of usage examples for org.jdom2 Element setAttribute
public Element setAttribute(final Attribute attribute)
This sets an attribute value for this element.
From source file:ca.nrc.cadc.xml.JsonInputter.java
License:Open Source License
public Document input(final String json) throws JSONException { JSONObject rootJson = new JSONObject(json); List<String> keys = Arrays.asList(JSONObject.getNames(rootJson)); List<Namespace> namespaces = new ArrayList<Namespace>(); Namespace namespace = getNamespace(namespaces, rootJson, keys); String rootKey = null;//from www . j ava2 s .com List<Attribute> attributes = new ArrayList<Attribute>(); for (String key : keys) { if (!key.startsWith("@xmlns")) { if (key.startsWith("@")) { String value; if (rootJson.isNull(key)) { value = ""; } else { value = getStringValue(rootJson.get(key)); } attributes.add(new Attribute(key.substring(1), value)); } else { // DOM can only have one root element. if (rootKey != null) { throw new IllegalStateException("Found multiple root entries"); } rootKey = key; } } } Element rootElement = new Element(rootKey, namespace); for (Attribute attribute : attributes) { rootElement.setAttribute(attribute); } Object value = rootJson.get(rootKey); processObject(rootKey, value, rootElement, namespace, namespaces); Document document = new Document(); document.setRootElement(rootElement); return document; }
From source file:ca.nrc.cadc.xml.JsonInputter.java
License:Open Source License
private void processJSONObject(JSONObject jsonObject, Element element, List<Namespace> namespaces) throws JSONException { List<String> keys = Arrays.asList(JSONObject.getNames(jsonObject)); Namespace namespace = getNamespace(namespaces, jsonObject, keys); if (namespace == null) { namespace = element.getNamespace(); }/* w w w . ja va 2 s . co m*/ for (String key : keys) { if (jsonObject.isNull(key)) { continue; } // attribute if (key.startsWith("@")) { Object value = jsonObject.get(key); element.setAttribute(new Attribute(key.substring(1), getStringValue(value))); continue; } // text content Object value = jsonObject.get(key); if (key.equals("$")) { element.setText(getStringValue(value)); continue; } Element child = new Element(key, namespace); if (listElementMap.containsKey(key)) { final String childKey = listElementMap.get(key); final Object childObject = ((JSONObject) value).get("$"); Element grandChild = new Element(childKey, namespace); if (childObject instanceof JSONArray) { processJSONArray(key, (JSONArray) childObject, child, namespace, namespaces); } else if (childObject instanceof JSONObject) { processJSONObject((JSONObject) childObject, grandChild, namespaces); child.addContent(grandChild); } } else if (value instanceof JSONObject) { processJSONObject((JSONObject) value, child, namespaces); } element.addContent(child); } }
From source file:codigoFonte.Sistema.java
public boolean addUser(User u) throws IOException { boolean success = false, matriculaExists = false; File file = new File("Sistema.xml"); Document newDocument = null;//from w ww .j a v a 2s .c o m Element root = null; Attribute matricula = null, nome = null, tipo = null, senha = null; Element user = null; if (u.getTipo().isEmpty() || u.getTipo().isEmpty() || u.getPassword().isEmpty()) { return success; } 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.getChildren().size() > 0) { List<Element> listUsers = root.getChildren(); for (Element a : listUsers) { if (a.getAttributeValue("matrcula").equals(u.getMatricula())) { matriculaExists = true; } } } if (!matriculaExists) { user = new Element("user"); matricula = new Attribute("matrcula", this.newId()); tipo = new Attribute("tipo", u.getTipo()); nome = new Attribute("nome", u.getNome()); senha = new Attribute("senha", u.getPassword()); user.setAttribute(matricula); user.setAttribute(nome); user.setAttribute(tipo); user.setAttribute(senha); //user.setAttribute(divida); root.addContent(user); success = true; } // 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); } return success; }
From source file:com.c4om.autoconf.ulysses.extra.svinchangesetgenerator.SVINChangesetGenerator.java
License:Apache License
/** * Recursive method that mixes two XML trees in the following way: * <ul>/* ww w. j av a 2s.c o m*/ * <li>If a child exists at the source leaf but not at destination, the * element is copied as a child to the destination leaf</li> * <li>If a child exists at both the source and the destination leafs and * the source child has children, this method is recursively called to mix * both children</li> * </ul> * Some important remarks: * <ul> * <li>Equality comparison is not made via common methods but via * {@link JDOMUtils#elementsEqualAtCNameAndAttributes(Element, Element)} * .</li> * <li>Results of this method are returned as changes to the * destinationLeaf.</li> * <li>An attribute may be appended to all the elements added to the * destination leaf by this method.</li> * <li>Elements of a concrete namespace can be ignored by this method, if desired.</li> * </ul> * * @param sourceLeaf * The source leaf to mix into the destination leaf. It remains * unchanged. * @param destinationLeaf * The destination leaf, where the source leaf will be mixed * into. Results will be returned as changes at this element, so * IT WILL NOT REMAIN UNCHANGED AFTER THIS METHOD (normally). You * should consider using {@link Element#clone()} if necessary. * @param metadataAttributeToAppend * an attribute to be appended to each element added by this * method to the destinationLeaf. If a node with descendants is * added, the attribute will be added only to the top-level * element (not to all the descendants). If null, no attribute * will be added. * @param ignoreNamespaceURIIfTextPresent any element whose namespace URI matches this one * will be ignored if the source element has text content. * If null, no element is ignored. */ private void mixTreesRecursive(Element sourceLeaf, Element destinationLeaf, Attribute metadataAttributeToAppend, String ignoreNamespaceURIIfTextPresent) { List<Content> sourceLeafContent = sourceLeaf.getContent(); //j is the index for "only-element" content for (int i = 0, j = 0; i < sourceLeafContent.size(); i++) { Content currentContent = sourceLeafContent.get(i); if (!(currentContent instanceof Element)) { continue; } Element currentSourceChild = (Element) currentContent; Element currentDestinationChild = searchElementEqualAtCNameAndAttributes(destinationLeaf.getChildren(), currentSourceChild); if (currentDestinationChild == null) { if (ignoreNamespaceURIIfTextPresent != null && !destinationLeaf.getTextNormalize().equals("") && ignoreNamespaceURIIfTextPresent.equals(currentSourceChild.getNamespaceURI())) { continue; } // There is not equivalent node at destination, so we copy the // whole currentSourceChild. Element elementToAdd = currentSourceChild.clone(); if (metadataAttributeToAppend != null) { elementToAdd.setAttribute(metadataAttributeToAppend.clone()); } destinationLeaf.addContent(j, elementToAdd); } else { // Element exists at destination. If it has children, we recurse // to fill them (they might be not completely filled). if (currentSourceChild.getChildren().size() > 0) { mixTreesRecursive(currentSourceChild, currentDestinationChild, metadataAttributeToAppend, ignoreNamespaceURIIfTextPresent); } } j++; } }
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 . j av a2s . 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
/** * This method:// w ww.j a v a 2 s. com * <ol> * <li>Takes an attribute from a source element</li> * <li>Detaches it</li> * <li>Removes its namespace</li> * <li>Attaches it to a destination element</li> * </ol> * @param sourceElement source element * @param destinationElement destination element * @param attrName the name of the attribute * @param attrNamespace the namespace of the source attribute (it will be removed at destination) */ private static void moveAndRemoveNSOfAttr(Element sourceElement, Element destinationElement, String attrName, Namespace attrNamespace) { Attribute mandatoryPathAttribute = sourceElement.getAttribute(attrName, attrNamespace); if (mandatoryPathAttribute != null) { mandatoryPathAttribute.detach(); mandatoryPathAttribute.setNamespace(Namespace.NO_NAMESPACE); destinationElement.setAttribute(mandatoryPathAttribute); } }
From source file:com.c4om.autoconf.ulysses.extra.svrlmultipathinterpreter.PartialNodeGenerator.java
License:Apache License
/** * Given a selectFromPath, it queries the runtime configuration to get the selectable values pointed by that path * and generates the met:possibleValues element that describes it. * @param selectFromPath the path to select from (including a document function, relative to the runtime configuration) * @param metamodelDoc the metamodel document, to extract probabilities from. * @param originalPath the path of the original element at the document * @return the desired met:possibleValues * @throws IOException If there are I/O errors while loading documents to select values from. * @throws JDOMException If there are problems at XML parsing while loading documents to select values from. *//*from www . ja va2s . c o m*/ private Element getPossibleValuesElement(String selectFromPath, Document metamodelDoc, String originalPath) throws JDOMException, IOException { Element possibleValuesElement = new Element("possibleValues", AutoconfXMLConstants.NAMESPACE_AUTOCONF_METADATA); List<String> gatheredPossibleValues = new ArrayList<>(); if (selectFromPath.contains("|")) { String[] singlePaths = selectFromPath.split("\\|"); for (int i = 0; i < singlePaths.length; i++) { String singlePath = singlePaths[i]; gatheredPossibleValues.addAll(getSelectableValuesFromSinglePath(singlePath)); } } else { gatheredPossibleValues = getSelectableValuesFromSinglePath(selectFromPath); } for (String possibleValue : gatheredPossibleValues) { Element currentPosibleValueElement = new Element("possibleValue", AutoconfXMLConstants.NAMESPACE_AUTOCONF_METADATA); String queryFrequencyStr = "sum(" + originalPath + "/" + metamodelAttributesPrefix + "Value[./@" + metamodelAttributesPrefix + "ValueAttr='" + possibleValue + "']/@" + metamodelAttributesPrefix + "Frequency)"; String queryParentFrequencyStr = "sum(" + originalPath + "/@" + metamodelAttributesPrefix + "Frequency)"; List<Double> queryFrequencyResults; List<Double> queryParentFrequencyResults; if (metamodelDoc != null) { queryFrequencyResults = performJAXENXPath(queryFrequencyStr, metamodelDoc, Filters.fdouble()); queryParentFrequencyResults = performJAXENXPath(queryParentFrequencyStr, metamodelDoc, Filters.fdouble()); } else { queryFrequencyResults = Collections.emptyList(); queryParentFrequencyResults = Collections.emptyList(); } if (queryParentFrequencyResults.size() > 0 && queryFrequencyResults.size() > 0) { double myFrequency = queryFrequencyResults.get(0); double myParentFrequency = queryParentFrequencyResults.get(0); double probability = myFrequency / myParentFrequency; String formattedProbability = String.format(Locale.US, "%.2f", probability); if (!formattedProbability.equalsIgnoreCase("nan")) { Attribute probabilityAttribute = new Attribute("probability", formattedProbability); currentPosibleValueElement.setAttribute(probabilityAttribute); } } currentPosibleValueElement.setText(possibleValue); possibleValuesElement.addContent(currentPosibleValueElement); } return possibleValuesElement; }
From source file:com.cybernostics.jsp2thymeleaf.api.elements.CopyElementConverter.java
protected void addAttributes(Element parent, JspElementContext node, JSPElementNodeConverter context) { final List<Attribute> attributes = convertAttributes(node, context); List<Attribute> atts = attributes.stream().map(a -> { Namespace ns = a.getNamespace(); if (ns.equals(XMLNS) || ns.getPrefix().equals("")) { if (a.getValue().startsWith("${") || a.getValue().startsWith("@{")) { a.setNamespace(TH);//w w w. jav a2 s. co m } } return a; }).collect(toList()); atts.forEach(it -> parent.setAttribute(it)); }
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 ww .j av a 2s. com 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 Element newElement(String name, Attribute attribute) { Element element = new Element(name); element.setAttribute(attribute); return element; }