Example usage for org.jdom2 Namespace getNamespace

List of usage examples for org.jdom2 Namespace getNamespace

Introduction

In this page you can find the example usage for org.jdom2 Namespace getNamespace.

Prototype

public static Namespace getNamespace(final String prefix, final String uri) 

Source Link

Document

This will retrieve (if in existence) or create (if not) a Namespace for the supplied prefix and uri.

Usage

From source file:sxql.java

License:Open Source License

/**
 * Execute a SQL query and return the result as XML
 * (as a String. But this can be changed to return a DOM/SAX/JDOM tree,
 * to be used, for example, as input to an XSLT processor)
 *///from  w ww  . j a v a 2 s.  c  om
public static String query(Connection con, String query, String root, String row, String ns, int maxRows,
        Vector<String> attributes, Vector<String> elements) throws Exception {
    // Execute SQL Query
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(query);

    // Create a ResultSetBuilder
    ResultSetBuilder builder = new ResultSetBuilder(rs);

    // Configure some parameters...

    if (root != null) {
        builder.setRootName(root);
    }

    if (row != null) {
        builder.setRowName(row);
    }

    if (ns != null) {
        String namespace = null;
        String url = null;
        int sep = ns.indexOf("/");

        if (sep > 0) {
            namespace = ns.substring(0, sep);
            url = ns.substring(sep + 1);
            builder.setNamespace(Namespace.getNamespace(namespace, url));
        }
    }

    if (maxRows > 0) {
        builder.setMaxRows(maxRows);
    }

    for (int i = 0; i < attributes.size(); i++) {
        String colName = attributes.get(i);
        String attrName = null;

        if (colName.indexOf("/") >= 0) {
            String col = colName;
            int sep = col.indexOf("/");
            colName = col.substring(0, sep);
            attrName = col.substring(sep + 1);
        }

        try { // If it looks like an integer, is the column number
            int colNum = Integer.parseInt(colName);

            if (attrName == null) {
                builder.setAsAttribute(colNum); // attrName = column Name
            } else {
                builder.setAsAttribute(colNum, attrName);
            }
        } catch (NumberFormatException e) {
            // Otherwise it's the column name
            if (attrName == null) {
                builder.setAsAttribute(colName); // attrName = column Name
            } else {
                builder.setAsAttribute(colName, attrName);
            }
        }
    }

    // Rename element
    for (int i = 0; i < elements.size(); i++) {
        String colName = elements.get(i);
        String elemName = null;

        if (colName.indexOf("/") >= 0) {
            String col = colName;
            int sep = col.indexOf("/");
            colName = col.substring(0, sep);
            elemName = col.substring(sep + 1);
        }

        try { // If it looks like an integer, is the column number
            int colNum = Integer.parseInt(colName);

            if (elemName != null) { // It must have an element name
                builder.setAsElement(colNum, elemName);
            }
        } catch (NumberFormatException e) {
            // Otherwise it's the column name
            if (elemName != null) { // It must have an element name
                builder.setAsElement(colName, elemName);
            }
        }
    }

    // Build a JDOM tree
    Document doc = builder.build();

    // Convert the result to XML (as String)
    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    outputter.output(doc, output);
    return output.toString();
}

From source file:AL_gui.java

