Example usage for org.dom4j Attribute getValue

List of usage examples for org.dom4j Attribute getValue

Introduction

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

Prototype

String getValue();

Source Link

Document

Returns the value of the attribute.

Usage

From source file:de.thischwa.pmcms.view.renderer.VelocityUtils.java

License:LGPL

/**
 * Construct the {@link de.thischwa.pmcms.view.context.object.tagtool.ImageTagTool}-call.
 * @throws RenderingException /*from  ww w.ja  v  a2s  .  c om*/
 */
private static String generateVelocityImageToolCall(final Site site, final Iterator<Attribute> attrIter)
        throws RenderingException {
    StringBuilder veloMacro = new StringBuilder();
    Map<String, String> attr = new HashMap<String, String>();
    veloMacro.append("$imagetagtool");
    veloMacro.append(".usedFromEditor()");
    for (Iterator<Attribute> iter = attrIter; iter.hasNext();) {
        Attribute attribute = iter.next();
        attr.put(attribute.getName(), attribute.getValue());
    }

    Dimension dim = Dimension.getDimensionFromAttr(attr);
    VirtualImage imageResource = new VirtualImage(site, false, false);
    imageResource.consructFromTagFromView(attr.get("src"));
    imageResource.setDimension(dim);
    veloMacro.append(".setSrc(\"").append(imageResource.getTagSrcForPreview()).append("\")");

    for (String key : attr.keySet()) {
        if (!key.equals("src"))
            veloMacro.append(".putAttribute(\"").append(key).append("\", \"").append(attr.get(key))
                    .append("\")");
    }
    return veloMacro.toString();
}

From source file:de.tud.kom.p2psim.impl.scenario.DefaultConfigurator.java

License:Open Source License

/**
 * Can be either a variable (if starts with $) or a plain value
 * //from  w  w  w .ja v a  2  s.co  m
 * @param attr
 * @return proper value
 */
private String getAttributeValue(Attribute attr) {
    // TODO implement some arithmetics
    if (attr == null)
        return null;
    String value = attr.getValue();
    value = parseValue(value);
    if (value == null)
        throw new IllegalStateException("Variable " + attr.getValue() + " has not been set");
    return value;
}

From source file:de.tud.kom.p2psim.impl.scenario.DefaultConfigurator.java

License:Open Source License

/**
 * Create an instance via the reflection of a class by using the given
 * (full) class name and the optional method name. If the method name is
 * null, the default constructor will be used. The method's signature should
 * have no arguments./*from  w  w  w  .j a v a  2s.c  o  m*/
 * 
 * @param className
 * @param staticMethod
 * @param consAttrs
 * @return create instance
 * @throws ConfigurationException
 */
private Object createInstance(String className, String staticMethod, Set<String> consAttrs,
        Element element2createfrom) throws ConfigurationException {
    try {
        Class<?> forName = Class.forName(className);
        Object component = null;
        if (staticMethod == null) {

            Constructor[] cs = forName.getConstructors();

            for (Constructor<?> c : cs) {
                XMLConfigurableConstructor a = c.getAnnotation(XMLConfigurableConstructor.class);
                if (a != null) {
                    String[] cArgs = a.value();
                    Class<?>[] types = c.getParameterTypes();
                    if (cArgs.length != types.length)
                        throw new ConfigurationException(
                                "The size of the argument list of the XML configurable constructor (" + cArgs
                                        + ") is unequal to the size of arguments of the constructor is was applied to.");

                    // Constructor can be called with the given XML
                    // attributes.
                    Object[] consArgs = new Object[cArgs.length];

                    boolean incompatible = false;
                    for (int i = 0; i < consArgs.length; i++) {
                        Attribute attr = element2createfrom.attribute(cArgs[i]);
                        if (attr == null) {
                            // Element elem =
                            // element2createfrom.element(cArgs[i]);
                            Element elem = Dom4jToolkit.getSubElementFromStrCaseInsensitive(element2createfrom,
                                    cArgs[i]);
                            if (elem == null) {
                                incompatible = true;
                                break;
                            }
                            consArgs[i] = configureComponent(elem);
                            if (consArgs[i].getClass().isAssignableFrom(types[i]))
                                throw new ConfigurationException(
                                        "The type of the component configured for the parameter '" + cArgs[i]
                                                + "', type is " + consArgs[i].getClass().getSimpleName()
                                                + " and is not equal to the type " + types[i].getSimpleName()
                                                + " required by the constructor as the argument " + i);
                        } else {
                            consArgs[i] = convertValue(attr.getValue(), types[i]);
                        }
                    }

                    if (!incompatible) {
                        component = c.newInstance(consArgs);

                        for (String consAttr : cArgs) {
                            consAttrs.add(consAttr.toLowerCase());
                        }
                        break;
                    }
                }
            }

            if (component == null)
                component = forName.newInstance();

        } else
            component = forName.getDeclaredMethod(staticMethod, new Class[0]).invoke(null, new Object[0]);
        return component;
    } catch (Exception e) {
        log.error(e);
        throw new ConfigurationException("Failed to create configurable " + className, e);
    }
}

