Example usage for javax.xml.xpath XPathExpressionException getCause

List of usage examples for javax.xml.xpath XPathExpressionException getCause

Introduction

In this page you can find the example usage for javax.xml.xpath XPathExpressionException getCause.

Prototype

public Throwable getCause() 

Source Link

Document

Get the cause of this XPathException.

Usage

From source file:com.cloud.network.resource.PaloAltoResource.java

public boolean responseNotEmpty(String response) throws ExecutionException {
    NodeList response_body;//from  ww w.  jav  a 2  s  . c  o m
    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;
    }
}

From source file:com.cloud.network.resource.PaloAltoResource.java

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;//from   ww w .ja  v a  2 s.com
        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;
}

From source file:com.cloud.network.resource.PaloAltoResource.java

public boolean validResponse(String response) throws ExecutionException {
    NodeList response_body;//from w  w w  .  j  a  v  a 2s  .c om
    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) {
        return true;
    } else {
        NodeList error_details;
        try {
            XPathExpression expr = xpath.compile("/response/msg/line/line");
            error_details = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            throw new ExecutionException(e.getCause().getMessage());
        }
        if (error_details.getLength() == 0) {
            try {
                XPathExpression expr = xpath.compile("/response/msg/line");
                error_details = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            } catch (XPathExpressionException e) {
                throw new ExecutionException(e.getCause().getMessage());
            }

            if (error_details.getLength() == 0) {
                try {
                    XPathExpression expr = xpath.compile("/response/result/msg");
                    error_details = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
                } catch (XPathExpressionException e) {
                    throw new ExecutionException(e.getCause().getMessage());
                }
            }
        }
        String error = "";
        for (int i = 0; i < error_details.getLength(); i++) {
            error = error + error_details.item(i).getTextContent() + "\n";
        }
        throw new ExecutionException(error);
    }
}

From source file:com.cloud.network.resource.PaloAltoResource.java

private String requestWithPolling(PaloAltoMethod method, Map<String, String> params) throws ExecutionException {
    String job_id;//from w ww  . j  a v a2 s .c om
    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 {
                    Thread.sleep(2000); // poll periodically for the status of the async job...
                } catch (InterruptedException e) { /* do nothing */
                }
            }
        }
    } else {
        return job_response;
    }
    return null;
}

From source file:com.cloud.network.resource.PaloAltoResource.java