License:Apache License

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    // TODO add your handling code here:
    try {/*from  w ww .j  a v  a 2s. c o  m*/
        String nnetName = JOptionPane.showInputDialog(jButton3, "Enter a filename, excluding extention.",
                "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
        if (nnetName == " ") {
            JOptionPane.showMessageDialog(null, "An input value must be entered.");
        }

        Element nnet = new Element("NNETWORK");
        nnet.setAttribute(new Attribute("noNamespaceSchemaLocation", "ANNeML.xsd",
                Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")));
        nnet.setAttribute(new Attribute("NNET_NAME", nnetName));
        Document doc = new Document(nnet);

        String subnnets = JOptionPane.showInputDialog(jButton3, "How many SUBNET(s)?", "ANNeML Wizard",
                JOptionPane.QUESTION_MESSAGE);
        if (subnnets == " ") {
            JOptionPane.showMessageDialog(null, "An input value must be entered.");
        }
        int numSubs = java.lang.Integer.parseInt(subnnets);
        int i = 0;
        do {
            Element subnet = new Element("SUBNET");
            String learningRate = JOptionPane.showInputDialog(jButton3, "SUBNET learning rate(eta)?",
                    "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
            if (learningRate == " ") {
                JOptionPane.showMessageDialog(null, "An input value must be entered.");
            }
            subnet.setAttribute(new Attribute("NNET_V2", learningRate));
            subnet.setAttribute(new Attribute("SNET_NAME", nnetName + "-subnet" + String.valueOf(i + 1)));
            subnet.setAttribute(new Attribute("ADJUST_LOCK", "0"));

            String input_layers = JOptionPane.showInputDialog(jButton3,
                    "How many <<INPUT>> LAYERS(s) in this subnet?", "ANNeML Wizard",
                    JOptionPane.QUESTION_MESSAGE);
            if (input_layers == " ") {
                JOptionPane.showMessageDialog(null, "An input value must be entered.");
            }
            int numInLayers = java.lang.Integer.parseInt(input_layers);
            int x = 0;
            do {
                Element inLayer = new Element("LAYER");
                inLayer.setAttribute(new Attribute("LAYER_NAME", "INPUT"));
                String transferFunc = JOptionPane.showInputDialog(jButton3,
                        "Which transfer function for this LAYER? 1(hyberbolic tangent) or 2(logarithmic sigmoid)",
                        "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
                if (transferFunc == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                inLayer.setAttribute(new Attribute("TRANSFER_FUNCTION", transferFunc));
                String inNodes = JOptionPane.showInputDialog(jButton3,
                        "How many NEURODE(s) in this <<INPUT>> LAYER?", "ANNeML Wizard",
                        JOptionPane.QUESTION_MESSAGE);
                if (inNodes == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                int numInNodes = java.lang.Integer.parseInt(inNodes);
                int y = 0;
                do {
                    Element node = new Element("NEURODE");
                    node.setAttribute(
                            new Attribute("N_ID", "IN" + String.valueOf(x + 1) + String.valueOf(y + 1)));
                    node.setAttribute(new Attribute("ACTIVE", "-1"));
                    node.setAttribute(new Attribute("ACTIVITY", "0.0"));
                    node.setAttribute(new Attribute("BIAS", "0.0"));
                    node.setAttribute(new Attribute("CNAME", "Input node#" + String.valueOf(y + 1)));
                    node.setAttribute(new Attribute("NNET_V4", "0.0"));
                    Element inSynapse = new Element("SYNAPSE");
                    inSynapse.setAttribute(new Attribute("WEIGHT", "1.00"));
                    inSynapse.setAttribute(new Attribute("ORG_NEURODE", "INPUT"));
                    node.addContent(inSynapse);
                    inLayer.addContent(node);
                    y++;
                } while (y < numInNodes);
                subnet.addContent(inLayer);
                x++;
            } while (x < numInLayers);

            String hidden_layers = JOptionPane.showInputDialog(jButton3,
                    "How many <<HIDDEN>> LAYERS(s) in this subnet?", "ANNeML Wizard",
                    JOptionPane.QUESTION_MESSAGE);
            if (hidden_layers == " ") {
                JOptionPane.showMessageDialog(null, "An input value must be entered.");
            }
            int numHLayers = java.lang.Integer.parseInt(hidden_layers);
            int z = 0;
            do {
                Element hLayer = new Element("LAYER");
                hLayer.setAttribute(new Attribute("LAYER_NAME", "HIDDEN"));
                String transferFunc = JOptionPane.showInputDialog(jButton3,
                        "Which transfer function for this LAYER? 1(hyberbolic tangent) or 2(logarithmic sigmoid)",
                        "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
                if (transferFunc == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                hLayer.setAttribute(new Attribute("TRANSFER_FUNCTION", transferFunc));
                String hNodes = JOptionPane.showInputDialog(jButton3,
                        "How many NEURODE(s) in this <<HIDDEN>> LAYER?", "ANNeML Wizard",
                        JOptionPane.QUESTION_MESSAGE);
                if (hNodes == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                int numhNodes = java.lang.Integer.parseInt(hNodes);
                int a = 0;
                do {
                    Random rnd = new Random();
                    Element node = new Element("NEURODE");
                    node.setAttribute(
                            new Attribute("N_ID", "N" + String.valueOf(z + 1) + String.valueOf(a + 1)));
                    node.setAttribute(new Attribute("ACTIVE", "-1"));
                    node.setAttribute(new Attribute("ACTIVITY", "0.0"));
                    node.setAttribute(new Attribute("BIAS", getRandomValue(rnd, low, high, decpl)));
                    node.setAttribute(new Attribute("CNAME", "Hidden node#" + String.valueOf(a + 1)));
                    node.setAttribute(new Attribute("NNET_V4", "0.0"));
                    hLayer.addContent(node);
                    a++;
                } while (a < numhNodes);
                subnet.addContent(hLayer);
                z++;
            } while (z < numHLayers);

            String output_layers = JOptionPane.showInputDialog(jButton3,
                    "How many <<OUTPUT>> LAYERS(s) in this subnet?", "ANNeML Wizard",
                    JOptionPane.QUESTION_MESSAGE);
            if (hidden_layers == " ") {
                JOptionPane.showMessageDialog(null, "An input value must be entered.");
            }
            int numOLayers = java.lang.Integer.parseInt(output_layers);
            int b = 0;
            do {
                Element oLayer = new Element("LAYER");
                oLayer.setAttribute(new Attribute("LAYER_NAME", "OUTPUT"));
                String transferFunc = JOptionPane.showInputDialog(jButton3,
                        "Which transfer function for this LAYER? 1(hyberbolic tangent) or 2(logarithmic sigmoid)",
                        "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
                if (transferFunc == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                oLayer.setAttribute(new Attribute("TRANSFER_FUNCTION", transferFunc));
                String oNodes = JOptionPane.showInputDialog(jButton3,
                        "How many NEURODE(s) in this <<OUTPUT>> LAYER?", "ANNeML Wizard",
                        JOptionPane.QUESTION_MESSAGE);
                if (oNodes == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                int numoNodes = java.lang.Integer.parseInt(oNodes);
                int d = 0;
                do {
                    Random rnd = new Random();
                    Element node = new Element("NEURODE");
                    node.setAttribute(
                            new Attribute("N_ID", "ON" + String.valueOf(b + 1) + String.valueOf(d + 1)));
                    node.setAttribute(new Attribute("ACTIVE", "-1"));
                    node.setAttribute(new Attribute("ACTIVITY", "0.0"));
                    node.setAttribute(new Attribute("BIAS", getRandomValue(rnd, low, high, decpl)));
                    node.setAttribute(new Attribute("CNAME", "Output node#" + String.valueOf(d + 1)));
                    node.setAttribute(new Attribute("NNET_V4", "0.0"));
                    oLayer.addContent(node);
                    d++;
                } while (d < numoNodes);
                subnet.addContent(oLayer);
                b++;
            } while (b < numOLayers);

            doc.getRootElement().addContent(subnet);
            i++;
        } while (i < numSubs);

        //generate fully interconnected SYNAPSE(s) for all NEURODE(s) within each SUBNET

        java.util.List subnets = XPath.newInstance("//SUBNET").selectNodes(doc);
        Iterator itSubslist = subnets.iterator();
        do {
            Element currentSnet = (Element) itSubslist.next();
            String snetName = currentSnet.getAttributeValue("SNET_NAME");
            //System.out.println(snetName);

            java.util.List Hnodes = XPath
                    .newInstance("//SUBNET[@SNET_NAME='" + snetName + "']/LAYER[@LAYER_NAME='HIDDEN']/NEURODE")
                    .selectNodes(doc);
            Iterator itHNodelist = Hnodes.iterator();
            do {
                Element node = (Element) itHNodelist.next();
                //System.out.println(node.getAttributeValue("N_ID"));
                java.util.List Inodes = XPath
                        .newInstance(
                                "//SUBNET[@SNET_NAME='" + snetName + "']/LAYER[@LAYER_NAME='INPUT']/NEURODE")
                        .selectNodes(doc);
                Iterator itNodelist = Inodes.iterator();
                do {
                    Element currentNode = (Element) itNodelist.next();
                    //System.out.println(currentNode.getAttributeValue("N_ID"));
                    Element hSynapse = new Element("SYNAPSE");
                    Random rnd = new Random();
                    hSynapse.setAttribute(new Attribute("WEIGHT", getRandomValue(rnd, low, high, decpl)));
                    hSynapse.setAttribute(new Attribute("ORG_NEURODE", currentNode.getAttributeValue("N_ID")));
                    node.addContent(hSynapse);
                } while (itNodelist.hasNext());
            } while (itHNodelist.hasNext());

            java.util.List Onodes = XPath
                    .newInstance("//SUBNET[@SNET_NAME='" + snetName + "']/LAYER[@LAYER_NAME='OUTPUT']/NEURODE")
                    .selectNodes(doc);
            Iterator itONodelist = Onodes.iterator();
            do {
                Element node = (Element) itONodelist.next();
                //System.out.println(node.getAttributeValue("N_ID"));
                java.util.List hnodes = XPath
                        .newInstance(
                                "//SUBNET[@SNET_NAME='" + snetName + "']/LAYER[@LAYER_NAME='HIDDEN']/NEURODE")
                        .selectNodes(doc);
                Iterator itNodelist = hnodes.iterator();
                do {
                    Element currentNode = (Element) itNodelist.next();
                    //System.out.println(currentNode.getAttributeValue("N_ID"));
                    Element hSynapse = new Element("SYNAPSE");
                    Random rnd = new Random();
                    hSynapse.setAttribute(new Attribute("WEIGHT", getRandomValue(rnd, low, high, decpl)));
                    hSynapse.setAttribute(new Attribute("ORG_NEURODE", currentNode.getAttributeValue("N_ID")));
                    node.addContent(hSynapse);
                } while (itNodelist.hasNext());
            } while (itONodelist.hasNext());

        } while (itSubslist.hasNext());

        // new XMLOutputter().output(doc, System.out);
        XMLOutputter xmlOutput = new XMLOutputter();

        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(doc, System.out);
        xmlOutput.output(doc, new FileWriter(nnetName + ".xml"));

        System.out.println("File Saved!");

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

From source file:ac.simons.syndication.utils.SyndicationContent.java

License:BSD License

public Element toElement() {
    final Element element = new Element("encoded",
            Namespace.getNamespace("content", "http://purl.org/rss/1.0/modules/content/"));
    element.addContent(new CDATA(content.getValue()));
    return element;
}

From source file:AIR.Common.xml.XmlNamespaceManager.java

License:Open Source License

public void addNamespace(String prefix, String url) {
    Namespace newNs = Namespace.getNamespace(prefix, url);
    for (int counter1 = 0; counter1 < nsList.size(); ++counter1) {
        Namespace existing = nsList.get(counter1);
        if (StringUtils.equals(existing.getPrefix(), newNs.getPrefix())) {
            nsList.remove(counter1);//from   w w w.  j a  v a 2s .c o m
            nsList.add(counter1, newNs);
            return;
        }
    }

    nsList.add(newNs);
}

From source file:broadwick.graph.writer.GraphMl.java

License:Apache License

/**
 * Get the string representation of the network.
 * @param network  the network object to be written.
 * @param directed a boolean flag, true if the network is directed.
 * @return a string representing a document.
 *///w ww  . ja va  2 s  .c  om
public static String toString(final Graph<? extends Vertex, ? extends Edge<?>> network,
        final boolean directed) {
    // graphml document header
    final Element graphml = new Element("graphml", "http://graphml.graphdrawing.org/xmlns");
    final Document document = new Document(graphml);
    final Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    final Namespace schemLocation = Namespace.getNamespace("schemLocation",
            "http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0rc/graphml.xsd");

    // add Namespace
    graphml.addNamespaceDeclaration(xsi);
    graphml.addNamespaceDeclaration(schemLocation);

    // keys for graphic representation
    for (VertexAttribute attr : network.getVertexAttributes()) {
        final Element element = new Element("key");
        element.setAttribute("id", attr.getName());
        element.setAttribute("for", "node");
        element.setAttribute("attr.name", attr.getName());
        element.setAttribute("attr.type", attr.getType().getName());
        if (attr.getDefaultValue() != null) {
            final Element defaultValueElement = new Element("default");
            defaultValueElement.addContent(attr.getDefaultValue().toString());
            element.addContent(defaultValueElement);
        }
        graphml.addContent(element);
    }

    for (EdgeAttribute attr : network.getEdgeAttributes()) {
        final Element element = new Element("key");
        element.setAttribute("id", attr.getName());
        element.setAttribute("for", "edge");
        element.setAttribute("attr.name", attr.getName());
        element.setAttribute("attr.type", attr.getType().getName());
        if (attr.getDefaultValue() != null) {
            final Element defaultValueElement = new Element("default");
            defaultValueElement.addContent(attr.getDefaultValue());
            element.addContent(defaultValueElement);
        }
        graphml.addContent(element);
    }

    final Element graph = new Element("graph");
    graph.setAttribute("id", "G");
    if (directed) {
        graph.setAttribute("edgedefault", "directed");
    } else {
        graph.setAttribute("edgedefault", "undirected");
    }
    graphml.addContent(graph);

    final ImmutableList<Vertex> vertices = ImmutableList.copyOf(network.getVertices());
    final Iterator<Vertex> vertexIterator = vertices.iterator();
    while (vertexIterator.hasNext()) {
        final Vertex vertex = vertexIterator.next();
        addNode(vertex, graph);
    }

    final ImmutableList<Edge<? extends Vertex>> edges;
    edges = (ImmutableList<Edge<? extends Vertex>>) ImmutableList.copyOf(network.getEdges());
    final UnmodifiableIterator<Edge<? extends Vertex>> edgeIterator = edges.iterator();
    while (edgeIterator.hasNext()) {
        addEdge(edgeIterator.next(), graph);
    }

    final XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    return outputter.outputString(document).replaceAll("xmlns=\"\" ", "");
}

From source file:by.epam.lw05.xml.ListToXml.java

private static Document listToDocument(List<Gun> guns) {
    Element root = new Element("arsenal", "tns", "http://www.example.com/Tarifes");
    root.addNamespaceDeclaration(Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"));
    Attribute attr = new Attribute("schemaLocation", "http://www.example.com/Tarifes myschema.xsd",
            Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"));
    root.setAttribute(attr);//w ww .  j a v a2  s  .co  m
    for (Gun gun : guns) {
        Element combatUnit = new Element("combatunit");

        combatUnit.setAttribute("serial", String.valueOf(gun.getSerial()));

        Element model = new Element("model");
        model.setText(gun.getModel());
        combatUnit.addContent(model);

        Element handy = new Element("handy");
        handy.setText(gun.getHandy());
        combatUnit.addContent(handy);

        Element origin = new Element("origin");
        origin.setText(String.valueOf(gun.getOrigin()));
        combatUnit.addContent(origin);

        Element ttx = new Element("ttx");

        Element distance = new Element("distance");
        distance.setText(String.valueOf(gun.getDistance()));
        ttx.addContent(distance);

        Element optics = new Element("optics");
        optics.setText(String.valueOf(gun.isOptics()));
        ttx.addContent(optics);
        combatUnit.addContent(ttx);

        root.addContent(combatUnit);
    }
    return new Document(root);
}

From source file:ca.nrc.cadc.caom2.xml.ObservationReader.java

License:Open Source License

private void init() {
    if (!initDone) {
        if (enableSchemaValidation) {
            String caom2SchemaUrl = XmlUtil.getResourceUrlString(CAOM20_SCHEMA_RESOURCE,
                    ObservationReader.class);
            log.debug("caom-2.0 schema URL: " + caom2SchemaUrl);

            String caom21SchemaUrl = XmlUtil.getResourceUrlString(CAOM21_SCHEMA_RESOURCE,
                    ObservationReader.class);
            log.debug("caom-2.1 schema URL: " + caom21SchemaUrl);

            String caom22SchemaUrl = XmlUtil.getResourceUrlString(CAOM22_SCHEMA_RESOURCE,
                    ObservationReader.class);
            log.debug("caom-2.2 schema URL: " + caom22SchemaUrl);

            String caom23SchemaUrl = XmlUtil.getResourceUrlString(CAOM23_SCHEMA_RESOURCE,
                    ObservationReader.class);
            log.debug("caom-2.3 schema URL: " + caom23SchemaUrl);

            String xlinkSchemaUrl = XmlUtil.getResourceUrlString(XLINK_SCHEMA_RESOURCE,
                    ObservationReader.class);
            log.debug("xlinkSchemaUrl: " + xlinkSchemaUrl);

            if (caom2SchemaUrl == null) {
                throw new RuntimeException("failed to load " + CAOM20_SCHEMA_RESOURCE + " from classpath");
            }// w ww. j a  v a2  s  .  c  o  m
            if (caom21SchemaUrl == null) {
                throw new RuntimeException("failed to load " + CAOM21_SCHEMA_RESOURCE + " from classpath");
            }
            if (caom22SchemaUrl == null) {
                throw new RuntimeException("failed to load " + CAOM22_SCHEMA_RESOURCE + " from classpath");
            }

            if (caom23SchemaUrl == null) {
                throw new RuntimeException("failed to load " + CAOM23_SCHEMA_RESOURCE + " from classpath");
            }
            if (xlinkSchemaUrl == null) {
                throw new RuntimeException("failed to load " + XLINK_SCHEMA_RESOURCE + " from classpath");
            }

            schemaMap = new HashMap<String, String>();
            schemaMap.put(XmlConstants.CAOM2_0_NAMESPACE, caom2SchemaUrl);
            schemaMap.put(XmlConstants.CAOM2_1_NAMESPACE, caom21SchemaUrl);
            schemaMap.put(XmlConstants.CAOM2_2_NAMESPACE, caom22SchemaUrl);
            schemaMap.put(XmlConstants.CAOM2_3_NAMESPACE, caom23SchemaUrl);
            schemaMap.put(XmlConstants.XLINK_NAMESPACE, xlinkSchemaUrl);
            log.debug("schema validation enabled");
        } else {
            log.debug("schema validation disabled");
        }

        xsiNamespace = Namespace.getNamespace("xsi", XmlConstants.XMLSCHEMA);
        this.initDone = true;
    }
}

From source file:ca.nrc.cadc.caom2.xml.ObservationWriter.java

License:Open Source License

/**
 * Constructor. This uses the specified CAOM namespace prefix (null is not
 * allowed). If writeEmptyCollections is true, empty elements will be
 * included for any collections that are empty; this is not necessary but is
 * valid in the schema so is useful for testing.
 *
 * @param caom2NamespacePrefix//from w ww  .j av a 2 s  . c  o m
 * @param namespace
 *            a valid CAOM-2.x target namespace
 * @param writeEmptyCollections
 */
public ObservationWriter(String caom2NamespacePrefix, String namespace, boolean writeEmptyCollections) {
    this.writeEmptyCollections = writeEmptyCollections;
    if (!StringUtil.hasText(caom2NamespacePrefix)) {
        throw new IllegalArgumentException(
                "null or 0-length namespace prefix is not allowed: " + caom2NamespacePrefix);
    }

    if (namespace == null) {
        namespace = XmlConstants.CAOM2_3_NAMESPACE; // default
        log.debug("default namespace: " + namespace);
    }

    if (XmlConstants.CAOM2_3_NAMESPACE.equals(namespace)) {
        this.caom2Namespace = Namespace.getNamespace(caom2NamespacePrefix, XmlConstants.CAOM2_3_NAMESPACE);
        docVersion = 23;
    } else if (XmlConstants.CAOM2_2_NAMESPACE.equals(namespace)) {
        this.caom2Namespace = Namespace.getNamespace(caom2NamespacePrefix, XmlConstants.CAOM2_2_NAMESPACE);
        docVersion = 22;
    } else if (XmlConstants.CAOM2_1_NAMESPACE.equals(namespace)) {
        this.caom2Namespace = Namespace.getNamespace(caom2NamespacePrefix, XmlConstants.CAOM2_1_NAMESPACE);
        docVersion = 21;
    } else if (XmlConstants.CAOM2_0_NAMESPACE.equals(namespace)) {
        this.caom2Namespace = Namespace.getNamespace(caom2NamespacePrefix, XmlConstants.CAOM2_0_NAMESPACE);
        docVersion = 20;
    } else {
        throw new IllegalArgumentException("invalid namespace: " + namespace);
    }

    this.xsiNamespace = Namespace.getNamespace("xsi", XmlConstants.XMLSCHEMA);

    log.debug("output version: " + docVersion + " " + caom2Namespace.getPrefix() + " -> "
            + caom2Namespace.getURI());
}

From source file:ca.nrc.cadc.vosi.avail.CheckWebService.java

License:Open Source License

void checkReturnedXml(String strXml) throws CheckException {
    Document doc;// www .j ava2s .  co  m
    String xpathStr;

    try {
        StringReader reader = new StringReader(strXml);
        doc = XmlUtil.buildDocument(reader, schemaMap);

        //get namespace and/or prefix from Document, then create xpath based on the prefix
        String nsp = doc.getRootElement().getNamespacePrefix(); //Namespace Prefix
        if (nsp != null && nsp.length() > 0)
            nsp = nsp + ":";
        else
            nsp = "";
        xpathStr = "/" + nsp + "availability/" + nsp + "available";
        XPathBuilder<Element> builder = new XPathBuilder<Element>(xpathStr, Filters.element());
        Namespace ns = Namespace.getNamespace(VOSI.NS_PREFIX, VOSI.AVAILABILITY_NS_URI);
        builder.setNamespace(ns);
        XPathExpression<Element> xpath = builder.compileWith(XPathFactory.instance());
        Element eleAvail = xpath.evaluateFirst(doc);
        log.debug(eleAvail);
        String textAvail = eleAvail.getText();

        // TODO: is this is actually valid? is the content not constrained by the schema?
        if (textAvail == null)
            throw new CheckException(wsURL + " output is invalid: no content in <available> element", null);

        if (!textAvail.equalsIgnoreCase("true")) {
            xpathStr = "/" + nsp + "availability/" + nsp + "note";
            builder = new XPathBuilder<Element>(xpathStr, Filters.element());
            builder.setNamespace(ns);
            xpath = builder.compileWith(XPathFactory.instance());
            Element eleNotes = xpath.evaluateFirst(doc);

            String textNotes = eleNotes.getText();
            throw new CheckException("service " + wsURL + " is not available, reported reason: " + textNotes,
                    null);
        }
    } catch (IOException e) {
        // probably an incorrect setup or bug in the checks
        throw new RuntimeException("failed to test " + wsURL, e);
    } catch (JDOMException e) {
        throw new CheckException(wsURL + " output is invalid", e);
    }
}

From source file:ca.nrc.cadc.vosi.Availability.java

License:Open Source License

public Document toXmlDocument() {
    DateFormat df = DateUtil.getDateFormat(DateUtil.IVOA_DATE_FORMAT, DateUtil.UTC);
    Namespace vosi = Namespace.getNamespace("vosi", VOSI.AVAILABILITY_NS_URI);

    Element eleAvailability = new Element("availability", vosi);

    Util.addChild(eleAvailability, vosi, "available", Boolean.toString(_status.isAvailable()));
    if (_status.getUpSince() != null)
        Util.addChild(eleAvailability, vosi, "upSince", df.format(_status.getUpSince()));
    if (_status.getDownAt() != null)
        Util.addChild(eleAvailability, vosi, "downAt", df.format(_status.getDownAt()));
    if (_status.getBackAt() != null)
        Util.addChild(eleAvailability, vosi, "backAt", df.format(_status.getBackAt()));
    if (_status.getNote() != null)
        Util.addChild(eleAvailability, vosi, "note", _status.getNote());

    Document document = new Document();
    document.addContent(eleAvailability);

    return document;
}