Example usage for org.dom4j.io SAXReader read

List of usage examples for org.dom4j.io SAXReader read

Introduction

In this page you can find the example usage for org.dom4j.io SAXReader read.

Prototype

public Document read(InputSource in) throws DocumentException 

Source Link

Document

Reads a Document from the given InputSource using SAX

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  ava 2  s .c om*/
 * @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;//w ww. ja  v  a2 s.c  o m

    try {
        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  w  w w  . ja  v a2s  .  co  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.josephalevin.gwtplug.maven.InheritModulesMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {/*from  w w w  . ja  v  a2 s . c  o  m*/
        Set<Artifact> artifacts = getProject().createArtifacts(getArtifactFactory(), null, null);

        ArtifactResolutionResult arr = getArtifactResolver().resolveTransitively(artifacts,
                getProject().getArtifact(), getProject().getRemoteArtifactRepositories(), getLocalRepository(),
                artifactMetadataSource);

        Set<Artifact> dependencies = arr.getArtifacts();

        List<URL> urls = new ArrayList<URL>();

        for (Artifact art : dependencies) {
            URL url = art.getFile().toURI().toURL();
            System.out.println(url);
            urls.add(url);
        }

        List<File> modules = new ArrayList<File>();
        Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(urls)
                .setScanners(new ResourcesScanner(), new GWTModuleScanner(modules)));

        if (reflections == null) {
            throw new IllegalStateException("Failed to execute reflections.");
        }

        List<String> advertiedModules = new ArrayList<String>();
        for (File file : modules) {
            //                System.out.println(file.getName());
            //                System.out.println(file.getRelativePath());

            if (file.getRelativePath().startsWith("com/google/gwt")) {
                //System.out.println(String.format("Skipping Google Module: %s", file.getRelativePath()));
                continue;
            }
            //                System.out.println(String.format("Scanning: %s", file.getRelativePath()));

            try {
                SAXReader sax = new SAXReader(false);

                Document doc = sax.read(file.getInputStream());
                Node node = doc
                        .selectSingleNode("/module/set-configuration-property[@name='gwtplug.advertised']");

                if (node instanceof Element) {
                    Element element = (Element) node;
                    Boolean advertised = false;
                    try {
                        advertised = Boolean.valueOf(element.attributeValue("value"));
                        if (advertised) {
                            String module = file.getRelativePath().replace("/", ".");
                            module = module.replaceAll("\\.gwt\\.xml$", "");
                            advertiedModules.add(module);
                            System.out.println(module);
                        }
                    } catch (Exception e) {
                        advertised = false;
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        System.out.println(createModule);

        java.io.File file = new java.io.File(generateDirectory, createModule.replace(".", "/") + ".gwt.xml");
        file.getParentFile().mkdirs();

        StringBuilder buffer = new StringBuilder();
        buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        buffer.append("\n");
        buffer.append("<module>");
        for (String mod : advertiedModules) {
            buffer.append(String.format("<inherits name=\"%s\"/>", mod));
        }
        buffer.append("</module>");
        buffer.append("\n");
        FileWriter writer = null;
        try {
            writer = new FileWriter(file);
            writer.write(buffer.toString());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    getProject().addCompileSourceRoot(generateDirectory.getAbsolutePath());

}

From source file:com.joseprado.levaetraztransporte.factory.RotaFactory.java

/**
 * Metodo responsvel em converter os dados retornados pelo webservice
 * @param url/*from w  ww .j  av a  2 s .  c o  m*/
 * @return
 * @throws DocumentException 
 */
public static Document getDocumento(URL url) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(url);
    return document;
}

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

License:Open Source License

/**
 * Load server name from xml/*from   www.j av a 2s.  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) {
        }
    }
}

From source file:com.lafengmaker.tool.util.XMLDataUtil.java

License:Open Source License

public static Document CreateDocumentFromFile(String fileName) throws Exception {
    Document doc = null;//from w  w w.ja v a  2 s .c o  m
    InputStream is = XMLDataUtil.class.getResourceAsStream(fileName);
    SAXReader reader = new SAXReader();
    doc = reader.read(is);

    return doc;
}

From source file:com.lafengmaker.tool.util.XMLDataUtil.java

License:Open Source License

public static Document loadDocument(String sFileName) throws Exception {
    InputStream is = XMLDataUtil.class.getResourceAsStream("/" + sFileName);
    SAXReader rd = new SAXReader();

    Document document = null;//from  www.  j a va2s. c o  m
    document = rd.read(is);
    return document;
}

From source file:com.laudandjolynn.mytv.MyTvData.java

License:Apache License

/**
 * ?//w ww .j  a v  a 2s. c  o  m
 */
private void loadData() {
    logger.debug("load data from my tv data file: " + Constant.MY_TV_DATA_FILE_PATH);
    File file = new File(Constant.MY_TV_DATA_FILE_PATH);
    if (!file.exists()) {
        this.dbInited = false;
        this.dataInited = false;
        this.stationCrawlerInited = false;
        this.programCrawlerInited = false;
        return;
    }
    SAXReader reader = new SAXReader();
    try {
        Document xmlDoc = reader.read(new File(Constant.MY_TV_DATA_FILE_PATH));
        List<?> nodes = xmlDoc.selectNodes("//" + Constant.XML_TAG_DB);
        if (nodes != null && nodes.size() > 0) {
            this.dbInited = Boolean.valueOf(((Element) nodes.get(0)).getText());
        }
        nodes = xmlDoc.selectNodes("//" + Constant.XML_TAG_DATA);
        if (nodes != null && nodes.size() > 0) {
            this.dataInited = Boolean.valueOf(((Element) nodes.get(0)).getText());
        }
        nodes = xmlDoc.selectNodes("//" + Constant.XML_TAG_STATION);
        if (nodes != null && nodes.size() > 0) {
            this.stationCrawlerInited = Boolean.valueOf(((Element) nodes.get(0)).getText());
        }

        nodes = xmlDoc.selectNodes("//" + Constant.XML_TAG_PROGRAM);
        if (nodes != null && nodes.size() > 0) {
            this.programCrawlerInited = Boolean.valueOf(((Element) nodes.get(0)).getText());
        }
    } catch (DocumentException e) {
        logger.debug("can't parse xml file.  -- " + Constant.MY_TV_DATA_FILE_PATH);
        this.dbInited = false;
        this.dataInited = false;
        this.stationCrawlerInited = false;
        this.programCrawlerInited = false;
        file.deleteOnExit();
    }
}

From source file:com.laudandjolynn.mytv.MyTvData.java

License:Apache License

public void writeData(String parent, String tag, String value) {
    logger.debug("write data to my tv data file: " + Constant.MY_TV_DATA_FILE_PATH);
    File file = new File(Constant.MY_TV_DATA_FILE_PATH);
    if (!file.exists()) {
        Document doc = DocumentHelper.createDocument();
        doc.addElement(Constant.APP_NAME);
        try {/*from   w ww.  j a v a2s .  c o  m*/
            FileUtils.writeWithNIO(doc.asXML().getBytes(), Constant.MY_TV_DATA_FILE_PATH);
        } catch (IOException e) {
            throw new MyTvException(
                    "error occur while write data to file. -- " + Constant.MY_TV_DATA_FILE_PATH);
        }
    }
    SAXReader reader = new SAXReader();
    try {
        Document xmlDoc = reader.read(file);
        Element parentElement = xmlDoc.getRootElement();
        if (parent != null) {
            List<?> nodes = xmlDoc.selectNodes("//" + parent);
            if (nodes != null && nodes.size() > 0) {
                parentElement = (Element) nodes.get(0);
            }
        }
        parentElement.addElement(tag).setText(value);
        try {
            XMLWriter writer = new XMLWriter(new FileWriter(file));
            writer.write(xmlDoc);
            writer.close();
        } catch (IOException e) {
            throw new MyTvException(
                    "error occur while write data to file. -- " + Constant.MY_TV_DATA_FILE_PATH);
        }
    } catch (DocumentException e) {
        String msg = "can't parse xml file. -- " + Constant.MY_TV_DATA_FILE_PATH;
        throw new MyTvException(msg);
    }
}