Example usage for javax.xml.xpath XPathExpression evaluate

List of usage examples for javax.xml.xpath XPathExpression evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPathExpression evaluate.

Prototype

public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException;

Source Link

Document

Evaluate the compiled XPath expression in the context of the specified InputSource and return the result as the specified type.

Usage

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

public boolean validResponse(String response) throws ExecutionException {
    NodeList response_body;//from w  ww.  ja  v  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) {
        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.photon.phresco.framework.actions.applications.Quality.java

private NodeList evaluateTestSuite(Document doc) throws PhrescoException, XPathExpressionException {
    ProjectAdministrator administrator = PhrescoFrameworkFactory.getProjectAdministrator();
    Project project = administrator.getProject(projectCode);
    String techId = project.getProjectInfo().getTechnology().getId();
    String testSuitePath = null;/*from  w  w w  .j  a  va2s  .c  o  m*/
    FrameworkUtil frameworkUtil = FrameworkUtil.getInstance();
    if (APP_UNIT_TEST.equals(testType)) {
        testSuitePath = frameworkUtil.getUnitTestSuitePath(techId);
    } else if (APP_FUNCTIONAL_TEST.equals(testType)) {
        testSuitePath = frameworkUtil.getFunctionalTestSuitePath(techId);
    }

    S_LOGGER.debug("Project info " + project.getProjectInfo().getName() + " Test suite path " + testSuitePath);

    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression xPathExpression = xpath.compile(testSuitePath);
    NodeList testSuiteNode = (NodeList) xPathExpression.evaluate(doc, XPathConstants.NODESET);
    return testSuiteNode;
}

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

private String requestWithPolling(PaloAltoMethod method, Map<String, String> params) throws ExecutionException {
    String job_id;//from   ww  w . j av a  2  s.c o  m
    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  ww  w  .  j  a v a 2  s  .c  o 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;//w  w  w.j  a v  a  2 s . co  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;/*from w ww.ja  va 2 s.  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:com.rapid.server.Designer.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    RapidRequest rapidRequest = new RapidRequest(this, request);

    try {//from   w  ww.  ja  va 2s  .co  m

        String output = "";

        // read bytes from request body into our own byte array (this means we can deal with images) 
        InputStream input = request.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        for (int length = 0; (length = input.read(_byteBuffer)) > -1;)
            outputStream.write(_byteBuffer, 0, length);
        byte[] bodyBytes = outputStream.toByteArray();

        // get the rapid application
        Application rapidApplication = getApplications().get("rapid");

        // check we got one
        if (rapidApplication != null) {

            // get rapid security
            SecurityAdapter rapidSecurity = rapidApplication.getSecurityAdapter();

            // check we got some
            if (rapidSecurity != null) {

                // get user name
                String userName = rapidRequest.getUserName();
                if (userName == null)
                    userName = "";

                // check permission
                if (rapidSecurity.checkUserRole(rapidRequest, Rapid.DESIGN_ROLE)) {

                    Application application = rapidRequest.getApplication();

                    if (application != null) {

                        if ("savePage".equals(rapidRequest.getActionName())) {

                            String bodyString = new String(bodyBytes, "UTF-8");

                            getLogger().debug("Designer POST request : " + request.getQueryString() + " body : "
                                    + bodyString);

                            JSONObject jsonPage = new JSONObject(bodyString);

                            // instantiate a new blank page
                            Page newPage = new Page();

                            // set page properties
                            newPage.setId(jsonPage.optString("id"));
                            newPage.setName(jsonPage.optString("name"));
                            newPage.setTitle(jsonPage.optString("title"));
                            newPage.setFormPageType(jsonPage.optInt("formPageType"));
                            newPage.setLabel(jsonPage.optString("label"));
                            newPage.setDescription(jsonPage.optString("description"));
                            newPage.setSimple(jsonPage.optBoolean("simple"));

                            // look in the JSON for an event array
                            JSONArray jsonEvents = jsonPage.optJSONArray("events");
                            // add the events if we found one
                            if (jsonEvents != null)
                                newPage.setEvents(Control.getEvents(this, jsonEvents));

                            // look in the JSON for a styles array
                            JSONArray jsonStyles = jsonPage.optJSONArray("styles");
                            // if there were styles
                            if (jsonStyles != null)
                                newPage.setStyles(Control.getStyles(this, jsonStyles));

                            // if there are child controls from the page loop them and add to the pages control collection
                            JSONArray jsonControls = jsonPage.optJSONArray("childControls");
                            if (jsonControls != null) {
                                for (int i = 0; i < jsonControls.length(); i++) {
                                    // get the JSON control
                                    JSONObject jsonControl = jsonControls.getJSONObject(i);
                                    // call our function so it can go iterative
                                    newPage.addControl(createControl(jsonControl));
                                }
                            }

                            // if there are roles specified for this page
                            JSONArray jsonUserRoles = jsonPage.optJSONArray("roles");
                            if (jsonUserRoles != null) {
                                List<String> userRoles = new ArrayList<String>();
                                for (int i = 0; i < jsonUserRoles.length(); i++) {
                                    // get the JSON role
                                    String jsonUserRole = jsonUserRoles.getString(i);
                                    // add to collection
                                    userRoles.add(jsonUserRole);
                                }
                                // assign to page
                                newPage.setRoles(userRoles);
                            }

                            // look in the JSON for a sessionVariables array
                            JSONArray jsonSessionVariables = jsonPage.optJSONArray("sessionVariables");
                            // if we found one
                            if (jsonSessionVariables != null) {
                                List<String> sessionVariables = new ArrayList<String>();
                                for (int i = 0; i < jsonSessionVariables.length(); i++) {
                                    sessionVariables.add(jsonSessionVariables.getString(i));
                                }
                                newPage.setSessionVariables(sessionVariables);
                            }

                            // look in the JSON for a pageVisibilityRules array
                            JSONArray jsonVisibilityConditions = jsonPage.optJSONArray("visibilityConditions");
                            // if we found one
                            if (jsonVisibilityConditions != null) {
                                List<Condition> visibilityConditions = new ArrayList<Condition>();
                                for (int i = 0; i < jsonVisibilityConditions.length(); i++) {
                                    visibilityConditions
                                            .add(new Condition(jsonVisibilityConditions.getJSONObject(i)));
                                }
                                newPage.setVisibilityConditions(visibilityConditions);
                            }

                            // look in the JSON for a pageVisibilityRules array is an and or or (default to and)
                            String jsonConditionsType = jsonPage.optString("conditionsType", "and");
                            // set what we got
                            newPage.setConditionsType(jsonConditionsType);

                            // retrieve the html body
                            String htmlBody = jsonPage.optString("htmlBody");
                            // if we got one trim it and retain in page
                            if (htmlBody != null)
                                newPage.setHtmlBody(htmlBody.trim());

                            // look in the JSON for rolehtml
                            JSONArray jsonRolesHtml = jsonPage.optJSONArray("rolesHtml");
                            // if we found some
                            if (jsonRolesHtml != null) {
                                // instantiate the roles html collection
                                ArrayList<Page.RoleHtml> rolesHtml = new ArrayList<Page.RoleHtml>();
                                // loop the entries
                                for (int i = 0; i < jsonRolesHtml.length(); i++) {
                                    // get the entry
                                    JSONObject jsonRoleHtml = jsonRolesHtml.getJSONObject(i);
                                    // retain the html
                                    String html = jsonRoleHtml.optString("html");
                                    // trim it if there is one
                                    if (html != null)
                                        html = html.trim();
                                    // create an array to hold the roles
                                    ArrayList<String> roles = new ArrayList<String>();
                                    // get the roles
                                    JSONArray jsonRoles = jsonRoleHtml.optJSONArray("roles");
                                    // if we got some
                                    if (jsonRoles != null) {
                                        // loop them
                                        for (int j = 0; j < jsonRoles.length(); j++) {
                                            // get the role
                                            String role = jsonRoles.getString(j);
                                            // add it to the roles collections
                                            roles.add(role);
                                        }
                                    }
                                    // create and add a new roleHtml  object
                                    rolesHtml.add(new Page.RoleHtml(roles, html));
                                }
                                // add it to the page
                                newPage.setRolesHtml(rolesHtml);
                            }

                            // fetch a copy of the old page (if there is one)
                            Page oldPage = application.getPages().getPage(getServletContext(), newPage.getId());
                            // if the page's name changed we need to remove it
                            if (oldPage != null) {
                                if (!oldPage.getName().equals(newPage.getName())) {
                                    oldPage.delete(this, rapidRequest, application);
                                }
                            }

                            // save the new page to file
                            newPage.save(this, rapidRequest, application, true);

                            // get any pages collection (we're only sent it if it's been changed)
                            JSONArray jsonPages = jsonPage.optJSONArray("pages");
                            // if we got some
                            if (jsonPages != null) {
                                // make a new map for the page orders
                                Map<String, Integer> pageOrders = new HashMap<String, Integer>();
                                // loop the page orders
                                for (int i = 0; i < jsonPages.length(); i++) {
                                    // add the order to the map
                                    pageOrders.put(jsonPages.getJSONObject(i).getString("id"), i);
                                }
                                // replace the application pageOrders map
                                application.setPageOrders(pageOrders);
                                // save the application and the new orders
                                application.save(this, rapidRequest, true);
                            }
                            boolean jsonPageOrderReset = jsonPage.optBoolean("pageOrderReset");
                            if (jsonPageOrderReset) {
                                // empty the application pageOrders map so everything goes alphabetical
                                application.setPageOrders(null);
                            }

                            // send a positive message
                            output = "{\"message\":\"Saved!\"}";

                            // set the response type to json
                            response.setContentType("application/json");

                        } else if ("testSQL".equals(rapidRequest.getActionName())) {

                            // turn the body bytes into a string
                            String bodyString = new String(bodyBytes, "UTF-8");

                            JSONObject jsonQuery = new JSONObject(bodyString);

                            JSONArray jsonInputs = jsonQuery.optJSONArray("inputs");

                            JSONArray jsonOutputs = jsonQuery.optJSONArray("outputs");

                            Parameters parameters = new Parameters();

                            if (jsonInputs != null) {

                                for (int i = 0; i < jsonInputs.length(); i++)
                                    parameters.addNull();

                            }

                            DatabaseConnection databaseConnection = application.getDatabaseConnections()
                                    .get(jsonQuery.optInt("databaseConnectionIndex", 0));

                            ConnectionAdapter ca = databaseConnection.getConnectionAdapter(getServletContext(),
                                    application);

                            DataFactory df = new DataFactory(ca);

                            int outputs = 0;

                            if (jsonOutputs != null)
                                outputs = jsonOutputs.length();

                            String sql = jsonQuery.getString("SQL");
                            // some jdbc drivers need the line breaks removing before they'll work properly - here's looking at you MS SQL Server!
                            sql = sql.replace("\n", " ");

                            if (outputs == 0) {

                                df.getPreparedStatement(rapidRequest, sql, parameters);

                            } else {

                                ResultSet rs = df.getPreparedResultSet(rapidRequest, sql, parameters);

                                ResultSetMetaData rsmd = rs.getMetaData();

                                int cols = rsmd.getColumnCount();

                                if (outputs > cols)
                                    throw new Exception(outputs + " outputs, but only " + cols + " column"
                                            + (cols > 1 ? "s" : "") + " selected");

                                for (int i = 0; i < outputs; i++) {

                                    JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                                    String field = jsonOutput.optString("field", "");

                                    if (!"".equals(field)) {

                                        field = field.toLowerCase();

                                        boolean gotOutput = false;

                                        for (int j = 0; j < cols; j++) {

                                            String sqlField = rsmd.getColumnLabel(j + 1).toLowerCase();

                                            if (field.equals(sqlField)) {
                                                gotOutput = true;
                                                break;
                                            }

                                        }

                                        if (!gotOutput) {
                                            rs.close();
                                            df.close();
                                            throw new Exception("Field \"" + field + "\" from output " + (i + 1)
                                                    + " is not present in selected columns");
                                        }

                                    }

                                }

                                // close the recordset
                                rs.close();
                                // close the data factory
                                df.close();

                            }

                            // send a positive message
                            output = "{\"message\":\"OK\"}";

                            // set the response type to json
                            response.setContentType("application/json");

                        } else if ("uploadImage".equals(rapidRequest.getActionName())
                                || "import".equals(rapidRequest.getActionName())) {

                            // get the content type from the request
                            String contentType = request.getContentType();
                            // get the position of the boundary from the content type
                            int boundaryPosition = contentType.indexOf("boundary=");
                            // derive the start of the meaning data by finding the boundary
                            String boundary = contentType.substring(boundaryPosition + 10);
                            // this is the double line break after which the data occurs
                            byte[] pattern = { 0x0D, 0x0A, 0x0D, 0x0A };
                            // find the position of the double line break
                            int dataPosition = Bytes.findPattern(bodyBytes, pattern);
                            // the body header is everything up to the data
                            String header = new String(bodyBytes, 0, dataPosition, "UTF-8");
                            // find the position of the filename in the data header
                            int filenamePosition = header.indexOf("filename=\"");
                            // extract the file name
                            String filename = header.substring(filenamePosition + 10,
                                    header.indexOf("\"", filenamePosition + 10));
                            // find the position of the file type in the data header
                            int fileTypePosition = header.toLowerCase().indexOf("type:");
                            // extract the file type
                            String fileType = header.substring(fileTypePosition + 6);

                            if ("uploadImage".equals(rapidRequest.getActionName())) {

                                // check the file type
                                if (!fileType.equals("image/jpeg") && !fileType.equals("image/gif")
                                        && !fileType.equals("image/png"))
                                    throw new Exception("Unsupported file type");

                                // get the web folder from the application
                                String path = rapidRequest.getApplication().getWebFolder(getServletContext());
                                // create a file output stream to save the data to
                                FileOutputStream fos = new FileOutputStream(path + "/" + filename);
                                // write the file data to the stream
                                fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length
                                        - dataPosition - pattern.length - boundary.length() - 9);
                                // close the stream
                                fos.close();

                                // log the file creation
                                getLogger().debug("Saved image file " + path + filename);

                                // create the response with the file name and upload type
                                output = "{\"file\":\"" + filename + "\",\"type\":\""
                                        + rapidRequest.getActionName() + "\"}";

                            } else if ("import".equals(rapidRequest.getActionName())) {

                                // check the file type
                                if (!"application/x-zip-compressed".equals(fileType)
                                        && !"application/zip".equals(fileType))
                                    throw new Exception("Unsupported file type");

                                // get the name
                                String appName = request.getParameter("name");

                                // check we were given one
                                if (appName == null)
                                    throw new Exception("Name must be provided");

                                // get the version
                                String appVersion = request.getParameter("version");

                                // check we were given one
                                if (appVersion == null)
                                    throw new Exception("Version must be provided");

                                // make the id from the safe and lower case name
                                String appId = Files.safeName(appName).toLowerCase();

                                // make the version from the safe and lower case name
                                appVersion = Files.safeName(appVersion);

                                // get application destination folder
                                File appFolderDest = new File(
                                        Application.getConfigFolder(getServletContext(), appId, appVersion));
                                // get web contents destination folder
                                File webFolderDest = new File(
                                        Application.getWebFolder(getServletContext(), appId, appVersion));

                                // look for an existing application of this name and version
                                Application existingApplication = getApplications().get(appId, appVersion);
                                // if we have an existing application 
                                if (existingApplication != null) {
                                    // back it up first
                                    existingApplication.backup(this, rapidRequest, false);
                                }

                                // get a file for the temp directory
                                File tempDir = new File(getServletContext().getRealPath("/WEB-INF/temp"));
                                // create it if not there
                                if (!tempDir.exists())
                                    tempDir.mkdir();

                                // the path we're saving to is the temp folder
                                String path = getServletContext()
                                        .getRealPath("/WEB-INF/temp/" + appId + ".zip");
                                // create a file output stream to save the data to
                                FileOutputStream fos = new FileOutputStream(path);
                                // write the file data to the stream
                                fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length
                                        - dataPosition - pattern.length - boundary.length() - 9);
                                // close the stream
                                fos.close();

                                // log the file creation
                                getLogger().debug("Saved import file " + path);

                                // get a file object for the zip file
                                File zipFile = new File(path);
                                // load it into a zip file object
                                ZipFile zip = new ZipFile(zipFile);
                                // unzip the file
                                zip.unZip();
                                // delete the zip file
                                zipFile.delete();

                                // unzip folder (for deletion)
                                File unZipFolder = new File(
                                        getServletContext().getRealPath("/WEB-INF/temp/" + appId));
                                // get application folders
                                File appFolderSource = new File(
                                        getServletContext().getRealPath("/WEB-INF/temp/" + appId + "/WEB-INF"));
                                // get web content folders
                                File webFolderSource = new File(getServletContext()
                                        .getRealPath("/WEB-INF/temp/" + appId + "/WebContent"));

                                // check we have the right source folders
                                if (webFolderSource.exists() && appFolderSource.exists()) {

                                    // get application.xml file
                                    File appFileSource = new File(appFolderSource + "/application.xml");

                                    if (appFileSource.exists()) {

                                        // delete the appFolder if it exists
                                        if (appFolderDest.exists())
                                            Files.deleteRecurring(appFolderDest);
                                        // delete the webFolder if it exists
                                        if (webFolderDest.exists())
                                            Files.deleteRecurring(webFolderDest);

                                        // copy application content
                                        Files.copyFolder(appFolderSource, appFolderDest);

                                        // copy web content
                                        Files.copyFolder(webFolderSource, webFolderDest);

                                        try {

                                            // load the new application (but don't initialise, nor load pages)
                                            Application appNew = Application.load(getServletContext(),
                                                    new File(appFolderDest + "/application.xml"), false);

                                            // update application name
                                            appNew.setName(appName);

                                            // get the old id
                                            String appOldId = appNew.getId();

                                            // make the new id
                                            appId = Files.safeName(appName).toLowerCase();

                                            // update the id
                                            appNew.setId(appId);

                                            // get the old version
                                            String appOldVersion = appNew.getVersion();

                                            // make the new version
                                            appVersion = Files.safeName(appVersion);

                                            // update the version
                                            appNew.setVersion(appVersion);

                                            // update the created date
                                            appNew.setCreatedDate(new Date());

                                            // set the status to In development
                                            appNew.setStatus(Application.STATUS_DEVELOPMENT);

                                            // a map of actions that might be removed from any of the pages
                                            Map<String, Integer> removedActions = new HashMap<String, Integer>();

                                            // look for page files
                                            File pagesFolder = new File(
                                                    appFolderDest.getAbsolutePath() + "/pages");
                                            // if the folder is there
                                            if (pagesFolder.exists()) {

                                                // create a filter for finding .page.xml files
                                                FilenameFilter xmlFilenameFilter = new FilenameFilter() {
                                                    public boolean accept(File dir, String name) {
                                                        return name.toLowerCase().endsWith(".page.xml");
                                                    }
                                                };

                                                // loop the .page.xml files 
                                                for (File pageFile : pagesFolder.listFiles(xmlFilenameFilter)) {

                                                    BufferedReader reader = new BufferedReader(
                                                            new InputStreamReader(new FileInputStream(pageFile),
                                                                    "UTF-8"));
                                                    String line = null;
                                                    StringBuilder stringBuilder = new StringBuilder();

                                                    while ((line = reader.readLine()) != null) {
                                                        stringBuilder.append(line);
                                                        stringBuilder.append("\n");
                                                    }
                                                    reader.close();

                                                    // retrieve the xml into a string
                                                    String fileString = stringBuilder.toString();

                                                    // prepare a new file string which will update into
                                                    String newFileString = null;

                                                    // if the old app did not have a version (for backwards compatibility)
                                                    if (appOldVersion == null) {

                                                        // replace all properties that appear to have a url, and all created links - note the fix for cleaning up the double encoding
                                                        newFileString = fileString
                                                                .replace("applications/" + appOldId + "/",
                                                                        "applications/" + appId + "/"
                                                                                + appVersion + "/")
                                                                .replace("~?a=" + appOldId + "&amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;")
                                                                .replace("~?a=" + appOldId + "&amp;amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;");

                                                    } else {

                                                        // replace all properties that appear to have a url, and all created links - note the fix for double encoding 
                                                        newFileString = fileString
                                                                .replace(
                                                                        "applications/" + appOldId + "/"
                                                                                + appOldVersion + "/",
                                                                        "applications/" + appId + "/"
                                                                                + appVersion + "/")
                                                                .replace(
                                                                        "~?a=" + appOldId + "&amp;v="
                                                                                + appOldVersion + "&amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;")
                                                                .replace(
                                                                        "~?a=" + appOldId + "&amp;amp;v="
                                                                                + appOldVersion + "&amp;amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;");
                                                    }

                                                    // now open the string into a document
                                                    Document pageDocument = XML.openDocument(newFileString);
                                                    // get an xpath factory
                                                    XPathFactory xPathfactory = XPathFactory.newInstance();
                                                    XPath xpath = xPathfactory.newXPath();
                                                    // an expression for any attributes with a local name of "type"
                                                    XPathExpression expr = xpath
                                                            .compile("//@*[local-name()='type']");
                                                    // get them
                                                    NodeList nl = (NodeList) expr.evaluate(pageDocument,
                                                            XPathConstants.NODESET);
                                                    // get out system actions
                                                    JSONArray jsonActions = getJsonActions();
                                                    // if we found any elements with a type attribute and we have system actions
                                                    if (nl.getLength() > 0 && jsonActions.length() > 0) {
                                                        // a list of action types
                                                        List<String> types = new ArrayList<String>();
                                                        // loop the json actions
                                                        for (int i = 0; i < jsonActions.length(); i++)
                                                            types.add(jsonActions.getJSONObject(i)
                                                                    .optString("type").toLowerCase());
                                                        // loop the action attributes we found
                                                        for (int i = 0; i < nl.getLength(); i++) {
                                                            // get this attribute
                                                            Attr a = (Attr) nl.item(i);
                                                            // get the value of the type 
                                                            String type = a.getTextContent().toLowerCase();
                                                            // get the element the attribute is in
                                                            Node n = a.getOwnerElement();
                                                            // if we don't know about this action type
                                                            if (!types.contains(type)) {
                                                                // get the parent node
                                                                Node p = n.getParentNode();
                                                                // remove this node
                                                                p.removeChild(n);
                                                                // if we have removed this type already
                                                                if (removedActions.containsKey(type)) {
                                                                    // increment the entry for this type
                                                                    removedActions.put(type,
                                                                            removedActions.get(type) + 1);
                                                                } else {
                                                                    // add an entry for this type
                                                                    removedActions.put(type, 1);
                                                                }
                                                            } // got type check                                                                                                                                             
                                                        } // attribute loop

                                                    } // attribute and system action check

                                                    // use the transformer to write to disk
                                                    TransformerFactory transformerFactory = TransformerFactory
                                                            .newInstance();
                                                    Transformer transformer = transformerFactory
                                                            .newTransformer();
                                                    DOMSource source = new DOMSource(pageDocument);
                                                    StreamResult result = new StreamResult(pageFile);
                                                    transformer.transform(source, result);

                                                } // page xml file loop

                                            } // pages folder check

                                            // now initialise with the new id but don't make the resource files (this reloads the pages and sets up the security adapter)
                                            appNew.initialise(getServletContext(), false);

                                            // get the security for this application
                                            SecurityAdapter security = appNew.getSecurityAdapter();

                                            // if we have one
                                            if (security != null) {

                                                // assume we don't have the user
                                                boolean gotUser = false;
                                                // get the current users record from the adapter
                                                User user = security.getUser(rapidRequest);
                                                // check the current user is present in the app's security adapter
                                                if (user != null) {
                                                    // now check the current user password is correct too
                                                    if (security.checkUserPassword(rapidRequest, userName,
                                                            rapidRequest.getUserPassword())) {
                                                        // we have the right user with the right password
                                                        gotUser = true;
                                                    } else {
                                                        // remove this user as the password does not match
                                                        security.deleteUser(rapidRequest);
                                                    }
                                                }

                                                // if we don't have the user
                                                if (!gotUser) {
                                                    // get the current user from the Rapid application
                                                    User rapidUser = rapidSecurity.getUser(rapidRequest);
                                                    // create a new user based on the Rapid user
                                                    user = new User(userName, rapidUser.getDescription(),
                                                            rapidUser.getPassword());
                                                    // add the new user 
                                                    security.addUser(rapidRequest, user);
                                                }

                                                // add Admin and Design roles for the new user if required
                                                if (!security.checkUserRole(rapidRequest,
                                                        com.rapid.server.Rapid.ADMIN_ROLE))
                                                    security.addUserRole(rapidRequest,
                                                            com.rapid.server.Rapid.ADMIN_ROLE);

                                                if (!security.checkUserRole(rapidRequest,
                                                        com.rapid.server.Rapid.DESIGN_ROLE))
                                                    security.addUserRole(rapidRequest,
                                                            com.rapid.server.Rapid.DESIGN_ROLE);
                                            }

                                            // if any items were removed
                                            if (removedActions.keySet().size() > 0) {
                                                // a description of what was removed
                                                String removed = "";
                                                // loop the entries
                                                for (String type : removedActions.keySet()) {
                                                    int count = removedActions.get(type);
                                                    removed += "removed " + count + " " + type + " action"
                                                            + (count == 1 ? "" : "s") + " on import\n";
                                                }
                                                // get the current description
                                                String description = appNew.getDescription();
                                                // if null set to empty string
                                                if (description == null)
                                                    description = "";
                                                // add a line break if need be
                                                if (description.length() > 0)
                                                    description += "\n";
                                                // add the removed
                                                description += removed;
                                                // set it back
                                                appNew.setDescription(description);
                                            }

                                            // reload the pages (actually clears down the pages collection and reloads the headers)
                                            appNew.getPages().loadpages(getServletContext());

                                            // save application (this will also initialise and rebuild the resources)
                                            appNew.save(this, rapidRequest, false);

                                            // add application to the collection
                                            getApplications().put(appNew);

                                            // delete unzip folder
                                            Files.deleteRecurring(unZipFolder);

                                            // send a positive message
                                            output = "{\"id\":\"" + appNew.getId() + "\",\"version\":\""
                                                    + appNew.getVersion() + "\"}";

                                        } catch (Exception ex) {

                                            // delete the appFolder if it exists
                                            if (appFolderDest.exists())
                                                Files.deleteRecurring(appFolderDest);
                                            // if the parent is empty delete it too
                                            if (appFolderDest.getParentFile().list().length <= 1)
                                                Files.deleteRecurring(appFolderDest.getParentFile());

                                            // delete the webFolder if it exists
                                            if (webFolderDest.exists())
                                                Files.deleteRecurring(webFolderDest);
                                            // if the parent is empty delete it too
                                            if (webFolderDest.getParentFile().list().length <= 1)
                                                Files.deleteRecurring(webFolderDest.getParentFile());

                                            // rethrow exception
                                            throw ex;

                                        }

                                    } else {

                                        // delete unzip folder
                                        Files.deleteRecurring(unZipFolder);

                                        // throw excpetion
                                        throw new Exception("Must be a valid Rapid " + Rapid.VERSION + " file");

                                    }

                                } else {

                                    // delete unzip folder
                                    Files.deleteRecurring(unZipFolder);

                                    // throw excpetion
                                    throw new Exception("Must be a valid Rapid file");

                                }

                            }

                        }

                        getLogger().debug("Designer POST response : " + output);

                        PrintWriter out = response.getWriter();
                        out.print(output);
                        out.close();

                    } // got an application

                } // got rapid design role

            } // got rapid security

        } // got rapid application

    } catch (Exception ex) {

        getLogger().error("Designer POST error : ", ex);

        sendException(rapidRequest, response, ex);

    }

}

