Example usage for org.jdom2 Element getChildText

List of usage examples for org.jdom2 Element getChildText

Introduction

In this page you can find the example usage for org.jdom2 Element getChildText.

Prototype

public String getChildText(final String cname, final Namespace ns) 

Source Link

Document

Returns the textual content of the named child element, or null if there's no such child.

Usage

From source file:no.imr.stox.functions.utils.JDOMUtils.java

public static String getNodeValue(Element node, String nodeName, String missingStr) {
    String res;//from  w ww. j  av a2  s .  c om
    if (node == null) {
        return null;
    }
    Attribute a = node.getAttribute(nodeName);
    if (a != null) {
        res = a.getValue();
    } else {
        res = node.getChildText(nodeName, node.getNamespace());
        if (res == null || res.isEmpty()) {
            res = missingStr;
        }
    }
    return res;
}

From source file:org.apache.marmotta.ucuenca.wk.provider.scopus.ScopusAuthorSearchProvider.java

License:Apache License

@Override
public List<String> parseResponse(String resource, String requestUrl, Model triples, InputStream input,
        String contentType) throws DataRetrievalException {
    log.debug("Request Successful to {0}", requestUrl);
    try {//from   ww  w. j  a v  a  2 s.  co  m
        ValueFactory factory = ValueFactoryImpl.getInstance();
        final Document doc = new SAXBuilder(XMLReaders.NONVALIDATING).build(input);
        Element aux = doc.getRootElement();
        for (Element element : aux.getChildren("entry", aux.getNamespace())) {
            String authorIDParam = element.getChildText("identifier", NAMESPACE_DC);
            String authorURL = element.getChildText("url", NAMESPACE_PRISM);
            ClientConfiguration conf = new ClientConfiguration();
            LDClient ldClient = new LDClient(conf);

            if (authorIDParam != null) {
                Model candidateModel = null;
                String authorUrlResourceCleaned = URLRESOURCE.replace("AuthorIdParam", authorIDParam)
                        .replace("apiKeyParam", apiKeyParam);
                triples.add(factory.createURI(resource), FOAF.MEMBER, factory.createURI(authorURL));

                ClientResponse response = ldClient.retrieveResource(authorUrlResourceCleaned);
                Model authorModel = response.getData();
                if (candidateModel == null) {
                    candidateModel = authorModel;
                } else {
                    candidateModel.addAll(authorModel);
                }

                triples.addAll(candidateModel);

            }

        }

    } catch (IOException e) {
        throw new DataRetrievalException("I/O error while parsing HTML response", e);
    } catch (JDOMException e) {
        throw new DataRetrievalException("could not parse XML response. It is not in proper XML format", e);
    }

    return Collections.emptyList();
}

From source file:org.apache.marmotta.ucuenca.wk.provider.scopus.ScopusPublicationSearchProvider.java

License:Apache License

