Example usage for org.apache.commons.lang3 StringUtils trimToNull

List of usage examples for org.apache.commons.lang3 StringUtils trimToNull

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils trimToNull.

Prototype

public static String trimToNull(final String str) 

Source Link

Document

Removes control characters (char <= 32) from both ends of this String returning null if the String is empty ("") after the trim or if it is null .

Usage

From source file:org.gbif.pubindex.service.impl.ArticleIndexerImpl.java

private String headContentType(String url) {
    // execute head request
    HttpHead req = new HttpHead(url);
    try {/*from  ww w  .ja  v a 2s .c  om*/
        HttpResponse response = client.execute(req);
        Header ct = response.getFirstHeader("Content-Type");
        return ct == null ? null : StringUtils.trimToNull(ct.getValue());
    } catch (Exception e) {
        LOG.warn("Head request for article {} failed: {}", url, e.getMessage());
    }
    return null;
}

From source file:org.gbif.pubindex.service.impl.ArticleIndexerImpl.java

private void findNamesInText(List<NameFound> names, String text, NameFound.Source source, Article article) {
    if (StringUtils.isBlank(text)) {
        LOG.debug("No text in {}", source);
    } else {//  ww  w .  ja va 2 s  .c o m
        // call taxon finder service
        Map<String, String> params = new HashMap<String, String>();
        params.put("input", text);
        params.put("type", "text");
        params.put("format", "json");
        try {
            HttpUtil.Response resp = http.post(finderWS, HttpUtil.map2Entity(params));
            LOG.debug("Names found in {} : {}", source, resp.content);

            Map<String, Object> json = mapper.readValue(resp.content, Map.class);
            List<Map<String, ?>> jsonNames = (List<Map<String, ?>>) json.get("names");
            for (Map<String, ?> n : jsonNames) {
                String sciname = StringUtils.trimToNull((String) n.get("scientificName"));
                if (sciname != null) {
                    NameFound name = new NameFound();
                    name.setArticleId(article.getId());
                    name.setSource(source);
                    name.setName(cleanTfArtifacts(sciname));
                    name.setNameVerbatim(StringUtils.trimToNull((String) n.get("verbatim")));
                    name.setNovum(false);
                    // require at least binomials - we'll use a lower confidence for monomials but still store them
                    if (sciname.contains(" ")) {
                        name.setConfidence(0);
                    } else {
                        name.setConfidence(1);
                    }
                    name.setOffsetStart((Integer) n.get("offsetStart"));
                    name.setOffsetEnd((Integer) n.get("offsetEnd"));
                    names.add(name);
                }
            }

        } catch (URISyntaxException e) {
            // wont happen :)
        } catch (Exception e) {
            LOG.error("Problem calling name finder: {}", e);
        }
    }
}

From source file:org.gbif.pubindex.service.impl.FeedParserRome.java

private Article handleFeedItem(SyndEntry item, String feedTitle) {
    Article a = new Article();

    a.setTitle(StringUtils.trimToNull(item.getTitle()));
    a.setUrl(StringUtils.trimToNull(item.getLink()));
    a.setAuthors(concat(item.getAuthors()));
    a.setKeywords(concatCategories(item.getCategories()));

    a.setPublishedDate(item.getPublishedDate());
    a.setPublishedIn(StringUtils.trimToNull(feedTitle));
    if (item.getDescription() != null) {
        a.setDescription(StringUtils.trimToNull(item.getDescription().getValue()));
    }// w  w  w .  ja va2  s.  c o m
    String guid = StringUtils.trimToNull(item.getUri());
    // dont trust BioStor UUIDs as they change all the time
    if (guid == null || guid.startsWith("urn:uuid")) {
        // if no guid was given use the link
        guid = StringUtils.trimToNull(item.getLink());
        if (guid == null) {
            // last resort use the hascode for the entire item
            guid = "" + item.hashCode();
        }
    }
    a.setGuid(guid);
    // check if url or guid containts a doi
    a.setDoi(findDOI(guid, a.getUrl()));

    // parse prism module
    PrismModule prism = (PrismModule) item.getModule(PrismModule.URI);
    if (prism != null) {
        if (prism.getDoi() != null) {
            a.setDoi(prism.getDoi());
        }
    }
    return a;
}

From source file:org.gbif.pubindex.service.impl.FeedParserRome.java

protected static String concat(List objs) {
    StringBuilder keywords = new StringBuilder();
    boolean first = true;
    for (Object cat : objs) {
        if (cat != null) {
            if (!first) {
                keywords.append("; ");
            }// ww  w .  j a  v a 2 s.c  o m
            keywords.append(cat.toString());
            first = false;
        }
    }
    return StringUtils.trimToNull(keywords.toString());
}

