Example usage for org.dom4j Element attributeValue

List of usage examples for org.dom4j Element attributeValue

Introduction

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

Prototype

String attributeValue(QName qName);

Source Link

Document

This returns the attribute value for the attribute with the given fully qualified name or null if there is no such attribute or the empty string if the attribute value is empty.

Usage

From source file:ch.javasoft.metabolic.parse.SbmlParser.java

License:BSD License

private static CompartmentMetaboliteRatio parseMetaboliteRatio(Element elReact, Element elRatio,
        Map<String, CompartmentMetabolite> metas, boolean educt) throws DocumentException {
    String metaId = elRatio.attributeValue(ATTRIBUTE_SPECIES);
    String sStoich = elRatio.attributeValue(ATTRIBUTE_STOICHIOMETRY);
    double stoich = sStoich == null ? 1d : Double.parseDouble(sStoich);
    CompartmentMetabolite meta = metas.get(metaId);
    if (meta == null) {
        throw new DocumentException(
                "metabolite '" + metaId + "' not found for reaction: " + elReact.attributeValue(ATTRIBUTE_ID));
    }//  w  ww .j  av  a  2  s  . c om
    return new CompartmentMetaboliteRatio(meta, educt ? -stoich : stoich);
}

From source file:ch.javasoft.metabolic.parse.SbmlParser.java

License:BSD License

@SuppressWarnings("unchecked")
private CompartmentMetabolicNetwork createNetwork(Element model, Map<String, CompartmentMetabolite> metas,
        Set<CompartmentReaction> reactions, Map<Annotateable, Map<String, String>> annotations)
        throws DocumentException {
    final CompartmentMetabolicNetwork net;
    if (compartmentOnly) {
        //only a network for the desired compartment, everything else is external
        Set<CompartmentMetabolite> cMetas = new LinkedHashSet<CompartmentMetabolite>();
        Set<CompartmentReaction> cReacts = new LinkedHashSet<CompartmentReaction>();
        for (CompartmentMetabolite meta : metas.values()) {
            if (compartmentName.equals(meta.getCompartment())) {
                if (!cMetas.add(meta)) {
                    throw new DocumentException("duplicate metabolite: " + meta.getName());
                }/*from ww w  . ja v a  2s.c  o m*/
            }
        }
        for (CompartmentReaction react : reactions) {
            ArrayIterable<? extends CompartmentMetaboliteRatio> ratios = react
                    .getMetabolieRatiosForCompartment(compartmentName);
            if (!ratios.isEmpty()) {
                List<CompartmentMetaboliteRatio> newRatios = new ArrayList<CompartmentMetaboliteRatio>(
                        ratios.toGenericArray(false));
                if (!react.getEductRatiosExcludeCompartment(compartmentName).isEmpty()) {
                    //we have also educts from other compartments, which makes this
                    //reaction being an external one                  
                    CompartmentMetabolite cMeta = new CompartmentMetabolite(
                            getExchangeMetaboliteName(react, false /*product*/), compartmentName);
                    CompartmentMetaboliteRatio ratio = new CompartmentMetaboliteRatio(cMeta, -1d);
                    CompartmentReaction xReact = createExchangeReaction(cMeta, true /*uptake*/,
                            react.getConstraints().isReversible());
                    newRatios.add(ratio);
                    if (!cMetas.add(cMeta)) {
                        throw new DocumentException("duplicate metabolite: " + cMeta.getName());
                    }
                    if (!cReacts.add(xReact)) {
                        throw new DocumentException("duplicate reaction: " + xReact.getName());
                    }
                }
                if (!react.getProductRatiosExcludeCompartment(compartmentName).isEmpty()) {
                    CompartmentMetabolite cMeta = new CompartmentMetabolite(
                            getExchangeMetaboliteName(react, true /*product*/), compartmentName);
                    CompartmentMetaboliteRatio ratio = new CompartmentMetaboliteRatio(cMeta, +1d);
                    CompartmentReaction xReact = createExchangeReaction(cMeta, false /*uptake*/,
                            react.getConstraints().isReversible());
                    newRatios.add(ratio);
                    if (!cMetas.add(cMeta)) {
                        throw new DocumentException("duplicate metabolite: " + cMeta.getName());
                    }
                    if (!cReacts.add(xReact)) {
                        throw new DocumentException("duplicate reaction: " + xReact.getName());
                    }
                }
                CompartmentReaction cReact = new CompartmentReaction(react.getName(), react.getFullName(),
                        newRatios, react.getConstraints().isReversible());
                if (!cReacts.add(cReact)) {
                    throw new DocumentException("duplicate reaction: " + cReact.getName());
                }
            }
        }
        net = new CompartmentMetabolicNetwork(cMetas, cReacts);
    } else {
        //add the exchange reactions for the external compartment metabolites
        for (CompartmentMetabolite meta : metas.values()) {
            if (compartmentName.equals(meta.getCompartment())) {
                CompartmentReaction react = createExchangeReaction(meta, false /*uptake*/, true /*reversible*/);
                if (!reactions.add(react)) {
                    throw new DocumentException("duplicate reaction: " + react.getName());
                }
            }
        }
        net = new CompartmentMetabolicNetwork(metas.values(), reactions);
    }

    //set compartment full names
    final Element elCmps = model.element(ELEMENT_COMPARTMENTS);
    for (Element elCmp : (List<Element>) elCmps.elements(ELEMENT_COMPARTMENT)) {
        final String cmpName = elCmp.attributeValue(ATTRIBUTE_ID);
        final String cmpFullName = elCmp.attributeValue(ATTRIBUTE_NAME);
        if (cmpFullName != null && !cmpFullName.equals(cmpName)) {
            net.setCompartmentFullName(cmpName, cmpFullName);
        }
    }

    //add the annotations
    //a) for the network
    parseAnnotations(model, net, annotations);
    //b) for the elements
    for (Annotateable elem : annotations.keySet()) {
        for (Map.Entry<String, String> annot : annotations.get(elem).entrySet()) {
            net.addAnnotation(elem, annot.getKey(), annot.getValue());
        }
    }
    return net;
}