@Override
public List<String> parseResponse(String resource, String requestUrl, Model triples, InputStream input,
        String contentType) throws DataRetrievalException {
    log.debug("Request Successful to {0}", requestUrl);
    try {//  ww  w  .  j  ava 2  s  . com
        final Document doc = new SAXBuilder(XMLReaders.NONVALIDATING).build(input);
        Element aux = doc.getRootElement();
        boolean ecuatoriano = false;
        for (Element element : aux.getChildren("entry", aux.getNamespace())) {
            if (affiliationEcuador(element.getChildren("affiliation", NAMESPACE_ATOM))) {
                ecuatoriano = true;
                break;
            }
        }
        if (ecuatoriano) {
            for (Element element : aux.getChildren("entry", aux.getNamespace())) {
                String abstractDoiParam = element.getChildText("doi", NAMESPACE_PRISM);
                String abstractURLParam = element.getChildText("url", NAMESPACE_PRISM);
                String abstractAbstractParam = element.getChildText("description", NAMESPACE_DC);
                List<String> creatorsList = new ArrayList<>();
                List<Element> creators = element.getChildren("author", NAMESPACE_ATOM);
                for (Element author : creators) {
                    creatorsList.add(author.getChildText("author-url", NAMESPACE_ATOM));
                }

                ClientConfiguration conf = new ClientConfiguration();
                LDClient ldClient = new LDClient(conf);
                if (abstractDoiParam != null) {
                    Model candidateModel = null;
                    String authorUrlResourceCleaned = URL_RESOURCE_PUBLICATION
                            .replace("DOIParam", abstractDoiParam).replace("apiKeyParam", apiKeyParam);

                    ClientResponse response = ldClient.retrieveResource(authorUrlResourceCleaned);
                    ValueFactory factory = ValueFactoryImpl.getInstance();
                    triples.add(
                            factory.createURI(
                                    "http://api.elsevier.com/content/author/author_id/" + authorIdParam),
                            FOAF.PUBLICATIONS, factory.createURI(abstractURLParam));
                    if (abstractAbstractParam != null) {
                        triples.add(factory.createStatement(factory.createURI(abstractURLParam),
                                factory.createURI("http://purl.org/ontology/bibo/abstract"),
                                factory.createLiteral(abstractAbstractParam)));
                    }
                    for (String uriCreator : creatorsList) {
                        triples.add(factory.createStatement(factory.createURI(abstractURLParam),
                                factory.createURI("http://purl.org/dc/terms/contributor"),
                                factory.createURI(uriCreator)));

                    }
                    Model authorModel = response.getData();
                    if (candidateModel == null) {
                        candidateModel = authorModel;
                    } else {
                        candidateModel.addAll(authorModel);
                    }
                    triples.addAll(candidateModel);

                }

            }
        }
    } catch (IOException e) {
        throw new DataRetrievalException("I/O error while parsing HTML response", e);
    } catch (JDOMException e) {
        throw new DataRetrievalException("could not parse XML response. It is not in proper XML format", e);
    }
    return Collections.emptyList();
}

From source file:org.apache.marmotta.ucuenca.wk.provider.scopus.ScopusPublicationSearchProvider.java

License:Apache License

private boolean affiliationEcuador(List<Element> affiliations) {
    boolean ecuadorian = false;

    for (Element affiliation : affiliations) {
        if (affiliation.getChildText("affiliation-country", NAMESPACE_ATOM).equalsIgnoreCase("ecuador")) {
            ecuadorian = true;/*w w  w .ja  va 2  s  .c o  m*/
            break;
        }
    }

    return ecuadorian;
}

From source file:org.artifactory.repo.remote.browse.S3RepositoryBrowser.java

License:Open Source License

/**
 * Detects the bucket url (i.e., root url). The given url is assumed to either point to the root or to "directory"
 * under the root. The most reliable way to get the root is to request non-existing resource and analyze the response.
 *
 * @param url URL to S3 repository/*from  www.  j a  v a  2 s  .com*/
 * @return The root url of the repository (the bucket)
 */
String detectRootUrl(String url) throws IOException {
    //noinspection RedundantStringConstructorCall
    String copyUrl = new String(url); //defense

    // force non-directory copyUrl. S3 returns 200 for directory paths
    url = url.endsWith("/") ? StringUtils.removeEnd(url, "/") : url;
    // generate a random string to force 404
    String randomString = RandomStringUtils.randomAlphanumeric(16);
    url = url + "/" + randomString;
    HttpGet method = new HttpGet(url);
    try (CloseableHttpResponse response = client.executeMethod(method)) {
        // most likely to get 404 if the repository exists
        assertSizeLimit(url, response);
        String responseString = IOUtils.toString(HttpUtils.getResponseBody(response), Charsets.UTF_8.name());
        log.debug("Detect S3 root url got response code {} with content: {}",
                response.getStatusLine().getStatusCode(), responseString);
        Document doc = XmlUtils.parse(responseString);
        Element root = doc.getRootElement();
        String errorCode = root.getChildText("Code", root.getNamespace());
        if (ERROR_CODE_NOSUCHKEY.equals(errorCode)) {
            String relativePath = root.getChildText("Key", root.getNamespace());
            rootUrl = StringUtils.removeEnd(url, relativePath);
        } else if (INVALID_ARGUMENT.equals(errorCode)) {
            if (isPro()) {
                String message = root.getChildText("Message");
                if (UNSUPPORTED_AUTHORIZATION_TYPE.equals(message)) {
                    rootUrl = detectRootUrlSecured(copyUrl);
                }
            } else {
                log.warn("Browsing secured S3 requires Artifactory Pro"); //TODO [mamo] should inform otherwise?
            }
        } else {
            throw new IOException("Couldn't detect S3 root URL. Unknown error code: " + errorCode);
        }
    }
    log.debug("Detected S3 root URL: {}", rootUrl);
    return rootUrl;
}

