Example usage for java.util Optional isPresent

List of usage examples for java.util Optional isPresent

Introduction

In this page you can find the example usage for java.util Optional isPresent.

Prototype

public boolean isPresent() 

Source Link

Document

If a value is present, returns true , otherwise false .

Usage

From source file:net.sf.jabref.logic.fetcher.ScienceDirect.java

@Override
public Optional<URL> findFullText(BibEntry entry) throws IOException {
    Objects.requireNonNull(entry);
    Optional<URL> pdfLink = Optional.empty();

    // Try unique DOI first
    Optional<DOI> doi = DOI.build(entry.getField("doi"));

    if (doi.isPresent()) {
        // Available in catalog?
        try {//from w w w. j a  va 2  s.c  o  m
            String sciLink = getUrlByDoi(doi.get().getDOI());

            if (!sciLink.isEmpty()) {
                // Retrieve PDF link
                Document html = Jsoup.connect(sciLink).ignoreHttpErrors(true).get();
                Element link = html.getElementById("pdfLink");

                if (link != null) {
                    LOGGER.info("Fulltext PDF found @ ScienceDirect.");
                    pdfLink = Optional.of(new URL(link.attr("pdfurl")));
                }
            }
        } catch (UnirestException e) {
            LOGGER.warn("ScienceDirect API request failed", e);
        }
    }
    return pdfLink;
}

From source file:io.kamax.mxisd.lookup.provider.ForwarderProvider.java

@Override
public Optional<SingleLookupReply> find(SingleLookupRequest request) {
    for (String label : cfg.getServers()) {
        for (String srv : mxCfg.getIdentity().getServers(label)) {
            log.info("Using forward server {}", srv);
            Optional<SingleLookupReply> answer = fetcher.find(srv, request);
            if (answer.isPresent()) {
                return answer;
            }//from  w  w w .j  a v  a 2  s  .c om
        }
    }

    return Optional.empty();
}

From source file:org.obiba.mica.micaConfig.rest.DataAccessResource.java

@GET
@Path("/form")
@Timed//from w ww . java  2s  .  com
public Mica.DataAccessFormDto getDataAccessForm(@QueryParam("lang") String lang) {
    Optional<DataAccessForm> d = dataAccessFormService.find();

    if (!d.isPresent())
        throw NoSuchDataAccessFormException.withDefaultMessage();

    DataAccessForm dataAccessForm = d.get();
    Mica.DataAccessFormDto.Builder builder = Mica.DataAccessFormDto.newBuilder(dtos.asDto(dataAccessForm))
            .clearProperties().clearPdfTemplates();

    String langTag = !Strings.isNullOrEmpty(lang) ? Locale.forLanguageTag(lang).toLanguageTag()
            : LanguageTag.UNDETERMINED;

    Map<String, LocalizedString> properties = dataAccessForm.getProperties().entrySet().stream()
            .map(e -> Maps.immutableEntry(e.getKey(),
                    new LocalizedString().forLanguageTag(langTag, e.getValue().get(langTag))))
            .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

    builder.addAllProperties(dtos.asDtoList(properties));

    return builder.build();
}

From source file:se.omegapoint.facepalm.application.FriendService.java

public void addFriend(final String username, final String friendUsername) {
    notBlank(username);//from w w w.java 2s. co  m
    notBlank(friendUsername);

    final Optional<User> user = getUser(username);
    final Optional<User> friend = getUser(friendUsername);

    if (user.isPresent() && friend.isPresent()) {
        userRepository.addFriend(user.get().username, friend.get().username);
    }
}

From source file:io.github.retz.db.Jobs.java

public void doRetry(List<Integer> ids) {
    try {/*w w  w  .j a v  a 2  s . co  m*/
        for (int id : ids) {
            Optional<Job> maybeJob = getJob(id);
            if (maybeJob.isPresent()) {
                Job job = maybeJob.get();
                job.doRetry();
                updateJob(job);
            }
        }
    } catch (SQLException e) {
        LOG.error(e.toString());
    } catch (IOException e) {
        LOG.error(e.toString()); // TODO: do we fail?
    }
}

From source file:alfio.manager.EventNameManager.java

/**
 * Generates and returns a short name based on the given display name.<br>
 * The generated short name will be returned only if it was not already used.<br>
 * The input parameter will be clean from "evil" characters such as punctuation and accents
 *
 * 1) if the {@code displayName} is a one-word name, then no further calculation will be done and it will be returned as it is, to lower case
 * 2) the {@code displayName} will be split by word and transformed to lower case. If the total length is less than 15, then it will be joined using "-" and returned
 * 3) the first letter of each word will be taken, excluding numbers
 * 4) a random code will be returned//  www  .j av a  2  s.  c om
 *
 * @param displayName
 * @return
 */
