Example usage for javax.xml.xpath XPath evaluate

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:lcmc.data.VMSXML.java

/** Modify xml of some device element. */
private void modifyXML(final Node domainNode, final String domainName, final Map<String, String> tagMap,
        final Map<String, String> attributeMap, final Map<String, String> parametersMap, final String path,
        final String elementName, final VirtualHardwareComparator vhc) {
    final String configName = namesConfigsMap.get(domainName);
    if (configName == null) {
        return;/*from  ww w.  j av  a 2s.c  o  m*/
    }
    //final Node domainNode = getDomainNode(domainName);
    if (domainNode == null) {
        return;
    }
    final XPath xpath = XPathFactory.newInstance().newXPath();
    final Node devicesNode = getDevicesNode(xpath, domainNode);
    if (devicesNode == null) {
        return;
    }
    try {
        final NodeList nodes = (NodeList) xpath.evaluate(path, domainNode, XPathConstants.NODESET);
        Element hwNode = vhc.getElement(nodes, parametersMap);
        if (hwNode == null) {
            hwNode = (Element) devicesNode
                    .appendChild(domainNode.getOwnerDocument().createElement(elementName));
        }
        for (final String param : parametersMap.keySet()) {
            final String value = parametersMap.get(param);
            if (!tagMap.containsKey(param) && attributeMap.containsKey(param)) {
                /* attribute */
                final Node attributeNode = hwNode.getAttributes().getNamedItem(attributeMap.get(param));
                if (attributeNode == null) {
                    if (value != null && !"".equals(value)) {
                        hwNode.setAttribute(attributeMap.get(param), value);
                    }
                } else if (value == null || "".equals(value)) {
                    hwNode.removeAttribute(attributeMap.get(param));
                } else {
                    attributeNode.setNodeValue(value);
                }
                continue;
            }
            Element node = (Element) getChildNode(hwNode, tagMap.get(param));
            if ((attributeMap.containsKey(param) || "True".equals(value)) && node == null) {
                node = (Element) hwNode
                        .appendChild(domainNode.getOwnerDocument().createElement(tagMap.get(param)));
            } else if (node != null && !attributeMap.containsKey(param)
                    && (value == null || "".equals(value))) {
                hwNode.removeChild(node);
            }
            if (attributeMap.containsKey(param)) {
                final Node attributeNode = node.getAttributes().getNamedItem(attributeMap.get(param));
                if (attributeNode == null) {
                    if (value != null && !"".equals(value)) {
                        node.setAttribute(attributeMap.get(param), value);
                    }
                } else {
                    if (value == null || "".equals(value)) {
                        node.removeAttribute(attributeMap.get(param));
                    } else {
                        attributeNode.setNodeValue(value);
                    }
                }
            }
        }
        final Element hwAddressNode = (Element) getChildNode(hwNode, HW_ADDRESS);
        if (hwAddressNode != null) {
            hwNode.removeChild(hwAddressNode);
        }
    } catch (final javax.xml.xpath.XPathExpressionException e) {
        Tools.appError("could not evaluate: ", e);
        return;
    }
}

From source file:com.ephesoft.gxt.systemconfig.server.SystemConfigServiceImpl.java