From source file:org.artifactory.repo.remote.browse.S3RepositoryBrowser.java

License:Open Source License

@SuppressWarnings({ "unchecked" })
private List<RemoteItem> parseResponse(String content) {
    List<RemoteItem> items = Lists.newArrayList();
    Document document = XmlUtils.parse(content);
    Element root = document.getRootElement();
    Namespace ns = root.getNamespace();
    String prefix = root.getChildText("Prefix", ns);

    // retrieve folders
    List<Element> folders = root.getChildren("CommonPrefixes", ns);
    for (Element folder : folders) {
        String directoryPath = folder.getChildText("Prefix", ns);
        String folderName = StringUtils.removeStart(directoryPath, prefix);
        if (StringUtils.isNotBlank(folderName)) {
            if (secured) {
                directoryPath = StringUtils.removeStart(directoryPath, getPrefix(rootUrl));
            }//from  w ww  . j a v  a2 s .  c  o m
            items.add(new RemoteItem(rootUrl + directoryPath, true));
        }
    }

    // retrieve files
    List<Element> files = root.getChildren("Contents", ns);
    for (Element element : files) {
        String filePath = element.getChildText("Key", ns);
        String fileName = StringUtils.removeStart(filePath, prefix);
        if (StringUtils.isNotBlank(fileName) && !folderDirectoryWithSameNameExists(fileName, items)) {
            // the date format is of the form yyyy-mm-ddThh:mm:ss.timezone, e.g., 2009-02-03T16:45:09.000Z
            String sizeStr = element.getChildText("Size", ns);
            long size = sizeStr == null ? 0 : Long.parseLong(sizeStr);
            String lastModifiedStr = element.getChildText("LastModified", ns);
            long lastModified = lastModifiedStr == null ? 0
                    : ISODateTimeFormat.dateTime().parseMillis(lastModifiedStr);
            if (secured) {
                RemoteItem remoteItem = new RemoteItem(rootUrl + filePath, false, size, lastModified);
                String filePath2 = StringUtils.removeStart(filePath, getPrefix(rootUrl));
                String url = rootUrl + filePath2;
                String securedPath = buildSecuredS3RequestUrl(url, httpRepo, getPrefix(url));
                remoteItem.setEffectiveUrl(securedPath);
                items.add(remoteItem);
            } else {
                items.add(new RemoteItem(rootUrl + filePath, false, size, lastModified));
            }
        }
    }

    return items;
}

From source file:org.artifactory.version.converter.SnapshotUniqueVersionConverter.java

License:Open Source License

@Override
public void convert(Document doc) {
    Element root = doc.getRootElement();
    Namespace ns = root.getNamespace();

    List localRepos = root.getChild("localRepositories", ns).getChildren();
    for (Object localRepo1 : localRepos) {
        Element localRepo = (Element) localRepo1;
        Element snapshotBehavior = localRepo.getChild("useSnapshotUniqueVersions", ns);
        if (snapshotBehavior != null) {
            // rename the element
            snapshotBehavior.setName("snapshotVersionBehavior");
            String repoKey = localRepo.getChildText("key", ns);
            log.debug(//from   ww  w. j  a  v  a2 s .co  m
                    "Renamed element 'useSnapshotUniqueVersions' to " + "'snapshotVersionBehavior' for repo {}",
                    repoKey);

            // change the element value
            if (snapshotBehavior.getText().equals("true")) {
                log.debug("Changed value 'true' to 'deployer' for repo {}", repoKey);
                snapshotBehavior.setText("deployer");
            } else if (snapshotBehavior.getText().equals("false")) {
                log.debug("Changed value 'false' to 'non-unique' for repo {}", repoKey);
                snapshotBehavior.setText("non-unique");
            }
        }
    }
}

From source file:org.artifactory.version.converter.v110.SnapshotNonUniqueValueConverter.java

License:Open Source License

@Override
public void convert(Document doc) {
    Element root = doc.getRootElement();
    Namespace ns = root.getNamespace();

    List localRepos = root.getChild("localRepositories", ns).getChildren();
    for (Object localRepo1 : localRepos) {
        Element localRepo = (Element) localRepo1;
        Element snapshotBehavior = localRepo.getChild("snapshotVersionBehavior", ns);
        if (snapshotBehavior != null && "nonunique".equals(snapshotBehavior.getText())) {
            log.debug("Changing value 'nonunique' to 'non-unique' for repo {}",
                    localRepo.getChildText("key", ns));
            snapshotBehavior.setText("non-unique");
        }/*from www . j  a v  a 2s .  c om*/
    }
}

