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 uri) 

Source Link

Document

This will retrieve (if in existence) or create (if not) a Namespace for the supplied URI, and make it usable as a default namespace, as no prefix is supplied.

Usage

From source file:org.dvlyyon.net.netconf.marshalling.NetconfUtil.java

License:Open Source License

/**
 * Processes the specified element and extracts all the attribute information from it; then sets these attributes
 * in the specified instance of the class represented by its mapping.
 * //from ww  w .  j  ava2  s  .  co  m
 * @param vo               POJO whose attributes are being converted from their XML representations.
 * @param classElement     Root XML node representing the instance.
 * @param cm               Class mapping that contains metadata about the class and its attributes.
 */
@SuppressWarnings("unchecked")
void setAttributesFromXml(final Object vo, final Element classElement, final ClassMapping cm) {
    //Namespace namespace = Namespace.getNamespace(cm.getXmlNamespace());
    Element elementToProcess = classElement;
    for (AttributeMapping am : cm.getAttributeMappings()) {
        Namespace attribNs = Namespace.getNamespace(am.getXmlNamespace());
        if (am.getType() == AttributeMapping.Type.Class) {
            Path childXmlPath = Path.fromString(cm.getXmlPath());
            PathSegment ps = new PathSegment(cm.getXmlNamespace(), cm.getXmlTag());
            PathSegment attrPs = new PathSegment(am.getXmlNamespace(), am.getXmlTag());
            childXmlPath.addSegment(ps);
            childXmlPath.addSegment(attrPs);
            ClassMapping childClass = m_model.getClassMappingByPath(childXmlPath);
            if (childClass == null) {
                throw new RuntimeException("Class mapping not found for path : " + childXmlPath);
            }
            if (childClass.getType() == ClassMapping.Type.Union) {
                List<Element> attribElements = elementToProcess.getChildren(am.getXmlTag(), attribNs);
                if (am.isList()) {
                    List<Object> listVal = new ArrayList<Object>();
                    for (Element attribElement : attribElements) {
                        Object unionValue = m_unionChoiceHelper.xmlToUnion(cm, attribElement);
                        listVal.add(unionValue);
                    }
                    BeanUtil.setDirectListValue(am.getJavaMemberName(), vo, listVal, "java.util.ArrayList");
                } else {
                    Element attribElement = attribElements.get(0);
                    if (attribElement != null) {
                        Object unionValue = m_unionChoiceHelper.xmlToUnion(cm, attribElement);
                        BeanUtil.setDirectFieldValue(am.getJavaMemberName(), vo, unionValue);
                    }
                }
            } else if (childClass.getType() == ClassMapping.Type.Choice) {
                Object choiceClass = m_unionChoiceHelper.xmlToChoice(cm, am.getXmlTag(), classElement);
                BeanUtil.setDirectFieldValue(am.getJavaMemberName(), vo, choiceClass);
            } else {
                //  Pass in an empty xpathOid and ignore containment, since we are rooted right here
                List<Object> kids = this.fromXml(elementToProcess, childClass, true);
                if (kids != null) {
                    if (am.isList()) {
                        BeanUtil.setDirectListValue(am.getJavaMemberName(), vo, kids,
                                childClass.getJavaClassName());
                    } else if (kids.size() > 0) {
                        BeanUtil.setDirectFieldValue(am.getJavaMemberName(), vo, kids.get(0));
                    }
                }
            }
        } else {
            // Built-in, enumeration and user-defined
            if (am.isList()) {
                // This is a leaf-list; get all the values and set the thing
                List<Element> attribElements = elementToProcess.getChildren(am.getXmlTag(), attribNs);
                List<Object> primitives = new ArrayList<Object>();
                String primitiveClass = "java.lang.String";
                for (Element attribElement : attribElements) {
                    Object value = am.convertStringToValue(attribElement.getText());
                    primitiveClass = value.getClass().getName();
                    primitives.add(value);
                }
                BeanUtil.setDirectListValue(am.getJavaMemberName(), vo, primitives, primitiveClass);
            } else {
                Element sourceNode = elementToProcess;
                if (!am.isSynthetic() || am.getType() == AttributeMapping.Type.Primitive_Boolean) {
                    Element attribElement = elementToProcess.getChild(am.getXmlTag(), attribNs);
                    if (attribElement == null) {
                        s_logger.debug("Attribute with tag: " + am.getXmlTag() + " not received.");
                        continue;
                    }
                    sourceNode = attribElement;
                }
                // This will take care of transformations from String to any primitive Java type
                BeanUtil.setDirectFieldValue(am.getJavaMemberName(), vo,
                        am.convertStringToValue(sourceNode.getText()));
            }
        }
    }
}

