Search in sources :

Example 86 with XPathExpression

use of javax.xml.xpath.XPathExpression in project GDSC-SMLM by aherbert.

the class BatchPeakFit method itemStateChanged.

/*
	 * (non-Javadoc)
	 * 
	 * @see java.awt.event.ItemListener#itemStateChanged(java.awt.event.ItemEvent)
	 */
public void itemStateChanged(ItemEvent e) {
    // When the checkbox is clicked, create a default configuration file and update the
    // GenericDialog with the file location.		
    Checkbox cb = (Checkbox) e.getSource();
    if (cb.getState()) {
        cb.setState(false);
        Document doc = getDefaultSettingsXmlDocument();
        if (doc == null)
            return;
        try {
            // Look for nodes that are part of the fit configuration
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile("//gdsc.smlm.engine.FitEngineConfiguration//*");
            // For each node, add the name and value to the BatchParameters
            BatchSettings batchSettings = new BatchSettings();
            batchSettings.resultsDirectory = System.getProperty("java.io.tmpdir");
            batchSettings.images.add("/path/to/image.tif");
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            for (int i = 0; i < nodes.getLength(); i++) {
                Node node = nodes.item(i);
                if (// Only nodes with a single text entry
                node.getChildNodes().getLength() == 1) {
                    batchSettings.parameters.add(new ParameterSettings(node.getNodeName(), node.getTextContent()));
                }
            }
            // Save the settings file
            String[] path = Utils.decodePath(configFilenameText.getText());
            OpenDialog chooser = new OpenDialog("Settings_file", path[0], path[1]);
            if (chooser.getFileName() != null) {
                String newFilename = chooser.getDirectory() + chooser.getFileName();
                if (!newFilename.endsWith(".xml"))
                    newFilename += ".xml";
                FileOutputStream fs = null;
                try {
                    fs = new FileOutputStream(newFilename);
                    xs.toXML(batchSettings, fs);
                } finally {
                    if (fs != null) {
                        fs.close();
                    }
                }
                // Update dialog filename
                configFilenameText.setText(newFilename);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) ParameterSettings(gdsc.smlm.ij.settings.ParameterSettings) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) TransformerException(javax.xml.transform.TransformerException) XStreamException(com.thoughtworks.xstream.XStreamException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) OpenDialog(ij.io.OpenDialog) XPathFactory(javax.xml.xpath.XPathFactory) BatchSettings(gdsc.smlm.ij.settings.BatchSettings) Checkbox(java.awt.Checkbox) FileOutputStream(java.io.FileOutputStream)

Example 87 with XPathExpression

use of javax.xml.xpath.XPathExpression in project cloudstack by apache.

the class PaloAltoResource method getPrivateSubnet.

private String getPrivateSubnet(String vlan) throws ExecutionException {
    String _interfaceName = genPrivateInterfaceName(Long.parseLong(vlan));
    Map<String, String> params = new HashMap<String, String>();
    params.put("type", "config");
    params.put("action", "get");
    params.put("xpath", "/config/devices/entry/network/interface/" + _privateInterfaceType + "/entry[@name='" + _privateInterface + "']/layer3/units/entry[@name='" + _interfaceName + "']/ip/entry");
    String response = request(PaloAltoMethod.GET, params);
    if (validResponse(response) && responseNotEmpty(response)) {
        NodeList response_body;
        Document doc = getDocument(response);
        XPath xpath = XPathFactory.newInstance().newXPath();
        try {
            XPathExpression expr = xpath.compile("/response[@status='success']/result/entry");
            response_body = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            throw new ExecutionException(e.getCause().getMessage());
        }
        if (response_body.getLength() > 0) {
            return response_body.item(0).getAttributes().getNamedItem("name").getTextContent();
        }
    }
    return null;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) HashMap(java.util.HashMap) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) ExecutionException(com.cloud.utils.exception.ExecutionException)

Example 88 with XPathExpression

use of javax.xml.xpath.XPathExpression in project cloudstack by apache.

the class PaloAltoResource method manageDstNatRule.

public boolean manageDstNatRule(ArrayList<IPaloAltoCommand> cmdList, PaloAltoPrimative prim, PortForwardingRuleTO rule) throws ExecutionException {
    String publicIp = rule.getSrcIp();
    String dstNatName = genDstNatRuleName(publicIp, rule.getId());
    String publicInterfaceName;
    String publicVlanTag;
    if (rule.getSrcVlanTag() == null) {
        publicInterfaceName = genPublicInterfaceName(new Long("9999"));
    } else {
        publicVlanTag = parsePublicVlanTag(rule.getSrcVlanTag());
        if (publicVlanTag.equals("untagged")) {
            publicInterfaceName = genPublicInterfaceName(new Long("9999"));
        } else {
            publicInterfaceName = genPublicInterfaceName(new Long(publicVlanTag));
        }
    }
    switch(prim) {
        case CHECK_IF_EXISTS:
            // check if one exists already
            Map<String, String> params = new HashMap<String, String>();
            params.put("type", "config");
            params.put("action", "get");
            params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/nat/rules/entry[@name='" + dstNatName + "']");
            String response = request(PaloAltoMethod.GET, params);
            boolean result = (validResponse(response) && responseNotEmpty(response));
            s_logger.debug("Destination NAT exists: " + dstNatName + ", " + result);
            return result;
        case ADD:
            if (manageDstNatRule(cmdList, PaloAltoPrimative.CHECK_IF_EXISTS, rule)) {
                return true;
            }
            // build source service xml
            String srcService;
            String protocol = rule.getProtocol();
            int[] srcPortRange = rule.getSrcPortRange();
            if (srcPortRange != null) {
                String portRange;
                if (srcPortRange.length == 1 || srcPortRange[0] == srcPortRange[1]) {
                    portRange = String.valueOf(srcPortRange[0]);
                } else {
                    portRange = String.valueOf(srcPortRange[0]) + "-" + String.valueOf(srcPortRange[1]);
                }
                manageService(cmdList, PaloAltoPrimative.ADD, protocol, portRange, null);
                srcService = genServiceName(protocol, portRange, null);
            } else {
                // no equivalent config in PA, so allow all traffic...
                srcService = "any";
            }
            // build destination port xml (single port limit in PA)
            String dstPortXML = "";
            int[] dstPortRange = rule.getDstPortRange();
            if (dstPortRange != null) {
                dstPortXML = "<translated-port>" + dstPortRange[0] + "</translated-port>";
            }
            // add public IP to the sub-interface
            Map<String, String> a_sub_params = new HashMap<String, String>();
            a_sub_params.put("type", "config");
            a_sub_params.put("action", "set");
            a_sub_params.put("xpath", "/config/devices/entry/network/interface/" + _publicInterfaceType + "/entry[@name='" + _publicInterface + "']/layer3/units/entry[@name='" + publicInterfaceName + "']/ip");
            a_sub_params.put("element", "<entry name='" + publicIp + "/32'/>");
            cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.GET, a_sub_params));
            // add the destination nat rule for the public IP
            String xml = "";
            xml += "<from><member>" + _publicZone + "</member></from>";
            xml += "<to><member>" + _publicZone + "</member></to>";
            xml += "<source><member>any</member></source>";
            xml += "<destination><member>" + publicIp + "</member></destination>";
            xml += "<service>" + srcService + "</service>";
            xml += "<nat-type>ipv4</nat-type>";
            xml += "<to-interface>" + publicInterfaceName + "</to-interface>";
            xml += "<destination-translation><translated-address>" + rule.getDstIp() + "</translated-address>" + dstPortXML + "</destination-translation>";
            Map<String, String> a_params = new HashMap<String, String>();
            a_params.put("type", "config");
            a_params.put("action", "set");
            a_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/nat/rules/entry[@name='" + dstNatName + "']");
            a_params.put("element", xml);
            cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, a_params));
            return true;
        case DELETE:
            if (!manageDstNatRule(cmdList, PaloAltoPrimative.CHECK_IF_EXISTS, rule)) {
                return true;
            }
            // determine if we need to delete the ip from the interface as well...
            Map<String, String> c_params = new HashMap<String, String>();
            c_params.put("type", "config");
            c_params.put("action", "get");
            c_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/nat/rules/entry[destination/member[text()='" + publicIp + "']]");
            String c_response = request(PaloAltoMethod.GET, c_params);
            String count = "";
            NodeList response_body;
            Document doc = getDocument(c_response);
            XPath xpath = XPathFactory.newInstance().newXPath();
            try {
                XPathExpression expr = xpath.compile("/response[@status='success']/result");
                response_body = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            } catch (XPathExpressionException e) {
                throw new ExecutionException(e.getCause().getMessage());
            }
            if (response_body.getLength() > 0 && response_body.item(0).getAttributes().getLength() > 0) {
                count = response_body.item(0).getAttributes().getNamedItem("count").getTextContent();
            }
            // delete the dst nat rule
            Map<String, String> d_params = new HashMap<String, String>();
            d_params.put("type", "config");
            d_params.put("action", "delete");
            d_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/nat/rules/entry[@name='" + dstNatName + "']");
            cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, d_params));
            if (!count.equals("") && Integer.parseInt(count) == 1) {
                // this dst nat rule is the last, so remove the ip...
                // delete IP from sub-interface...
                Map<String, String> d_sub_params = new HashMap<String, String>();
                d_sub_params.put("type", "config");
                d_sub_params.put("action", "delete");
                d_sub_params.put("xpath", "/config/devices/entry/network/interface/" + _publicInterfaceType + "/entry[@name='" + _publicInterface + "']/layer3/units/entry[@name='" + publicInterfaceName + "']/ip/entry[@name='" + publicIp + "/32']");
                cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.GET, d_sub_params));
            }
            return true;
        default:
            s_logger.debug("Unrecognized command.");
            return false;
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) HashMap(java.util.HashMap) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) ExecutionException(com.cloud.utils.exception.ExecutionException)

