Example usage for org.jdom2 Attribute getValue

List of usage examples for org.jdom2 Attribute getValue

Introduction

In this page you can find the example usage for org.jdom2 Attribute getValue.

Prototype

public String getValue() 

Source Link

Document

This will return the actual textual value of this Attribute.

Usage

From source file:com.sun.syndication.io.impl.RSS20Parser.java

License:Open Source License

public boolean isMyType(Document document) {
    boolean ok;/*from w  ww.  jav  a 2  s  . c  o  m*/
    Element rssRoot = document.getRootElement();
    ok = rssRoot.getName().equals("rss");
    if (ok) {
        ok = false;
        Attribute version = rssRoot.getAttribute("version");
        if (version != null) {
            // At this point, as far ROME is concerned RSS 2.0, 2.00 and 
            // 2.0.X are all the same, so let's use startsWith for leniency.
            ok = version.getValue().startsWith(getRSSVersion());
        }
    }
    return ok;
}

From source file:com.swordlord.gozer.builder.Parser.java

License:Open Source License

@SuppressWarnings("unchecked")
private void parseElement(Element element, ObjectBase parent) {
    if (!_objectTags.containsKey(element.getName())) {
        String msg = MessageFormat.format("Element {0} unknown, parsing aborted.", element.getName());
        LOG.error(msg);/*from w  w w  .  ja  v a  2 s.com*/
        return;
    }

    ObjectBase ob = instantiateClass(_objectTags.get(element.getName()));
    if (ob == null) {
        String msg = MessageFormat.format("Class for {0} could not be instantiated, parsing aborted.", element);
        LOG.error(msg);
        return;
    }

    if (element.getText() != null) {
        ob.setContent(element.getText());
    }
    List attributes = element.getAttributes();
    Iterator itAttributes = attributes.iterator();
    while (itAttributes.hasNext()) {
        Attribute attr = (Attribute) itAttributes.next();

        ob.putAttribute(attr.getName(), attr.getValue());
    }

    if (parent != null) {
        ob.inheritParent(parent);
        parent.putChild(ob);
    } else {
        _objectTree.setRoot(ob);
    }

    List children = element.getChildren();
    Iterator itChildren = children.iterator();
    while (itChildren.hasNext()) {
        parseElement((Element) itChildren.next(), ob);
    }
}

From source file:com.thoughtworks.go.config.ConfigCipherUpdater.java

License:Apache License

public void migrate() {
    File cipherFile = systemEnvironment.getDESCipherFile();
    String timestamp = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(timeProvider.currentTime());

    File backupCipherFile = new File(systemEnvironment.getConfigDir(), "cipher.original." + timestamp);
    File configFile = new File(systemEnvironment.getCruiseConfigFile());
    File backupConfigFile = new File(configFile.getParentFile(),
            configFile.getName() + ".original." + timestamp);
    try {//from  w  ww .  j  a va  2 s  .c o m
        if (!cipherFile.exists() || !FileUtils.readFileToString(cipherFile, UTF_8).equals(FLAWED_VALUE)) {
            return;
        }
        LOGGER.info("Found unsafe cipher {} on server, Go will make an attempt to rekey", FLAWED_VALUE);
        FileUtils.copyFile(cipherFile, backupCipherFile);
        LOGGER.info("Old cipher was successfully backed up to {}", backupCipherFile.getAbsoluteFile());
        FileUtils.copyFile(configFile, backupConfigFile);
        LOGGER.info("Old config was successfully backed up to {}", backupConfigFile.getAbsoluteFile());

        String oldCipher = FileUtils.readFileToString(backupCipherFile, UTF_8);
        new DESCipherProvider(systemEnvironment).resetCipher();

        String newCipher = FileUtils.readFileToString(cipherFile, UTF_8);

        if (newCipher.equals(oldCipher)) {
            LOGGER.warn("Unable to generate a new safe cipher. Your cipher is unsafe.");
            FileUtils.deleteQuietly(backupCipherFile);
            FileUtils.deleteQuietly(backupConfigFile);
            return;
        }
        Document document = new SAXBuilder().build(configFile);
        List<String> encryptedAttributes = Arrays.asList("encryptedPassword", "encryptedManagerPassword");
        List<String> encryptedNodes = Arrays.asList("encryptedValue");
        XPathFactory xPathFactory = XPathFactory.instance();
        for (String attributeName : encryptedAttributes) {
            XPathExpression<Element> xpathExpression = xPathFactory
                    .compile(String.format("//*[@%s]", attributeName), Filters.element());
            List<Element> encryptedPasswordElements = xpathExpression.evaluate(document);
            for (Element element : encryptedPasswordElements) {
                Attribute encryptedPassword = element.getAttribute(attributeName);
                encryptedPassword.setValue(reEncryptUsingNewKey(decodeHex(oldCipher), decodeHex(newCipher),
                        encryptedPassword.getValue()));
                LOGGER.debug("Replaced encrypted value at {}", element.toString());
            }
        }
        for (String nodeName : encryptedNodes) {
            XPathExpression<Element> xpathExpression = xPathFactory.compile(String.format("//%s", nodeName),
                    Filters.element());
            List<Element> encryptedNode = xpathExpression.evaluate(document);
            for (Element element : encryptedNode) {
                element.setText(
                        reEncryptUsingNewKey(decodeHex(oldCipher), decodeHex(newCipher), element.getValue()));
                LOGGER.debug("Replaced encrypted value at {}", element.toString());
            }
        }
        try (FileOutputStream fileOutputStream = new FileOutputStream(configFile)) {
            XmlUtils.writeXml(document, fileOutputStream);
        }
        LOGGER.info("Successfully re-encrypted config");
    } catch (Exception e) {
        LOGGER.error("Re-keying of cipher failed with error: [{}]", e.getMessage(), e);
        if (backupCipherFile.exists()) {
            try {
                FileUtils.copyFile(backupCipherFile, cipherFile);
            } catch (IOException e1) {
                LOGGER.error(
                        "Could not replace the cipher file [{}] with original one [{}], please do so manually. Error: [{}]",
                        cipherFile.getAbsolutePath(), backupCipherFile.getAbsolutePath(), e.getMessage(), e);
                bomb(e1);
            }
        }
    }
}