From source file:org.gbif.pubindex.service.impl.FeedParserRome.java

protected static String concatCategories(List<SyndCategoryImpl> objs) {
    StringBuilder keywords = new StringBuilder();
    boolean first = true;
    for (Object cat : objs) {
        if (cat != null) {
            if (!first) {
                keywords.append("; ");
            }/*from w w w .  java2  s. co  m*/
            keywords.append(((SyndCategoryImpl) cat).getName());
            first = false;
        }
    }
    return StringUtils.trimToNull(keywords.toString());
}

From source file:org.haiku.haikudepotserver.api1.RepositoryApiImpl.java

@Override
public CreateRepositorySourceMirrorResult createRepositorySourceMirror(
        CreateRepositorySourceMirrorRequest request) throws ObjectNotFoundException {
    Preconditions.checkArgument(null != request, "the request must be supplied");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(request.repositorySourceCode),
            "the code for the new repository source mirror");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(request.countryCode),
            "the country code should be supplied");

    final ObjectContext context = serverRuntime.newContext();

    Country country = Country.tryGetByCode(context, request.countryCode)
            .orElseThrow(() -> new ObjectNotFoundException(Country.class.getSimpleName(), request.countryCode));
    RepositorySource repositorySource = RepositorySource.tryGetByCode(context, request.repositorySourceCode)
            .orElseThrow(() -> new ObjectNotFoundException(RepositorySource.class.getSimpleName(),
                    request.repositorySourceCode));

    if (!authorizationService.check(context, tryObtainAuthenticatedUser(context).orElse(null),
            repositorySource.getRepository(), Permission.REPOSITORY_EDIT)) {
        throw new AuthorizationFailureException();
    }//from   w w  w  .  j a  v a2  s .c  o m

    // if there is no other mirror then this should be the primary.

    RepositorySourceMirror mirror = context.newObject(RepositorySourceMirror.class);
    mirror.setIsPrimary(!repositorySource.tryGetPrimaryMirror().isPresent());
    mirror.setBaseUrl(request.baseUrl);
    mirror.setRepositorySource(repositorySource);
    mirror.setCountry(country);
    mirror.setDescription(StringUtils.trimToNull(request.description));
    mirror.setCode(UUID.randomUUID().toString());

    repositorySource.getRepository().setModifyTimestamp();
    context.commitChanges();

    LOGGER.info("did add mirror [{}] to repository source [{}]", country.getCode(), repositorySource.getCode());

    CreateRepositorySourceMirrorResult result = new CreateRepositorySourceMirrorResult();
    result.code = mirror.getCode();
    return result;
}

From source file:org.haiku.haikudepotserver.api1.RepositoryApiImpl.java

@Override
public UpdateRepositorySourceMirrorResult updateRepositorySourceMirror(
        UpdateRepositorySourceMirrorRequest request) throws ObjectNotFoundException {
    Preconditions.checkArgument(null != request, "the request must be supplied");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(request.code), "the code for the mirror to update");

    final ObjectContext context = serverRuntime.newContext();

    RepositorySourceMirror repositorySourceMirror = RepositorySourceMirror.tryGetByCode(context, request.code)
            .orElseThrow(() -> new ObjectNotFoundException(RepositorySourceMirror.class.getSimpleName(),
                    request.code));//  w  w w .  ja  va2s.c  o  m

    if (!authorizationService.check(context, tryObtainAuthenticatedUser(context).orElse(null),
            repositorySourceMirror.getRepositorySource().getRepository(), Permission.REPOSITORY_EDIT)) {
        throw new AuthorizationFailureException();
    }

    for (UpdateRepositorySourceMirrorRequest.Filter filter : CollectionUtils.emptyIfNull(request.filter)) {
        switch (filter) {
        case ACTIVE:
            if (repositorySourceMirror.getIsPrimary()) {
                throw new ValidationException(
                        new ValidationFailure(RepositorySourceMirror.ACTIVE.getName(), "confict"));
            }
            repositorySourceMirror.setActive(null != request.active && request.active);
            break;
        case BASE_URL:
            repositorySourceMirror.setBaseUrl(request.baseUrl);
            break;
        case COUNTRY:
            Country country = Country.tryGetByCode(context, request.countryCode).orElseThrow(
                    () -> new ObjectNotFoundException(Country.class.getSimpleName(), request.countryCode));
            repositorySourceMirror.setCountry(country);
            break;
        case IS_PRIMARY:
            boolean isPrimary = null != request.isPrimary && request.isPrimary;

            if (isPrimary != repositorySourceMirror.getIsPrimary()) {
                if (isPrimary) {
                    // in this case, the former primary should loose it's primary
                    // status so that it can be swapped to this one.
                    repositorySourceMirror.getRepositorySource().getPrimaryMirror().setIsPrimary(false);
                    repositorySourceMirror.setIsPrimary(true);
                } else {
                    throw new ValidationException(
                            new ValidationFailure(RepositorySourceMirror.IS_PRIMARY.getName(), "confict"));
                }
            }
            break;
        case DESCRIPTION:
            repositorySourceMirror.setDescription(StringUtils.trimToNull(request.description));
            break;
        default:
            throw new IllegalStateException("unknown change filter for mirror [" + filter + "]");
        }
    }

    if (context.hasChanges()) {
        repositorySourceMirror.getRepositorySource().getRepository().setModifyTimestamp();
    }

    context.commitChanges();
    LOGGER.info("did update mirror [{}]", repositorySourceMirror.getCode());
    return new UpdateRepositorySourceMirrorResult();
}

