Example usage for org.jdom2.xpath XPathFactory instance

List of usage examples for org.jdom2.xpath XPathFactory instance

Introduction

In this page you can find the example usage for org.jdom2.xpath XPathFactory instance.

Prototype

public static final XPathFactory instance() 

Source Link

Document

Obtain an instance of an XPathFactory using the default mechanisms to determine what XPathFactory implementation to use.

Usage

From source file:org.mule.tools.apikit.input.parsers.APIKitConfigParser.java

License:Open Source License

@Override
public Map<String, APIKitConfig> parse(Document document) {
    Map<String, APIKitConfig> apikitConfigs = new HashMap<String, APIKitConfig>();
    XPathExpression<Element> xp = XPathFactory.instance().compile(
            "//*/*[local-name()='" + APIKitConfig.ELEMENT_NAME + "']",
            Filters.element(APIKitTools.API_KIT_NAMESPACE.getNamespace()));
    List<Element> elements = xp.evaluate(document);
    for (Element element : elements) {
        Attribute name = element.getAttribute(APIKitConfig.NAME_ATTRIBUTE);
        Attribute raml = element.getAttribute(APIKitConfig.RAML_ATTRIBUTE);
        Attribute consoleEnabled = element.getAttribute(APIKitConfig.CONSOLE_ENABLED_ATTRIBUTE);
        Attribute consolePath = element.getAttribute(APIKitConfig.CONSOLE_PATH_ATTRIBUTE);

        if (raml == null) {
            throw new IllegalArgumentException(APIKitConfig.RAML_ATTRIBUTE + " attribute is required");
        }/*w w  w .  jav  a  2s  .co m*/

        APIKitConfig.Builder configBuilder = new APIKitConfig.Builder(raml.getValue());
        if (name != null) {
            configBuilder.setName(name.getValue());
        }
        if (consoleEnabled != null) {
            configBuilder.setConsoleEnabled(Boolean.valueOf(consoleEnabled.getValue()));
        }
        if (consolePath != null) {
            configBuilder.setConsolePath(consolePath.getValue());
        }

        APIKitConfig config = configBuilder.build();
        String configId = config.getName() != null ? config.getName() : APIKitFlow.UNNAMED_CONFIG_NAME;
        apikitConfigs.put(configId, config);
    }

    return apikitConfigs;
}

From source file:org.mule.tools.apikit.input.parsers.APIKitFlowsParser.java

License:Open Source License

@Override
public Set<ResourceActionMimeTypeTriplet> parse(Document document) {
    Set<ResourceActionMimeTypeTriplet> entries = new HashSet<ResourceActionMimeTypeTriplet>();
    XPathExpression<Element> xp = XPathFactory.instance().compile("//*/*[local-name()='flow']",
            Filters.element(XMLNS_NAMESPACE.getNamespace()));
    List<Element> elements = xp.evaluate(document);
    for (Element element : elements) {
        String name = element.getAttributeValue("name");
        APIKitFlow flow;//from  w  w w  .j  av a  2 s .c o  m
        try {
            flow = APIKitFlow.buildFromName(name, includedApis.keySet());
        } catch (IllegalArgumentException iae) {
            LOGGER.info("Flow named '" + name
                    + "' is not an APIKit Flow because it does not follow APIKit naming convention.");
            continue;
        }

        API api = includedApis.get(flow.getConfigRef());

        String resource = flow.getResource();
        if (api != null) {
            if (!resource.startsWith("/")) {
                resource = "/" + resource;
            }

            if (api.getPath() == null) {
                throw new IllegalStateException("Api path is invalid");
            }
            String path = APIKitTools.getCompletePathFromBasePathAndPath(
                    api.getHttpListenerConfig().getBasePath(), api.getPath());
            entries.add(new ResourceActionMimeTypeTriplet(api, path + resource, flow.getAction(),
                    flow.getMimeType()));
        } else {
            throw new IllegalStateException("No APIKit entries found in Mule config");
        }
    }
    return entries;
}

From source file:org.mule.tools.apikit.input.parsers.APIKitRoutersParser.java

License:Open Source License