private synchronized boolean requestWithCommit(ArrayList<IPaloAltoCommand> commandList)
        throws ExecutionException {
    boolean result = true;

    if (commandList.size() > 0) {
        // CHECK IF THERE IS PENDING CHANGES THAT HAVE NOT BEEN COMMITTED...
        String pending_changes;/*from   w  w w  .j  av a2 s  .  co  m*/
        Map<String, String> check_params = new HashMap<String, String>();
        check_params.put("type", "op");
        check_params.put("cmd", "<check><pending-changes></pending-changes></check>");
        String check_response = request(PaloAltoMethod.GET, check_params);
        Document check_doc = getDocument(check_response);
        XPath check_xpath = XPathFactory.newInstance().newXPath();
        try {
            XPathExpression expr = check_xpath.compile("/response[@status='success']/result/text()");
            pending_changes = (String) expr.evaluate(check_doc, XPathConstants.STRING);
        } catch (XPathExpressionException e) {
            throw new ExecutionException(e.getCause().getMessage());
        }
        if (pending_changes.equals("yes")) {
            throw new ExecutionException(
                    "The Palo Alto has uncommited changes, so no changes can be made.  Try again later or contact your administrator.");
        } else {
            // ADD A CONFIG LOCK TO CAPTURE THE PALO ALTO RESOURCE
            String add_lock_status;
            Map<String, String> add_lock_params = new HashMap<String, String>();
            add_lock_params.put("type", "op");
            add_lock_params.put("cmd", "<request><config-lock><add></add></config-lock></request>");
            String add_lock_response = request(PaloAltoMethod.GET, add_lock_params);
            Document add_lock_doc = getDocument(add_lock_response);
            XPath add_lock_xpath = XPathFactory.newInstance().newXPath();
            try {
                XPathExpression expr = add_lock_xpath.compile("/response[@status='success']/result/text()");
                add_lock_status = (String) expr.evaluate(add_lock_doc, XPathConstants.STRING);
            } catch (XPathExpressionException e) {
                throw new ExecutionException(e.getCause().getMessage());
            }
            if (add_lock_status.length() == 0) {
                throw new ExecutionException("The Palo Alto is locked, no changes can be made at this time.");
            }

            try {
                // RUN THE SEQUENCE OF COMMANDS
                for (IPaloAltoCommand command : commandList) {
                    result = (result && command.execute()); // run commands and modify result boolean
                }

                // COMMIT THE CHANGES (ALSO REMOVES CONFIG LOCK)
                String commit_job_id;
                Map<String, String> commit_params = new HashMap<String, String>();
                commit_params.put("type", "commit");
                commit_params.put("cmd", "<commit></commit>");
                String commit_response = requestWithPolling(PaloAltoMethod.GET, commit_params);
                Document commit_doc = getDocument(commit_response);
                XPath commit_xpath = XPathFactory.newInstance().newXPath();
                try {
                    XPathExpression expr = commit_xpath
                            .compile("/response[@status='success']/result/job/id/text()");
                    commit_job_id = (String) expr.evaluate(commit_doc, XPathConstants.STRING);
                } catch (XPathExpressionException e) {
                    throw new ExecutionException(e.getCause().getMessage());
                }
                if (commit_job_id.length() == 0) { // no commit was done, so release the lock...
                    // REMOVE THE CONFIG LOCK TO RELEASE THE PALO ALTO RESOURCE
                    String remove_lock_status;
                    Map<String, String> remove_lock_params = new HashMap<String, String>();
                    remove_lock_params.put("type", "op");
                    remove_lock_params.put("cmd",
                            "<request><config-lock><remove></remove></config-lock></request>");
                    String remove_lock_response = request(PaloAltoMethod.GET, remove_lock_params);
                    Document remove_lock_doc = getDocument(remove_lock_response);
                    XPath remove_lock_xpath = XPathFactory.newInstance().newXPath();
                    try {
                        XPathExpression expr = remove_lock_xpath
                                .compile("/response[@status='success']/result/text()");
                        remove_lock_status = (String) expr.evaluate(remove_lock_doc, XPathConstants.STRING);
                    } catch (XPathExpressionException e) {
                        throw new ExecutionException(e.getCause().getMessage());
                    }
                    if (remove_lock_status.length() == 0) {
                        throw new ExecutionException(
                                "Could not release the Palo Alto device.  Please notify an administrator!");
                    }
                }

            } catch (ExecutionException ex) {
                // REVERT TO RUNNING
                String revert_job_id;
                Map<String, String> revert_params = new HashMap<String, String>();
                revert_params.put("type", "op");
                revert_params.put("cmd", "<load><config><from>running-config.xml</from></config></load>");
                requestWithPolling(PaloAltoMethod.GET, revert_params);

                // REMOVE THE CONFIG LOCK TO RELEASE THE PALO ALTO RESOURCE
                String remove_lock_status;
                Map<String, String> remove_lock_params = new HashMap<String, String>();
                remove_lock_params.put("type", "op");
                remove_lock_params.put("cmd",
                        "<request><config-lock><remove></remove></config-lock></request>");
                String remove_lock_response = request(PaloAltoMethod.GET, remove_lock_params);
                Document remove_lock_doc = getDocument(remove_lock_response);
                XPath remove_lock_xpath = XPathFactory.newInstance().newXPath();
                try {
                    XPathExpression expr = remove_lock_xpath
                            .compile("/response[@status='success']/result/text()");
                    remove_lock_status = (String) expr.evaluate(remove_lock_doc, XPathConstants.STRING);
                } catch (XPathExpressionException e) {
                    throw new ExecutionException(e.getCause().getMessage());
                }
                if (remove_lock_status.length() == 0) {
                    throw new ExecutionException(
                            "Could not release the Palo Alto device.  Please notify an administrator!");
                }

                throw ex; // Bubble up the reason we reverted...
            }

            return result;
        }
    } else {
        return true; // nothing to do
    }
}

