Example usage for java.util Optional ifPresent

List of usage examples for java.util Optional ifPresent

Introduction

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

Prototype

public void ifPresent(Consumer<? super T> action) 

Source Link

Document

If a value is present, performs the given action with the value, otherwise does nothing.

Usage

From source file:nu.yona.server.ThymeleafConfigurationTest.java

private String buildEmailSubject(Optional<Locale> locale) {
    Context ctx = ThymeleafUtil.createContext();
    locale.ifPresent(l -> ctx.setLocale(l));

    return emailTemplateEngine.process("buddy-invitation-subject.txt", ctx);
}

From source file:net.sf.jabref.gui.ClipBoardManager.java

public List<BibEntry> extractBibEntriesFromClipboard() {
    // Get clipboard contents, and see if TransferableBibtexEntry is among the content flavors offered
    Transferable content = CLIPBOARD.getContents(null);

    List<BibEntry> result = new ArrayList<>();
    if (content.isDataFlavorSupported(TransferableBibtexEntry.entryFlavor)) {
        // We have determined that the clipboard data is a set of entries.
        try {/*from   w  ww  . j  ava  2 s  .  c  o  m*/
            result = (List<BibEntry>) content.getTransferData(TransferableBibtexEntry.entryFlavor);
        } catch (UnsupportedFlavorException | ClassCastException ex) {
            LOGGER.warn("Could not paste this type", ex);
        } catch (IOException ex) {
            LOGGER.warn("Could not paste", ex);
        }
    } else if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        try {
            String data = (String) content.getTransferData(DataFlavor.stringFlavor);
            // fetch from doi
            if (DOI.build(data).isPresent()) {
                LOGGER.info("Found DOI in clipboard");
                Optional<BibEntry> entry = new DOItoBibTeXFetcher().getEntryFromDOI(new DOI(data).getDOI());
                entry.ifPresent(result::add);
            } else {
                // parse bibtex string
                BibtexParser bp = new BibtexParser(new StringReader(data));
                BibDatabase db = bp.parse().getDatabase();
                LOGGER.info("Parsed " + db.getEntryCount() + " entries from clipboard text");
                if (db.hasEntries()) {
                    result = db.getEntries();
                }
            }
        } catch (UnsupportedFlavorException ex) {
            LOGGER.warn("Could not parse this type", ex);
        } catch (IOException ex) {
            LOGGER.warn("Data is no longer available in the requested flavor", ex);
        }

    }
    return result;
}

From source file:com.github.achatain.catalog.service.impl.CollectionServiceImpl.java

@Override
public Optional<CollectionDto> readCollection(final String userId, final String collectionId) {
    final Optional<CollectionDto> optionalCollectionDto = collectionDao.findById(userId, collectionId)
            .map(colToColDto);//from   ww  w  .j  ava 2 s . c  o m

    optionalCollectionDto.ifPresent(colDto -> populateIndexedInFields.accept(colDto,
            collectionDao.listCollectionIndexes(userId, collectionId)));

    return optionalCollectionDto;
}

From source file:com.rockagen.gnext.service.spring.security.extension.ExAuthenticationHandler.java

/**
 * Success register//  w ww  .j  a v  a  2  s  . c o m
 *
 * @param uid     uid
 * @param request request
 */
private void successRegister(String uid, HttpServletRequest request) {
    String currentIp = new ExWebAuthenticationDetails(request).getRemoteAddress();
    Optional<AuthUser> user = authUserServ.load(uid);
    user.ifPresent(x -> {
        Date now = new Date();
        x.setLastSignInAt(x.getCurrentSignInAt());
        x.setCurrentSignInAt(now);
        x.setLastSignInIp(x.getCurrentSignInIp());
        x.setCurrentSignInIp(currentIp);
        Integer signCount = Optional.ofNullable(x.getSignInCount()).orElse(0);
        x.setSignInCount(++signCount);
        x.setFailedAttempts(0);
        // Referer
        String referer = request.getHeader(userReferer);
        x.setLastUserReferer(getReferer(referer));
        authUserServ.add(x);
    });
}

From source file:org.echocat.marquardt.example.ExampleApplication.java