From source file:org.dvlyyon.net.netconf.NotificationStream.java

License:Open Source License

/**
 * Creates the <b>getStreams</b> request to send to the NETCONF client.
 *
 * @param wrap    false if just the request XML is desired, true if the complete (valid) XML RPC is required. 
 * @return        The XML node representing the getStreams request (if unwrapped) or the completely formed RPC request (if wrapped)
 *//*from   ww w. ja v a  2s .com*/
public static Element createGetStreamRequest(boolean wrap) {
    final Element get = new Element("get", s_xmlns);
    final Element filter = new Element("filter", s_xmlns);
    filter.setAttribute("type", "subtree");
    get.addContent(filter);
    final Element netconf = new Element("netconf", s_notificationNs);
    filter.addContent(netconf);
    final Element streams = new Element("streams", s_notificationNs);
    netconf.addContent(streams);
    if (wrap) {
        Namespace xmlns = Namespace.getNamespace("urn:ietf:params:xml:ns:netconf:base:1.0");
        Element rpcRequest = new Element("rpc", xmlns);
        rpcRequest.setAttribute("message-id", "000");
        rpcRequest.addContent(get);
        return rpcRequest;
    } else {
        return get;
    }
}

From source file:org.dvlyyon.net.netconf.transport.ssh.AsyncSshConnection.java

License:Open Source License

/**
 * Called when a hello message is received. We process the capabilities to check if notifications are supported by the device.
 *//*from  ww w .  jav  a2  s .c  om*/
@Override
@SuppressWarnings("unchecked")
protected void handleHelloResponse(Element response) {
    // Process the Hello response to make sure we have notification capabilities
    Namespace xmlns = Namespace.getNamespace(BASE_NAMESPACE);
    Element capsRoot = response.getChild("capabilities", xmlns);
    if (capsRoot == null) {
        s_logger.error("Invalid hello response received; no capabilites sent by device.");
    } else {
        List<Element> caps = capsRoot.getChildren("capability", xmlns);
        for (Element capElem : caps) {
            String capName = capElem.getText().trim();
            if (capName.equals("urn:ietf:params:netconf:capability:notification:1.0")) {
                m_notificationsSupported = true;
                break;
            }
        }
    }
}

From source file:org.dvlyyon.net.netconf.transport.ssh.AsyncSshConnection.java

License:Open Source License

/**
 * Called when a regular (non-hello) message is received. The message can be one of three types:<ol>
 * <li>rpc-reply - This would be a response to the <b>create-subscription</b> message</li>
 * <li>replayComplete - This is an indicator that says old notifications have been replayed - ignored</li>
 * <li>notification - This is an actual notification - call the registered listener</li>
 * </ol>//from   w  ww .  jav  a2s.  co  m
 */
@Override
@SuppressWarnings("unchecked")
protected void handleResponse(Element response) {
    try {
        // We are interested in three types of responses
        // RPC-OK (in response to create-subscription); verify using the message ID and OK response
        String responseType = response.getName();
        if (responseType.equals("rpc-reply")) {
            // This must be a response to the create-subscription message; verify using the message ID
            Namespace ns = Namespace.getNamespace(BASE_NAMESPACE);
            String messageId = response.getAttributeValue("message-id");
            if (m_createSubscriptionMessageId.equals(messageId)) {
                Element ok = response.getChild("ok", ns);
                if (ok != null) {
                    s_logger.debug("Got an OK response to create-subscription.");
                    m_readyToReceiveNotifications = true;
                } else {
                    s_logger.warn("Expected an OK response to create-subscription; did not get one");
                    s_logger.warn("Actual response: " + XmlUtils.toXmlString(response));
                }
            } else {
                //s_logger.info(XmlUtils.toXmlString(response));
                s_logger.info("Reply received to keep-alive ping on async. channel");
            }
        } else if (responseType.equals("replayComplete")) {
            // We don't really care about this one
            s_logger.info("Received ReplayComplete indicator from device");
        } else if (responseType.equals("notification")) {
            Element root = null;
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Top-level notification XML: " + XmlUtils.toXmlString(response));
            }
            // Notifications (call the listener)
            s_logger.debug("Got a notification from device: " + responseType);
            Timestamp eventTime = null;
            ArrayList<Element> dataNodes = new ArrayList<Element>();
            List<Element> kids = (List<Element>) response.getChildren();
            for (Element kid : kids) {
                if (kid.getName().equals("eventTime") && kid.getNamespaceURI().equals(NOTIF_NAMESPACE)) {
                    try {
                        eventTime = new RFC3399Timestamp(kid.getText()).getSqlTimestamp();
                    } catch (final Exception ex) {
                        s_logger.warn("Error parsing event date: " + kid.getText() + " using current time");
                        ;
                        eventTime = new Timestamp(System.currentTimeMillis());
                    }
                } else {
                    dataNodes.add(kid);
                }
            }
            if (dataNodes.size() > 0) {
                root = new Element("data");
                for (Element dataNode : dataNodes) {
                    dataNode.detach();
                    root.addContent(dataNode);
                }
                if (s_logger.isDebugEnabled())
                    s_logger.debug("Notification data: " + XmlUtils.toXmlString(root));
            }
            m_lastReceivedNotificationTime = eventTime;
            m_listener.notify(eventTime, root);
        } else {
            s_logger.warn("Unexpected XML message received from device: " + responseType);
        }
    } catch (final Exception fex) {
        // Any exception in event processing should just ignore the event, instead of throwing it to the
        // caller (since the thread it is being called in will bag out otherwise)
        s_logger.error("Error processing notification: " + XmlUtils.toXmlString(response, true));
        if (s_logger.isDebugEnabled()) {
            s_logger.error(fex, fex);
        }
    }
}