From source file:ch.javasoft.polco.config.Arithmetic.java

License:BSD License

/**
 * Creates a typed {@link Numeric} instance of the specified class, using 
 * the generic types from this arithmetic instance. The given {@code config} 
 * is used to determine the factory for the instance to create, as well as
 * for the factory to initialize the created instance.
 * /*  ww  w.  j  a  va2  s .c om*/
 * @param <U>      The untyped class of the expected instance 
 * @param <T>      The typed class of the expected instance, should be
 *                same class object as {@code U}
 * @param clazz      The class argument to specify the desired return type 
 * @param config   The config used to specify the factory to use, specified 
 *                in a factory attribute. It is also passed to the factory 
 *                to initialize the returned instance
 * @return   the new instance, generically typed by this arithmetic instance
 * 
 * @throws IllegalFactoryException   if the factory was not appropriate for
 *                            the desired return type
 * @throws ConfigException         if the factory did not like the 
 *                            configuration contents
 * @throws FactoryNotFoundException   if factory class was not found
 */
public <U extends Numeric, T extends U> T createNumeric(Class<U> clazz, Element config)
        throws IllegalFactoryException, ConfigException, FactoryNotFoundException {
    final String factoryClassName = config.attributeValue(XmlAttribute.factory.getXmlName());
    if (factoryClassName == null) {
        throw new ConfigException(
                "factory class-name attribute not found: " + XmlAttribute.factory.getXmlName(),
                XmlUtil.getElementPath(config, true));
    }
    final Class<?> factoryClass;
    try {
        factoryClass = Class.forName(factoryClassName);
    } catch (ClassNotFoundException e) {
        throw new FactoryNotFoundException(factoryClassName, e);
    }
    final Class<? extends NumericFactory> numFacClass;
    try {
        numFacClass = factoryClass.asSubclass(NumericFactory.class);
    } catch (ClassCastException e) {
        throw new IllegalFactoryException(
                "not an instance of " + NumericFactory.class.getName() + ": " + factoryClass.getName());
    }
    return createNumeric(clazz, numFacClass, config);
}

From source file:ch.javasoft.xml.config.StreamConfigParser.java

License:BSD License

/**
 * Parses an output stream of any type, see class comments  
 * (stream element can be named differently).
 *//*w  w  w.  j  av  a2 s . com*/
public static OutputStream parseOutputStream(Element streamElement) throws XmlConfigException {
    String typeName = streamElement.attributeValue(XmlAttribute.type.getXmlName());
    XmlOutputStreamType type = XmlOutputStreamType.find(typeName);
    if (type == null) {
        throw new XmlConfigException("unknown stream type '" + typeName + "'", streamElement);
    }
    switch (type) {
    case file:
        return parseFileOutputStream(streamElement);
    case console:
        return parseConsolePrintStream(streamElement);
    case logger:
        return parseLoggerStream(streamElement);

    default:
        //should not happen
        throw new XmlConfigException("internal error, unknown stream type " + type, streamElement);
    }
}

From source file:ch.javasoft.xml.config.StreamConfigParser.java

License:BSD License

/**
 * Parses (stream element can be named differently):
 * <pre>/*  ww  w .java 2  s .  c  o  m*/
   <stream type="console">
 <console type="out"/>
   </stream>      
 * </pre>
 */
public static PrintStream parseConsolePrintStream(Element streamElement) throws XmlConfigException {
    Element elConsole = XmlUtil.getRequiredSingleChildElement(streamElement, XmlElement.console);
    String consoleName = elConsole.attributeValue(XmlAttribute.type.getXmlName());
    ConsoleType type = ConsoleType.find(consoleName);
    if (type == null) {
        throw new XmlConfigException("Unknown console type '" + consoleName + "' for "
                + XmlElement.console.getXmlName() + " element", streamElement);
    }
    return type.getStream();
}

From source file:ch.javasoft.xml.config.StreamConfigParser.java

License:BSD License

/**
 * Parses (stream element can be named differently):
 * <pre>/*from   ww w .ja va  2  s  .  c o  m*/
   <stream type="logger">
 <logger name="" level="INFO"/>
   </stream>
 * </pre>
 */