From source file:de.tudarmstadt.ukp.lmf.transform.XMLToDBTransformer.java

License:Apache License

@Override
public void onStart(ElementPath epath) {
    Element el = epath.getCurrent();
    String n = el.getName();//from  w w w.  j  a v a 2  s .  c  o m

    // Remove empty attributes and invalid characters.
    Iterator<?> attrIter = el.attributeIterator();
    while (attrIter.hasNext()) {
        Attribute attr = (Attribute) attrIter.next();
        if ("NULL".equals(attr.getStringValue())) {
            attrIter.remove();
        } else {
            attr.setValue(StringUtils.replaceNonUtf8(attr.getValue()));
        }
    }

    if ("LexicalResource".equals(n)) {
        // If no lexical resource exists yet, create a new one.
        if (lexicalResource == null) {
            lexicalResource = new LexicalResource();
            lexicalResource.setName(el.attributeValue("name"));
            lexicalResource.setDtdVersion(el.attributeValue("dtdVersion"));
            session.save(lexicalResource);
        } else {
            externalLexicalResource = true;
        }
    } else if ("Lexicon".equals(n)) {
        // Create a new, empty lexicon.
        lexicon = new Lexicon();
        lexicon.setId(el.attributeValue("id"));
        lexicon.setName(el.attributeValue("name"));
        lexicon.setLanguageIdentifier(el.attributeValue("languageIdentifier"));
        lexicalResource.addLexicon(lexicon);
        saveCascade(lexicon, lexicalResource);
    }
    // Save some global information if we're using a new lexical resource.
    else if ("GlobalInformation".equals(n) && !externalLexicalResource) {
        GlobalInformation glInformation = new GlobalInformation();
        glInformation.setLabel(el.attributeValue("label"));
        lexicalResource.setGlobalInformation(glInformation);
        saveCascade(glInformation, lexicalResource);
        commit();
        lexicalResource.setGlobalInformation(null);
    }
}

From source file:de.xaniox.heavyspleef.flag.presets.ItemStackFlag.java

License:Open Source License

@SuppressWarnings("unchecked")
static void unmarshalElement(Element baseElement, Map<String, Object> map) {
    List<Element> childElements = baseElement.elements();

    for (Element childElement : childElements) {
        String name = childElement.getName();
        Attribute itemMetaAttribute = childElement.attribute("itemmeta");

        Object value;//from   www.  j a  va 2s. c om

        if (itemMetaAttribute != null && Boolean.valueOf(itemMetaAttribute.getValue()).booleanValue()) {
            Map<String, Object> metaMap = Maps.newHashMap();
            unmarshalElement(childElement, metaMap);

            Material material = Material.valueOf((String) map.get("type"));
            ItemMeta metaDummy = Bukkit.getItemFactory().getItemMeta(material);

            Class<?> deserializationClass = metaDummy.getClass();

            do {
                if (!deserializationClass.isAnnotationPresent(DelegateDeserialization.class)) {
                    break;
                }

                DelegateDeserialization annotation = deserializationClass
                        .getAnnotation(DelegateDeserialization.class);
                deserializationClass = annotation.value();
            } while (true);

            ItemMeta meta;

            try {
                Method method = deserializationClass.getMethod("deserialize", Map.class);
                meta = (ItemMeta) method.invoke(null, metaMap);
            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                    | IllegalArgumentException | InvocationTargetException e) {
                throw new IllegalStateException("Cannot deserialize item meta", e);
            }

            value = meta;
        } else {
            value = deserializeObject(childElement);
        }

        map.put(name, value);
    }
}