From source file:com.thoughtworks.go.config.parser.GoConfigFieldLoader.java

License:Apache License

public void parse() {
    if (isImplicitCollection()) {
        Object val = GoConfigClassLoader
                .classParser(e, field.getType(), configCache, new GoCipher(), registry, configReferenceElements)
                .parseImplicitCollection();
        setValue(val);
    } else if (isSubtag(field)) {
        Object val = subtagParser(e, field, configCache, registry, configReferenceElements).parse();
        setValue(val);
    } else if (isAttribute(field)) {
        Object val = attributeParser(e, field).parse(defaultValue());
        setValue(val);
    } else if (isConfigValue()) {
        Object val = e.getText();
        setValue(val);
    } else if (isAnnotationPresent(field, ConfigReferenceElement.class)) {
        ConfigReferenceElement referenceField = field.getAnnotation(ConfigReferenceElement.class);
        Attribute attribute = e.getAttribute(referenceField.referenceAttribute());
        if (attribute == null) {
            bomb(String.format("Expected attribute `%s` to be present for %s.",
                    referenceField.referenceAttribute(), e.getName()));
        }/*from ww  w.  j a  v  a 2 s  .co m*/
        String refId = attribute.getValue();
        Object referredObject = configReferenceElements.get(referenceField.referenceCollection(), refId);
        setValue(referredObject);
    }
}

From source file:com.thoughtworks.go.util.ConfigUtil.java

License:Apache License

public String getAttribute(Element e, String attribute) {
    Attribute attr = e.getAttribute(attribute);
    if (attr == null) {
        throw bomb("Error finding attribute '" + attribute + "' in config: " + configFile + elementOutput(e));
    }// w  w w  .j  a va2s  . com
    return attr.getValue();
}

From source file:com.xebialabs.overcast.support.libvirt.jdom.DiskXml.java

License:Apache License

/** Get the disks connected to the domain. */
public static List<Disk> getDisks(Connect connect, Document domainXml) {
    try {//w w  w.j  av  a2  s.  c om
        List<Disk> ret = Lists.newArrayList();
        XPathFactory xpf = XPathFactory.instance();
        XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element());
        XPathExpression<Attribute> typeExpr = xpf.compile(XPATH_DISK_TYPE, Filters.attribute());
        XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute());
        XPathExpression<Attribute> devExpr = xpf.compile(XPATH_DISK_DEV, Filters.attribute());
        List<Element> disks = diskExpr.evaluate(domainXml);
        for (Element disk : disks) {
            Attribute type = typeExpr.evaluateFirst(disk);
            Attribute file = fileExpr.evaluateFirst(disk);
            Attribute dev = devExpr.evaluateFirst(disk);

            StorageVol volume = LibvirtUtil.findVolume(connect, file.getValue());

            ret.add(new Disk(dev.getValue(), file.getValue(), volume, type.getValue()));
        }
        return ret;
    } catch (LibvirtException e) {
        throw new LibvirtRuntimeException(e);
    }
}