@Override
public Map<String, API> parse(Document document) {
    Map<String, API> includedApis = new HashMap<String, API>();

    XPathExpression<Element> xp = XPathFactory.instance().compile("//*/*[local-name()='router']",
            Filters.element(APIKitTools.API_KIT_NAMESPACE.getNamespace()));
    List<Element> elements = xp.evaluate(document);
    for (Element element : elements) {
        Attribute configRef = element.getAttribute("config-ref");
        String configId = configRef != null ? configRef.getValue() : APIKitFlow.UNNAMED_CONFIG_NAME;

        APIKitConfig config = apikitConfigs.get(configId);
        if (config == null) {
            throw new IllegalStateException("An Apikit configuration is mandatory.");
        }//from w ww.  j  a v  a 2 s  . c o  m

        for (File yamlPath : yamlPaths) {
            if (yamlPath.getName().equals(config.getRaml())) {
                Element listener = element.getParentElement().getChildren().get(0);

                Attribute httpListenerConfigRef = listener.getAttribute("config-ref");
                String httpListenerConfigId = httpListenerConfigRef != null ? httpListenerConfigRef.getValue()
                        : HttpListenerConfig.DEFAULT_CONFIG_NAME;

                HttpListenerConfig httpListenerConfig = httpListenerConfigs.get(httpListenerConfigId);
                if (httpListenerConfig == null) {
                    throw new IllegalStateException("An HTTP Listener configuration is mandatory.");
                }

                // TODO Unhack, it is assuming that the router will always be in a flow
                // where the first element is going to be an http listener
                if (!"listener".equals(listener.getName())) {
                    throw new IllegalStateException("The first element of the main flow must be a listener");
                }
                String path = getPathFromListener(listener);

                includedApis.put(configId,
                        apiFactory.createAPIBinding(yamlPath, file, config, httpListenerConfig, path));
            }
        }
    }
    return includedApis;
}

From source file:org.mule.tools.apikit.input.parsers.HttpListenerConfigParser.java

License:Open Source License

public Map<String, HttpListenerConfig> parse(Document document) {
    Map<String, HttpListenerConfig> httpListenerConfigMap = new HashMap<String, HttpListenerConfig>();
    XPathExpression<Element> xp = XPathFactory.instance().compile(
            "//*/*[local-name()='" + HttpListenerConfig.ELEMENT_NAME + "']",
            Filters.element(HTTP_NAMESPACE.getNamespace()));
    List<Element> elements = xp.evaluate(document);
    for (Element element : elements) {
        String name = element.getAttributeValue("name");
        if (name == null) {
            throw new IllegalStateException("Cannot retrieve name.");
        }/*  ww w .  j av a  2s .co m*/
        String host = element.getAttributeValue("host");
        if (host == null) {
            throw new IllegalStateException("Cannot retrieve host.");
        }
        String port = element.getAttributeValue("port");
        if (port == null) {
            port = HttpListenerConfig.DEFAULT_PORT;
        }
        String basePath = element.getAttributeValue("basePath");
        if (basePath == null) {
            basePath = "/";
        } else if (!basePath.startsWith("/")) {
            basePath = "/" + basePath;
        }
        httpListenerConfigMap.put(name, new HttpListenerConfig(name, host, port, basePath));
    }
    return httpListenerConfigMap;
}

From source file:org.mule.tools.apikit.output.MuleConfigGenerator.java

License:Open Source License

private void generateAPIKitConfig(API api, Document doc) {
    XPathExpression muleExp = XPathFactory.instance().compile("//*[local-name()='mule']");
    List<Element> mules = muleExp.evaluate(doc);
    Element mule = mules.get(0);//from   ww  w .j ava2  s  .c o  m
    if (api.getHttpListenerConfig() == null) {
        api.setHttpListenerConfig(
                new HttpListenerConfig(HttpListenerConfig.DEFAULT_CONFIG_NAME, HttpListenerConfig.DEFAULT_HOST,
                        HttpListenerConfig.DEFAULT_PORT, HttpListenerConfig.DEFAULT_BASE_PATH));
    }
    new HttpListenerConfigScope(api, mule).generate();
    new APIKitConfigScope(api.getConfig(), mule).generate();
    Element exceptionStrategy = new ExceptionStrategyScope(mule, api.getId()).generate();
    String configRef = api.getConfig() != null ? api.getConfig().getName() : null;

    String listenerConfigRef = api.getHttpListenerConfig().getName();
    new FlowScope(mule, exceptionStrategy.getAttribute("name").getValue(), api, configRef, listenerConfigRef)
            .generate();
}

From source file:org.mycore.datamodel.metadata.MCRDerivate.java

License:Open Source License

/**
 * Reads all files and urns from the derivate.
 * /*w w  w .j av a  2s.  c o  m*/
 * @return A {@link Map} which contains the files as key and the urns as value. If no URN assigned the map will be empty.
 */