From source file:de.xaniox.heavyspleef.persistence.xml.GameAccessor.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from   w w w .  jav  a  2 s.c  om
public Game fetch(Element element) {
    Game game;
    rl.lock();

    try {
        String name = element.attributeValue("name");
        String worldName = element.attributeValue("world");

        if (name == null) {
            throw new RuntimeException("Name of game cannot be null");
        }

        // Not at all thread safe, but it is the only way to get a world instance.
        // Bukkit#getWorlds() returns an new arraylist instance, so iterating is safe
        // but the internal ArrayList::new(Collection) isn't
        World world = null;
        worldLock.lock();
        try {
            List<World> worlds = Bukkit.getWorlds();
            for (World w : worlds) {
                if (w.getName().equals(worldName)) {
                    world = w;
                }
            }
        } finally {
            worldLock.unlock();
        }

        if (world == null) {
            throw new RuntimeException("World \"" + worldName + "\" does not exist (game: " + name + ")");
        }

        game = new Game(heavySpleef, name, world);

        Attribute disabledAttribute = element.attribute("disabled");
        if (disabledAttribute != null) {
            game.setGameState(GameState.DISABLED);
        }

        Attribute enableRatingAttribute = element.attribute("enable-rating");
        if (enableRatingAttribute != null) {
            boolean enabled = Boolean.parseBoolean(enableRatingAttribute.getValue());
            game.getStatisticRecorder().setEnableRating(enabled);
        }

        Element flagsElement = element.element("flags");
        List<Element> flagElementsList = flagsElement.elements("flag");

        for (Element flagElement : flagElementsList) {
            String flagName = flagElement.attributeValue("name");
            AbstractFlag<?> flag = null;

            boolean loadUnloaded = false;
            if (flagRegistry.isFlagPresent(flagName)) {
                Class<? extends AbstractFlag<?>> clazz = flagRegistry.getFlagClass(flagName);
                Flag data = flagRegistry.getFlagData(clazz);
                HookReference[] refs = data.depend();
                if (refs.length != 0) {
                    HookManager hookManager = heavySpleef.getHookManager();

                    for (HookReference ref : refs) {
                        if (hookManager.getHook(ref).isProvided()) {
                            continue;
                        }

                        loadUnloaded = true;
                        break;
                    }
                }

                String[] pluginDepends = data.pluginDepend();
                if (pluginDepends.length != 0) {
                    PluginManager manager = Bukkit.getPluginManager();
                    for (String depend : pluginDepends) {
                        if (manager.isPluginEnabled(depend)) {
                            continue;
                        }

                        loadUnloaded = true;
                        break;
                    }
                }

                if (!loadUnloaded) {
                    flag = flagRegistry.newFlagInstance(flagName, AbstractFlag.class, game);
                    flag.unmarshal(flagElement);
                }
            }

            if (loadUnloaded) {
                //This flag class has not been registered yet
                UnloadedFlag unloaded = new UnloadedFlag();
                unloaded.setXmlElement(flagElement);
                flag = unloaded;
            }

            game.addFlag(flag, false);
        }

        for (AbstractFlag<?> flag : game.getFlagManager().getFlags()) {
            flag.onFlagAdd(game);
        }

        FlagManager flagManager = game.getFlagManager();
        flagManager.revalidateParents();

        ExtensionRegistry extRegistry = heavySpleef.getExtensionRegistry();
        Element extensionsElement = element.element("extensions");
        List<Element> extensionElementsList = extensionsElement.elements("extension");

        for (Element extensionElement : extensionElementsList) {
            String extName = extensionElement.attributeValue("name");
            Class<? extends GameExtension> clazz = extRegistry.getExtensionClass(extName);

            if (clazz == null) {
                heavySpleef.getLogger().log(Level.SEVERE, "Could not load extension with name \"" + extName
                        + "\"): No corresponding class found for extension name");
                continue;
            }

            GameExtension extension;

            try {
                Constructor<? extends GameExtension> constructor = clazz.getDeclaredConstructor();
                if (!constructor.isAccessible()) {
                    constructor.setAccessible(true);
                }

                extension = constructor.newInstance();
            } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException
                    | IllegalArgumentException | InvocationTargetException e) {
                heavySpleef.getLogger().log(Level.SEVERE, "Could not load extension for class \""
                        + clazz.getName() + "\" (name = \"" + extName + "\"): ", e);
                continue;
            }

            extension.setHeavySpleef(heavySpleef);
            extension.setGame(game);
            extension.unmarshal(extensionElement);
            game.addExtension(extension);
        }

        /*Element propertiesElement = element.element("properties");
        List<Element> propertiesElementList = propertiesElement.elements("property");
                
        for (Element propertyElement : propertiesElementList) {
           String key = propertyElement.attributeValue("key");
           String className = propertyElement.attributeValue("class");
                   
           GameProperty property = GameProperty.forName(key);
           Object value = getPropertyValue(className, propertyElement.getText());
                   
           game.requestProperty(property, value);
        }*/

        Element deathzonesElement = element.element("deathzones");
        List<Element> deathzoneElementList = deathzonesElement.elements("deathzone");

        for (Element deathzoneElement : deathzoneElementList) {
            String deathzoneName = deathzoneElement.attributeValue("name");
            String persistenceName = deathzoneElement.attributeValue("regiontype");
            RegionType regionType = RegionType.byPersistenceName(persistenceName);

            XMLRegionMetadataCodec<Region> metadataCodec = (XMLRegionMetadataCodec<Region>) METADATA_CODECS
                    .get(regionType.getRegionClass());
            Region region = metadataCodec.asRegion(deathzoneElement);

            game.addDeathzone(deathzoneName, region);
        }
    } finally {
        rl.unlock();
    }

    return game;
}

