Example usage for org.dom4j Element attribute

List of usage examples for org.dom4j Element attribute

Introduction

In this page you can find the example usage for org.dom4j Element attribute.

Prototype

Attribute attribute(QName qName);

Source Link

Document

DOCUMENT ME!

Usage

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./*  w  w  w .j av  a2s .  com*/
 * 
 * @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.tu_berlin.cit.intercloud.xmpp.component.ResourceContainerComponent.java

License:Apache License

/**
 * Override this method to handle the IQ stanzas of type <tt>get</tt> that
 * could not be processed by the {@link AbstractComponent} implementation.
 * /*  ww  w. j  ava  2 s.c o m*/
 * Note that, as any IQ stanza of type <tt>get</tt> must be replied to,
 * returning <tt>null</tt> from this method equals returning an IQ error
 * stanza of type 'feature-not-implemented' (this behavior can be disabled
 * by setting the <tt>enforceIQResult</tt> argument in the constructor to
 * <tt>false</tt>).
 * 
 * Note that if this method throws an Exception, an IQ stanza of type
 * <tt>error</tt>, condition 'internal-server-error' will be returned to the
 * sender of the original request.
 * 
 * The default implementation of this method returns <tt>null</tt>. It is
 * expected that most child classes will override this method.
 * 
 * @param iq
 *            The IQ request stanza of type <tt>get</tt> that was received
 *            by this component.
 * @return the response the to request stanza, or <tt>null</tt> to indicate
 *         'feature-not-available'.
 */
@Override
protected IQ handleIQGet(IQ iq) throws Exception {
    logger.info("the following iq get stanza has been received:" + iq.toString());
    Element child = iq.getChildElement();
    String path = child.attribute("path").getValue();
    ResourceTypeDocument xwadl = this.container.getXWADL(path);
    Document doc = DocumentHelper.parseText(xwadl.toString());
    IQ response = IQ.createResultIQ(iq);
    response.setChildElement(doc.getRootElement());
    logger.info("the following iq result stanza will be send:" + response.toString());
    return response;
}

From source file:de.tu_berlin.cit.rwx4j.component.ResourceContainerComponent.java

License:Apache License

/**
 * Override this method to handle the IQ stanzas of type <tt>get</tt> that
 * could not be processed by the {@link AbstractComponent} implementation.
 * //from  www  .  j a v  a2  s  .c o  m
 * Note that, as any IQ stanza of type <tt>get</tt> must be replied to,
 * returning <tt>null</tt> from this method equals returning an IQ error
 * stanza of type 'feature-not-implemented' (this behavior can be disabled
 * by setting the <tt>enforceIQResult</tt> argument in the constructor to
 * <tt>false</tt>).
 * 
 * Note that if this method throws an Exception, an IQ stanza of type
 * <tt>error</tt>, condition 'internal-server-error' will be returned to the
 * sender of the original request.
 * 
 * The default implementation of this method returns <tt>null</tt>. It is
 * expected that most child classes will override this method.
 * 
 * @param iq
 *            The IQ request stanza of type <tt>get</tt> that was received
 *            by this component.
 * @return the response the to request stanza, or <tt>null</tt> to indicate
 *         'feature-not-available'.
 */
@Override
protected IQ handleIQGet(IQ iq) throws Exception {
    logger.info("the following iq get stanza has been received:" + iq.toString());
    Element child = iq.getChildElement();
    String path = child.attribute("path").getValue();
    XwadlDocument xwadl = this.container.getXWADL(path);
    Document doc = DocumentHelper.parseText(xwadl.toString());
    IQ response = IQ.createResultIQ(iq);
    response.setChildElement(doc.getRootElement());
    logger.info("the following iq result stanza will be send:" + response.toString());
    return response;
}

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  ww  w.  j av  a  2s .  co  m*/

        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 ww.  java  2s.c o  m*/
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:edu.umd.cs.findbugs.filter.Filter.java

License:Open Source License

/**
 * Get a Matcher for given Element./*from ww  w  .j a  v a 2s .c  om*/
 * 
 * @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.ml.GenerateUIDs.java

License:Open Source License