@Override
public Boolean addNewPlugin(String newPluginName, String xmlSourcePath, String jarSourcePath)
        throws UIException {

    LOGGER.info("Saving the new plugin with following details:\n Plugin Name:\t" + newPluginName
            + "\n Plugin Xml Path:\t" + xmlSourcePath + "\n Plugin Jar path:\t" + jarSourcePath);
    PluginXmlDTO pluginXmlDTO = null;//  ww  w. ja  v  a2s  .c o m
    boolean pluginAdded = false;
    // Parse the data from xmlSourcePath file
    XPathFactory xFactory = new org.apache.xpath.jaxp.XPathFactoryImpl();
    XPath xpath = xFactory.newXPath();
    org.w3c.dom.Document pluginXmlDoc = null;

    try {
        pluginXmlDoc = XMLUtil
                .createDocumentFrom(FileUtils.getInputStreamFromZip(newPluginName, xmlSourcePath));
    } catch (Exception e) {
        String errorMsg = "Invalid xml content. Please try again.";
        LOGGER.error(errorMsg + e.getMessage(), e);
        throw new UIException(errorMsg);
    }

    if (pluginXmlDoc != null) {

        // correct syntax
        NodeList pluginNodeList = null;
        try {
            pluginNodeList = (NodeList) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_EXPR, pluginXmlDoc,
                    XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            String errorMsg = SystemConfigSharedConstants.INVALID_XML_CONTENT_MESSAGE;
            LOGGER.error(errorMsg + e.getMessage(), e);
            throw new UIException(errorMsg);
        }
        if (pluginNodeList != null && pluginNodeList.getLength() == 1) {
            LOGGER.info("Reading the Xml contents");
            String backUpFileName = SystemConfigSharedConstants.EMPTY_STRING;
            String jarName = SystemConfigSharedConstants.EMPTY_STRING;
            String methodName = SystemConfigSharedConstants.EMPTY_STRING;
            String description = SystemConfigSharedConstants.EMPTY_STRING;
            String pluginName = SystemConfigSharedConstants.EMPTY_STRING;
            String workflowName = SystemConfigSharedConstants.EMPTY_STRING;
            String scriptFileName = SystemConfigSharedConstants.EMPTY_STRING;
            String serviceName = SystemConfigSharedConstants.EMPTY_STRING;
            String pluginApplicationContextPath = SystemConfigSharedConstants.EMPTY_STRING;
            boolean isScriptingPlugin = false;
            boolean overrideExisting = false;
            try {
                backUpFileName = (String) xpath.evaluate(SystemConfigSharedConstants.BACK_UP_FILE_NAME_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                jarName = (String) xpath.evaluate(SystemConfigSharedConstants.JAR_NAME_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                methodName = (String) xpath.evaluate(SystemConfigSharedConstants.METHOD_NAME_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                description = (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_DESC_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                pluginName = (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_NAME_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                workflowName = (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_WORKFLOW_NAME_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                scriptFileName = (String) xpath.evaluate(SystemConfigSharedConstants.SCRIPT_FILE_NAME_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                serviceName = (String) xpath.evaluate(SystemConfigSharedConstants.SERVICE_NAME_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                isScriptingPlugin = Boolean
                        .parseBoolean((String) xpath.evaluate(SystemConfigSharedConstants.IS_SCRIPT_PLUGIN_EXPR,
                                pluginNodeList.item(0), XPathConstants.STRING));
                pluginApplicationContextPath = (String) xpath.evaluate(
                        SystemConfigSharedConstants.APPLICATION_CONTEXT_PATH, pluginNodeList.item(0),
                        XPathConstants.STRING);
                overrideExisting = Boolean
                        .parseBoolean((String) xpath.evaluate(SystemConfigSharedConstants.OVERRIDE_EXISTING,
                                pluginNodeList.item(0), XPathConstants.STRING));
            } catch (Exception e) {
                String errorMsg = "Error in xml content. A mandatory tag is missing or invalid.";
                LOGGER.error(errorMsg + e.getMessage(), e);
                throw new UIException(errorMsg);
            }

            LOGGER.info("Back Up File Name: " + backUpFileName);
            LOGGER.info("Jar Name" + jarName);
            LOGGER.info("Method Name" + methodName);
            LOGGER.info("Description: " + description);
            LOGGER.info("Name: " + pluginName);
            LOGGER.info("Workflow Name" + workflowName);
            LOGGER.info("Script file Name" + scriptFileName);
            LOGGER.info("Service Name" + serviceName);
            LOGGER.info("Is scripting Plugin:" + isScriptingPlugin);
            LOGGER.info("Plugin application context path: " + pluginApplicationContextPath);
            if (!backUpFileName.isEmpty() && !jarName.isEmpty() && !methodName.isEmpty()
                    && !description.isEmpty() && !pluginName.isEmpty() && !workflowName.isEmpty()
                    && !serviceName.isEmpty() && !pluginApplicationContextPath.isEmpty()) {

                if (isScriptingPlugin && scriptFileName.isEmpty()) {
                    String errorMsg = "Error in xml content. A mandatory field is missing.";
                    LOGGER.error(errorMsg);
                    throw new UIException(errorMsg);
                }
                pluginXmlDTO = setPluginInfo(backUpFileName, jarName, methodName, description, pluginName,
                        workflowName, scriptFileName, serviceName, pluginApplicationContextPath,
                        isScriptingPlugin, overrideExisting);

                extractPluginConfigs(pluginXmlDTO, xpath, pluginNodeList);

                extractPluginDependenciesFromXml(pluginXmlDTO, xpath, pluginNodeList);

                boolean pluginAlreadyExists = !checkIfPluginExists(pluginName);

                saveOrUpdatePluginToDB(pluginXmlDTO);
                createAndDeployPluginProcessDefinition(pluginXmlDTO);
                copyJarToLib(newPluginName, jarSourcePath);

                if (pluginAlreadyExists) {
                    addPathToApplicationContext(pluginXmlDTO.getApplicationContextPath());
                }
                pluginAdded = true;
                LOGGER.info("Plugin added successfully.");
            } else {
                String errorMsg = SystemConfigSharedConstants.INVALID_XML_CONTENT_MESSAGE;
                LOGGER.error(errorMsg);
                throw new UIException(errorMsg);
            }
        } else {
            String errorMsg = "Invalid xml content. Number of plugins expected is one.";
            LOGGER.error(errorMsg);
            throw new UIException(errorMsg);
        }
    }

    return pluginAdded;
}

From source file:it.imtech.metadata.MetaUtility.java

private void create_uwmetadata_recursive(Document w, Element e, Map<Object, Metadata> submetadatas,
        HashMap<String, String> defValues, int pagenum, String collTitle, String panelname) throws Exception {
    try {/* w  w  w  .  j a v a 2s .  c  om*/
        ResourceBundle bundle = ResourceBundle.getBundle(Globals.RESOURCES, Globals.CURRENT_LOCALE,
                Globals.loader);
        boolean classificationtag = false;
        String expression = "//*[local-name()='classification']";
        XPath xpath = XPathFactory.newInstance().newXPath();

        for (Map.Entry<Object, Metadata> field : submetadatas.entrySet()) {
            String oefospath = panelname + "----" + field.getValue().sequence;
            if (field.getValue().MID == 2) {
                this.objectTitle = field.getValue().value;
            }
            if (field.getValue().datatype.equals("Node")) {
                if (field.getValue().MID == 45 && this.oefos_path.get(oefospath) == null) {
                    continue;
                } else if (field.getValue().MID == 45 && this.oefos_path.get(oefospath).size() < 1) {
                    continue;
                } else {
                    //Set classification tag
                    NodeList nodeList = (NodeList) xpath.evaluate(expression, w, XPathConstants.NODESET);

                    String book = Utility.getValueFromKey(metadata_namespaces, field.getValue().foxmlnamespace);
                    Element link = w.createElement(book + ":" + field.getValue().foxmlname);
                    if (!field.getValue().sequence.equals("") && field.getValue().MID != 45)
                        e.setAttribute("seq", field.getValue().sequence);

                    if ((field.getValue().MID != 22 && field.getValue().MID != 45) || nodeList.getLength() <= 0)
                        e.appendChild(link);
                    else {
                        if (field.getValue().MID == 45) {
                            nodeList.item(0).appendChild(link);
                        }
                    }
                    create_uwmetadata_recursive(w, link, field.getValue().submetadatas, defValues, pagenum,
                            collTitle, panelname);
                }
            } else if (field.getValue().MID == 46) {
                //Set source tag
                if (this.oefos_path.get(oefospath).size() > 0) {
                    String book = Utility.getValueFromKey(metadata_namespaces, field.getValue().foxmlnamespace);
                    Element link = w.createElement(book + ":" + field.getValue().foxmlname);

                    String classiflink = this.selectedClassificationList
                            .get(panelname + "---" + field.getValue().sequence);
                    String CID = this.classificationIDS.get(classiflink);

                    link.setTextContent(CID);

                    e.appendChild(link);
                }
            } else if (field.getValue().MID == 47 && this.oefos_path.get(oefospath).size() > 0) {
                //Set taxonpaths tags
                for (Map.Entry<Integer, Integer> iField : this.oefos_path.get(oefospath).entrySet()) {
                    String book = Utility.getValueFromKey(metadata_namespaces, field.getValue().foxmlnamespace);
                    Element link = w.createElement(book + ":" + field.getValue().foxmlname);

                    link.setTextContent(Integer.toString(iField.getValue()));
                    link.setAttribute("seq", Integer.toString(iField.getKey() - 1));
                    e.setAttribute("seq", field.getValue().sequence);
                    e.appendChild(link);
                }
            } else if (field.getValue().editable.equals("Y")) {
                String value = "";

                if (field.getValue().value != null) {

                    if (field.getValue().MID == 2 && !collTitle.equals(""))
                        value = collTitle;
                    else {
                        if (field.getValue().MID == 2 && pagenum > 0) {
                            value = field.getValue().value + " - " + Utility.getBundleString("seite", bundle)
                                    + " " + Integer.toString(pagenum);
                        } else {
                            value = field.getValue().value;
                        }
                    }
                } else if (defValues != null) {
                    if (defValues.containsKey(field.getValue().foxmlname)) {
                        value = defValues.get(field.getValue().foxmlname);
                    } else {
                        value = "en";
                    }
                }

                if (value.length() > 0) {
                    String book = Utility.getValueFromKey(metadata_namespaces, field.getValue().foxmlnamespace);
                    Element link = w.createElement(book + ":" + field.getValue().foxmlname);

                    if (field.getValue().datatype.equals("LangString")) {
                        link.setAttribute("language", field.getValue().language);
                    }

                    link.setTextContent(value);
                    if (!field.getValue().sequence.equals(""))
                        e.setAttribute("seq", field.getValue().sequence);

                    e.appendChild(link);

                    if (field.getValue().datatype.equals("CharacterString") && field.getValue().MID == 63) {
                        bundle = ResourceBundle.getBundle(Globals.RESOURCES, Globals.CURRENT_LOCALE,
                                Globals.loader);
                        //String text = ;
                        //String title= ;
                        ConfirmDialog confirm = new ConfirmDialog(BookImporter.getInstance(), true,
                                Utility.getBundleString("singlemetadata1title", bundle),
                                Utility.getBundleString("singlemetadata1", bundle),
                                Utility.getBundleString("confirm", bundle),
                                Utility.getBundleString("annulla", bundle));

                        Element type = w.createElement(book + ":type");
                        type.setTextContent("institution");
                        e.appendChild(type);
                    }
                }
            } else if (field.getValue().editable.equals("N") && defValues != null) {
                String value = null;
                if (field.getValue().foxmlname.equals("location")) {
                    value = SelectedServer.getInstance(null).getPhaidraURL() + "/"
                            + defValues.get("identifier");
                    value = defValues.get("identifier");
                } else {
                    value = defValues.get(field.getValue().foxmlname);
                }

                String book = Utility.getValueFromKey(metadata_namespaces, field.getValue().foxmlnamespace);
                Element link = w.createElement(book + ":" + field.getValue().foxmlname);
                link.setTextContent(value);
                e.appendChild(link);
            }
        }
    } catch (Exception ex) {
        ResourceBundle bundle = ResourceBundle.getBundle(Globals.RESOURCES, Globals.CURRENT_LOCALE,
                Globals.loader);
        throw new Exception(Utility.getBundleString("error7", bundle) + ": " + ex.getMessage());
    }
}

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

public static String getConsentText(String language) {
    String translation = "";
    language = language.replaceAll("_", "-");
    try {//from   w w  w  . j  ava2  s  . c  o m
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        URL url = cl.getResource("content/language/consent/Consent_LegalText_" + language + ".xml");

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(url.getFile());
        doc.getDocumentElement().normalize();
        XPath xpath = XPathFactory.newInstance().newXPath();

        String xpathExpression = "/Consent/LegalText";
        NodeList nodes = (NodeList) xpath.evaluate(xpathExpression, doc, XPathConstants.NODESET);
        translation = nodes.item(0).getTextContent();
    } catch (Exception e) {
        Log.error("Error getting consent text for country " + language);
    }
    return translation;
}

From source file:net.cbtltd.rest.nextpax.A_Handler.java

private void createBooking(String rq, Reservation reservation, long timestamp, Map<String, String> result)
        throws Throwable {
    String rs = getConnection(rq);
    LOG.debug("\nBookResponse rs: \n" + rs + "\n");
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    InputSource inputSource = new InputSource(new StringReader(rs.toString()));
    String bookID = (String) xpath.evaluate("//BookID", inputSource, XPathConstants.STRING);
    if (bookID.isEmpty()) {
        throw new ServiceException(Error.reservation_api, reservation.getId());
    } else {/*from  ww  w .  j  av  a2  s .  co m*/
        reservation.setAltid(bookID);
        reservation.setAltpartyid(getAltpartyid());
        reservation.setMessage(reservation.getMessage());
        reservation.setVersion(new Date(timestamp));
        reservation.setState(Reservation.State.Confirmed.name());
        result.put(GatewayHandler.STATE, GatewayHandler.ACCEPTED);
    }
}

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

/**
 * Gets the test cases./*from   ww w. ja va 2 s . c o m*/
 *
 * @param appDirName the app dir name
 * @param testSuites the test suites
 * @param testSuitePath the test suite path
 * @param testCasePath the test case path
 * @return the test cases
 * @throws PhrescoException the phresco exception
 */
private List<TestCase> getTestCases(String rootModulePath, String subModule, List<NodeList> testSuites,
        String testSuitePath, String testCasePath, String testStepPath, String testType)
        throws PhrescoException {
    InputStream fileInputStream = null;
    StringBuilder screenShotDir = new StringBuilder();
    try {
        List<TestCase> testCases = new ArrayList<TestCase>();
        for (NodeList testSuite : testSuites) {
            StringBuilder testCaseBuilder = new StringBuilder();
            testCaseBuilder.append(testSuitePath);
            testCaseBuilder.append(NAME_FILTER_PREFIX);
            testCaseBuilder.append(getTestSuite());
            testCaseBuilder.append(NAME_FILTER_SUFIX);
            testCaseBuilder.append(testCasePath);
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList nodeList = (NodeList) xpath.evaluate(testCaseBuilder.toString(),
                    testSuite.item(0).getParentNode(), XPathConstants.NODESET);
            // For tehnologies like php and drupal duoe to plugin change xml
            // testcase path modified
            if (nodeList.getLength() == 0) {
                StringBuilder sbMulti = new StringBuilder();
                sbMulti.append(testSuitePath);
                sbMulti.append(NAME_FILTER_PREFIX);
                sbMulti.append(getTestSuite());
                sbMulti.append(NAME_FILTER_SUFIX);
                sbMulti.append(XPATH_TESTSUTE_TESTCASE);
                nodeList = (NodeList) xpath.evaluate(sbMulti.toString(), testSuite.item(0).getParentNode(),
                        XPathConstants.NODESET);
            }

            // For technology sharepoint
            if (nodeList.getLength() == 0) {
                StringBuilder sbMulti = new StringBuilder();
                sbMulti.append(XPATH_MULTIPLE_TESTSUITE);
                sbMulti.append(NAME_FILTER_PREFIX);
                sbMulti.append(getTestSuite());
                sbMulti.append(NAME_FILTER_SUFIX);
                sbMulti.append(testCasePath);
                nodeList = (NodeList) xpath.evaluate(sbMulti.toString(), testSuite.item(0).getParentNode(),
                        XPathConstants.NODESET);
            }

            if (testType.equals(FUNCTIONAL)) {
                screenShotDir = screenShotDir(rootModulePath, subModule);
            }
            int failureTestCases = 0;
            int errorTestCases = 0;
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                NodeList childNodes = node.getChildNodes();
                NamedNodeMap nameNodeMap = node.getAttributes();
                TestCase testCase = new TestCase();
                List<TestStep> testSteps = new ArrayList<TestStep>();
                for (int k = 0; k < nameNodeMap.getLength(); k++) {
                    Node attribute = nameNodeMap.item(k);
                    String attributeName = attribute.getNodeName();
                    String attributeValue = attribute.getNodeValue();
                    if (ATTR_NAME.equals(attributeName)) {
                        testCase.setName(attributeValue);
                    } else if (ATTR_CLASS.equals(attributeName) || ATTR_CLASSNAME.equals(attributeName)) {
                        testCase.setTestClass(attributeValue);
                    } else if (ATTR_FILE.equals(attributeName)) {
                        testCase.setFile(attributeValue);
                    } else if (ATTR_LINE.equals(attributeName)) {
                        testCase.setLine(Float.parseFloat(attributeValue));
                    } else if (ATTR_ASSERTIONS.equals(attributeName)) {
                        testCase.setAssertions(Float.parseFloat(attributeValue));
                    } else if (ATTR_TIME.equals(attributeName)) {
                        testCase.setTime(attributeValue);
                    }
                }

                if (childNodes != null && childNodes.getLength() > 0) {
                    for (int j = 0; j < childNodes.getLength(); j++) {
                        Node childNode = childNodes.item(j);
                        if (ELEMENT_FAILURE.equals(childNode.getNodeName())) {
                            failureTestCases++;
                            TestCaseFailure failure = getFailure(childNode);
                            if (failure != null) {
                                File file = new File(screenShotDir.toString() + testCase.getName()
                                        + FrameworkConstants.DOT + IMG_PNG_TYPE);
                                if (file.exists()) {
                                    failure.setHasFailureImg(true);
                                    fileInputStream = new FileInputStream(file);
                                    if (fileInputStream != null) {
                                        byte[] imgByte = null;
                                        imgByte = IOUtils.toByteArray(fileInputStream);
                                        byte[] encodedImage = Base64.encodeBase64(imgByte);
                                        failure.setScreenshotPath(new String(encodedImage));
                                    }
                                }
                                testCase.setTestCaseFailure(failure);
                            }
                        }

                        if (ELEMENT_ERROR.equals(childNode.getNodeName())) {
                            errorTestCases++;
                            TestCaseError error = getError(childNode);
                            if (error != null) {
                                File file = new File(screenShotDir.toString() + testCase.getName()
                                        + FrameworkConstants.DOT + IMG_PNG_TYPE);
                                if (file.exists()) {
                                    error.setHasErrorImg(true);
                                    fileInputStream = new FileInputStream(file);
                                    if (fileInputStream != null) {
                                        byte[] imgByte = null;
                                        imgByte = IOUtils.toByteArray(fileInputStream);
                                        byte[] encodedImage = Base64.encodeBase64(imgByte);
                                        error.setScreenshotPath(new String(encodedImage));
                                    }
                                }
                                testCase.setTestCaseError(error);
                            }
                        }

                        //To Calculate teststep if it present
                        if (StringUtils.isNotEmpty(testStepPath)
                                && testStepPath.equalsIgnoreCase(childNode.getNodeName())) {
                            TestStep testStep = new TestStep();
                            Node testStepNode = childNode;
                            NamedNodeMap testStepAttributes = testStepNode.getAttributes();
                            if (testStepAttributes != null && testStepAttributes.getLength() > 0) {
                                for (int k = 0; k < testStepAttributes.getLength(); k++) {
                                    Node attribute = testStepAttributes.item(k);
                                    String attributeName = attribute.getNodeName();
                                    String attributeValue = attribute.getNodeValue();
                                    if (ATTR_NAME.equals(attributeName)) {
                                        testStep.setName(attributeValue);
                                    } else if (ATTR_ACTION.equals(attributeName)) {
                                        testStep.setAction(attributeValue);
                                    } else if (ATTR_TIME.equals(attributeName)) {
                                        testStep.setTime(attributeValue);
                                    }
                                }
                                NodeList testStepChilds = testStepNode.getChildNodes();
                                if (testStepChilds != null && testStepChilds.getLength() > 0) {
                                    for (int z = 0; z < testStepChilds.getLength(); z++) {
                                        Node testStepChildNode = testStepChilds.item(z);
                                        constructTestStepFailure(testCase, testStep, testStepChildNode);
                                        constructTestStepError(testCase, testStep, testStepChildNode);
                                    }
                                }
                                testSteps.add(testStep);
                                testCase.setTestSteps(testSteps);
                            }
                        }
                    }
                }
                testCases.add(testCase);
            }
            setSetFailureTestCases(failureTestCases);
            setErrorTestCases(errorTestCases);
            setNodeLength(nodeList.getLength());
            //
        }
        return testCases;
    } catch (PhrescoException e) {
        throw e;
    } catch (XPathExpressionException e) {
        throw new PhrescoException(e);
    } catch (IOException e) {
        throw new PhrescoException(e);
    } finally {
        try {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        } catch (IOException e) {

        }
    }
}

From source file:net.cbtltd.rest.nextpax.A_Handler.java

/**
 * Returns if the property is available for the reservation.
 * //from  ww  w . ja v a  2  s  . c o m
 * @param sqlSession the current SQL session.
 * @param reservation the reservation for collisions
 * @return list of collisions
 */
@Override
public boolean isAvailable(SqlSession sqlSession, Reservation reservation) {
    StringBuilder sb = new StringBuilder();
    Date now = new Date();
    long time = now.getTime();
    String SenderSessionID = time + "bookingnetS";
    String ReceiverSessionID = time + "bookingnetR";
    String rq;
    String rs = null;
    boolean available = false;
    if (reservation.notActive()) {
        throw new ServiceException(Error.reservation_state,
                reservation.getId() + " state " + reservation.getState());
    }

    Product product = sqlSession.getMapper(ProductMapper.class).read(reservation.getProductid());
    if (product == null) {
        throw new ServiceException(Error.product_id, reservation.getProductid());
    }
    if (reservation.noAgentid()) {
        throw new ServiceException(Error.reservation_agentid);
    }
    Party agent = sqlSession.getMapper(PartyMapper.class).read(reservation.getAgentid());
    if (agent == null) {
        throw new ServiceException(Error.party_id, reservation.getAgentid());
    }
    if (reservation.noCustomerid()) {
        reservation.setCustomerid(Party.NO_ACTOR);
    }
    Party customer = sqlSession.getMapper(PartyMapper.class).read(reservation.getCustomerid());
    if (customer == null) {
        throw new ServiceException(Error.reservation_customerid, reservation.getCustomerid());
    }

    try {
        sb.append("<?xml version='1.0' ?>");
        sb.append("<TravelMessage VersionID='1.8N'>");
        sb.append(" <Control Language='NL' Test='nee'>");
        sb.append("    <SenderSessionID>" + SenderSessionID + "</SenderSessionID>");
        sb.append("    <ReceiverSessionID>" + ReceiverSessionID + "</ReceiverSessionID>");
        sb.append("    <Date>" + DF.format(new Date()) + "</Date>");
        sb.append("    <Time Reliability='zeker'>" + TF.format(new Date()) + "</Time>");
        sb.append("   <MessageSequence>1</MessageSequence>");
        sb.append("   <SenderID>" + SENDERID + "</SenderID>");
        sb.append("  <ReceiverID>NPS001</ReceiverID>");
        sb.append("   <RequestID>AvailabilitybookingnetRequest</RequestID>");
        sb.append("   <ResponseID>AvailabilitybookingnetResponse</ResponseID>");
        sb.append(" </Control>");
        sb.append("  <TRequest>");
        sb.append("    <AvailabilitybookingnetRequest>");
        sb.append("      <PackageDetails WaitListCheck='ja'>");
        sb.append("          <AccommodationID>" + "A" + product.getAltid() + "</AccommodationID>");
        sb.append("          <ArrivalDate>" + DF.format(reservation.getFromdate()) + "</ArrivalDate>");
        sb.append("        <Duration DurationType='dagen'>" + reservation.getDuration(Time.DAY).intValue()
                + "</Duration>");
        sb.append("     </PackageDetails>");
        sb.append("   </AvailabilitybookingnetRequest>");
        sb.append("  </TRequest>");
        sb.append("</TravelMessage>");

        rq = sb.toString();
        LOG.debug("isAvailable rq: \n" + rq + "\n");

        rs = getConnection(rq);
        LOG.debug("isAvailable rs: \n" + rs + "\n");

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        InputSource inputSource = new InputSource(new StringReader(rs.toString()));
        Double bookID = (Double) xpath.evaluate("//PackageID", inputSource, XPathConstants.NUMBER);
        available = !bookID.isNaN();
    } catch (Throwable e) {
        LOG.error(e.getMessage());
    }
    return available;
}

From source file:lcmc.data.VMSXML.java

/** Modify xml of the domain. */
public Node modifyDomainXML(final String domainName, final Map<String, String> parametersMap) {
    final String configName = namesConfigsMap.get(domainName);
    if (configName == null) {
        return null;
    }//w w  w  .j  a v  a2  s. co  m
    final Node domainNode = getDomainNode(domainName);
    if (domainNode == null) {
        return null;
    }
    final XPath xpath = XPathFactory.newInstance().newXPath();
    final Map<String, String> paths = new HashMap<String, String>();
    paths.put(VM_PARAM_MEMORY, "memory");
    paths.put(VM_PARAM_CURRENTMEMORY, "currentMemory");
    paths.put(VM_PARAM_VCPU, "vcpu");
    paths.put(VM_PARAM_BOOTLOADER, "bootloader");
    paths.put(VM_PARAM_BOOT, "os/boot");
    paths.put(VM_PARAM_BOOT_2, "os/boot");
    paths.put(VM_PARAM_TYPE, "os/type");
    paths.put(VM_PARAM_TYPE_ARCH, "os/type");
    paths.put(VM_PARAM_TYPE_MACHINE, "os/type");
    paths.put(VM_PARAM_INIT, "os/init");
    paths.put(VM_PARAM_LOADER, "os/loader");
    paths.put(VM_PARAM_CPU_MATCH, "cpu");
    paths.put(VM_PARAM_ACPI, "features");
    paths.put(VM_PARAM_APIC, "features");
    paths.put(VM_PARAM_PAE, "features");
    paths.put(VM_PARAM_HAP, "features");
    paths.put(VM_PARAM_ON_POWEROFF, "on_poweroff");
    paths.put(VM_PARAM_ON_REBOOT, "on_reboot");
    paths.put(VM_PARAM_ON_CRASH, "on_crash");
    paths.put(VM_PARAM_EMULATOR, "devices/emulator");
    final Document doc = domainNode.getOwnerDocument();
    try {
        for (final String param : parametersMap.keySet()) {
            final String path = paths.get(param);
            if (path == null) {
                continue;
            }
            final NodeList nodes = (NodeList) xpath.evaluate(path, domainNode, XPathConstants.NODESET);
            Element node = (Element) nodes.item(0);
            if (node == null) {
                continue;
            }
            if (VM_PARAM_BOOT_2.equals(param)) {
                if (nodes.getLength() > 1) {
                    node = (Element) nodes.item(1);
                } else {
                    node = (Element) node.getParentNode().appendChild(doc.createElement(OS_BOOT_NODE));
                }
            }
            String value = parametersMap.get(param);
            if (VM_PARAM_MEMORY.equals(param) || VM_PARAM_CURRENTMEMORY.equals(param)) {
                value = Long.toString(Tools.convertToKilobytes(value));
            }
            if (VM_PARAM_CPU_MATCH.equals(param) || VM_PARAM_ACPI.equals(param) || VM_PARAM_APIC.equals(param)
                    || VM_PARAM_PAE.equals(param) || VM_PARAM_HAP.equals(param)) {
                domainNode.removeChild(node);
            } else if (VM_PARAM_BOOT.equals(param)) {
                node.setAttribute(OS_BOOT_NODE_DEV, value);
            } else if (VM_PARAM_BOOT_2.equals(param)) {
                if (value == null || "".equals(value)) {
                    node.getParentNode().removeChild(node);
                } else {
                    node.setAttribute(OS_BOOT_NODE_DEV, value);
                }
            } else if (VM_PARAM_TYPE_ARCH.equals(param)) {
                node.setAttribute("arch", value);
            } else if (VM_PARAM_TYPE_MACHINE.equals(param)) {
                node.setAttribute("machine", value);
            } else if (VM_PARAM_CPU_MATCH.equals(param)) {
                if ("".equals(value)) {
                    node.getParentNode().removeChild(node);
                } else {
                    node.setAttribute("match", value);
                }
            } else if (VM_PARAM_CPUMATCH_TOPOLOGY_THREADS.equals(param)) {
                node.setAttribute("threads", value);
            } else {
                final Node n = getChildNode(node, "#text");
                if (n == null) {
                    node.appendChild(doc.createTextNode(value));
                } else {
                    n.setNodeValue(value);
                }
            }
        }
        addCPUMatchNode(doc, domainNode, parametersMap);
        addFeatures(doc, domainNode, parametersMap);
    } catch (final javax.xml.xpath.XPathExpressionException e) {
        Tools.appError("could not evaluate: ", e);
        return null;
    }
    return domainNode;
}

From source file:no.kantega.publishing.common.data.attributes.ListAttribute.java

@Override
public void setConfig(Element config, Map<String, String> model)
        throws InvalidTemplateException, SystemException {
    super.setConfig(config, model);

    if (config != null) {
        String multiple = config.getAttribute("multiple");
        if ("true".equalsIgnoreCase(multiple)) {
            this.multiple = true;
        }/*from  ww  w.  ja  v  a2  s.  c o m*/

        key = StringUtils.defaultString(config.getAttribute("key"));

        options = new ArrayList<>();

        try {
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList nodes = (NodeList) xpath.evaluate("options/option", config, XPathConstants.NODESET);
            for (int i = 0; i < nodes.getLength(); i++) {
                Element elmOption = (Element) nodes.item(i);
                String optText = elmOption.getFirstChild().getNodeValue();
                String optVal = elmOption.getAttribute("value");
                String optSel = elmOption.getAttribute("selected");
                ListOption option = new ListOption();
                option.setText(optText);
                option.setValue(optVal);
                if ("true".equalsIgnoreCase(optSel)) {
                    option.setDefaultSelected(true);
                }
                options.add(option);
            }

        } catch (XPathExpressionException e) {
            log.error("Error getting list options", e);
        }
        ignoreVariant = Boolean.valueOf(config.getAttribute("ignorevariant"));
    }
}

From source file:no.trank.openpipe.solr.step.SolrDocumentProcessor.java

private void loadIndexSchema(URL url)
        throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
    solrFields.clear();/*  w w w.  j a  va 2 s. c om*/
    solrDynamicFields.clear();

    InputStream sIn;
    if (url.getProtocol().equals("file")) {
        sIn = url.openStream();
    } else {
        GetMethod get = new GetMethod(url.toExternalForm());
        httpClient.executeMethod(get);
        sIn = get.getResponseBodyAsStream();
    }
    final InputStream in = new XmlInputStream(sIn);
    try {

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        org.w3c.dom.Document document = builder.parse(in);

        final XPath xpath = XPathFactory.newInstance().newXPath();
        final NodeList nodes = (NodeList) xpath.evaluate("/schema/fields/field | /schema/fields/dynamicField",
                document, XPathConstants.NODESET);

        for (int i = 0; i < nodes.getLength(); i++) {
            final Node node = nodes.item(i);
            final String name = ((Element) node).getAttribute("name");
            final String nodeName = node.getNodeName();
            if ("field".equals(nodeName)) {
                addField(name);
            } else if ("dynamicField".equals(nodeName)) {
                addDynamicField(name);
            }
        }

        if (idFieldName == null) {
            Node idNode = (Node) xpath.evaluate("/schema/uniqueKey", document, XPathConstants.NODE);
            idFieldName = idNode.getTextContent().trim();
        }

    } finally {
        try {
            in.close();
        } catch (Exception e) {
            // Do nothing
        }
    }
}