public static PrintStream parseLoggerStream(Element streamElement) throws XmlConfigException {
    Element elLogLevel = XmlUtil.getRequiredSingleChildElement(streamElement, XmlElement.logger);
    String loggerName = elLogLevel.attributeValue(XmlAttribute.name.getXmlName());
    String levelName = elLogLevel.attributeValue(XmlAttribute.level.getXmlName());
    Level logLevel;
    try {
        logLevel = Level.parse(levelName);
    } catch (Exception ex) {
        throw new XmlConfigException("invalid log level: " + levelName, elLogLevel);
    }
    Logger logger = Logger.getLogger(loggerName == null ? "" : loggerName);
    try {
        Class<?> streamClass = Class.forName(LOG_PRINT_STREAM_CLASSNAME);
        Constructor cons = streamClass.getConstructor(new Class[] { Logger.class, Level.class });
        return (PrintStream) cons.newInstance(new Object[] { logger, logLevel });
    } catch (Exception ex) {
        throw new XmlConfigException("cannot instantiate log print stream, e=" + ex, elLogLevel);
    }
}

From source file:ch.javasoft.xml.config.StreamConfigParser.java

License:BSD License

/**
 * Parses (stream element can be named differently):
 * <pre>/*from   www  .j  a va2 s .  c  o m*/
   <stream type="file">
 <file name="{work-dir}/{-out[2]}"/>               
   </stream>
   <stream type="url">
 <url name="http://..."/>               
   </stream>
   <input type="file">
 <file name="{work-dir}/{-out[2]}"/>               
   </input>
 * </pre>
 */
public static InputStream parseInputStream(Element streamElement) throws XmlConfigException {
    String typeName = streamElement.attributeValue(XmlAttribute.type.getXmlName());
    XmlInputStreamType type = XmlInputStreamType.find(typeName);
    if (type == null) {
        throw new XmlConfigException("unknown stream type '" + typeName + "'", streamElement);
    }
    switch (type) {
    case file:
        return parseFileInputStream(streamElement);
    case url:
        return parseURLInputStream(streamElement);
    default:
        //should not happen
        throw new XmlConfigException("internal error, unknown stream type " + type, streamElement);
    }
}

From source file:ch.javasoft.xml.config.URLConfigParser.java

License:BSD License

/**
 * Parses:/*  w ww . j a v  a 2 s  . c  om*/
 * <pre>
   <url name="{work-dir}/{-out[2]}"/>               
 * </pre>
 */
public static URL parseURL(Element urlElement) throws XmlConfigException {
    XmlUtil.checkExpectedElementName(urlElement, XmlElement.url);
    String urlName = urlElement.attributeValue(XmlAttribute.name.getXmlName());
    if (urlName == null) {
        throw new XmlConfigException(XmlAttribute.name.getXmlName() + " attribute missing for "
                + XmlElement.url.getXmlName() + " element", urlElement);
    }
    try {
        return new URL(urlName);
    } catch (MalformedURLException ex) {
        throw new XmlConfigException("cannot parse url '" + urlName + "', e=" + ex, urlElement, ex);
    }
}

From source file:ch.javasoft.xml.config.XmlConfig.java

License:BSD License

/**
 * Parses the given document and returns an XmlConfig instance. Note that
 * this document is expected to contain an application element (direct child
 * of root element) with a name attribute and possible with arg child nodes.
 * Such a document is usually received by calling {@link #toXmlDocument()}.
 *///from  www.  jav  a 2s.c  o m
@SuppressWarnings("unchecked")
public static XmlConfig fromXmlDocument(Document doc) {
    final Element app = doc.getRootElement().element(XmlElement.application.getXmlName());
    final String appName = app.attributeValue(XmlAttribute.name.getXmlName());
    final List<String> args = new ArrayList<String>();
    final Iterator<Element> it = app.elementIterator(XmlElement.arg.getXmlName());
    while (it.hasNext()) {
        args.add(it.next().attributeValue(XmlAttribute.value.getXmlName()));
    }
    doc.remove(app);
    return new XmlConfig(appName, doc, args.toArray(new String[args.size()]));
}

From source file:ch.javasoft.xml.config.XmlConfig.java

License:BSD License

@SuppressWarnings("unchecked")
public Document getConfigDocument(String name) throws XmlConfigException {
    if (name == null)
        throw new NullPointerException("name argument is required");
    Iterator<Element> it = getRootElement().elementIterator(XmlElement.config.getXmlName());
    while (it.hasNext()) {
        Element cfg = it.next();
        String cfgName = cfg.attributeValue(XmlAttribute.name.getXmlName());
        if (name.equals(cfgName)) {
            final Element copy = cfg.createCopy();
            List<Element> resolved = resolve(copy, XmlUtil.getElementPath(copy, false /*recurseParents*/));
            if (resolved.size() != 1) {
                throw new XmlConfigException("resolved config not unique", cfg);
            }/*from  w  w  w  .  j  a v  a2 s. c  o  m*/
            return createDocument(resolved.get(0), name);
        }
    }
    throw new IllegalArgumentException("no such config: " + name);
}