From source file:org.haiku.haikudepotserver.repository.job.RepositoryHpkrIngressJobRunner.java

/**
 * <p>Each repository has a little &quot;repo.info&quot; file that resides next to the HPKR data.
 * This method will pull this in and process the data into the repository source.</p>
 *///from   ww  w .  j  a v a  2  s .  c  o  m

private void runImportInfoForRepositorySource(ObjectContext mainContext, RepositorySource repositorySource)
        throws RepositoryHpkrIngressException {
    URL url = repositorySource.tryGetDownloadRepoInfoURL()
            .orElseThrow(() -> new RepositoryHpkrIngressException("unable to download for ["
                    + repositorySource.getCode() + "] as no download repo info url was available"));

    // now shift the URL's data into a temporary file and then process it.
    File temporaryFile = null;

    try {
        temporaryFile = File.createTempFile(repositorySource.getCode() + "__import", ".repo-info");

        LOGGER.info("will copy data for repository info [{}] ({}) to temporary file", repositorySource,
                url.toString());

        FileHelper.streamUrlDataToFile(url, temporaryFile, TIMEOUT_REPOSITORY_SOURCE_FETCH);

        try (InputStream inputStream = new FileInputStream(temporaryFile);
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charsets.UTF_8);
                BufferedReader reader = new BufferedReader(inputStreamReader)) {
            String urlParameterValue = DriverSettings.parse(reader).stream()
                    .filter(p -> p.getName().equals(PARAMETER_NAME_URL))
                    .filter(p -> CollectionUtils.isNotEmpty(p.getValues())).findAny()
                    .map(v -> StringUtils.trimToNull(v.getValues().get(0)))
                    .orElseThrow(() -> new DriverSettingsException(
                            "the 'repo.info' file is expected to have " + "a [" + PARAMETER_NAME_URL
                                    + "] entry as identifier, but this appears to be " + "missing"));

            if (!Objects.equals(urlParameterValue, repositorySource.getUrl())) {
                LOGGER.info("updated the repo info url to [{}] for repository source [{}]", urlParameterValue,
                        repositorySource.getCode());
                repositorySource.setUrl(urlParameterValue);
                repositorySource.getRepository().setModifyTimestamp();
                mainContext.commitChanges();
            }

        }
    } catch (IOException | DriverSettingsException e) {
        throw new RepositoryHpkrIngressException(
                "a problem has arisen parsing or dealing with the 'repo.info' file", e);
    } finally {
        if (null != temporaryFile && temporaryFile.exists()) {
            if (!temporaryFile.delete()) {
                LOGGER.error("unable to delete the file; {}" + temporaryFile.getAbsolutePath());
            }
        }

    }

}

From source file:org.hawkular.client.test.BaseTest.java

private URI getEndpointFromEnv() throws URISyntaxException {
    String endpoint = System.getenv("HAWKULAR_ENDPOINT");
    if (StringUtils.trimToNull(endpoint) == null) {
        Reporter.log("HAWKULAR_ENDPOINT env not defined. Defaulting to 'localhost'");
        endpoint = "http://localhost:8080";
    }//from  w  w  w .j  av  a 2s.com

    return new URI(endpoint);
}

From source file:org.hawkular.client.test.BaseTest.java

private String getUsername() {
    String username = System.getenv("HAWKULAR_USER");
    if (StringUtils.trimToNull(username) == null) {
        Reporter.log("HAWKULAR_USER env not defined. Defaulting to 'jdoe'");
        username = "jdoe";
    }/*from w  w w.ja v a2s  .c  om*/

    return username;
}