From source file:com.cloud.network.resource.PaloAltoResource.java

public boolean manageDstNatRule(ArrayList<IPaloAltoCommand> cmdList, PaloAltoPrimative prim,
        PortForwardingRuleTO rule) throws ExecutionException {
    String publicIp = rule.getSrcIp();
    String dstNatName = genDstNatRuleName(publicIp, rule.getId());

    String publicInterfaceName;//from w ww.j  a  v a  2 s .  c o  m
    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;
    }
}

From source file:com.cloud.network.resource.PaloAltoResource.java

public boolean manageFirewallRule(ArrayList<IPaloAltoCommand> cmdList, PaloAltoPrimative prim,
        FirewallRuleTO rule) throws ExecutionException {
    String ruleName;/*w  ww . j a  v a  2s .  c  o m*/
    if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
        ruleName = genFirewallRuleName(rule.getId(), rule.getSrcVlanTag());
    } else {
        ruleName = genFirewallRuleName(rule.getId());
    }

    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/security/rules/entry[@name='"
                        + ruleName + "']");
        String response = request(PaloAltoMethod.GET, params);
        boolean result = (validResponse(response) && responseNotEmpty(response));
        s_logger.debug("Firewall policy exists: " + ruleName + ", " + result);
        return result;

    case ADD:
        if (manageFirewallRule(cmdList, PaloAltoPrimative.CHECK_IF_EXISTS, rule)) {
            return true;
        }

        String srcZone;
        String dstZone;
        String dstAddressXML;
        String appXML;
        String serviceXML;

        String protocol = rule.getProtocol();
        String action = "allow";

        // Only ICMP will use an Application, so others will be any.
        if (protocol.equals(Protocol.ICMP.toString())) {
            appXML = "<member>icmp</member><member>ping</member><member>traceroute</member>"; // use the default icmp applications...
        } else {
            appXML = "<member>any</member>";
        }

        // Only TCP and UDP will use a Service, others will use any.
        if (protocol.equals(Protocol.TCP.toString()) || protocol.equals(Protocol.UDP.toString())) {
            String portRange;
            if (rule.getSrcPortRange() != null) {
                int startPort = rule.getSrcPortRange()[0];
                int endPort = rule.getSrcPortRange()[1];
                if (startPort == endPort) {
                    portRange = String.valueOf(startPort);
                } else {
                    portRange = String.valueOf(startPort) + "-" + String.valueOf(endPort);
                }
                manageService(cmdList, PaloAltoPrimative.ADD, protocol, portRange, null);
                serviceXML = "<member>" + genServiceName(protocol, portRange, null) + "</member>";
            } else {
                // no equivalent config in PA, so allow all traffic...
                serviceXML = "<member>any</member>";
            }
        } else {
            serviceXML = "<member>any</member>";
        }

        // handle different types of fire wall rules (egress | ingress)
        if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) { // Egress Rule
            srcZone = _privateZone;
            dstZone = _publicZone;
            dstAddressXML = "<member>any</member>";

            // defaults to 'allow', the deny rules are as follows
            if (rule.getType() == FirewallRule.FirewallRuleType.System) {
                if (!rule.isDefaultEgressPolicy()) { // default of deny && system rule, so deny
                    action = "deny";
                }
            } else {
                if (rule.isDefaultEgressPolicy()) { // default is allow && user rule, so deny
                    action = "deny";
                }
            }
        } else { // Ingress Rule
            srcZone = _publicZone;
            dstZone = _privateZone;
            dstAddressXML = "<member>" + rule.getSrcIp() + "</member>";
        }

        // build the source cidr xml
        String srcCidrXML = "";
        List<String> ruleSrcCidrList = rule.getSourceCidrList();
        if (ruleSrcCidrList.size() > 0) { // a cidr was entered, modify as needed...
            for (int i = 0; i < ruleSrcCidrList.size(); i++) {
                if (ruleSrcCidrList.get(i).trim().equals("0.0.0.0/0")) { // allow any
                    if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
                        srcCidrXML += "<member>" + getPrivateSubnet(rule.getSrcVlanTag()) + "</member>";
                    } else {
                        srcCidrXML += "<member>any</member>";
                    }
                } else {
                    srcCidrXML += "<member>" + ruleSrcCidrList.get(i).trim() + "</member>";
                }
            }
        } else { // no cidr was entered, so allow ALL according to firewall rule type
            if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
                srcCidrXML = "<member>" + getPrivateSubnet(rule.getSrcVlanTag()) + "</member>";
            } else {
                srcCidrXML = "<member>any</member>";
            }
        }

        // build new rule xml
        String xml = "";
        xml += "<from><member>" + srcZone + "</member></from>";
        xml += "<to><member>" + dstZone + "</member></to>";
        xml += "<source>" + srcCidrXML + "</source>";
        xml += "<destination>" + dstAddressXML + "</destination>";
        xml += "<application>" + appXML + "</application>";
        xml += "<service>" + serviceXML + "</service>";
        xml += "<action>" + action + "</action>";
        xml += "<negate-source>no</negate-source>";
        xml += "<negate-destination>no</negate-destination>";
        if (_threatProfile != null && action.equals("allow")) { // add the threat profile if it exists
            xml += "<profile-setting><group><member>" + _threatProfile + "</member></group></profile-setting>";
        }
        if (_logProfile != null && action.equals("allow")) { // add the log profile if it exists
            xml += "<log-setting>" + _logProfile + "</log-setting>";
        }

        boolean has_default = false;
        String defaultEgressRule = "";
        if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
            // check if a default egress rule exists because it always has to be after the other rules.
            Map<String, String> e_params = new HashMap<String, String>();
            e_params.put("type", "config");
            e_params.put("action", "get");
            e_params.put("xpath",
                    "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_"
                            + rule.getSrcVlanTag() + "']");
            String e_response = request(PaloAltoMethod.GET, e_params);
            has_default = (validResponse(e_response) && responseNotEmpty(e_response));

            // there is an existing default rule, so we need to remove it and add it back after the new rule is added.
            if (has_default) {
                s_logger.debug("Moving the default egress rule after the new rule: " + ruleName);
                NodeList response_body;
                Document doc = getDocument(e_response);
                XPath xpath = XPathFactory.newInstance().newXPath();
                try {
                    XPathExpression expr = xpath.compile("/response[@status='success']/result/entry/node()");
                    response_body = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
                } catch (XPathExpressionException e) {
                    throw new ExecutionException(e.getCause().getMessage());
                }
                for (int i = 0; i < response_body.getLength(); i++) {
                    Node n = response_body.item(i);
                    defaultEgressRule += nodeToString(n);
                }
                Map<String, String> dd_params = new HashMap<String, String>();
                dd_params.put("type", "config");
                dd_params.put("action", "delete");
                dd_params.put("xpath",
                        "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_"
                                + rule.getSrcVlanTag() + "']");
                cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, dd_params));
            }
        }

        // add the new rule...
        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/security/rules/entry[@name='"
                        + ruleName + "']");
        a_params.put("element", xml);
        cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, a_params));

        // add back the default rule
        if (rule.getTrafficType() == FirewallRule.TrafficType.Egress && has_default) {
            Map<String, String> da_params = new HashMap<String, String>();
            da_params.put("type", "config");
            da_params.put("action", "set");
            da_params.put("xpath",
                    "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_"
                            + rule.getSrcVlanTag() + "']");
            da_params.put("element", defaultEgressRule);
            cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, da_params));
            s_logger.debug("Completed move of the default egress rule after rule: " + ruleName);
        }

        return true;

    case DELETE:
        if (!manageFirewallRule(cmdList, PaloAltoPrimative.CHECK_IF_EXISTS, rule)) {
            return true;
        }

        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/security/rules/entry[@name='"
                        + ruleName + "']");
        cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, d_params));

        return true;

    default:
        s_logger.debug("Unrecognized command.");
        return false;
    }
}

