Example usage for org.dom4j Document getRootElement

List of usage examples for org.dom4j Document getRootElement

Introduction

In this page you can find the example usage for org.dom4j Document getRootElement.

Prototype

Element getRootElement();

Source Link

Document

Returns the root Element for this document.

Usage

From source file:com.jonschang.ai.ga.WSGenerationEvaluator.java

License:LGPL

/**
 * Called by the GeneticAlgWSManagerEndpoint when a Phenotype has completed evaluation.
 * //from   w  w w . j a v  a  2s.com
 * @param uuid The uuid generated by this class to identify the Phenotype
 * @param phenotypeXml The Xml to use reconstructing the Phenotype, or a Stack Trace
 * @return true if this evaluator handles the phenotype, else false
 */
public boolean notifyComplete(String uuid, String phenotypeXml) {
    if (phenotypes.get(uuid) == null)
        return false;
    if (1 == 0) {
        // if the phenotype failed, 
    } else {
        SAXReader sr = new SAXReader();
        try {
            Document d = sr.read(new StringReader(phenotypeXml));
            phenotypes.get(uuid).setXml(d.getRootElement());
        } catch (Exception e) {
            Logger.getLogger(uuid + " An exception occured reading phenotypexml " + this.getClass())
                    .error(StringUtils.stackTraceToString(e));
        } finally {
            synchronized (phenotypes) {
                phenotypes.remove(uuid);
                if (phenotypes.size() == 0 && waiting.value() == true) {
                    Logger.getLogger(this.getClass()).trace("notifying that phenotypes are all evaluated");
                    waiting.value(false);
                }
            }
        }
    }
    return true;
}

From source file:com.jonschang.ai.network.feedforward.FeedForwardXmlUnmarshaller.java

License:LGPL