From source file:com.xebialabs.overcast.support.libvirt.jdom.FilesystemXml.java

License:Apache License

/**
 * Get map of {@link Filesystem}s. The key in the map is the target inside the domain. This will only return
 * filesystems of type 'mount'./*from   w  ww. j av a 2s . co  m*/
 */
public static Map<String, Filesystem> getFilesystems(Document domainXml) {
    Map<String, Filesystem> ret = Maps.newHashMap();
    XPathFactory xpf = XPathFactory.instance();
    XPathExpression<Element> fsExpr = xpf.compile(XPATH_FILESYSTEM, Filters.element());
    List<Element> filesystems = fsExpr.evaluate(domainXml);
    for (Element fs : filesystems) {
        Attribute accessMode = fs.getAttribute("accessmode");
        String source = fs.getChild("source").getAttribute("dir").getValue();
        String target = fs.getChild("target").getAttribute("dir").getValue();
        boolean readOnly = fs.getChild("readonly") != null;

        ret.put(target, new Filesystem(source, target,
                AccessMode.valueOf(accessMode.getValue().toUpperCase(Locale.US)), readOnly));
    }
    return ret;
}

From source file:cz.muni.fi.pb138.scxml2voicexmlj.XmlHelper.java

/**
 * Get attribute value from {@code element}
 * @throws IllegalArgumentException if no such attribute is present
 *//*from  w w w  .j ava  2s . c  o m*/
public String extractAttribute(Element element, String name) {
    Attribute attribute = element.getAttribute(name);
    if (attribute == null) {
        throw new IllegalArgumentException("Element " + element + " doesnt have attribute " + name);
    }
    return attribute.getValue();
}

From source file:de.andrena.tools.macker.rule.RuleSetBuilder.java

License:Open Source License

public Pattern buildPattern(final Element patternElem, final RuleSet ruleSet, final boolean isTopElem,
        final Pattern nextPat) throws RulesException {
    // handle options

    final String otherPatName = patternElem.getAttributeValue("pattern");
    final String className = getClassNameAttributeValue(patternElem);
    final String filterName = patternElem.getAttributeValue("filter");

    CompositePatternType patType;//ww w  . j a v a  2  s . c  om
    if (patternElem.getName().equals("include")) {
        patType = CompositePatternType.INCLUDE;
    } else if (patternElem.getName().equals("exclude")) {
        patType = filterName == null ? CompositePatternType.EXCLUDE : CompositePatternType.INCLUDE;
    } else if (isTopElem) {
        patType = CompositePatternType.INCLUDE;
    } else {
        throw new RulesDocumentException(patternElem,
                "Invalid element <" + patternElem.getName() + "> --" + " expected <include> or <exclude>");
    }

    if (otherPatName != null && className != null) {
        throw new RulesDocumentException(patternElem,
                "patterns cannot have both a \"pattern\" and a \"class\" attribute");
    }

    // do the head thing

    Pattern head = null;
    if (className != null) {
        head = new RegexPattern(className);
    } else if (otherPatName != null) {
        head = ruleSet.getPattern(otherPatName);
        if (head == null) {
            throw new UndeclaredPatternException(otherPatName);
        }
    }

    // build up children

    Pattern childrenPat = null;
    final List<Element> children = new ArrayList<Element>(getChildren(patternElem)); // !
    // workaround
    // for
    // bug
    // in
    // JUnit
    // List children = patternElem.getChildren(); // this should work
    // instead when JUnit bug is fixed
    for (final ListIterator<Element> childIter = children.listIterator(children.size()); childIter
            .hasPrevious();) {
        final Element subElem = childIter.previous();
        if (subElem.getName().equals("message")) {
            continue;
        }

        childrenPat = buildPattern(subElem, ruleSet, false, childrenPat);
    }

    // wrap head in a filter if necessary

    if (filterName != null) {
        final Map<String, String> options = new HashMap<String, String>();
        for (final Attribute attr : getAttributes(patternElem)) {
            options.put(attr.getName(), attr.getValue());
        }
        options.remove("name");
        options.remove("pattern");
        options.remove("class");
        options.remove("regex");

        final Filter filter = FilterFinder.findFilter(filterName);
        head = filter.createPattern(ruleSet,
                head == null ? new ArrayList<Pattern>() : Collections.singletonList(head), options);

        if (patternElem.getName().equals("exclude")) {
            head = CompositePattern.create(CompositePatternType.EXCLUDE, head, null, null);
        }
    }

    // pull together composite

    return CompositePattern.create(patType, head, childrenPat, nextPat);
}

