Example usage for javax.xml.xpath XPathFactory newXPath

List of usage examples for javax.xml.xpath XPathFactory newXPath

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newXPath.

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:org.gluu.oxtrust.ldap.service.Shibboleth2ConfService.java

public boolean isFederationMetadata(String spMetaDataFN) {
    if (spMetaDataFN == null) {
        return false;
    }/*from  w w w .  j  a v  a2  s. c o m*/
    File spMetaDataFile = new File(getSpMetadataFilePath(spMetaDataFN));
    InputStream is = null;
    InputStreamReader isr = null;
    Document xmlDocument = null;
    try {
        is = FileUtils.openInputStream(spMetaDataFile);
        isr = new InputStreamReader(is, "UTF-8");
        try {
            xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(isr));
        } catch (Exception ex) {
            log.error("Failed to parse metadata file '{0}'", ex, spMetaDataFile.getAbsolutePath());
        }
    } catch (IOException ex) {
        log.error("Failed to read metadata file '{0}'", ex, spMetaDataFile.getAbsolutePath());
    } finally {
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
    }

    if (xmlDocument == null) {
        return false;
    }

    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();

    String federationTag = null;
    try {
        federationTag = xPath.compile("count(/EntitiesDescriptor)").evaluate(xmlDocument);
    } catch (XPathExpressionException ex) {
        log.error("Failed to find IDP metadata file in relaying party file '{0}'", ex,
                spMetaDataFile.getAbsolutePath());
    }

    return Integer.parseInt(federationTag) > 0;
}

From source file:org.gluu.oxtrust.ldap.service.Shibboleth3ConfService.java

public String getIdpMetadataFilePath() {
    //TODO: change for IDP3

    if (applicationConfiguration.getShibboleth2IdpRootDir() == null) {
        throw new InvalidConfigurationException(
                "Failed to find IDP metadata file due to undefined IDP root folder");
    }/*from   w w w .ja va  2s  .c o  m*/

    String idpConfFolder = applicationConfiguration.getShibboleth2IdpRootDir() + File.separator
            + SHIB3_IDP_CONF_FOLDER + File.separator;

    File relyingPartyFile = new File(idpConfFolder + SHIB3_IDP_RELYING_PARTY);
    if (!relyingPartyFile.exists()) {
        log.error("Failed to find IDP metadata file name because relaying party file '{0}' doesn't exist",
                relyingPartyFile.getAbsolutePath());
        return null;
    }

    InputStream is = null;
    InputStreamReader isr = null;
    Document xmlDocument = null;
    try {
        is = FileUtils.openInputStream(relyingPartyFile);
        isr = new InputStreamReader(is, "UTF-8");
        try {
            xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(isr));
        } catch (Exception ex) {
            log.error("Failed to parse relying party file '{0}'", ex, relyingPartyFile.getAbsolutePath());
        }
    } catch (IOException ex) {
        log.error("Failed to read relying party file '{0}'", ex, relyingPartyFile.getAbsolutePath());
    } finally {
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
    }

    if (xmlDocument == null) {
        return null;
    }

    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();

    String filePath = null;
    try {
        filePath = xPath.compile(
                "/RelyingPartyGroup/MetadataProvider[@id='ShibbolethMetadata']/MetadataProvider[@id='IdPMD']/MetadataResource/@file")
                .evaluate(xmlDocument);
    } catch (XPathExpressionException ex) {
        log.error("Failed to find IDP metadata file in relaying party file '{0}'", ex,
                relyingPartyFile.getAbsolutePath());
    }

    if (filePath == null) {
        log.error("Failed to find IDP metadata file in relaying party file '{0}'",
                relyingPartyFile.getAbsolutePath());
    }

    return filePath;
}

From source file:org.gluu.oxtrust.ldap.service.Shibboleth3ConfService.java

public boolean isFederationMetadata(String spMetaDataFN) {
    //TODO: change for IDP3
    if (spMetaDataFN == null) {
        return false;
    }/*from   w ww  . ja va  2s.c  om*/
    File spMetaDataFile = new File(getSpMetadataFilePath(spMetaDataFN));
    InputStream is = null;
    InputStreamReader isr = null;
    Document xmlDocument = null;
    try {
        is = FileUtils.openInputStream(spMetaDataFile);
        isr = new InputStreamReader(is, "UTF-8");
        try {
            xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(isr));
        } catch (Exception ex) {
            log.error("Failed to parse metadata file '{0}'", ex, spMetaDataFile.getAbsolutePath());
        }
    } catch (IOException ex) {
        log.error("Failed to read metadata file '{0}'", ex, spMetaDataFile.getAbsolutePath());
    } finally {
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
    }

    if (xmlDocument == null) {
        return false;
    }

    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();

    String federationTag = null;
    try {
        federationTag = xPath.compile("count(/EntitiesDescriptor)").evaluate(xmlDocument);
    } catch (XPathExpressionException ex) {
        log.error("Failed to find IDP metadata file in relaying party file '{0}'", ex,
                spMetaDataFile.getAbsolutePath());
    }

    return Integer.parseInt(federationTag) > 0;
}