From source file:org.apache.ode.bpel.elang.xpath20.runtime.XPath20ExpressionRuntime.java

private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type)
        throws FaultException, EvaluationException {
    try {//w  w w .j ava  2 s  .  c o m
        OXPath20ExpressionBPEL20 oxpath20 = ((OXPath20ExpressionBPEL20) cexp);

        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(ctx, oxpath20);
        JaxpVariableResolver varResolver = new JaxpVariableResolver(ctx, oxpath20,
                ((XPathFactoryImpl) _xpf).getConfiguration());
        XPath xpe = _xpf.newXPath();
        xpe.setXPathFunctionResolver(funcResolver);
        xpe.setXPathVariableResolver(varResolver);
        xpe.setNamespaceContext(oxpath20.namespaceCtx);
        String xpath = ((OXPath10Expression) cexp).xpath;
        XPathExpression expr = xpe.compile(xpath);
        Node contextNode = ctx.getRootNode();
        if (contextNode == null) {
            contextNode = DOMUtils.newDocument();
        }
        // Create step nodes in XPath in case it is incompletely instantiated
        if (oxpath20.insertMissingData) {
            XPath20ExpressionModifier modifier = new XPath20ExpressionModifier(oxpath20.namespaceCtx,
                    ((XPathFactoryImpl) _xpf).getConfiguration().getNamePool());

            Node temp = ctx.getRootNode();
            if (temp.getLocalName().equals("message") && temp.getNamespaceURI() == null) {
                int startind = xpath.indexOf('.');
                int endind = xpath.indexOf('/');
                if (startind != -1) {
                    String part = null;
                    if (endind != -1) {
                        part = xpath.substring(startind + 1, endind);
                    } else {
                        part = xpath.substring(startind + 1);
                    }
                    Element partElem = DOMUtils.findChildByName((Element) temp, new QName(null, part));

                    if (partElem != null && partElem.getFirstChild() != null) {
                        temp = partElem.getFirstChild();
                    }
                }
            }

            modifier.insertMissingData(expr, temp);
        }
        Object evalResult = expr.evaluate(contextNode, type);
        if (evalResult != null && __log.isDebugEnabled()) {
            __log.debug("Expression " + cexp.toString() + " generated result " + evalResult + " - type="
                    + evalResult.getClass().getName());
            if (ctx.getRootNode() != null)
                __log.debug("Was using context node " + DOMUtils.domToString(ctx.getRootNode()));
        }
        return evalResult;
    } catch (XPathExpressionException e) {
        // Extracting the real cause from all this wrapping isn't a simple task
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        if (cause instanceof XPathException) {
            Throwable th = ((XPathException) cause).getException();
            if (th != null) {
                cause = th;
                if (cause.getCause() != null)
                    cause = cause.getCause();
            }
        }
        throw new EvaluationException("Error while executing an XPath expression: " + cause.toString(), cause);
    } catch (WrappedResolverException wre) {
        __log.debug("Could not evaluate expression because of ", wre);
        throw (FaultException) wre.getCause();
    } catch (Throwable t) {
        __log.debug("Could not evaluate expression because of ", t);
        throw new EvaluationException("Error while executing an XPath expression: ", t);
    }
}

