List of usage examples for org.w3c.dom Element hasAttribute
public boolean hasAttribute(String name);
true
when an attribute with a given name is specified on this element or has a default value, false
otherwise. From source file:com.codename1.android.AndroidLayoutImporter.java
private String get(Element el, String att, String defaultValue) { if (el.getOwnerDocument() == inputDOM && !el.hasAttributeNS(NS_ANDROID, att)) { return defaultValue; } else if (el.getOwnerDocument() != inputDOM && !el.hasAttribute(att)) { return defaultValue; }/*w w w .ja v a 2 s . c o m*/ String val = el.getOwnerDocument() == inputDOM ? el.getAttributeNS(NS_ANDROID, att) : el.getAttribute(att); if (val == null) { return defaultValue; } return val; }
From source file:com.codename1.android.AndroidLayoutImporter.java
public void execute() throws TransformerConfigurationException, FileNotFoundException, TransformerException, UnsupportedElementException, IOException { Element inRoot = inputDOM.getDocumentElement(); Element dstRoot = convertElement(inputDOM, outputDOM, inRoot); if (!dstRoot.hasAttribute("layout")) { // We may need to wrap our root Element newRoot = outputDOM.createElement("component"); newRoot.setAttribute("type", "Container"); applyBoxLayoutY(newRoot);/* ww w . j av a 2s . c om*/ newRoot.appendChild(dstRoot); dstRoot = newRoot; } dstRoot.setAttribute("name", outputFile.getName().replaceFirst("\\.gui$", "")); outputDOM.appendChild(dstRoot); // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(outputDOM); StreamResult result = new StreamResult(new FileOutputStream(outputFile)); transformer.transform(source, result); if (saveResourceFile) { try (FileOutputStream fos = new FileOutputStream(outputResourceFile)) { outputResources.save(fos); } } }
From source file:com.codename1.android.AndroidLayoutImporter.java
protected void convertElement(Element inputSrcElement, Element out) throws UnsupportedElementException { String id = inputSrcElement.getAttributeNS(NS_ANDROID, "id"); if (id != null) { id = id.substring(id.indexOf("/") + 1); out.setAttribute("name", id.replaceAll("[^a-zA-Z0-9]", "")); }/*from w w w . j a v a 2s. com*/ //out.setAttribute("uiid", "android."+inputSrcElement.getTagName()); out.setAttribute("type", "Container"); out.setAttribute("layout", "FlowLayout"); Node inputParentNode = inputSrcElement.getParentNode(); if (inputParentNode != null && inputParentNode instanceof Element) { Element inputParent = (Element) inputParentNode; if ("FrameLayout".equals(inputParent.getTagName())) { out.setAttribute("layout", "BorderLayout"); String gravity = inputSrcElement.getAttributeNS(NS_ANDROID, "layout_gravity"); String layoutConstraint = "CENTER"; switch (gravity) { case "top": layoutConstraint = "NORTH"; break; case "left": layoutConstraint = "WEST"; break; case "right": layoutConstraint = "EAST"; break; case "bottom": layoutConstraint = "SOUTH"; break; case "fill_vertical": case "center_vertical": case "center_horizontal": case "fill_horizontal": case "center": case "fill": layoutConstraint = "CENTER"; break; default: layoutConstraint = "CENTER"; } Element layoutConstraintEl = out.getOwnerDocument().createElement("layoutConstraint"); layoutConstraintEl.setAttribute("value", layoutConstraint); out.appendChild(layoutConstraintEl); } } switch (inputSrcElement.getTagName()) { case "LinearLayout": convertLinearLayout(inputSrcElement, out); break; case "android.support.v7.widget.RecyclerView": convertRecyclerView(inputSrcElement, out); break; case "FrameLayout": convertFrameLayout(inputSrcElement, out); break; case "android.support.design.widget.CoordinatorLayout": convertCoordinatorLayout(inputSrcElement, out); break; case "android.support.design.widget.CollapsingToolbarLayout": convertCollapsingToolbarLayout(inputSrcElement, out); break; case "android.support.design.widget.AppBarLayout": convertAppBarLayout(inputSrcElement, out); break; case "android.support.v7.widget.Toolbar": convertToolbar(inputSrcElement, out); break; case "android.support.design.widget.FloatingActionButton": convertFloatingActionButton(inputSrcElement, out); break; case "include": { try { convertInclude(inputSrcElement, out); } catch (IOException ex) { Logger.getLogger(AndroidLayoutImporter.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(AndroidLayoutImporter.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(AndroidLayoutImporter.class.getName()).log(Level.SEVERE, null, ex); } } break; case "android.support.v4.widget.NestedScrollView": convertNestedScrollView(inputSrcElement, out); break; case "ListView": convertListView(inputSrcElement, out); break; case "ProgressBar": convertProgressBar(inputSrcElement, out); break; case "TextView": convertTextView(inputSrcElement, out); break; case "Button": convertButton(inputSrcElement, out); break; case "ScrollView": convertScrollView(inputSrcElement, out); break; case "EditText": convertEditText(inputSrcElement, out); break; case "CheckBox": convertCheckBox(inputSrcElement, out); break; case "View": convertView(inputSrcElement, out); break; case "merge": convertMerge(inputSrcElement, out); break; case "RadioGroup": convertRadioGroup(inputSrcElement, out); break; case "RadioButton": convertRadioButton(inputSrcElement, out); break; case "Spinner": convertSpinner(inputSrcElement, out); break; case "RelativeLayout": convertRelativeLayout(inputSrcElement, out); break; case "ImageButton": convertImageButton(inputSrcElement, out); break; case "ImageView": convertImageView(inputSrcElement, out); break; case "SeekBar": convertSeekBar(inputSrcElement, out); break; case "QuickContactBadge": convertQuickContactBadge(inputSrcElement, out); break; case "ViewAnimator": convertViewAnimator(inputSrcElement, out); break; case "ViewStub": convertViewStub(inputSrcElement, out); break; case "Space": convertSpace(inputSrcElement, out); break; default: if (suppressUnsupportedElementExceptions) { this.convertOther(inputSrcElement, out); } else { throw new UnsupportedElementException(inputSrcElement); } } convertChildren(inputSrcElement, out); if (out.hasAttribute("layout") && "BorderLayout".equals(out.getAttribute("layout"))) { // Make sure that border layout children have appropriate constraint Set<String> allowable = new HashSet<String>( Arrays.asList(new String[] { "NORTH", "SOUTH", "EAST", "WEST", "CENTER" })); Map<String, Element> childMap = new HashMap<String, Element>(); List<ElementConstraint> childList = getBorderLayoutChildren(out); Set<ElementConstraint> used = new HashSet<ElementConstraint>(); for (ElementConstraint ec : childList) { if (ec.constraint != null && allowable.contains(ec.constraint) && !childMap.containsKey(ec.constraint)) { childMap.put(ec.constraint, ec.el); used.add(ec); } } childList.removeAll(used); if (!childList.isEmpty()) { // We weren't able to place all of the elements in the border layout // this is either because we filled all of the slots, or there were two // in some slots // Let's simplify things for now by just adding all of the extras in a // BoxLayout.Y inside the CENTER Element center = out.getOwnerDocument().createElement("component"); center.setAttribute("type", "Container"); applyBoxLayoutX(center); Element centerConstraint = out.getOwnerDocument().createElement("layoutConstraint"); centerConstraint.setAttribute("value", "CENTER"); center.appendChild(centerConstraint); if (childMap.containsKey("CENTER")) { //System.out.println("Removing center from "+childMap); out.removeChild(childMap.get("CENTER")); center.appendChild(childMap.get("CENTER")); } for (ElementConstraint ec : childList) { removeLayoutConstraint(ec.el); out.removeChild(ec.el); center.appendChild(ec.el); } out.appendChild(center); } } else if (out.hasAttribute("layout")) { // Not a boxlayout. NodeList children = out.getChildNodes(); int len = children.getLength(); for (int i = 0; i < len; i++) { Node n = children.item(i); if (n instanceof Element) { removeLayoutConstraint((Element) n); } } } applyStyles(inputSrcElement, out); }
From source file:net.sourceforge.pmd.rules.RuleFactory.java
/** * Decorates a referenced rule with the metadata that are overridden in the given rule element. * * <p>Declaring a property in the overriding element throws an exception (the property must exist in the referenced * rule).//from ww w .ja v a 2 s.co m * * @param referencedRule Referenced rule * @param ruleSetReference the ruleset, where the referenced rule is defined * @param ruleElement Element overriding some metadata about the rule * * @return A rule reference to the referenced rule */ public RuleReference decorateRule(Rule referencedRule, RuleSetReference ruleSetReference, Element ruleElement) { RuleReference ruleReference = new RuleReference(referencedRule, ruleSetReference); if (ruleElement.hasAttribute(DEPRECATED)) { ruleReference.setDeprecated(Boolean.parseBoolean(ruleElement.getAttribute(DEPRECATED))); } if (ruleElement.hasAttribute(NAME)) { ruleReference.setName(ruleElement.getAttribute(NAME)); } if (ruleElement.hasAttribute(MESSAGE)) { ruleReference.setMessage(ruleElement.getAttribute(MESSAGE)); } if (ruleElement.hasAttribute(EXTERNAL_INFO_URL)) { ruleReference.setExternalInfoUrl(ruleElement.getAttribute(EXTERNAL_INFO_URL)); } for (int i = 0; i < ruleElement.getChildNodes().getLength(); i++) { Node node = ruleElement.getChildNodes().item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { switch (node.getNodeName()) { case DESCRIPTION: ruleReference.setDescription(parseTextNode(node)); break; case EXAMPLE: ruleReference.addExample(parseTextNode(node)); break; case PRIORITY: ruleReference.setPriority(RulePriority.valueOf(Integer.parseInt(parseTextNode(node)))); break; case PROPERTIES: setPropertyValues(ruleReference, (Element) node); break; default: throw new IllegalArgumentException("Unexpected element <" + node.getNodeName() + "> encountered as child of <rule> element for Rule " + ruleReference.getName()); } } } return ruleReference; }
From source file:net.sourceforge.pmd.rules.RuleFactory.java
/** * Parses a rule element and returns a new rule instance. * * <p>Notes: The ruleset name is not set here. Exceptions raised from this method indicate invalid XML structure, * with regards to the expected schema, while RuleBuilder validates the semantics. * * @param ruleElement The rule element to parse * * @return A new instance of the rule described by this element * @throws IllegalArgumentException if the element doesn't describe a valid rule. *///from w w w . ja va 2 s . c om public Rule buildRule(Element ruleElement) { checkRequiredAttributesArePresent(ruleElement); String name = ruleElement.getAttribute(NAME); RuleBuilder builder = new RuleBuilder(name, ruleElement.getAttribute(CLASS), ruleElement.getAttribute("language")); if (ruleElement.hasAttribute(MINIMUM_LANGUAGE_VERSION)) { builder.minimumLanguageVersion(ruleElement.getAttribute(MINIMUM_LANGUAGE_VERSION)); } if (ruleElement.hasAttribute(MAXIMUM_LANGUAGE_VERSION)) { builder.maximumLanguageVersion(ruleElement.getAttribute(MAXIMUM_LANGUAGE_VERSION)); } if (ruleElement.hasAttribute(SINCE)) { builder.since(ruleElement.getAttribute(SINCE)); } builder.message(ruleElement.getAttribute(MESSAGE)); builder.externalInfoUrl(ruleElement.getAttribute(EXTERNAL_INFO_URL)); builder.setDeprecated(hasAttributeSetTrue(ruleElement, DEPRECATED)); builder.usesDFA(hasAttributeSetTrue(ruleElement, "dfa")); builder.usesTyperesolution(hasAttributeSetTrue(ruleElement, "typeResolution")); // Disabled until it's safe // builder.usesMultifile(hasAttributeSetTrue(ruleElement, "multifile")); Element propertiesElement = null; final NodeList nodeList = ruleElement.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) { continue; } switch (node.getNodeName()) { case DESCRIPTION: builder.description(parseTextNode(node)); break; case EXAMPLE: builder.addExample(parseTextNode(node)); break; case PRIORITY: builder.priority(Integer.parseInt(parseTextNode(node).trim())); break; case PROPERTIES: parsePropertiesForDefinitions(builder, node); propertiesElement = (Element) node; break; default: throw new IllegalArgumentException("Unexpected element <" + node.getNodeName() + "> encountered as child of <rule> element for Rule " + name); } } Rule rule; try { rule = builder.build(); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) { LOG.log(Level.SEVERE, "Error instantiating a rule", e); throw new RuntimeException(e); } if (propertiesElement != null) { setPropertyValues(rule, propertiesElement); } return rule; }
From source file:net.sourceforge.pmd.rules.RuleFactory.java
private void checkRequiredAttributesArePresent(Element ruleElement) { // add an attribute name here to make it required for (String att : REQUIRED_ATTRIBUTES) { if (!ruleElement.hasAttribute(att)) { throw new IllegalArgumentException("Missing '" + att + "' attribute"); }//from w w w . j a va 2 s .c om } }
From source file:net.sourceforge.pmd.rules.RuleFactory.java
/** * Finds out if the property element defines a property. * * @param node Property element/*from w w w . ja v a2 s .c om*/ * * @return True if this element defines a new property, false if this is just stating a value */ private static boolean isPropertyDefinition(Element node) { return node.hasAttribute(PropertyDescriptorField.TYPE.attributeName()); }
From source file:net.sourceforge.pmd.rules.RuleFactory.java
private static boolean hasAttributeSetTrue(Element element, String attributeId) { return element.hasAttribute(attributeId) && "true".equalsIgnoreCase(element.getAttribute(attributeId)); }
From source file:net.sourceforge.pmd.RuleSetFactory.java
/** * Parse a ruleset node to construct a RuleSet. * * @param ruleSetReferenceId//from ww w. ja v a2 s. co m * The RuleSetReferenceId of the RuleSet being parsed. * @param withDeprecatedRuleReferences * whether rule references that are deprecated should be ignored * or not * @return The new RuleSet. */ private RuleSet parseRuleSetNode(RuleSetReferenceId ruleSetReferenceId, boolean withDeprecatedRuleReferences) throws RuleSetNotFoundException { try (CheckedInputStream inputStream = new CheckedInputStream( ruleSetReferenceId.getInputStream(resourceLoader), new Adler32());) { if (!ruleSetReferenceId.isExternal()) { throw new IllegalArgumentException( "Cannot parse a RuleSet from a non-external reference: <" + ruleSetReferenceId + ">."); } DocumentBuilder builder = createDocumentBuilder(); InputSource inputSource; if (compatibilityFilter != null) { inputSource = new InputSource(compatibilityFilter.filterRuleSetFile(inputStream)); } else { inputSource = new InputSource(inputStream); } Document document = builder.parse(inputSource); Element ruleSetElement = document.getDocumentElement(); RuleSetBuilder ruleSetBuilder = new RuleSetBuilder(inputStream.getChecksum().getValue()) .withFileName(ruleSetReferenceId.getRuleSetFileName()); if (ruleSetElement.hasAttribute("name")) { ruleSetBuilder.withName(ruleSetElement.getAttribute("name")); } else { LOG.warning("RuleSet name is missing. Future versions of PMD will require it."); ruleSetBuilder.withName("Missing RuleSet Name"); } NodeList nodeList = ruleSetElement.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { String nodeName = node.getNodeName(); if (DESCRIPTION.equals(nodeName)) { ruleSetBuilder.withDescription(parseTextNode(node)); } else if ("include-pattern".equals(nodeName)) { ruleSetBuilder.addIncludePattern(parseTextNode(node)); } else if ("exclude-pattern".equals(nodeName)) { ruleSetBuilder.addExcludePattern(parseTextNode(node)); } else if ("rule".equals(nodeName)) { parseRuleNode(ruleSetReferenceId, ruleSetBuilder, node, withDeprecatedRuleReferences); } else { throw new IllegalArgumentException(UNEXPECTED_ELEMENT + node.getNodeName() + "> encountered as child of <ruleset> element."); } } } if (!ruleSetBuilder.hasDescription()) { LOG.warning("RuleSet description is missing. Future versions of PMD will require it."); ruleSetBuilder.withDescription("Missing description"); } ruleSetBuilder.filterRulesByPriority(minimumPriority); return ruleSetBuilder.build(); } catch (ReflectiveOperationException ex) { ex.printStackTrace(); throw new RuntimeException("Couldn't find the class " + ex.getMessage(), ex); } catch (ParserConfigurationException | IOException | SAXException ex) { ex.printStackTrace(); throw new RuntimeException("Couldn't read the ruleset " + ruleSetReferenceId + ": " + ex.getMessage(), ex); } }
From source file:net.sourceforge.pmd.RuleSetFactory.java
/** * Check whether the given ruleName is contained in the given ruleset. * * @param ruleSetReferenceId the ruleset to check * @param ruleName the rule name to search for * * @return {@code true} if the ruleName exists *///from ww w . j a v a2 s .c om private boolean containsRule(RuleSetReferenceId ruleSetReferenceId, String ruleName) { boolean found = false; try (InputStream ruleSet = ruleSetReferenceId.getInputStream(resourceLoader)) { DocumentBuilder builder = createDocumentBuilder(); Document document = builder.parse(ruleSet); Element ruleSetElement = document.getDocumentElement(); NodeList rules = ruleSetElement.getElementsByTagName("rule"); for (int i = 0; i < rules.getLength(); i++) { Element rule = (Element) rules.item(i); if (rule.hasAttribute("name") && rule.getAttribute("name").equals(ruleName)) { found = true; break; } } } catch (Exception e) { throw new RuntimeException(e); } return found; }