From source file:org.artifactory.version.converter.v132.LdapListConverter.java

License:Open Source License

@Override
public void convert(Document doc) {
    Element root = doc.getRootElement();
    Namespace ns = root.getNamespace();

    Element security = root.getChild("security", ns);
    if (security == null) {
        log.debug("No security settings defned");
        return;//  w  ww. j ava  2  s .c  o  m
    }

    Element oldLdapSettings = security.getChild("ldapSettings", ns);
    if (oldLdapSettings == null) {
        log.debug("No ldap settings configured");
        return;
    }

    int location = security.indexOf(oldLdapSettings);
    security.removeContent(oldLdapSettings);

    Element ldapSettings = new Element("ldapSettings", ns);
    security.addContent(location, ldapSettings);

    String ldapUrl = oldLdapSettings.getChildText("ldapUrl", ns);

    // manager dn and password only relevant for search based authentications
    String managerDn = oldLdapSettings.getChildText("managerDn", ns);
    String managerPassword = oldLdapSettings.getChildText("managerPassword", ns);

    // convert authentication patterns
    Element authPatternsElement = oldLdapSettings.getChild("authenticationPatterns", ns);
    List authPatterns = authPatternsElement.getChildren("authenticationPattern", ns);
    log.debug("Found {} patterns to convert" + authPatterns.size());

    // create new ldap setting for each authentication pattern
    int ldapKeyIndex = 1;
    for (Object pattern : authPatterns) {
        Element authPattern = (Element) pattern;

        Element ldapSetting = new Element("ldapSetting", ns);
        ldapSettings.addContent(ldapSetting);

        // add the key
        ldapSetting.addContent(createTextElement("key", ns, "ldap" + ldapKeyIndex++));

        // set enabled true
        ldapSetting.addContent(createTextElement("enabled", ns, "true"));

        // add the ldap url
        ldapSetting.addContent(createTextElement("ldapUrl", ns, ldapUrl));

        // add user dn if not empty
        String userDn = authPattern.getChildText("userDnPattern", ns);
        if (userDn != null) {
            ldapSetting.addContent(createTextElement("userDnPattern", ns, userDn));
        }

        // create and add search element if search filter exists
        String searchFilter = authPattern.getChildText("searchFilter", ns);
        if (searchFilter != null) {
            Element search = new Element("search", ns);
            ldapSetting.addContent(search);

            search.addContent(createTextElement("searchFilter", ns, searchFilter));

            String searchBase = authPattern.getChildText("searchBase", ns);
            if (searchBase != null) {
                search.addContent(createTextElement("searchBase", ns, searchBase));
            }

            String searchSubTree = authPattern.getChildText("searchSubTree", ns);
            if (searchSubTree != null) {
                search.addContent(createTextElement("searchSubTree", ns, searchSubTree));
            }

            if (managerDn != null) {
                search.addContent(createTextElement("managerDn", ns, managerDn));
            }

            if (managerPassword != null) {
                search.addContent(createTextElement("managerPassword", ns, managerPassword));
            }
        }
    }
}

From source file:org.artifactory.version.converter.v152.BlackDuckProxyConverter.java

License:Open Source License

@Override
public void convert(Document doc) {
    log.info("Converting BlackDuck intergration proxy settings");
    Element rootElement = doc.getRootElement();
    Namespace namespace = rootElement.getNamespace();

    Element defaultProxy = findDefaultProxy(rootElement, namespace);
    Element externalProviders = rootElement.getChild("externalProviders", namespace);
    if (externalProviders == null) {
        return;//from   w  w  w  . j  a va2  s. c om
    }
    Element blackDuckConf = externalProviders.getChild("blackduck", namespace);
    if (defaultProxy != null && blackDuckConf != null) {
        if (blackDuckConf.getChild("proxyRef") != null) {
            return;
        }
        Element proxyTag = new Element("proxyRef", namespace);
        proxyTag.setText(defaultProxy.getChildText("key", namespace));
        blackDuckConf.addContent(proxyTag);
    }
}