From source file:org.apache.ode.bpel.rtrep.v1.xpath10.jaxp.JaxpXPath10ExpressionRuntime.java

private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type) throws FaultException {
    try {//w w  w.  ja v  a2 s .c o m
        OXPath10Expression oxpath = (OXPath10Expression) cexp;
        __log.debug("JAXP runtime: evaluating " + oxpath.xpath);
        // use default XPath implementation
        XPathFactory xpf = XPathFactory.newInstance();
        __log.debug("JAXP runtime: XPathFactory impl = " + xpf.getClass());
        XPath xpe = xpf.newXPath();
        xpe.setXPathFunctionResolver(new JaxpFunctionResolver(ctx, oxpath));
        xpe.setXPathVariableResolver(new JaxpVariableResolver(ctx, oxpath));
        xpe.setNamespaceContext(oxpath.namespaceCtx);
        XPathExpression expr = xpe.compile(((OXPath10Expression) cexp).xpath);
        Object evalResult = expr
                .evaluate(ctx.getRootNode() == null ? DOMUtils.newDocument() : ctx.getRootNode(), type);
        if (evalResult != null && __log.isDebugEnabled()) {
            __log.debug("Expression " + cexp.toString() + " generated result " + evalResult + " - type="
                    + evalResult.getClass().getName());
            if (ctx.getRootNode() != null)
                __log.debug("Was using context node " + DOMUtils.domToString(ctx.getRootNode()));
        }
        return evalResult;
    } catch (XPathExpressionException e) {
        // Extracting the real cause from all this wrapping isn't a simple task
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, cause.getMessage(),
                cause);
    } catch (WrappedFaultException wre) {
        __log.debug("Could not evaluate expression because of ", wre);
        throw (FaultException) wre.getCause();
    } catch (Throwable t) {
        __log.debug("Could not evaluate expression because of ", t);
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, t.getMessage(), t);
    }

}