From source file:org.hyperic.hq.plugin.activemq.ActiveMQServerDetector.java

@Override
protected ServerResource createServerResource(String installpath) {
    ServerResource server = super.createServerResource(installpath);
    log.debug("[createServerResource] installpath=" + installpath);
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();

    try {/* w w  w  .ja  v  a 2 s  .  co m*/
        File cfg = new File(installpath, "conf/activemq.xml");
        log.debug("[createServerResource] cfg=" + cfg);
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.parse(cfg);
        String bName = xpath.evaluate("/beans/broker/@brokerName", document);
        System.out.println("bName=" + bName);
        server.setName(server.getName() + " " + bName);
    } catch (Exception ex) {
        log.debug("[createServerResource] Error when looking for the broker name: " + ex.getMessage(), ex);
    }
    return server;
}

From source file:org.hyperic.hq.plugin.jboss7.JBossDetectorBase.java

final ConfigResponse getServerProductConfig(Map<String, String> args) {
    ConfigResponse cfg = new ConfigResponse();
    String port = null;// w ww .ja  v  a  2 s . c om
    String address = null;

    File cfgFile = getConfigFile(args);

    try {
        log.debug("[getProductConfig] cfgFile=" + cfgFile.getCanonicalPath());
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = (Document) dBuilder.parse(cfgFile);

        XPathFactory factory = XPathFactory.newInstance();
        XPathExpression expr = factory.newXPath()
                .compile(getConfigRoot() + "/management/management-interfaces/http-interface");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodeList = (NodeList) result;

        String mgntIf = null;
        for (int i = 0; i < nodeList.getLength(); i++) {
            if (nodeList.item(i).getAttributes().getNamedItem("port") != null) {
                port = nodeList.item(i).getAttributes().getNamedItem("port").getNodeValue();
                mgntIf = nodeList.item(i).getAttributes().getNamedItem("interface").getNodeValue();
            }
        }

        if (mgntIf != null) {
            expr = factory.newXPath()
                    .compile(getConfigRoot() + "/interfaces/interface[@name='" + mgntIf + "']/inet-address");
            result = expr.evaluate(doc, XPathConstants.NODESET);
            nodeList = (NodeList) result;

            for (int i = 0; i < nodeList.getLength(); i++) {
                address = nodeList.item(i).getAttributes().getNamedItem("value").getNodeValue();
            }
        }

        setUpExtraProductConfig(cfg, doc);

    } catch (Exception ex) {
        log.debug("Error discovering the jmx.url : " + ex, ex);
    }

    log.debug("[getProductConfig] address='" + address + "' port='" + port + "'");
    if ((address != null) && (port != null)) {
        cfg.setValue(PORT, port);
        cfg.setValue(ADDR, parseAddress(address, args));
    }
    return cfg;
}

From source file:org.hyperic.hq.plugin.jboss7.JBossHostControllerDetector.java

@Override
void setUpExtraProductConfig(ConfigResponse cfg, Document doc) throws XPathException {
    XPathFactory factory = XPathFactory.newInstance();
    XPathExpression expr = factory.newXPath().compile(getConfigRoot());
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodeList = (NodeList) result;
    String name = nodeList.item(0).getAttributes().getNamedItem("name").getNodeValue();
    cfg.setValue(HOST, name);/*from w w  w .  j a  v  a2 s .c om*/
}

From source file:org.hyperic.hq.plugin.jboss7.JBossManagedDetector.java

private List<String> getServersNames(String config) {
    List<String> names = new ArrayList<String>();
    File cfgFile = new File(config);

    try {// w  w w  .j  a  va2 s  . c  o m
        log.debug("[getServerProductConfig] cfgFile=" + cfgFile.getCanonicalPath());
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = (Document) dBuilder.parse(cfgFile);

        XPathFactory factory = XPathFactory.newInstance();
        XPathExpression expr = factory.newXPath().compile("//host/servers/server");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodeList = (NodeList) result;

        for (int i = 0; i < nodeList.getLength(); i++) {
            names.add(nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue());
        }
    } catch (Exception ex) {
        log.debug("Error discovering the servers names : " + ex, ex);
    }
    return names;
}