public void unmarshal(FeedForward obj, Reader xmlReader) throws XmlException {
    SAXReader reader = new SAXReader();
    Document doc = null;

    try {/*from   w  w  w .  j  av a 2  s  .  c  o m*/
        doc = reader.read(xmlReader);
    } catch (Exception e) {
        throw new XmlException("Could not read the Xml document", e);
    }

    Element root = doc.getRootElement();
    Element current = null;

    Map<Integer, Neuron> intToNeuronMap = new HashMap<Integer, Neuron>();
    Map<Integer, Activator> intToActivatorMap = new HashMap<Integer, Activator>();
    int neuronIndex = 0, activators = 0;
    Attribute attr = null;
    Neuron neuron = null;
    Neuron outputNeuron = null;

    obj.getAllLayers().clear();

    // build all the neurons and cache them in an
    // index-to-neuron map
    for (Object e : root.elements())
        if (e instanceof Element) {
            current = (Element) e;

            if (current.getName().compareTo("layers") == 0) {
                for (Object layerObject : current.elements())
                    if (((Element) layerObject).getName().compareTo("layer") == 0) {
                        List<Neuron> thisLayer = new ArrayList<Neuron>();
                        for (Object neuronObject : ((Element) layerObject).elements())
                            if (((Element) neuronObject).getName().compareTo("neuron") == 0) {
                                neuron = new GenericNeuron();

                                intToNeuronMap.put(neuronIndex, neuron);

                                attr = ((Element) neuronObject).attribute("threshold");
                                neuron.setThreshold(Double.valueOf(attr.getValue()));

                                thisLayer.add(neuron);

                                neuronIndex++;
                            }
                        obj.getAllLayers().add(thisLayer);
                    }
            } else if (current.getName().compareTo("activators") == 0 && current.elements().size() > 0) {
                for (Object a : current.elements())
                    if (a instanceof Element) {
                        Element activator = (Element) a;
                        ActivatorXmlFactory axf = new ActivatorXmlFactory();
                        Activator activatorObject = null;
                        String clazz = activator.attributeValue("type");
                        try {
                            activatorObject = (Activator) Class.forName(clazz).newInstance();
                            @SuppressWarnings(value = "unchecked")
                            XmlUnmarshaller<Activator> m = (XmlUnmarshaller<Activator>) axf
                                    .getUnmarshaller(activatorObject);
                            m.unmarshal(activatorObject, new StringReader(activator.asXML()));
                        } catch (Exception cnfe) {
                            throw new XmlException(cnfe);
                        }
                        intToActivatorMap.put(activators, activatorObject);
                        activators++;
                    }

            }
        }

    // now that we've built a cross-reference of index-to-neuron
    // we can process the synapses and easily reconstruct
    // the connections between neurons
    Integer inputIndex = 0, outputIndex, activatorIndex = 0;
    Double weight;
    for (Object e : root.elements())
        if (((Element) e).getName().compareTo("layers") == 0) {
            for (Object layerObject : current.elements())
                if (((Element) layerObject).getName().compareTo("layer") == 0) {
                    for (Object neuronObject : ((Element) layerObject).elements())
                        if (((Element) neuronObject).getName().compareTo("neuron") == 0) {
                            current = (Element) neuronObject;

                            neuron = intToNeuronMap.get(inputIndex);

                            // set the activator 
                            attr = current.attribute("activator-index");
                            activatorIndex = Integer.valueOf(attr.getValue());
                            neuron.setActivator(intToActivatorMap.get(activatorIndex));

                            // process the out-going synapses of the neuron
                            if (current.element("synapses") != null
                                    && current.element("synapses").element("synapse") != null) {
                                for (Object e2 : current.element("synapses").elements())
                                    if (e2 instanceof Element) {
                                        current = (Element) e2;

                                        // get the synapses output neuron
                                        attr = current.attribute("output");
                                        outputIndex = Integer.valueOf(attr.getValue());
                                        outputNeuron = intToNeuronMap.get(outputIndex);

                                        // set the weight of the synapse
                                        attr = current.attribute("weight");
                                        weight = Double.valueOf(attr.getValue());
                                        Synapse s = new GenericSynapse();
                                        neuron.setSynapseTo(s, outputNeuron);
                                        s.setWeight(weight);
                                    }
                            }
                            inputIndex++;
                        }
                }
        }

    obj.getInputNeurons().clear();
    obj.getOutputNeurons().clear();
    obj.getInputNeurons().addAll(obj.getAllLayers().get(0));
    obj.getOutputNeurons().addAll(obj.getAllLayers().get(obj.getAllLayers().size() - 1));
}

From source file:com.jonschang.investing.stocks.service.YahooHistoricalStockQuoteService.java

License:LGPL