From source file:dkpro.similarity.uima.io.RTECorpusReader.java

License:Apache License

@Override
public List<CombinationPair> getAlignedPairs() throws ResourceInitializationException {
    List<CombinationPair> pairs = new ArrayList<CombinationPair>();

    SAXReader reader = null;//  w  ww  .  j av a2  s  .com
    InputStream is = null;
    URL url;
    try {
        reader = new SAXReader(false);

        // Disable DTD resolution (which fails due to relative path to DTD file)
        NullEntityResolver resolver = new NullEntityResolver();
        reader.setEntityResolver(resolver);

        url = ResourceUtils.resolveLocation(inputFile, this, this.getUimaContext());
        Document document = reader.read(new BufferedInputStream(url.openStream()));
        Element root = document.getRootElement();

        final XPath pairXPath = new Dom4jXPath("//pair");

        int i = 0;
        for (Object element : pairXPath.selectNodes(root)) {
            i++;
            String text1 = "";
            String text2 = "";
            String entailmentOutcome = "";
            if (element instanceof Element) {
                Element node = (Element) element;

                String tXPath = "child::t";

                for (Object tElement : new Dom4jXPath(tXPath).selectNodes(node)) {
                    if (tElement instanceof Element) {
                        text1 = ((Element) tElement).getText();
                    }
                }

                String hXPath = "child::h";

                for (Object hElement : new Dom4jXPath(hXPath).selectNodes(node)) {
                    if (hElement instanceof Element) {
                        text2 = ((Element) hElement).getText();
                    }
                }

                // print out entailment value for use as gold standard
                for (Object o : node.attributes()) {
                    Attribute attribute = (Attribute) o;
                    String name = attribute.getName().toLowerCase();
                    if (name.equals("value") || name.equals("entailment")) {
                        entailmentOutcome = attribute.getValue();
                        System.out.println(i + ":" + entailmentOutcome);
                    }
                }
            }

            EntailmentPair pair = new EntailmentPair(url.toString());
            pair.setID1("t1-" + i);
            pair.setID2("t2-" + i);
            pair.setText1(text1);
            pair.setText2(text2);
            pair.setEntailmentOutcome(entailmentOutcome);

            pairs.add(pair);
        }
    } catch (JaxenException e) {
        throw new ResourceInitializationException(e);
    } catch (DocumentException e) {
        throw new ResourceInitializationException(e);
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    } finally {
        IOUtils.closeQuietly(is);
    }

    return pairs;
}