From source file:org.apache.ode.bpel.rtrep.v1.xpath20.XPath20ExpressionRuntime.java

private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type) throws FaultException {
    try {/*from w  ww .j av a  2s  .  c  om*/
        OXPath20ExpressionBPEL20 oxpath20 = ((OXPath20ExpressionBPEL20) cexp);
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        // JAXP based XPath 1.0 runtime does not work anymore after a XPath 2.0 has been evaluated if this is set.
        // System.setProperty("javax.xml.xpath.XPathFactory:"+XPathConstants.DOM_OBJECT_MODEL,
        //        "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_JDOM,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_XOM,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_DOM4J,
                "net.sf.saxon.xpath.XPathFactoryImpl");

        XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(ctx, oxpath20);
        JaxpVariableResolver varResolver = new JaxpVariableResolver(ctx, oxpath20,
                ((XPathFactoryImpl) xpf).getConfiguration());
        xpf.setXPathFunctionResolver(funcResolver);
        xpf.setXPathVariableResolver(varResolver);
        XPath xpe = xpf.newXPath();
        xpe.setNamespaceContext(oxpath20.namespaceCtx);
        XPathExpression expr = xpe.compile(((OXPath10Expression) cexp).xpath);
        Node contextNode = ctx.getRootNode() == null ? DOMUtils.newDocument() : ctx.getRootNode();
        Object evalResult = expr.evaluate(contextNode, type);
        if (evalResult != null && __log.isDebugEnabled()) {
            __log.debug("Expression " + cexp.toString() + " generated result " + evalResult + " - type="
                    + evalResult.getClass().getName());
            if (ctx.getRootNode() != null)
                __log.debug("Was using context node " + DOMUtils.domToString(ctx.getRootNode()));
        }
        return evalResult;
    } catch (XPathExpressionException e) {
        // Extracting the real cause from all this wrapping isn't a simple task
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        if (cause instanceof DynamicError) {
            Throwable th = ((DynamicError) cause).getException();
            if (th != null) {
                cause = th;
                if (cause.getCause() != null)
                    cause = cause.getCause();
            }
        }
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, cause.getMessage(),
                cause);
    } catch (WrappedFaultException wre) {
        __log.debug("Could not evaluate expression because of ", wre);
        throw (FaultException) wre.getCause();
    } catch (Throwable t) {
        __log.debug("Could not evaluate expression because of ", t);
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, t.getMessage(), t);
    }
}