From source file:com.ext.portlet.epsos.EpsosHelperService.java

public static void changeNode(Document dom, XPath xpath, String path, String nodeName, String value) {
    try {//from   w  w  w . j a va 2  s . c  o m
        XPathExpression salRO = xpath.compile(path + "/" + nodeName);
        NodeList salRONodes = (NodeList) salRO.evaluate(dom, XPathConstants.NODESET);
        if (salRONodes.getLength() > 0) {
            for (int t = 0; t < salRONodes.getLength(); t++) {
                Node AddrNode = salRONodes.item(t);
                if (AddrNode.getNodeName().equals("name")) {
                    AddrNode.setTextContent(value);
                }
            }
        }
    } catch (Exception e) {
        _log.error("Error fixing node ...");
    }
}

From source file:com.ext.portlet.epsos.EpsosHelperService.java

public static void fixNode(Document dom, XPath xpath, String path, String nodeName, String value) {
    try {//from  w  w  w  . j a va2 s  .com
        XPathExpression salRO = xpath.compile(path + "/" + nodeName);
        NodeList salRONodes = (NodeList) salRO.evaluate(dom, XPathConstants.NODESET);
        if (salRONodes.getLength() == 0) {
            XPathExpression salAddr = xpath.compile(path);
            NodeList salAddrNodes = (NodeList) salAddr.evaluate(dom, XPathConstants.NODESET);
            if (salAddrNodes.getLength() > 0) {
                for (int t = 0; t < salAddrNodes.getLength(); t++) {
                    Node AddrNode = salAddrNodes.item(t);
                    Node city = dom.createElement(nodeName);
                    Text cityValue = dom.createTextNode(value);
                    city.appendChild(cityValue);
                    AddrNode.appendChild(city);
                }
            }
        }
    } catch (Exception e) {
        _log.error("Error fixing node ...");
    }
}

From source file:com.photon.phresco.framework.rest.api.QualityService.java

/**
 * Evaluate test suite.//from   w w w  .  ja v  a 2  s.co  m
 *
 * @param doc the doc
 * @param testSuitePath the test suite path
 * @return the node list
 * @throws PhrescoException the phresco exception
 */
private NodeList evaluateTestSuite(Document doc, String testSuitePath) throws PhrescoException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression xPathExpression;
    NodeList testSuiteNode = null;
    try {
        if (StringUtils.isNotEmpty(testSuitePath)) {
            xPathExpression = xpath.compile(testSuitePath);
            testSuiteNode = (NodeList) xPathExpression.evaluate(doc, XPathConstants.NODESET);
        }
    } catch (XPathExpressionException e) {
        throw new PhrescoException(e);
    }
    return testSuiteNode;
}