From source file:edu.umd.cs.findbugs.filter.Filter.java

License:Open Source License

/**
 * Get a Matcher for given Element./*w  w  w  .  j a  v  a  2 s .  c  o  m*/
 * 
 * @param element
 *            the Element
 * @return a Matcher representing that element
 * @throws FilterException
 */
private static Matcher getMatcher(Element element) throws FilterException {
    // These will be either BugCode, Priority, Class, Method, Field, or Or
    // elements.
    String name = element.getName();
    if (name.equals("BugCode")) {
        return new BugMatcher(element.valueOf("@name"), "", "");
    } else if (name.equals("Local")) {
        return new LocalMatcher(element.valueOf("@name"));
    } else if (name.equals("BugPattern")) {
        return new BugMatcher("", element.valueOf("@name"), "");
    } else if (name.equals("Bug")) {
        return new BugMatcher(element.valueOf("@code"), element.valueOf("@pattern"),
                element.valueOf("@category"));
    } else if (name.equals("Priority") || name.equals("Confidence")) {
        return new PriorityMatcher(element.valueOf("@value"));
    } else if (name.equals("Rank")) {
        return new RankMatcher(element.valueOf("@value"));
    } else if (name.equals("Class")) {
        Attribute nameAttr = element.attribute("name");

        if (nameAttr == null)
            throw new FilterException("Missing name attribute in Class element");

        return new ClassMatcher(nameAttr.getValue());
    } else if (name.equals("Package")) {
        Attribute nameAttr = element.attribute("name");

        if (nameAttr == null)
            throw new FilterException("Missing name attribute in Package element");

        String pName = nameAttr.getValue();
        pName = pName.startsWith("~") ? pName : "~" + pName.replace(".", "\\.");
        return new ClassMatcher(pName + "\\.[^.]+");
    } else if (name.equals("Method")) {
        Attribute nameAttr = element.attribute("name");
        String nameValue;
        Attribute paramsAttr = element.attribute("params");
        Attribute returnsAttr = element.attribute("returns");
        Attribute roleAttr = element.attribute("role");

        if (nameAttr == null)
            if (paramsAttr == null || returnsAttr == null)
                throw new FilterException(
                        "Method element must have eiter name or params and returnss attributes");
            else
                nameValue = "~.*"; // any name
        else
            nameValue = nameAttr.getValue();

        if ((paramsAttr != null || returnsAttr != null) && (paramsAttr == null || returnsAttr == null))
            throw new FilterException(
                    "Method element must have both params and returns attributes if either is used");

        if (paramsAttr == null)
            if (roleAttr == null)
                return new MethodMatcher(nameValue);
            else
                return new MethodMatcher(nameValue, roleAttr.getValue());
        else if (roleAttr == null)
            return new MethodMatcher(nameValue, paramsAttr.getValue(), returnsAttr.getValue());
        else
            return new MethodMatcher(nameValue, paramsAttr.getValue(), returnsAttr.getValue(),
                    roleAttr.getValue());

    } else if (name.equals("Field")) {
        Attribute nameAttr = element.attribute("name");
        String nameValue;
        Attribute typeAttr = element.attribute("type");

        if (nameAttr == null)
            if (typeAttr == null)
                throw new FilterException("Field element must have either name or type attribute");
            else
                nameValue = "~.*"; // any name
        else
            nameValue = nameAttr.getValue();

        if (typeAttr == null)
            return new FieldMatcher(nameValue);
        else
            return new FieldMatcher(nameValue, typeAttr.getValue());
    } else if (name.equals("Or")) {
        OrMatcher orMatcher = new OrMatcher();
        Iterator<?> i = element.elementIterator();
        while (i.hasNext()) {
            orMatcher.addChild(getMatcher((Element) i.next()));
        }
        return orMatcher;
    } else
        throw new FilterException("Unknown element: " + name);
}