From source file:org.dvlyyon.net.netconf.transport.ssh.AsyncSshConnection.java

License:Open Source License

/**
 * Create the <b>create-subscription</b> message to send to the device.
 *
 * @param messageId     Message ID to use.
 * @param stream        Stream to create subscription for (NULL to use the default stream). 
 * @param startTime     Start time from when messages need to be replayed (NULL if no replay is required).
 * @return              XML representing the create-subscription message.
 *///  www.j  a  v a2  s  . c o  m
private static Element createSubscriptionMessageXml(final String messageId, final String stream,
        final Timestamp startTime) {
    Namespace netconfNs = Namespace.getNamespace(BASE_NAMESPACE);
    Element rpc = new Element("rpc", netconfNs);
    rpc.setAttribute("message-id", messageId);
    Namespace notificationNs = Namespace.getNamespace(NOTIF_NAMESPACE);
    Element cs = new Element("create-subscription", notificationNs);
    rpc.addContent(cs);
    // Add the stream name (if specified)
    if (stream != null) {
        Element streamElem = new Element("stream", notificationNs);
        streamElem.setText(stream);
        cs.addContent(streamElem);
    }
    // Add the start time (if specified)
    if (startTime != null) {
        Element fromWhen = new Element("startTime", notificationNs);
        RFC3399Timestamp ts = new RFC3399Timestamp(startTime);
        fromWhen.setText(ts.toString());
        cs.addContent(fromWhen);
    }
    return rpc;
}

From source file:org.dvlyyon.net.netconf.transport.ssh.AsyncSshConnection.java

License:Open Source License

private static Element createSubscriptionMessageXml(final String messageId, final String stream,
        final Element filter, final String startTime, final String stopTime) {
    Namespace netconfNs = Namespace.getNamespace(BASE_NAMESPACE);
    Element rpc = new Element("rpc", netconfNs);
    rpc.setAttribute("message-id", messageId);
    Namespace notificationNs = Namespace.getNamespace(NOTIF_NAMESPACE);
    Element cs = new Element("create-subscription", notificationNs);
    rpc.addContent(cs);/* www .j a  v a2 s  .c o  m*/
    // Add the stream name (if specified)
    if (stream != null) {
        Element streamElem = new Element("stream", notificationNs);
        streamElem.setText(stream);
        cs.addContent(streamElem);
    }

    if (filter != null) {
        cs.addContent(filter);
    }

    // Add the start time (if specified)
    if (startTime != null) {
        Element fromWhen = new Element("startTime", notificationNs);
        fromWhen.setText(startTime);
        cs.addContent(fromWhen);
    }

    if (stopTime != null) {
        Element stopAt = new Element("stopTime", notificationNs);
        stopAt.setText(stopTime);
        cs.addContent(stopAt);
    }
    return rpc;
}

From source file:org.dvlyyon.net.netconf.transport.ssh.SshConnection.java

License:Open Source License

/**
 * Sends the <i>hello</i> handshake, which is the first data exchange on a new NETCONF connection.
 *///from  w  w  w.  j a  va2s.com