From source file:org.hyperic.plugin.vrealize.automation.VRAUtils.java

public static String executeXMLQuery(String xmlPath, File xmlFile) {
    String res = null;/*from   w w  w  . ja v a2 s  .c  o m*/
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = (Document) builder.parse(xmlFile);

        XPathFactory xFactory = XPathFactory.newInstance();
        XPath xpath = xFactory.newXPath();

        res = xpath.evaluate(xmlPath, doc);
    } catch (Exception ex) {
        log.debug("[executeXMLQuery] " + ex, ex);
    }
    return res;
}

From source file:org.iish.visualmets.services.TocDaoImp.java

private XPathExpression getXPathExpression(String xquery) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    // http://www.ibm.com/developerworks/library/x-javaxpathapi.html
    NamespaceContext ns = new NamespaceContext() {

        @Override//from   w w  w  .  j av  a2s. c  o  m
        public String getPrefix(String namespaceURI) {
            throw new UnsupportedOperationException();
        }

        @Override
        public Iterator getPrefixes(String namespaceURI) {
            throw new UnsupportedOperationException();
        }

        @Override
        public String getNamespaceURI(String prefix) {
            final String metsNs = "http://www.loc.gov/METS/";
            if (prefix == null)
                throw new NullPointerException(metsNs);

            if (prefix.equalsIgnoreCase("mets"))
                return metsNs;

            if (prefix.equalsIgnoreCase("xml"))
                return XMLConstants.XML_NS_URI;

            return XMLConstants.NULL_NS_URI;
        }
    };

    //        if ( !namespaceName.equals("") ) {
    xpath.setNamespaceContext(ns);
    //        }
    XPathExpression expr = xpath.compile(xquery);

    return expr;
}

From source file:org.infoscoop.request.filter.GadgetFilter.java

public static byte[] gadget2html(String baseUrl, Document doc, Map<String, String> urlParameters,
        I18NConverter i18n, Locale locale) throws Exception {
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    Boolean specCompair = compareVersion(getModuleVersion(doc));
    String quirks = getQuirks(doc);

    VelocityContext context = new VelocityContext();

    //quirks mode
    context.put("doctype", getDoctype(specCompair, quirks));
    context.put("charset", getCharset(specCompair, quirks));

    context.put("baseUrl", baseUrl);
    context.put("content", replaceContentStr(doc, i18n, urlParameters));

    context.put("widgetId", urlParameters.get(PARAM_MODULE_ID));
    context.put("staticContentURL", urlParameters.get(PARAM_STATIC_CONTENT_URL));
    context.put("hostPrefix", urlParameters.get(PARAM_HOST_PREFIX));
    context.put("tabId", urlParameters.get(PARAM_TAB_ID));
    context.put("gadgetUrl", urlParameters.get("url"));

    // ModulePrefs
    JSONObject req = getRequires(xpath, doc, urlParameters.get("view"));
    context.put("requires", req);

    if (req.has("opensocial-i18n")) {
        String localeName = getLocaleNameForLoadingI18NConstants(locale);
        String dateTimeConstants = DATE_TIME_PATH + localeName + ".js";
        String numberFormatConstants = DATE_NUMBER_PATH + localeName + ".js";

        StringBuilder sb = new StringBuilder();
        try {//from  w  w w. j  a va  2s  . c  om
            sb.append(ResourceLoader.getContent(dateTimeConstants)).append("\n")
                    .append(ResourceLoader.getContent(numberFormatConstants));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new Exception(e);
        }
        context.put("i18nDataConstants", sb.toString());
    } else {
        // Must set blank
        context.put("i18nDataConstants", "");
    }
    context.put("oauthServicesJson", getOAuthServicesJson(xpath, doc));
    context.put("oauth2ServicesJson", getOAuth2ServicesJson(xpath, doc));

    context.put("i18nMsgs", new JSONObject(i18n.getMsgs()));
    context.put("userPrefs", getUserPrefs(urlParameters));
    context.put("dir", i18n.getDirection());

    StringWriter writer = new StringWriter();
    Template template = Velocity.getTemplate("gadget-html.vm", "UTF-8");
    template.merge(context, writer);

    return writer.toString().getBytes("UTF-8");
}