@Bean
public SessionCreator<PersistentUser, PersistentSession> sessionCreator(
        final SessionStore<PersistentSession> sessionStore, final UserCatalog<PersistentUser> userCatalog,
        final ExpiryDateCalculator<PersistentUser> expiryDateCalculator,
        final KeyPairProvider issuerKeyProvider, final Optional<SessionCreationPolicy> sessionCreationPolicy) {
    final SessionCreator<PersistentUser, PersistentSession> result = new SessionCreator<>(sessionStore,
            userCatalog, expiryDateCalculator, issuerKeyProvider);
    sessionCreationPolicy.ifPresent(result::setSessionCreationPolicy);
    return result;
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile.deck.DeckProfileFactory.java

@Override
protected void setProfile(Profile profile, DeploymentConfiguration deploymentConfiguration,
        SpinnakerRuntimeSettings endpoints) {
    StringResource configTemplate = new StringResource(profile.getBaseContents());
    UiSecurity uiSecurity = deploymentConfiguration.getSecurity().getUiSecurity();
    profile.setUser(ApacheSettings.APACHE_USER);

    Features features = deploymentConfiguration.getFeatures();
    Map<String, String> bindings = new HashMap<>();
    String version = deploymentConfiguration.getVersion();

    // Configure global settings
    bindings.put("gate.baseUrl", endpoints.getServices().getGate().getBaseUrl());
    bindings.put("timezone", deploymentConfiguration.getTimezone());
    bindings.put("version", deploymentConfiguration.getVersion());

    Optional<Versions.Version> validatedVersion = versionsService.getVersions().getVersion(version);

    validatedVersion.ifPresent(v -> {
        String changelog = v.getChangelog();
        bindings.put("changelog.gist.id", changelog.substring(changelog.lastIndexOf("/") + 1));
        bindings.put("changelog.gist.name", "changelog.md");
    });/*from  w ww . j  a  v a2s  .c om*/

    // Configure feature-flags
    bindings.put("features.auth", Boolean.toString(features.isAuth(deploymentConfiguration)));
    bindings.put("features.chaos", Boolean.toString(features.isChaos()));
    bindings.put("features.jobs", Boolean.toString(features.isJobs()));
    bindings.put("features.fiat",
            Boolean.toString(deploymentConfiguration.getSecurity().getAuthz().isEnabled()));

    // Configure Kubernetes
    KubernetesProvider kubernetesProvider = deploymentConfiguration.getProviders().getKubernetes();
    bindings.put("kubernetes.default.account", kubernetesProvider.getPrimaryAccount());
    bindings.put("kubernetes.default.namespace", "default");
    bindings.put("kubernetes.default.proxy", "localhost:8001");

    // Configure GCE
    GoogleProvider googleProvider = deploymentConfiguration.getProviders().getGoogle();
    bindings.put("google.default.account", googleProvider.getPrimaryAccount());
    bindings.put("google.default.region", "us-central1");
    bindings.put("google.default.zone", "us-central1-f");

    // Configure Azure
    AzureProvider azureProvider = deploymentConfiguration.getProviders().getAzure();
    bindings.put("azure.default.account", azureProvider.getPrimaryAccount());
    bindings.put("azure.default.region", "westus");

    // Configure Appengine
    AppengineProvider appengineProvider = deploymentConfiguration.getProviders().getAppengine();
    bindings.put("appengine.default.account", appengineProvider.getPrimaryAccount());
    bindings.put("appengine.enabled", Boolean.toString(appengineProvider.getPrimaryAccount() != null));

    // Configure DC/OS
    final DCOSProvider dcosProvider = deploymentConfiguration.getProviders().getDcos();
    bindings.put("dcos.default.account", dcosProvider.getPrimaryAccount());
    //TODO(willgorman) need to set the proxy url somehow

    // Configure Openstack
    OpenstackProvider openstackProvider = deploymentConfiguration.getProviders().getOpenstack();
    bindings.put("openstack.default.account", openstackProvider.getPrimaryAccount());
    if (openstackProvider.getPrimaryAccount() != null) {
        OpenstackAccount openstackAccount = (OpenstackAccount) accountService.getProviderAccount(
                deploymentConfiguration.getName(), "openstack", openstackProvider.getPrimaryAccount());
        //Regions in openstack are a comma separated list. Use the first as primary.
        String firstRegion = StringUtils.substringBefore(openstackAccount.getRegions(), ",");
        bindings.put("openstack.default.region", firstRegion);
    }

    profile.appendContents(configTemplate.setBindings(bindings).toString())
            .setRequiredFiles(backupRequiredFiles(uiSecurity, deploymentConfiguration.getName()));
}

From source file:com.blackducksoftware.integration.hub.detect.detector.clang.DependenciesListFileManager.java

public Set<String> generateDependencyFilePaths(final File workingDir, final CompileCommand compileCommand,
        final boolean cleanup) {
    final Set<String> dependencyFilePaths = new HashSet<>();
    final Optional<File> depsMkFile = generate(workingDir, compileCommand);
    dependencyFilePaths.addAll(parse(depsMkFile.orElse(null)));
    if (cleanup) {
        depsMkFile.ifPresent(File::delete);
    }/*  w w w.  java2  s.co  m*/
    return dependencyFilePaths;
}

From source file:ddf.catalog.validation.impl.validator.RelationshipValidator.java

@Override
public Optional<MetacardValidationReport> validateMetacard(Metacard metacard) {
    Attribute attribute = metacard.getAttribute(sourceAttribute);
    if (attribute != null && attribute.getValues().stream().anyMatch(Objects::nonNull)
            && (StringUtils.isEmpty(sourceValue) || attribute.getValues().contains(sourceValue))) {
        MetacardValidationReportImpl report = new MetacardValidationReportImpl();
        Attribute actualAttribute = metacard.getAttribute(targetAttribute);
        Collection<String> actualValues = actualAttribute == null ? Collections.emptyList()
                : actualAttribute.getValues().stream().map(Objects::toString).filter(StringUtils::isNotEmpty)
                        .collect(Collectors.toList());
        Optional<ValidationViolation> violation = relationships.get(relationship).apply(actualValues);
        violation.ifPresent(report::addAttributeViolation);
        if (violation.isPresent()) {
            return Optional.of(report);
        } else {//from ww  w . j  a v a2  s.  c  om
            return Optional.empty();
        }
    } else {
        return Optional.empty();
    }
}

From source file:org.trustedanalytics.servicecatalog.service.rest.ServiceInstancesController.java

@ApiOperation(value = "Get services instances filtering by broker in space", notes = "Privilege level: Consumer of this endpoint must be a member of specified space")
@RequestMapping(value = GET_ALL_SERVICE_INSTANCES_URL, method = GET, produces = APPLICATION_JSON_VALUE)
public Collection<ServiceInstance> getAllServiceInstances(@RequestParam(required = false) UUID space,
        @RequestParam(required = false) UUID broker) {
    if (space == null) {
        throw new UnsupportedOperationException("Handling not filtered request, not implemented yet");
    }//  w  ww. j  a v  a  2 s.  co  m

    CcSummary summary = ccClient.getSpaceSummary(space);

    Collection<ServiceInstance> serviceInstances = FormatTranslator.getServiceInstancesFromPlainSummary(summary,
            broker);
    for (ServiceInstance i : serviceInstances) {
        Optional<ServiceInstanceMetadata> metadata = Optional
                .ofNullable(serviceInstanceRegistry.getInstanceCreator(i.getGuid()));
        metadata.ifPresent(m -> i.setMetadata(m));
    }
    return serviceInstances;
}

From source file:at.yawk.buycraft.BuycraftApiImpl.java

@Override
public Set<Purchase> payments(String limit, Optional<String> user) throws IOException {
    URIBuilder builder = new URIBuilder();
    builder.setParameter("limit", limit);
    user.ifPresent(u -> builder.setParameter("ign", u));
    JsonObject object = get("payments", builder);
    Set<Purchase> purchases = new HashSet<>();
    object.getAsJsonArray("payload").forEach(ele -> {
        JsonObject entry = ele.getAsJsonObject();
        List<Integer> packages = new ArrayList<>();
        entry.getAsJsonArray("packages").forEach(pack -> packages.add(pack.getAsInt()));
        Purchase purchase = new Purchase(entry.get("time").getAsLong(), entry.get("humanTime").getAsString(),
                entry.get("ign").getAsString(), entry.get("uuid").getAsString(),
                entry.get("price").getAsString(), entry.get("currency").getAsString(),
                Collections.unmodifiableCollection(packages));
        purchases.add(purchase);/*from   ww w  .ja  v a2  s  .  co  m*/
    });
    return purchases;
}