public Map<String, String> getUrnMap() {
    Map<String, String> fileUrnMap = new HashMap<String, String>();

    XPathExpression<Element> filesetPath = XPathFactory.instance().compile("./mycorederivate/derivate/fileset",
            Filters.element());

    Element result = filesetPath.evaluateFirst(this.createXML());
    if (result == null) {
        return fileUrnMap;
    }
    String urn = result.getAttributeValue("urn");

    if (urn != null) {
        XPathExpression<Element> filePath = XPathFactory.instance()
                .compile("./mycorederivate/derivate/fileset[@urn='" + urn + "']/file", Filters.element());
        List<Element> files = filePath.evaluate(this.createXML());

        for (Element currentFileElement : files) {
            String currentUrn = currentFileElement.getChildText("urn");
            String currentFile = currentFileElement.getAttributeValue("name");
            fileUrnMap.put(currentFile, currentUrn);
        }
    }
    return fileUrnMap;
}

From source file:org.mycore.datamodel.metadata.validator.MCREditorOutValidator.java

License:Open Source License

/**
 * tries to generate a valid MCRObject as JDOM Document.
 * /*  w  w w.  j a  va2  s .  com*/
 * @return MCRObject
 */
public Document generateValidMyCoReObject() throws JDOMException, SAXParseException, IOException {
    MCRObject obj;
    // load the JDOM object
    XPathFactory.instance().compile("/mycoreobject/*/*/*/@editor.output", Filters.attribute()).evaluate(input)
            .forEach(Attribute::detach);
    try {
        byte[] xml = new MCRJDOMContent(input).asByteArray();
        obj = new MCRObject(xml, true);
    } catch (SAXParseException e) {
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        LOGGER.warn("Failure while parsing document:\n" + xout.outputString(input));
        throw e;
    }
    Date curTime = new Date();
    obj.getService().setDate("modifydate", curTime);

    // return the XML tree
    input = obj.createXML();
    return input;
}

From source file:org.mycore.frontend.editor.MCREditorDataResolver.java

License:Open Source License

/**
 * Returns the current editor input from the form with the given editor session ID.
 * //from  ww  w . ja  v a  2 s .c  o  m
 * @param href
 *            Syntax: editorData:[sessionID]:[xPath]
 */
@Override
public Source resolve(String href, String base) throws TransformerException {
    String[] tokens = href.split(":", 3);
    String sessionID = tokens[1];
    String xPath = tokens[2];
    xPath = fixAttributeConditionsInXPath(xPath);

    LOGGER.debug("MCREditorDataResolver editor session = " + sessionID);
    LOGGER.debug("MCREditorDataResolver xPath = " + xPath);

    Element editor = MCREditorSessionCache.instance().getEditorSession(sessionID).getXML();
    MCREditorSubmission sub = new MCREditorSubmission(editor);
    Document xml = sub.getXML();
    XPathExpression<Element> xp = XPathFactory.instance().compile(xPath, Filters.element(), null,
            sub.getNamespaceMap().values());
    Element resolved = xp.evaluateFirst(xml);
    return new JDOMSource(resolved == null ? new Element("nothingFound") : resolved);
}

From source file:org.mycore.frontend.editor.MCREditorSubmission.java

License:Open Source License

