Example usage for org.dom4j Node valueOf

List of usage examples for org.dom4j Node valueOf

Introduction

In this page you can find the example usage for org.dom4j Node valueOf.

Prototype

String valueOf(String xpathExpression);

Source Link

Document

valueOf evaluates an XPath expression and returns the textual representation of the results the XPath string-value of this node.

Usage

From source file:net.bpfurtado.tas.runner.savegame.SaveGamePersister.java

License:Open Source License

public static SaveGame read(File saveGameFile) {
    try {//from   ww  w. j  a v  a2s .  c  o m
        SAXReader xmlReader = new SAXReader();
        Document xml = xmlReader.read(saveGameFile);

        Element root = xml.getRootElement();

        Node xmlPlayer = root.selectSingleNode("player");

        Player player = new Player("noName", 0, integer(xmlPlayer, "stamina"));
        player.setDamage(integer(xmlPlayer, "damage"));

        List<Node> skills = xmlPlayer.selectNodes("skills/skill");
        for (Node skill : skills) {
            player.addSkill(skill.valueOf("@name"), integer(skill, "level"));
        }

        List<Node> attributes = xmlPlayer.selectNodes("attributes/attribute");
        for (Node attribute : attributes) {
            String key = attribute.valueOf("@key");
            String val = attribute.valueOf("@value");
            try {
                player.addAttribute(key, Integer.parseInt(val));
            } catch (NumberFormatException e) {
                player.addAttribute(key, val);
            }
        }

        Workspace workspace = Workspace.loadFrom(root.valueOf("@workspaceId"));
        SaveGame saveGame = new SaveGame(workspace, player, integer(root, "sceneId"),
                root.valueOf("@creation"));
        saveGame.setFile(saveGameFile);
        return saveGame;
    } catch (DocumentException e) {
        throw new AdventureReaderException("Error reading XML document", e);
    }
}

From source file:net.bpfurtado.tas.runner.savegame.SaveGamePersister.java

License:Open Source License

public static int integer(Node node, String attribute) {
    return Integer.parseInt(node.valueOf("@" + attribute));
}

From source file:net.form105.rm.server.ant.container.InboundConfiguration.java

License:Apache License

public void readXml(Node xmlNode) {

    List<Node> nodes;
    XPath xPath;/*from  ww  w. ja  va 2 s . c  o m*/

    inboundType = xmlNode.valueOf("@type");

    xPath = DocumentHelper.createXPath("//inbound/parameters/parameter");
    nodes = (List<Node>) xPath.selectNodes(xmlNode);

    for (Node node : nodes) {
        logger.info(node);
        paramMap.addParameter(new ConfigParameter(node.valueOf("@key"), node.valueOf("@value")));
    }

    xPath = DocumentHelper.createXPath("//inbound/validators/validator");
    nodes = (List<Node>) xPath.selectNodes(xmlNode);
    for (Node node : nodes) {

        IInboundValidator validator = (IInboundValidator) Agent.getComponentById(node.getText());
        validatorList.add(validator);
    }

    xPath = DocumentHelper.createXPath("//inbound/listeners/listener");
    nodes = (List<Node>) xPath.selectNodes(xmlNode);
    for (Node node : nodes) {
        IInboundListener inboundListener = (IInboundListener) Agent.getComponentById(node.getText());
        listenerList.add(inboundListener);
    }

    xPath = DocumentHelper.createXPath("//inbound/executor");
    logger.info(xPath.selectSingleNode(xmlNode).getText());

    command = (AbstractCallbackCommand) Agent.getComponentById(xPath.selectSingleNode(xmlNode).getText());
}

From source file:nl.architolk.ldt.processors.HttpClientProcessor.java

License:Open Source License