@SuppressWarnings("unchecked")
public void execute() throws IOException, DocumentException {
    InputStream in = null;/*from w  ww .jav  a  2  s  .c om*/
    try {
        if (inputFilename.equals("-")) {
            in = System.in;
        } else {
            in = new BufferedInputStream(new FileInputStream(inputFilename));
            if (inputFilename.endsWith(".gz"))
                in = new GZIPInputStream(in);
        }

        bugCollection.readXML(in);
        in = null;
    } finally {
        if (in != null)
            in.close();
    }
    Document document = DocumentFactory.getInstance().createDocument();
    Dom4JXMLOutput xmlOutput = new Dom4JXMLOutput(document);
    bugCollection.writeXML(xmlOutput);

    int count = 0;

    List<Element> bugInstanceList = document.selectNodes("/BugCollection/BugInstance");
    for (Element element : bugInstanceList) {
        Attribute uidAttr = element.attribute("uid");
        if (uidAttr == null) {
            element.addAttribute("uid", Integer.toString(count++));
        }
    }

    OutputStream out;
    if (outputFilename.equals("-")) {
        out = System.out;
    } else {
        out = new BufferedOutputStream(new FileOutputStream(outputFilename));
    }

    XMLWriter xmlWriter = new XMLWriter(out, OutputFormat.createPrettyPrint());
    try {
        xmlWriter.write(document);
    } finally {
        xmlWriter.close();
    }
}

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

License:BSD License

/**
 * @param category The Document element which represents a Category 
 * @return InputCategory Object for given Category Element.
 *///from  w w w  . java  2s  .c om
private InputCategory getInputCategory(Element category) {
    InputCategory inputCategory = new InputCategory();
    List<InputCategory> subCategories = new ArrayList<InputCategory>();
    InputCategorialClass rootClass = null;
    Element rootCategorialClass = null;
    List<Element> elements = category.elements();

    for (Element e : elements) {
        if (e.getName().equals("CategorialClass")) {
            rootCategorialClass = (Element) category.elementIterator().next();
            rootClass = getInputCategorialClass(rootCategorialClass);
        } else if (e.getName().equals("Category")) {
            subCategories.add(getInputCategory(e));
        }
    }

    String name = category.attribute("name").getValue();
    inputCategory.setName(name);

    String description = category.attribute("description").getValue();
    inputCategory.setDescription(description);
    inputCategory.setRootCategorialClass(rootClass);
    inputCategory.setSubCategories(subCategories);
    return inputCategory;
}

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  w  w. j a v a2  s.  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;
}

From source file:edu.wustl.cab2b.server.multimodelcategory.MultiModelCategoryXmlParser.java

License:BSD License

/**
 * @param category The Document element which represents a MultiModel Category 
 * @return MultiModelCategory Object.//  w ww. j av a2 s.  com
 */
MultiModelCategoryBean populateMultiModelCategory(Document document) {
    Element mmcRoot = document.getRootElement();
    MultiModelCategoryBean mmc = new MultiModelCategoryBean();

    String mmcName = mmcRoot.attribute("name").getValue();
    mmc.setName(mmcName);

    String mmcDescription = mmcRoot.attribute("description").getValue();
    mmc.setDescription(mmcDescription);

    List<ModelGroupInterface> modelGroups = new ModelGroupOperations().getAllModelGroups();
    String modelGroupName = mmcRoot.attribute("applicationGroup").getValue();
    for (ModelGroupInterface modelGroup : modelGroups) {
        if (modelGroup.getModelGroupName().equals(modelGroupName)) {
            mmc.setApplicationGroup(modelGroup);
            break;
        }
    }

    Map<String, List<Element>> arrtribAndPaths = getArrtribAndPaths(mmcRoot);

    List<Element> attributes = arrtribAndPaths.get("MultiModelCategoryAttributes");
    Collection<MultiModelAttributeBean> mmcAttribs = populateMMCAttribs(attributes);
    mmc.setMultiModelAttributes(mmcAttribs);

    List<Element> paths = arrtribAndPaths.get("Paths");
    Collection<IPath> mmcPaths = populateMMCPaths(paths);
    mmc.setPaths(mmcPaths);

    return mmc;
}