private void exchangeHellos() {
    // Send the "hello" message to the other end
    Namespace ns = Namespace.getNamespace("urn:ietf:params:xml:ns:netconf:base:1.0");
    final Element hello = new Element("hello", ns);
    final Element caps = new Element("capabilities", ns);
    hello.addContent(caps);
    addCapabilities(caps, ns);

    // send this way to force non-chunked.  Hello's must be non-chunked
    streamDataOutToWire(hello, false, false);
    streamDataInFromWire(false, false);

    // syncSend(hello, true, false);
}

From source file:org.esa.s2tbx.dataio.s2.gml.GmlFilter.java

License:Open Source License

public Pair<String, List<EopPolygon>> parse(InputStream stream) {
    SAXBuilder builder = new SAXBuilder();
    Document jdomDoc = null;/*w  w  w.  j av a  2 s.co m*/

    try {
        jdomDoc = builder.build(stream);

        //get the root element
        Element web_app = jdomDoc.getRootElement();
        String maskEpsg = "";

        Namespace gml = Namespace.getNamespace("http://www.opengis.net/gml/3.2");
        Namespace eop = Namespace.getNamespace("http://www.opengis.net/eop/2.0");

        List<Element> targeted = web_app.getChildren("boundedBy", gml);
        if (!targeted.isEmpty()) {
            Element aEnvelope = targeted.get(0).getChild("Envelope", gml);
            if (aEnvelope != null) {
                maskEpsg = aEnvelope.getAttribute("srsName").getValue();
            }
        }

        List<EopPolygon> recoveredGeometries = new ArrayList<>();

        IteratorIterable<Content> contents = web_app.getDescendants();
        while (contents.hasNext()) {
            Content web_app_content = contents.next();
            if (!web_app_content.getCType().equals(CType.Text)
                    && !web_app_content.getCType().equals(CType.Comment)) {
                boolean withGml = (web_app_content.getNamespacesInScope().get(0).getPrefix().contains("gml"));
                if (withGml) {
                    boolean parentNotGml = !(web_app_content.getParentElement().getNamespace().getPrefix()
                            .contains("gml"));
                    if (parentNotGml) {
                        Element capturedElement = (Element) web_app_content;
                        Attribute attr = null;
                        String polygonId = "";
                        String typeId = "";
                        if (capturedElement.getName().contains("Polygon")) {
                            attr = capturedElement.getAttribute("id", gml);
                            if (attr != null) {
                                polygonId = attr.getValue();
                                if (polygonId.indexOf('.') != -1) {
                                    typeId = polygonId.substring(0, polygonId.indexOf('.'));
                                }
                            }
                        }

                        Document newDoc = new Document(capturedElement.clone().detach());

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        xmlOutput.output(newDoc, baos);
                        String replacedContent = baos.toString().replace("/www.opengis.net/gml/3.2",
                                "/www.opengis.net/gml");

                        InputStream ois = new ByteArrayInputStream(replacedContent.getBytes());

                        List<Polygon> pols = streamParseGML3(ois);
                        for (Polygon pol : pols) {
                            recoveredGeometries.add(new EopPolygon(polygonId, typeId, pol));
                        }
                    }
                }

            }
        }

        return new Pair<String, List<EopPolygon>>(maskEpsg, recoveredGeometries);
    } catch (JDOMException e) {
        // {@report "parse xml problem !"}
    } catch (IOException e) {
        // {@report "IO problem !"}
    }

    return new Pair<String, List<EopPolygon>>("", new ArrayList<>());
}

From source file:org.fiware.cybercaptor.server.api.IDMEFManagement.java

License:Open Source License

/**
 * Load the IDMEF from an XML file (containing the alerts in IDMEF format)
 * cf https://www.ietf.org/rfc/rfc4765.txt.
 * Serialize this list of alerts in a file, in order to send them to the client when it
 * makes the proper request.//from w  ww  .j a v a2s . co m
 *
 * @param idmefXMLString the XML string of the alerts
 * @throws JDOMException
 * @throws IOException
 */