private void pullKeyEventData(String urlString, Stock stock, BusinessCalendar cal, TimeInterval interval,
        DateRange range, Map<Date, StockQuote> dateToQuoteMap) throws Exception {
    URL url = getDateYearsUrl(urlString, stock.getSymbol(), range.getStart(), range.getEnd());
    SAXReader reader = new SAXReader();
    Document doc = reader.read(url.openConnection().getInputStream());
    Element rootElement = doc.getRootElement();

    // ok, so the date range specifiable to the keyevents service is not very fine-grained,
    // therefore, we'll assume that if there are any StockEvent's at all in a StockQuote,
    // that we pulled them here at an earlier call.
    List<Element> seriesList = rootElement.elements("series");
    if (seriesList.size() != 1)
        throw new ServiceException(
                "Expecting only a single 'series' tag in the XML document returned from " + url.toURI());
    Element series = seriesList.get(0);

    List<Element> valuesList = series.elements("values");
    if (valuesList.size() != 1)
        throw new ServiceException(
                "Expecting only a single 'values' tag in the XML document returned from " + url.toURI());
    List<Element> values = valuesList.get(0).elements("value");

    int type = 0;
    if (urlString.compareTo(m_splitUrl) == 0)
        type = 1; // split
    else if (urlString.compareTo(m_dividendUrl) == 0)
        type = 2; // dividend
    StockEventSplit split = null;//from www.j a v  a 2  s  .  c o m
    StockEventDividend div = null;

    List<Element> ps = series.elements("p");
    for (Element p : ps) {

        if (urlString.compareTo(m_splitUrl) == 0)
            split = new StockEventSplit();
        else if (urlString.compareTo(m_dividendUrl) == 0)
            div = new StockEventDividend();

        List<Element> theseValues = p.elements("v");
        if (theseValues.size() != values.size())
            throw new ServiceException("Expecting the number of 'v' tags to match the number of 'values'");

        Date vDate = new SimpleDateFormat("yyyyMMdd").parse(p.attribute("ref").getText());
        cal.setTimeInMillis(vDate.getTime());
        cal.normalizeToInterval(interval);
        vDate = cal.getTime();

        StockQuote quote = dateToQuoteMap.get(vDate);
        if (quote == null)
            continue;
        if (quote.getStockEvents() != null
                && !((type == 1 && stockEventsHas(StockEventSplit.class, quote.getStockEvents()))
                        || (type == 2 && stockEventsHas(StockEventDividend.class, quote.getStockEvents()))))
            continue;

        List<StockEvent> events = quote.getStockEvents();
        if (events == null) {
            events = new ArrayList<StockEvent>();
            quote.setStockEvents(events);
        }

        int idx = 0;
        for (Element v : theseValues) {
            Element value = values.get(idx);
            if (value.attribute("id").getText().compareTo("denominator") == 0) {
                split.setDenominator(Double.valueOf(v.getTextTrim()).floatValue());
            } else if (value.attribute("id").getText().compareTo("numerator") == 0) {
                split.setNumerator(Double.valueOf(v.getTextTrim()).floatValue());
            } else if (value.attribute("id").getText().compareTo("dividend") == 0) {
                div.setDividend(Double.valueOf(v.getTextTrim()));
            }
            idx++;
        }

        // split
        if (type == 1) {
            split.setStockQuote(quote);
            events.add(split);
        } else
        // dividend
        if (type == 2) {
            div.setStockQuote(quote);
            events.add(div);
        }
    }
}

From source file:com.kingmed.dp.mail.util.XMLHandler.java

@SuppressWarnings("rawtypes")
public static Map<String, String> transXmltoMapForSpec(String xmlInfo) throws DocumentException {
    Document doc = DocumentHelper.parseText(xmlInfo); // xml
    Map<String, String> map = new HashMap<String, String>();
    Element rootElt = doc.getRootElement();
    Iterator iter = rootElt.elementIterator();
    while (iter.hasNext()) {
        Element dataElement = (Element) iter.next();
        map.put(dataElement.getName(), dataElement.getText());
    }//from   ww w. j  ava 2 s  .  c  o  m
    Element e = (Element) (rootElt.element("specimen").elements().get(0));
    map.put("specimen", e.asXML());
    return map;
}

From source file:com.kingmed.dp.mail.util.XMLHandler.java

public static Map<String, Object> transXmltoMapForReport(String xmlInfo) throws DocumentException {
    Document doc = DocumentHelper.parseText(xmlInfo); // xml
    Map<String, Object> map = new HashMap<String, Object>();
    Element rootElt = doc.getRootElement();
    @SuppressWarnings("rawtypes")
    Iterator iter = rootElt.elementIterator();
    while (iter.hasNext()) {
        Element dataElement = (Element) iter.next();
        map.put(dataElement.getName(), dataElement.getText());
    }//  w w  w  .  j  a  v a2 s .com
    /*
    Element e = (Element) (rootElt.element("Data"));
    String data = "";
    if (e != null) {
    data = ((Element) e.elements().get(0)).asXML();
    map.put("Data", "<Data>" + data + "</Data>");
    } else {
    data = xmlInfo;
    map.put("Data", data);
    }
    */
    return map;
}

From source file:com.kingmed.dp.mail.util.XMLHandler.java

public static Map<String, String> transSimpleXmltoMap(String xmlInfo) throws DocumentException {
    Document doc = DocumentHelper.parseText(xmlInfo); // xml
    Map<String, String> map = new HashMap<String, String>();
    Element rootElt = doc.getRootElement();
    @SuppressWarnings("rawtypes")
    Iterator iter = rootElt.elementIterator();
    while (iter.hasNext()) {
        Element dataElement = (Element) iter.next();
        map.put(dataElement.getName(), dataElement.getText());
    }//from   w  w w.  ja v a 2  s . c  om
    return map;
}