From source file:de.nava.informa.parsers.FeedParser.java

License:Open Source License

private static synchronized ChannelIF parse(ChannelBuilderIF cBuilder, Document doc) throws ParseException {

    if (cBuilder == null) {
        throw new RuntimeException("Without builder no channel can " + "be created.");
    }/*from ww  w.  ja  va  2  s  . c  om*/
    LOGGER.debug("start parsing.");
    // Get the root element (must be rss)
    Element root = doc.getRootElement();
    String rootElement = root.getName().toLowerCase();
    // Decide which parser to use
    if (rootElement.startsWith("rss")) {
        String rssVersion = root.getAttribute("version").getValue();
        if (rssVersion.contains("0.91")) {
            LOGGER.info("Channel uses RSS root element (Version 0.91).");
            return RSS_0_91_Parser.getInstance().parse(cBuilder, root);
        } else if (rssVersion.contains("0.92")) {
            LOGGER.info("Channel uses RSS root element (Version 0.92).");
            // logger.warn("RSS 0.92 not fully supported yet, fall back to 0.91.");
            // TODO: support RSS 0.92 when aware of all subtle differences.
            return RSS_0_91_Parser.getInstance().parse(cBuilder, root);
        } else if (rootElement.contains("0.93")) {
            LOGGER.info("Channel uses RSS root element (Version 0.93).");
            LOGGER.warn("RSS 0.93 not fully supported yet, fall back to 0.91.");
            // TODO: support RSS 0.93 when aware of all subtle differences.
        } else if (rootElement.contains("0.94")) {
            LOGGER.info("Channel uses RSS root element (Version 0.94).");
            LOGGER.warn("RSS 0.94 not fully supported yet, will use RSS 2.0");
            // TODO: support RSS 0.94 when aware of all subtle differences.
            return RSS_2_0_Parser.getInstance().parse(cBuilder, root);
        } else if (rssVersion.contains("2.0") || rssVersion.equals("2")) {
            LOGGER.info("Channel uses RSS root element (Version 2.0).");
            return RSS_2_0_Parser.getInstance().parse(cBuilder, root);
        } else {
            throw new UnsupportedFormatException("Unsupported RSS version [" + rssVersion + "].");
        }
    } else if (rootElement.contains("rdf")) {
        return RSS_1_0_Parser.getInstance().parse(cBuilder, root);
    } else if (rootElement.contains("feed")) {
        Attribute versionAttr = root.getAttribute("version");
        Namespace namespace = ParserUtils.getDefaultNS(root);
        if (versionAttr != null) {
            String feedVersion = versionAttr.getValue();
            if (feedVersion.contains("0.1") || feedVersion.contains("0.2")) {
                LOGGER.info("Channel uses feed root element (Version " + feedVersion + ").");
                LOGGER.warn("This atom version is not really supported yet, assume Atom 0.3 format");
                return Atom_0_3_Parser.getInstance().parse(cBuilder, root);
            } else if (feedVersion.contains("0.3")) {
                LOGGER.info("Channel uses feed root element (Version 0.3).");
                return Atom_0_3_Parser.getInstance().parse(cBuilder, root);
            }
        } else if (namespace != null && namespace.getURI() != null) {
            if (!namespace.getURI().equals("http://www.w3.org/2005/Atom")) {
                LOGGER.warn("Channel uses unknown namespace in feed root element, assume Atom 1.0 format.");
            } else {
                LOGGER.info("Channel uses feed root element (Atom 1.0 format).");
            }
            return Atom_1_0_Parser.getInstance().parse(cBuilder, root);
        }
    }

    // did not match anything
    throw new UnsupportedFormatException("Unsupported root element [" + rootElement + "].");
}