private void validate(MCRRequestParameters parms, Element editor) {
    LOGGER.info("Validating editor input... ");

    for (Enumeration e = parms.getParameterNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();

        if (!name.startsWith("_sortnr-")) {
            continue;
        }//  w ww  .  ja v  a 2  s  .c  om

        name = name.substring(8);

        String ID = parms.getParameter("_id@" + name);

        if (ID == null || ID.trim().length() == 0) {
            continue;
        }

        String[] values = { "" };

        if (parms.getParameterValues(name) != null) {
            values = parms.getParameterValues(name);
        }

        Element component = MCREditorDefReader.findElementByID(ID, editor);

        if (component == null) {
            continue;
        }

        List conditions = component.getChildren("condition");

        if (conditions == null) {
            continue;
        }

        // Skip variables with values equal to autofill text
        String attrib = component.getAttributeValue("autofill");
        String elem = component.getChildTextTrim("autofill");
        String autofill = null;

        if (attrib != null && attrib.trim().length() > 0) {
            autofill = attrib.trim();
        } else if (attrib != null && attrib.trim().length() > 0) {
            autofill = elem.trim();
        }

        if (values[0].trim().equals(autofill)) {
            values[0] = "";
        }

        for (Object condition1 : conditions) {
            Element condition = (Element) condition1;

            boolean ok = true;
            for (int j = 0; j < values.length && ok; j++) {
                String nname = j == 0 ? name : name + "[" + (j + 1) + "]";
                ok = checkCondition(condition, nname, values[j]);

                if (!ok) {
                    String sortNr = parms.getParameter("_sortnr-" + name);
                    failed.put(sortNr, condition);

                    if (LOGGER.isDebugEnabled()) {
                        String cond = new XMLOutputter(Format.getCompactFormat()).outputString(condition);
                        LOGGER.debug("Validation condition failed:");
                        LOGGER.debug(nname + " = \"" + values[j] + "\"");
                        LOGGER.debug(cond);
                    }
                }
            }
        }
    }

    for (Enumeration e = parms.getParameterNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();

        if (!name.startsWith("_cond-")) {
            continue;
        }

        String path = name.substring(6);
        String[] ids = parms.getParameterValues(name);

        if (ids != null) {
            for (String id : ids) {
                Element condition = MCREditorDefReader.findElementByID(id, editor);

                if (condition == null) {
                    continue;
                }

                String field1 = condition.getAttributeValue("field1", "");
                String field2 = condition.getAttributeValue("field2", "");

                if (!field1.isEmpty() || !field2.isEmpty()) {
                    String pathA = path + ((!field1.isEmpty() && !field1.equals(".")) ? "/" + field1 : "");
                    String pathB = path + ((!field2.isEmpty() && !field2.equals(".")) ? "/" + field2 : "");

                    String valueA = parms.getParameter(pathA);
                    String valueB = parms.getParameter(pathB);

                    String sortNrA = parms.getParameter("_sortnr-" + pathA);
                    String sortNrB = parms.getParameter("_sortnr-" + pathB);

                    boolean pairValuesAlreadyInvalid = (failed.containsKey(sortNrA)
                            || failed.containsKey(sortNrB));

                    if (!pairValuesAlreadyInvalid) {
                        MCRValidator validator = MCRValidatorBuilder.buildPredefinedCombinedPairValidator();
                        setValidatorProperties(validator, condition);
                        if (!validator.isValid(valueA, valueB)) {
                            failed.put(sortNrA, condition);
                            failed.put(sortNrB, condition);
                        }
                    }
                } else {
                    XPathExpression<Element> xpath = XPathFactory.instance().compile(path, Filters.element(),
                            null, getNamespaceMap().values());
                    Element current = xpath.evaluateFirst(getXML());
                    if (current == null) {
                        LOGGER.debug("Could not validate, because no element found at xpath " + path);
                        continue;
                    }

                    MCRValidator validator = MCRValidatorBuilder.buildPredefinedCombinedElementValidator();
                    setValidatorProperties(validator, condition);
                    if (!validator.isValid(current)) {
                        String sortNr = parms.getParameter("_sortnr-" + path);
                        failed.put(sortNr, condition);
                    }
                }
            }
        }
    }
}

From source file:org.mycore.frontend.xeditor.MCRBinding.java

License:Open Source License

private void bind(String xPath, boolean buildIfNotExists, String initialValue) throws JaxenException {
    this.xPath = xPath;

    Map<String, Object> variables = buildXPathVariables();

    XPathExpression<Object> xPathExpr = XPathFactory.instance().compile(xPath, Filters.fpassthrough(),
            variables, MCRConstants.getStandardNamespaces());

    boundNodes.addAll(xPathExpr.evaluate(parent.getBoundNodes()));

    for (Object boundNode : boundNodes)
        if (!(boundNode instanceof Element || boundNode instanceof Attribute || boundNode instanceof Document))
            throw new RuntimeException(
                    "XPath MUST only bind either element, attribute or document nodes: " + xPath);

    LOGGER.debug("Bind to " + xPath + " selected " + boundNodes.size() + " node(s)");

    if (boundNodes.isEmpty() && buildIfNotExists) {
        MCRNodeBuilder builder = new MCRNodeBuilder(variables);
        Object built = builder.buildNode(xPath, initialValue, (Parent) (parent.getBoundNode()));
        LOGGER.debug("Bind to " + xPath + " generated node " + MCRXPathBuilder.buildXPath(built));
        boundNodes.add(built);/*from w  w  w.  j a v  a2s  .c  o  m*/
        trackNodeCreated(builder.getFirstNodeBuilt());
    }
}