public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException {

    try {//from www. j  av  a  2  s.co  m
        CloseableHttpClient httpclient = HttpClientProperties.createHttpClient();

        try {
            // Read content of config pipe
            Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
            Node configNode = configDocument.selectSingleNode("//config");

            URL theURL = new URL(configNode.valueOf("url"));

            if (configNode.valueOf("auth-method").equals("basic")) {
                HttpHost targetHost = new HttpHost(theURL.getHost(), theURL.getPort(), theURL.getProtocol());
                //Authentication support
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                        configNode.valueOf("username"), configNode.valueOf("password")));
                // logger.info("Credentials: "+configNode.valueOf("username")+"/"+configNode.valueOf("password"));
                // Create AuthCache instance
                AuthCache authCache = new BasicAuthCache();
                authCache.put(targetHost, new BasicScheme());

                // Add AuthCache to the execution context
                httpContext = HttpClientContext.create();
                httpContext.setCredentialsProvider(credsProvider);
                httpContext.setAuthCache(authCache);
            } else if (configNode.valueOf("auth-method").equals("form")) {
                //Sign in. Cookie will be remembered bij httpclient
                HttpPost authpost = new HttpPost(configNode.valueOf("auth-url"));
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("userName", configNode.valueOf("username")));
                nameValuePairs.add(new BasicNameValuePair("password", configNode.valueOf("password")));
                authpost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                CloseableHttpResponse httpResponse = httpclient.execute(authpost);
                // logger.info("Signin response:"+Integer.toString(httpResponse.getStatusLine().getStatusCode()));
            }

            CloseableHttpResponse response;
            if (configNode.valueOf("method").equals("post")) {
                // POST
                HttpPost httpRequest = new HttpPost(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("put")) {
                // PUT
                HttpPut httpRequest = new HttpPut(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("delete")) {
                //DELETE
                HttpDelete httpRequest = new HttpDelete(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("head")) {
                //HEAD
                HttpHead httpRequest = new HttpHead(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("options")) {
                //OPTIONS
                HttpOptions httpRequest = new HttpOptions(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else {
                //Default = GET
                HttpGet httpRequest = new HttpGet(configNode.valueOf("url"));
                String acceptHeader = configNode.valueOf("accept");
                if (!acceptHeader.isEmpty()) {
                    httpRequest.addHeader("accept", configNode.valueOf("accept"));
                }
                //Add proxy route if needed
                HttpClientProperties.setProxy(httpRequest, theURL.getHost());
                response = executeRequest(httpRequest, httpclient);
            }

            try {
                contentHandler.startDocument();

                int status = response.getStatusLine().getStatusCode();
                AttributesImpl statusAttr = new AttributesImpl();
                statusAttr.addAttribute("", "status", "status", "CDATA", Integer.toString(status));
                contentHandler.startElement("", "response", "response", statusAttr);
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    Header contentType = response.getFirstHeader("Content-Type");
                    if (entity != null && contentType != null) {
                        //logger.info("Contenttype: " + contentType.getValue());
                        //Read content into inputstream
                        InputStream inStream = entity.getContent();

                        // output-type = json means: response is json, convert to xml
                        if (configNode.valueOf("output-type").equals("json")) {
                            //TODO: net.sf.json.JSONObject might nog be the correct JSONObject. javax.json.JsonObject might be better!!!
                            //javax.json contains readers to read from an inputstream
                            StringWriter writer = new StringWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            JSONObject json = JSONObject.fromObject(writer.toString());
                            parseJSONObject(contentHandler, json);
                            // output-type = xml means: response is xml, keep it
                        } else if (configNode.valueOf("output-type").equals("xml")) {
                            try {
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = jsonld means: reponse is json-ld, (a) convert to nquads; (b) convert to xml
                        } else if (configNode.valueOf("output-type").equals("jsonld")) {
                            try {
                                Object jsonObject = JsonUtils.fromInputStream(inStream, "UTF-8"); //TODO: UTF-8 should be read from response!
                                Object nquads = JsonLdProcessor.toRDF(jsonObject, new NQuadTripleCallback());

                                Any23 runner = new Any23();
                                DocumentSource source = new StringDocumentSource((String) nquads,
                                        configNode.valueOf("url"));
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inJsonStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inJsonStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = rdf means: response is some kind of rdf (except json-ld...), convert to xml
                        } else if (configNode.valueOf("output-type").equals("rdf")) {
                            try {
                                Any23 runner = new Any23();

                                DocumentSource source;
                                //If contentType = text/html than convert from html to xhtml to handle non-xml style html!
                                logger.info("Contenttype: " + contentType.getValue());
                                if (configNode.valueOf("tidy").equals("yes")
                                        && contentType.getValue().startsWith("text/html")) {
                                    org.jsoup.nodes.Document doc = Jsoup.parse(inStream, "UTF-8",
                                            configNode.valueOf("url")); //TODO UTF-8 should be read from response!

                                    RDFCleaner cleaner = new RDFCleaner();
                                    org.jsoup.nodes.Document cleandoc = cleaner.clean(doc);
                                    cleandoc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
                                    cleandoc.outputSettings()
                                            .syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
                                    cleandoc.outputSettings().charset("UTF-8");

                                    source = new StringDocumentSource(cleandoc.html(),
                                            configNode.valueOf("url"), contentType.getValue());
                                } else {
                                    source = new ByteArrayDocumentSource(inStream, configNode.valueOf("url"),
                                            contentType.getValue());
                                }

                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inAnyStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inAnyStream));

                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                        } else {
                            CharArrayWriter writer = new CharArrayWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            contentHandler.characters(writer.toCharArray(), 0, writer.size());
                        }
                    }
                }
                contentHandler.endElement("", "response", "response");

                contentHandler.endDocument();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    } catch (Exception e) {
        throw new OXFException(e);
    }

}

From source file:nl.architolk.ldt.processors.HttpClientProcessor.java

License:Open Source License

private void setBody(HttpEntityEnclosingRequestBase httpRequest, PipelineContext context, Node configNode)
        throws IOException {
    Document dataDocument = readInputAsDOM4J(context, INPUT_DATA);
    if (configNode.valueOf("input-type").equals("form")) {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        Element rootElement = dataDocument.getRootElement();
        Iterator<?> elit = rootElement.elementIterator();
        while (elit.hasNext()) {
            Element child = (Element) elit.next();
            nameValuePairs.add(new BasicNameValuePair(child.getQName().getName(), child.getText()));
        }//ww w.  ja  va  2  s  . c om
        httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } else {
        String jsonstr;
        if (configNode.valueOf("input-type").equals("json")) {
            //Conversion of XML input to JSON
            JSONObject jsondata = new JSONObject();
            populateJSONObject(jsondata, dataDocument);
            jsonstr = jsondata.toString();
        } else {
            //No conversion, just use plain text in input
            jsonstr = dataDocument.getRootElement().getText();
        }
        httpRequest.setEntity(new StringEntity(jsonstr));
    }
}

From source file:nl.architolk.ldt.processors.MarkDownConverter.java

License:Open Source License

public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(MarkDownConverter.this, name) {
        public void readImpl(PipelineContext context, XMLReceiver xmlReceiver) {
            // Read content of config pipe
            Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
            Node configNode = configDocument.selectSingleNode("//config");
            String uri = configNode.valueOf("uri");
            // Read en process content of input pipe
            readInputAsSAX(context, INPUT_DATA, new MarkDownXMLReceiver(xmlReceiver, uri));
        }//from w  w  w .j  av a2s.  c  om

        @Override
        public OutputCacheKey getKeyImpl(PipelineContext pipelineContext) {
            return getInputKey(pipelineContext, getInputByName(INPUT_DATA));
        }

        @Override
        public Object getValidityImpl(PipelineContext pipelineContext) {
            return getInputValidity(pipelineContext, getInputByName(INPUT_DATA));
        }
    };
    addOutput(name, output);
    return output;
}

From source file:nl.architolk.ldt.processors.RDF4JProcessor.java

License:Open Source License

public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException {

    Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
    Node configNode = configDocument.selectSingleNode("//config");

    contentHandler.startDocument();//from w  ww. j  ava2 s.  c om
    contentHandler.startElement("", "response", "response", new AttributesImpl());

    String action = configNode.valueOf("action"); // The action to perform
    String cgraph = configNode.valueOf("cgraph"); // Container graph, the main graph
    String tgraph = configNode.valueOf("tgraph"); // The target graph
    String pgraph = configNode.valueOf("pgraph"); // The parent graph, for version information
    String postQuery = configNode.valueOf("postquery"); // Some post query, optional
    String uriPrefix = configNode.valueOf("uriprefix"); // The uri prefix for relative uri's

    String errorMsg = "";

    db = RDF4JProperties.createRepository();
    if (db == null) {
        errorMsg = "Unknown database. \n";
    } else {
        conn = db.getConnection();

        try {
            if (!(conn instanceof SPARQLConnection)) {
                conn.begin(IsolationLevels.NONE);
            }

            // Clear target graph, partially (all triples in original container) or completely
            if (action.equals("replace")) {
                String msg = "Target graph <" + tgraph + "> cleared";
                try {
                    IRI tgraphResource = db.getValueFactory().createIRI(tgraph);
                    conn.clear(tgraphResource);
                } catch (Exception e) {
                    // In case of an error, put the errormessage in the result, but don't throw the exception
                    msg = e.toString();
                    errorMsg += e.getMessage() + ". \n";
                }
                contentHandler.startElement("", "scene", "scene", new AttributesImpl());
                contentHandler.characters(msg.toCharArray(), 0, msg.length());
                contentHandler.endElement("", "scene", "scene");
            } else if (action.equals("part")) {
                String msg = "Target graph <" + tgraph + "> partially cleared";
                try {
                    conn.prepareUpdate(
                            "delete { graph <" + tgraph + "> {?s?p?o}} using <" + cgraph + "> where {?s?p?o}")
                            .execute();
                } catch (Exception e) {
                    // In case of an error, put the errormessage in the result, but don't throw the exception
                    msg = e.toString();
                    errorMsg += e.getMessage() + ". \n";
                }
                contentHandler.startElement("", "scene", "scene", new AttributesImpl());
                contentHandler.characters(msg.toCharArray(), 0, msg.length());
                contentHandler.endElement("", "scene", "scene");
            }

            // Clear container, except when action = insert
            if (!action.equals("insert")) {
                String msg = "Container <" + cgraph + "> cleared";
                try {
                    IRI cgraphResource = db.getValueFactory().createIRI(cgraph);
                    conn.clear(cgraphResource);
                } catch (Exception e) {
                    // In case of an error, put the errormessage in the result, but don't throw the exception
                    msg = e.toString();
                    errorMsg += e.getMessage() + ". \n";
                }
                contentHandler.startElement("", "scene", "scene", new AttributesImpl());
                contentHandler.characters(msg.toCharArray(), 0, msg.length());
                contentHandler.endElement("", "scene", "scene");
            }

            // Insert documents into container graph
            Document dataDocument = readInputAsDOM4J(context, INPUT_DATA);
            List filelist = dataDocument.selectNodes("//filelist//file");
            Iterator<?> elit = filelist.listIterator();
            while (elit.hasNext()) {
                Node child = (Node) elit.next();
                String msg = "file uploaded: " + child.valueOf("@name");
                try {
                    uploadFile(child.valueOf("@name"), child.getText(), cgraph, uriPrefix);
                } catch (Exception e) {
                    // In case of an error, put the errormessage in the result, but don't throw the exception
                    msg = "[" + child.valueOf("@name") + "] " + e.getMessage();
                    errorMsg += e.getMessage();
                    if (e.getCause() != null) {
                        msg += " (" + e.getCause().getMessage() + ")";
                        errorMsg += " (" + e.getCause().getMessage() + ")";
                    }
                    errorMsg += ". \n";
                }
                contentHandler.startElement("", "scene", "scene", new AttributesImpl());
                contentHandler.characters(msg.toCharArray(), 0, msg.length());
                contentHandler.endElement("", "scene", "scene");
            }

            // Remove existing properties in case of action = update
            if (action.equals("update")) {
                String msg = "Target graph cleared for update";
                try {
                    conn.prepareUpdate("delete {graph <" + tgraph + "> {?s?x?y}} using <" + cgraph + "> using <"
                            + tgraph + "> where {graph <" + tgraph + "> {?s?x?y} graph <" + cgraph
                            + "> {?s?p?o}}").execute();
                    // Remove orphant blank nodes (to third degree, beter option could be to count the number of deleted nodes and repeat when not equal to zero)
                    conn.prepareUpdate("delete {graph <" + tgraph + "> {?bs?bp?bo}} using <" + tgraph
                            + "> where {?bs?bp?bo FILTER(isblank(?bs)) FILTER NOT EXISTS {?s?p?bs}}").execute();
                    conn.prepareUpdate("delete {graph <" + tgraph + "> {?bs?bp?bo}} using <" + tgraph
                            + "> where {?bs?bp?bo FILTER(isblank(?bs)) FILTER NOT EXISTS {?s?p?bs}}").execute();
                    conn.prepareUpdate("delete {graph <" + tgraph + "> {?bs?bp?bo}} using <" + tgraph
                            + "> where {?bs?bp?bo FILTER(isblank(?bs)) FILTER NOT EXISTS {?s?p?bs}}").execute();
                } catch (Exception e) {
                    // In case of an error, put the errormessage in the result, but don't throw the exception
                    msg = e.toString();
                    errorMsg += e.getMessage() + ". \n";
                }
                contentHandler.startElement("", "scene", "scene", new AttributesImpl());
                contentHandler.characters(msg.toCharArray(), 0, msg.length());
                contentHandler.endElement("", "scene", "scene");
            }

            // Populate target graph with content of the container-graph
            if (action.equals("part") || action.equals("replace") || action.equals("update")) {
                String msg = "Target graph <" + tgraph + "> populated from container <" + cgraph + ">";
                try {
                    conn.prepareUpdate(
                            "insert { graph <" + tgraph + "> {?s?p?o}} using <" + cgraph + "> where {?s?p?o}")
                            .execute();
                } catch (Exception e) {
                    // In case of an error, put the errormessage in the result, but don't throw the exception
                    msg = e.toString();
                    errorMsg += e.getMessage() + ". \n";
                }
                contentHandler.startElement("", "scene", "scene", new AttributesImpl());
                contentHandler.characters(msg.toCharArray(), 0, msg.length());
                contentHandler.endElement("", "scene", "scene");
            }

            // Insert version-info into parent graph, if applicable
            if (!(cgraph.equals(pgraph) || pgraph.isEmpty())) {
                String msg = "Version metadata inserted into parent graph";
                try {
                    conn.prepareUpdate("insert data {graph <" + pgraph + "> {<" + pgraph
                            + "> <http://purl.org/dc/terms/hasVersion> <" + cgraph + ">}}").execute();
                } catch (Exception e) {
                    // In case of an error, put the errormessage in the result, but don't throw the exception
                    msg = e.toString();
                    errorMsg += e.getMessage() + ". \n";
                }
                contentHandler.startElement("", "scene", "scene", new AttributesImpl());
                contentHandler.characters(msg.toCharArray(), 0, msg.length());
                contentHandler.endElement("", "scene", "scene");
            }

            // Execute post query
            if (!postQuery.isEmpty()) {
                String msg = "Post query executed";
                try {
                    conn.prepareUpdate(postQuery).execute();
                } catch (Exception e) {
                    // In case of an error, put the errormessage in the result, but don't throw the exception
                    msg = e.toString();
                    errorMsg += e.getMessage() + ". \n";
                }
                contentHandler.startElement("", "scene", "scene", new AttributesImpl());
                contentHandler.characters(msg.toCharArray(), 0, msg.length());
                contentHandler.endElement("", "scene", "scene");
            }
            if (!(conn instanceof SPARQLConnection)) {
                conn.commit();
            }

        } finally {
            conn.close();
        }

    }

    if (!errorMsg.isEmpty()) {
        contentHandler.startElement("", "error", "error", new AttributesImpl());
        contentHandler.characters(errorMsg.toCharArray(), 0, errorMsg.length());
        contentHandler.endElement("", "error", "error");
    }
    contentHandler.endElement("", "response", "response");
    contentHandler.endDocument();
}

From source file:nl.ru.cmbi.pisa.wrapper.PisaCachedWebDao.java

License:Apache License

/**
 * Gets the 3D rotation-translation biomolecule matrices from PISA.
 * <p>/*  ww  w.j a va  2 s  .  c o m*/
 * These matrices detail how chains in the specified PDB entry should be manipulated to obtain desired the PISA
 * assembly.
 * 
 * @param rawPdbId
 *            the 4-letter PDB code we want the assembly of (e.g. "1crn")
 * @param setNr
 *            the PISA assembly set. "1" is most stable in solution, higher numbers increasingly unstable.
 * @param assemblyNr
 *            the substructure within an assembly. Note that structurally identical substructures get the
 *            same assemblyNr. This DAO ignores all but the first substructure. Ignored chains (those chains not
 *            needed to make this assembly) are listed in the {@link MatricesResult#ignoredChains} property of the
 *            returned result.
 * @return A compound result of the transformation matrices to apply and the ignored chains (I.E. those
 *         chains whose transformation lead to an identical substructure to the one returned). This result may be
 *         empty.
 * @throws IOException
 *             when web-fetching fails.
 */
@SuppressWarnings("unchecked")
public MatricesResult getMatrices(final String rawPdbId, final int setNr, final int assemblyNr)
        throws IOException {

    final String pdbId = rawPdbId.trim().toLowerCase();
    Document mmrInfo;
    try {
        mmrInfo = parseDocumentOf(getRawMultimerInfoSingle(pdbId));
    } catch (final DocumentException docex) {
        log.error("Problem parsing Pisa raw multimer info for {}, see debug level for details", pdbId);
        log.debug("Exception: ", docex);
        throw new IOException("Problem parsing multimer XML document", docex);
    }

    final List<ChainTransform> output = new ArrayList<ChainTransform>();
    final Set<String> ignoredChainIds = new HashSet<String>();

    try {
        // Unfortunately, multiple assemblies share the same <ID> subnode if they are structurally identical
        // So, we need indexing ("[1]") to get only the first of an identical set of assemblies
        // ('identical' meaning "structurally identical except for ChainIDs")
        // Sigh... reusing IDs for different things!
        final String matricesXpath = String.format(
                "(/pisa_multimers/pdb_entry[ pdb_code='%s' ]/asm_set[ ser_no=%d ]/assembly[ id=%d ])[1]/molecule",
                pdbId, setNr, assemblyNr);

        final List<Node> matrices = mmrInfo.selectNodes(matricesXpath);

        for (final Node node : matrices) {
            final ChainTransform ct = new ChainTransform(node.valueOf("chain_id"),
                    // X-row
                    (Double) node.numberValueOf("rxx"), (Double) node.numberValueOf("rxy"),
                    (Double) node.numberValueOf("rxz"), (Double) node.numberValueOf("tx"),
                    // Y-row
                    (Double) node.numberValueOf("ryx"), (Double) node.numberValueOf("ryy"),
                    (Double) node.numberValueOf("ryz"), (Double) node.numberValueOf("ty"),
                    // Z-row
                    (Double) node.numberValueOf("rzx"), (Double) node.numberValueOf("rzy"),
                    (Double) node.numberValueOf("rzz"), (Double) node.numberValueOf("tz"));
            if (ct.isUnity() && ct.isStationary()) {
                ct.setDuplication(false);
            } else {
                ct.setDuplication(true);
            }

            output.add(ct);
        }

        final String ignoredMatricesXpath = String.format(
                "(/pisa_multimers/pdb_entry[ pdb_code='%s' ]/asm_set[ ser_no=%d ]/assembly[ id=%d ])[position() > 1]/molecule/chain_id",
                pdbId, setNr, assemblyNr);
        final List<Node> ignoredChains = mmrInfo.selectNodes(ignoredMatricesXpath);

        for (final Node ignoredChain : ignoredChains) {
            ignoredChainIds.add(ignoredChain.getText());
        }

    } catch (final ClassCastException ccex) {
        log.error(
                "malformed XML response from PISA when getting matrices for assembly {}:{}.{}: expected list of matrix nodes, but obtained something else",
                new Object[] { pdbId, setNr, assemblyNr });
        throw new IOException("malformed XML response from PISA when getting matrices for assembly of " + pdbId
                + ": expected list of matrix nodes, but obtained something else", ccex);
    }

    return new MatricesResult(output, ignoredChainIds);
}

From source file:nnga.NNGA.java

License:Open Source License

@Override
public void continueOptimization(ProblemXMLData problemData, ComponentXMLData representationData,
        ComponentXMLData rankingData, Hashtable<String, XMLFieldEntry> properties, Document doc) {

    // load and calculate parameters
    parameters.initialize(getProperties());

    if (!loadFromDoc(problemData, representationData, doc)) {
        return;//from  ww w .  ja v a2 s. c  o  m
    }

    // record the best fitness over the evolution
    Node dpopulations = doc.selectSingleNode("/frevo/populations");
    double best_fitness = Double.parseDouble(dpopulations.valueOf("./@best_fitness"));
    int lastGeneration = Integer.parseInt(dpopulations.valueOf("./@generation"));

    createStatistics();

    // Mutate all populations except when this is the last generation
    for (SimplePopulation population : pops) {
        try {
            population.evolve(lastGeneration, pops);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    try {

        NNGAStep step = new NNGAStep(problemData, rankingData);

        step.setBestFitness(best_fitness);

        // Iterate through generations
        for (int generation = lastGeneration + 1; generation < parameters.getGenerations(); generation++) {

            step.setGeneration(generation);

            if (!evolve(step)) {
                break;
            }
        }
    } catch (InstantiationException e1) {
        e1.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // finalize progress
    setProgress(1f);
}

From source file:nnga.NNGA.java

License:Open Source License

@Override
public ArrayList<ArrayList<AbstractRepresentation>> loadFromXML(Document doc) {
    // final list to be returned
    ArrayList<ArrayList<AbstractRepresentation>> populations = new ArrayList<ArrayList<AbstractRepresentation>>();

    // get population root node
    Node dpopulations = doc.selectSingleNode("/frevo/populations");

    // get number of populations
    int populationCount = Integer.parseInt(dpopulations.valueOf("./@count"));
    // get number of current generation
    int currentGeneration = Integer.parseInt(dpopulations.valueOf("./@generation"));

    // get population size
    @SuppressWarnings("unchecked")
    List<? extends Node> populationsNode = dpopulations.selectNodes(".//population");
    int populationSize = populationsNode.get(0).selectNodes("*").size();

    // calculate total representations
    int totalRepresentations = populationCount * populationSize;
    int currentPopulation = 0;
    int currentRepresentation = 0;

    // Iterate through the population nodes
    Iterator<?> populationIterator = populationsNode.iterator();
    while (populationIterator.hasNext()) {
        Node populationNode = (Node) populationIterator.next();

        // create list of candidate representations for this population
        ArrayList<AbstractRepresentation> result = new ArrayList<AbstractRepresentation>();

        // track current progress
        currentRepresentation = 0;//from  ww w . j av a 2  s.  co m
        try {
            // Obtain an iterator over the representations
            List<?> representations = populationNode.selectNodes("./*");
            Iterator<?> representationsIterator = representations.iterator();

            while (representationsIterator.hasNext()) {
                // calculate current position for progress reporting
                int currentItem = currentPopulation * populationSize + currentRepresentation + 1;

                // report loading state
                FrevoMain.setLoadingProgress((float) currentItem / totalRepresentations);

                // step to next node
                Node net = (Node) representationsIterator.next();

                // construct representation based on loaded representation
                // data
                ComponentXMLData representation = FrevoMain
                        .getSelectedComponent(ComponentType.FREVO_REPRESENTATION);
                AbstractRepresentation member = representation.getNewRepresentationInstance(0, 0, null);

                // load representation data from the XML into the instance
                member.loadFromXML(net);

                // add data to current population list
                result.add(member);

                // increment tracker
                currentRepresentation++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        populations.add(result);

        currentPopulation++;
    }

    // Load the number of generations
    XMLFieldEntry gensize = getProperties().get("generations");
    if (gensize != null) {
        int generations = Integer.parseInt(gensize.getValue());
        // TODO check max fitness also
        // set boolean value which shows possibility of continuation of experiment
        // if maximum number of generations hasn't been reached.
        setCanContinue(currentGeneration + 1 < generations);
    }

    return populations;
}