From source file:com.kingmed.yuyt.util.XMLHandler.java

public static Map<String, String> transXmltoMapForSpec(String xmlInfo) throws DocumentException {
    Document doc = DocumentHelper.parseText(xmlInfo); // xml
    Map<String, String> map = new HashMap<String, String>();
    Element rootElt = doc.getRootElement();
    Iterator iter = rootElt.elementIterator();
    while (iter.hasNext()) {
        Element dataElement = (Element) iter.next();
        map.put(dataElement.getName(), dataElement.getText());
    }/*w  w w . j  a v a  2s  . co m*/
    Element e = (Element) (rootElt.element("specimen").elements().get(0));
    map.put("specimen", e.asXML());
    return map;
}

From source file:com.kingmed.yuyt.util.XMLHandler.java

public static Map<String, Object> transXmltoMapForReport(String xmlInfo) throws DocumentException {
    Document doc = DocumentHelper.parseText(xmlInfo); // xml
    Map<String, Object> map = new HashMap<String, Object>();
    Element rootElt = doc.getRootElement();
    Iterator iter = rootElt.elementIterator();
    while (iter.hasNext()) {
        Element dataElement = (Element) iter.next();
        map.put(dataElement.getName(), dataElement.getText());
    }/*from w w w . j a v a2  s.c  o  m*/
    /*
    Element e = (Element) (rootElt.element("Data"));
    String data = "";
    if (e != null) {
    data = ((Element) e.elements().get(0)).asXML();
    map.put("Data", "<Data>" + data + "</Data>");
    } else {
    data = xmlInfo;
    map.put("Data", data);
    }
    */
    return map;
}

From source file:com.kingmed.yuyt.util.XMLHandler.java

public static Map<String, String> transSimpleXmltoMap(String xmlInfo) throws DocumentException {
    Document doc = DocumentHelper.parseText(xmlInfo); // xml
    Map<String, String> map = new HashMap<String, String>();
    Element rootElt = doc.getRootElement();
    Iterator iter = rootElt.elementIterator();
    while (iter.hasNext()) {
        Element dataElement = (Element) iter.next();
        map.put(dataElement.getName(), dataElement.getText());
    }/*ww w  .j  a v a2s  .  c  o  m*/
    return map;
}

From source file:com.l2jfree.loginserver.dao.impl.GameserversDAOXml.java

License:Open Source License

/**
 * Load server name from xml/*from w  ww. ja  va2s.c  o m*/
 */
public GameserversDAOXml() {
    InputStream in = null;
    try {
        try {
            in = new FileInputStream("servername.xml");
        } catch (FileNotFoundException e) {
            // just for eclipse development, we have to search in dist folder
            in = new FileInputStream("dist/servername.xml");
        }

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

        Element root = document.getRootElement();

        // Find all servers_list (should have only one)
        for (Iterator<?> i = root.elementIterator("server"); i.hasNext();) {
            Element server = (Element) i.next();
            Integer id = null;
            String name = null;
            // For each server, read the attributes
            for (Iterator<?> iAttr = server.attributeIterator(); iAttr.hasNext();) {
                Attribute attribute = (Attribute) iAttr.next();
                if (attribute.getName().equals("id")) {
                    id = new Integer(attribute.getValue());
                } else if (attribute.getName().equals("name")) {
                    name = attribute.getValue();
                }
            }
            if (id != null && name != null) {
                Gameservers gs = new Gameservers();
                gs.setServerId(id);
                gs.setServerName(name);
                serverNames.put(id, gs);
            }
        }
        _log.info("Loaded " + serverNames.size() + " server names");
    } catch (FileNotFoundException e) {
        _log.warn("servername.xml could not be loaded : " + e.getMessage(), e);
    } catch (DocumentException e) {
        _log.warn("servername.xml could not be loaded : " + e.getMessage(), e);
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (Exception e) {
        }
    }
}