public static void loadIDMEFAlertsFromXML(String idmefXMLString)
        throws JDOMException, IOException, ClassNotFoundException {
    String alertsTemporaryPath = ProjectProperties.getProperty("alerts-temporary-path");
    if (alertsTemporaryPath == null || alertsTemporaryPath.isEmpty()) {
        alertsTemporaryPath = ProjectProperties.getProperty("output-path") + "/alerts.bin";
    }
    if (alertsTemporaryPath == null || alertsTemporaryPath.isEmpty()) {
        throw new IllegalStateException("The path where the alerts should be saved is invalid.");
    }

    //Load the alerts history
    File alertsFile = new File(alertsTemporaryPath);
    List<Alert> alerts;
    if (alertsFile.exists()) {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(alertsTemporaryPath));
        try {
            alerts = (List<Alert>) ois.readObject();
        } catch (InvalidClassException exception) {
            // The sources have been changed since the alerts where saved, reinitialize the database
            alerts = new ArrayList<Alert>();
        }
    } else {
        alerts = new ArrayList<Alert>();
    }

    //Load the alerts from the XML
    SAXBuilder sxb = new SAXBuilder();
    Document document = sxb.build(new StringReader(idmefXMLString));
    Namespace idmefNamespace = Namespace.getNamespace("http://iana.org/idmef");
    Element root = document.getRootElement();
    for (Element alertElement : root.getChildren("Alert", idmefNamespace)) {
        Alert alert = new Alert(alertElement);
        alerts.add(alert);
    }

    //Save to the alerts in temporary file
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(alertsFile));
    oos.writeObject(alerts);
    Logger.getAnonymousLogger().log(Level.INFO, alerts.size() + " alerts are now stored in temporary file.");
}

From source file:org.fiware.cybercaptor.server.dra.Alert.java

License:Open Source License

/**
 * Load an alert from a idmef:Alert element
 *
 * @param alertElement the DOM element idmef:Alert
 *///  www .  ja v a2s .co  m
public Alert(Element alertElement) {
    Namespace idmefNamespace = Namespace.getNamespace("http://iana.org/idmef");
    if (alertElement == null || !alertElement.getName().equals("Alert")) {
        throw new IllegalStateException("The IDMEF alert to parse is not valid");
    }

    Element createTimeElement = alertElement.getChild("CreateTime", idmefNamespace);
    if (createTimeElement != null) {
        timestamp = new TimeStamp(createTimeElement.getAttributeValue("ntpstamp").replaceAll("0x", ""))
                .getDate();
    }
    Element detectTimeElement = alertElement.getChild("DetectTime", idmefNamespace);
    if (detectTimeElement != null) {
        timestamp = new TimeStamp(detectTimeElement.getAttributeValue("ntpstamp").replaceAll("0x", ""))
                .getDate();
    }
    if (timestamp == null)
        throw new IllegalStateException("invalid timestamp for the IDMEF alert");

    //sources
    for (Element sourceElement : alertElement.getChildren("Source", idmefNamespace)) {
        Element sourceNode = sourceElement.getChild("Node", idmefNamespace);
        if (sourceNode != null) {
            Element sourceAddress = sourceNode.getChild("Address", idmefNamespace);
            //If there is an address
            if (sourceAddress != null) {
                Element sourceIP = sourceAddress.getChild("address", idmefNamespace);
                Element sourceMask = sourceAddress.getChild("netmask", idmefNamespace);
                if (sourceIP != null && sourceMask != null) {
                    this.sources.add(sourceIP.getText() + "/" + sourceMask);
                } else if (sourceIP != null) {
                    this.sources.add(sourceIP.getText());
                }
            } else { // There is no address, their must be a "name"
                Element sourceName = sourceNode.getChild("name", idmefNamespace);
                if (sourceName != null) {
                    this.sources.add(sourceName.getText());
                }
            }
        }
    }

    //targets
    for (Element targetElement : alertElement.getChildren("Target", idmefNamespace)) {
        Element targetNode = targetElement.getChild("Node", idmefNamespace);
        if (targetNode != null) {
            Element targetAddress = targetNode.getChild("Address", idmefNamespace);
            //If there is an address
            if (targetAddress != null) {
                Element targetIP = targetAddress.getChild("address", idmefNamespace);
                Element targetMask = targetAddress.getChild("netmask", idmefNamespace);
                if (targetIP != null && targetMask != null) {
                    this.targets.add(targetIP.getText() + "/" + targetMask);
                } else if (targetIP != null) {
                    this.targets.add(targetIP.getText());
                }
            } else { // There is no address, their must be a "name"
                Element targetName = targetNode.getChild("name", idmefNamespace);
                if (targetName != null) {
                    this.targets.add(targetName.getText());
                }
            }
        }
    }

    //add classification information
    Element classificationElement = alertElement.getChild("Classification", idmefNamespace);
    if (classificationElement != null) {
        this.name = classificationElement.getAttributeValue("text");
        for (Element referenceElement : classificationElement.getChildren("Reference", idmefNamespace)) {
            switch (referenceElement.getAttributeValue("origin")) {
            case "cve":
                cveLinks.put(referenceElement.getChild("name", idmefNamespace).getText(),
                        referenceElement.getChild("url", idmefNamespace).getText());
                break;
            }
        }
    }
}