From source file:edu.umd.cs.findbugs.xml.XPathFind.java

License:Open Source License

public static void main(String[] argv) throws Exception {
    if (argv.length != 2) {
        System.err.println("Usage: " + XPathFind.class.getName() + ": <filename> <xpath expression>");
        System.exit(1);/*w w  w  . j av  a2  s .c om*/
    }

    String fileName = argv[0];
    String xpath = argv[1];

    SAXReader reader = new SAXReader();
    Document document = reader.read(fileName);

    XPathFind finder = new XPathFind(document) {
        @Override
        protected void match(Node node) {
            // System.out.println(node.toString());
            if (node instanceof Element) {
                Element element = (Element) node;
                System.out.println("Element: " + element.getQualifiedName());
                System.out.println("\tText: " + element.getText());
                System.out.println("\tAttributes:");
                for (Iterator<?> i = element.attributeIterator(); i.hasNext();) {
                    Attribute attribute = (Attribute) i.next();
                    System.out.println("\t\t" + attribute.getName() + "=" + attribute.getValue());
                }
            } else if (node instanceof Attribute) {
                Attribute attribute = (Attribute) node;
                System.out.println("Attribute: " + attribute.getName() + "=" + attribute.getValue());
            }
        }
    };

    finder.find(xpath);
}

From source file:edu.wustl.cab2b.server.category.CategoryXmlParser.java

License:BSD License

/**
 * @param categorialClass The Document element which represents a CategorialClass
 * @return InputCategorialClass Object for given CategorialClass Element.
 *//*w ww .ja v a  2s  .c  o  m*/
private InputCategorialClass getInputCategorialClass(Element categorialClass) {
    List<InputCategorialAttribute> attributeList = new ArrayList<InputCategorialAttribute>();
    List<InputCategorialClass> children = new ArrayList<InputCategorialClass>();

    String pathFromParent = categorialClass.attribute("IdOfPathFromParentToThis").getValue();
    InputCategorialClass inputCategorialClass = new InputCategorialClass();
    inputCategorialClass.setPathFromParent(Long.parseLong(pathFromParent));
    String entityName = categorialClass.attribute("name").getValue();

    List<Element> elements = categorialClass.elements();
    for (Element element : elements) {
        if (element.getName().equals("Attribute")) {
            String attrName = element.attribute("name").getValue();
            Attribute attribute = element.attribute("displayName");
            String displayName = (attribute == null ? attrName : attribute.getValue());

            AttributeInterface attr = DynamicExtensionUtility.getAttribute(entityName, attrName);
            if (!attrName.equals(attr.getName())) {
                throw new RuntimeException(
                        "Expected attribute : " + attrName + " Returned Attribute : " + attr.getName());
            }
            InputCategorialAttribute inputCategorialAttribute = new InputCategorialAttribute();
            inputCategorialAttribute.setDynamicExtAttribute(attr);
            inputCategorialAttribute.setDisplayName(displayName);
            attributeList.add(inputCategorialAttribute);

        } else if (element.getName().equals("CategorialClass")) {
            children.add(getInputCategorialClass(element));
        }
    }

    inputCategorialClass.setAttributeList(attributeList);
    inputCategorialClass.setChildren(children);

    return inputCategorialClass;
}