Example 89 with XPathExpression

use of javax.xml.xpath.XPathExpression in project cloudstack by apache.

the class PaloAltoResource method responseNotEmpty.

/* Validate that the response is not empty. */
public boolean responseNotEmpty(String response) throws ExecutionException {
    NodeList response_body;
    Document doc = getDocument(response);
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        XPathExpression expr = xpath.compile("/response[@status='success']");
        response_body = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new ExecutionException(e.getCause().getMessage());
    }
    if (response_body.getLength() > 0 && (!response_body.item(0).getTextContent().equals("") || (response_body.item(0).hasChildNodes() && response_body.item(0).getFirstChild().hasChildNodes()))) {
        return true;
    } else {
        return false;
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) ExecutionException(com.cloud.utils.exception.ExecutionException)

Example 90 with XPathExpression

use of javax.xml.xpath.XPathExpression in project cloudstack by apache.

the class PaloAltoResource method requestWithPolling.

/* Used for requests that require polling to get a result (eg: commit) */
private String requestWithPolling(PaloAltoMethod method, Map<String, String> params) throws ExecutionException {
    String job_id;
    String job_response = request(method, params);
    Document doc = getDocument(job_response);
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        XPathExpression expr = xpath.compile("/response[@status='success']/result/job/text()");
        job_id = (String) expr.evaluate(doc, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new ExecutionException(e.getCause().getMessage());
    }
    if (job_id.length() > 0) {
        boolean finished = false;
        Map<String, String> job_params = new HashMap<String, String>();
        job_params.put("type", "op");
        job_params.put("cmd", "<show><jobs><id>" + job_id + "</id></jobs></show>");
        while (!finished) {
            String job_status;
            String response = request(PaloAltoMethod.GET, job_params);
            Document job_doc = getDocument(response);
            XPath job_xpath = XPathFactory.newInstance().newXPath();
            try {
                XPathExpression expr = job_xpath.compile("/response[@status='success']/result/job/status/text()");
                job_status = (String) expr.evaluate(job_doc, XPathConstants.STRING);
            } catch (XPathExpressionException e) {
                throw new ExecutionException(e.getCause().getMessage());
            }
            if (job_status.equals("FIN")) {
                finished = true;
                String job_result;
                try {
                    XPathExpression expr = job_xpath.compile("/response[@status='success']/result/job/result/text()");
                    job_result = (String) expr.evaluate(job_doc, XPathConstants.STRING);
                } catch (XPathExpressionException e) {
                    throw new ExecutionException(e.getCause().getMessage());
                }
                if (!job_result.equals("OK")) {
                    NodeList job_details;
                    try {
                        XPathExpression expr = job_xpath.compile("/response[@status='success']/result/job/details/line");
                        job_details = (NodeList) expr.evaluate(job_doc, XPathConstants.NODESET);
                    } catch (XPathExpressionException e) {
                        throw new ExecutionException(e.getCause().getMessage());
                    }
                    String error = "";
                    for (int i = 0; i < job_details.getLength(); i++) {
                        error = error + job_details.item(i).getTextContent() + "\n";
                    }
                    throw new ExecutionException(error);
                }
                return response;
            } else {
                try {
                    // poll periodically for the status of the async job...
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                /* do nothing */
                }
            }
        }
    } else {
        return job_response;
    }
    return null;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) HashMap(java.util.HashMap) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) ExecutionException(com.cloud.utils.exception.ExecutionException)

Aggregations

XPathExpression (javax.xml.xpath.XPathExpression)98 XPath (javax.xml.xpath.XPath)69 NodeList (org.w3c.dom.NodeList)56 Document (org.w3c.dom.Document)48 XPathExpressionException (javax.xml.xpath.XPathExpressionException)40 XPathFactory (javax.xml.xpath.XPathFactory)40 Node (org.w3c.dom.Node)38 DocumentBuilder (javax.xml.parsers.DocumentBuilder)24 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)19 Test (org.junit.Test)15 ArrayList (java.util.ArrayList)13 HashMap (java.util.HashMap)13 Element (org.w3c.dom.Element)12 PBXNativeTarget (com.facebook.buck.apple.xcode.xcodeproj.PBXNativeTarget)11 PBXTarget (com.facebook.buck.apple.xcode.xcodeproj.PBXTarget)11 ImmutableMap (com.google.common.collect.ImmutableMap)11 IOException (java.io.IOException)11 Path (java.nio.file.Path)11 PBXFileReference (com.facebook.buck.apple.xcode.xcodeproj.PBXFileReference)10 InputSource (org.xml.sax.InputSource)9