public String generateShortName(String displayName) {
    Validate.isTrue(StringUtils.isNotBlank(displayName));
    String cleanDisplayName = StringUtils.stripAccents(StringUtils.normalizeSpace(displayName))
            .toLowerCase(Locale.ENGLISH).replaceAll(FIND_EVIL_CHARACTERS, "-");
    if (!StringUtils.containsWhitespace(cleanDisplayName) && isUnique(cleanDisplayName)) {
        return cleanDisplayName;
    }
    Optional<String> dashedName = getDashedName(cleanDisplayName);
    if (dashedName.isPresent()) {
        return dashedName.get();
    }
    Optional<String> croppedName = getCroppedName(cleanDisplayName);
    if (croppedName.isPresent()) {
        return croppedName.get();
    }
    return generateRandomName();
}

From source file:com.fredhopper.core.connector.index.generate.validator.ListAttributeValidator.java

@Override
protected boolean hasValidValueId(final FhAttributeData attribute, final List<Violation> violations) {
    final Table<Optional<String>, Optional<Locale>, String> values = attribute.getValues();
    for (final Optional<String> optional : values.rowKeySet()) {
        final String key = optional == null || !optional.isPresent() ? "_absent_" : optional.get();
        if (!key.matches(VALUE_ID_PATTERN)) {
            rejectValue(attribute, violations, "The \"list\" attribute valueId key \"" + key
                    + "\" does not match the appropriate pattern.");
            return false;
        }//from  w  w  w  . j  ava  2s  . co m
    }
    return true;
}

From source file:org.camunda.bpm.spring.boot.starter.configuration.impl.custom.EnterLicenseKeyConfiguration.java

@Override
public void postProcessEngineBuild(ProcessEngine processEngine) {
    if (!version.isEnterprise()) {
        return;// www.  j  a v a2s  . co  m
    }

    URL fileUrl = camundaBpmProperties.getLicenseFile();

    Optional<String> licenseKey = readLicenseKeyFromUrl(fileUrl);
    if (!licenseKey.isPresent()) {
        fileUrl = EnterLicenseKeyConfiguration.class.getClassLoader().getResource(defaultLicenseFile);
        licenseKey = readLicenseKeyFromUrl(fileUrl);
    }

    if (!licenseKey.isPresent()) {
        return;
    }

    try (Connection connection = dataSource(processEngine).getConnection()) {
        if (readLicenseKeyFromDatasource(connection).isPresent()) {
            return;
        }
        try (PreparedStatement statement = connection.prepareStatement(getSql(INSERT_SQL))) {
            statement.setString(1, licenseKey.get());
            statement.execute();
            LOG.enterLicenseKey(fileUrl);
        }
    } catch (SQLException ex) {
        throw new CamundaBpmNestedRuntimeException(ex.getMessage(), ex);
    }
}

From source file:com.spotify.styx.api.StyxConfigResource.java

private Response<StyxConfig> patchStyxConfig(Request request) {
    final Optional<String> enabledParameter = request.parameter("enabled");
    if (!enabledParameter.isPresent()) {
        return Response.forStatus(Status.BAD_REQUEST.withReasonPhrase("Missing 'enabled' query parameter"));
    }//w  w w . j a va 2s.co  m

    final boolean enabled = Boolean.parseBoolean(enabledParameter.get());

    try {
        storage.setGlobalEnabled(enabled);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

    return Response.forPayload(StyxConfig.create(enabled));
}

From source file:com.fredhopper.core.connector.index.generate.validator.SetAttributeValidator.java

@Override
protected boolean hasValidValueId(final FhAttributeData attribute, final List<Violation> violations) {
    final Table<Optional<String>, Optional<Locale>, String> values = attribute.getValues();
    for (final Optional<String> optional : values.rowKeySet()) {
        final String key = optional == null || !optional.isPresent() ? "_absent_" : optional.get();
        if (!key.matches(VALUE_ID_PATTERN)) {
            rejectValue(attribute, violations, "The \"set\" attribute valueId key \"" + key
                    + "\" does not match the appropriate pattern.");
            return false;
        }/*from   w  ww  .  j av a  2 s .com*/
    }
    return true;
}