Example usage for java.util Optional get

List of usage examples for java.util Optional get

Introduction

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

Prototype

public T get() 

Source Link

Document

If a value is present, returns the value, otherwise throws NoSuchElementException .

Usage

From source file:me.yanaga.winter.data.jpa.PersonRepositoryTest.java

@Test
public void testFindOnePredicate() {
    Person first = new Person();
    first.setName("Yanaga");
    personRepository.save(first);// ww w.  j  a v  a  2  s .  c  o  m
    Optional<Person> found = personRepository.findOne(Persons.withNameContaining("a"));
    assertThat(found.get()).isEqualTo(first);
}

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

@Override
public void validate(Metacard metacard) throws ValidationException {
    Optional<MetacardValidationReport> report = validateMetacard(metacard);
    if (report.isPresent() && !report.get().getAttributeValidationViolations().isEmpty()) {
        List<String> errors = report.get().getAttributeValidationViolations().stream()
                .filter(v -> v.getSeverity() == ValidationViolation.Severity.ERROR)
                .map(ValidationViolation::getMessage).collect(Collectors.toList());
        errors.addAll(report.get().getMetacardValidationViolations().stream()
                .filter(v -> v.getSeverity() == ValidationViolation.Severity.ERROR)
                .map(ValidationViolation::getMessage).collect(Collectors.toList()));
        List<String> warnings = report.get().getAttributeValidationViolations().stream()
                .filter(v -> v.getSeverity() == ValidationViolation.Severity.WARNING)
                .map(ValidationViolation::getMessage).collect(Collectors.toList());
        errors.addAll(report.get().getMetacardValidationViolations().stream()
                .filter(v -> v.getSeverity() == ValidationViolation.Severity.WARNING)
                .map(ValidationViolation::getMessage).collect(Collectors.toList()));
        throw new ValidationExceptionImpl(report.toString(), errors, warnings);
    }//from   w w w.  j  ava  2  s.  co  m
}

From source file:io.gravitee.gateway.env.GatewayConfigurationTest.java

@Test
public void shouldReturnTenantFromSystemProperty() {
    System.setProperty(GatewayConfiguration.MULTI_TENANT_SYSTEM_PROPERTY, "europe");
    gatewayConfiguration.afterPropertiesSet();

    Optional<String> tenantOpt = gatewayConfiguration.tenant();
    Assert.assertTrue(tenantOpt.isPresent());

    Assert.assertEquals("europe", tenantOpt.get());
}

From source file:io.gravitee.gateway.env.GatewayConfigurationTest.java

@Test
public void shouldReturnTenantFromConfiguration() {
    Mockito.when(environment.getProperty(GatewayConfiguration.MULTI_TENANT_CONFIGURATION)).thenReturn("europe");
    gatewayConfiguration.afterPropertiesSet();

    Optional<String> tenantOpt = gatewayConfiguration.tenant();
    Assert.assertTrue(tenantOpt.isPresent());

    Assert.assertEquals("europe", tenantOpt.get());
}

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

@GET
@Path("/pdf")
public FileResource getDataAccessPdf(@QueryParam("lang") String lang) {
    Optional<DataAccessForm> d = dataAccessFormService.find();

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

    DataAccessForm dataAccessForm = d.get();
    Locale locale = Locale
            .forLanguageTag(!Strings.isNullOrEmpty(lang) ? Locale.forLanguageTag(lang).toLanguageTag()
                    : LanguageTag.UNDETERMINED);

    if (!dataAccessForm.getPdfTemplates().containsKey(locale))
        throw NoSuchDataAccessFormException.withDefaultMessage();

    fileResource.setAttachment(dataAccessForm.getPdfTemplates().get(locale));

    return fileResource;
}

From source file:com.arpnetworking.kairosdb.aggregators.DelegatingAggregator.java

@Override
public String getAggregatedGroupType(final String groupType) {
    final Optional<Provider<? extends RangeAggregator>> provider = _aggregatorMap
            .aggregatorForGroupType(groupType);
    if (provider.isPresent()) {
        return provider.get().get().getAggregatedGroupType(groupType);
    }/*from  ww  w  . j a  v  a2 s .com*/
    throw new IllegalArgumentException("Cannot aggregate a " + groupType);
}

From source file:com.ejisto.core.classloading.javassist.ObjectEditor.java

/**
 * Edits a field access replacing the code
 * with a call to {@link PropertyManager#mockField(String, String, String, Class, Object)}}.
 *
 * @param f the "fieldAccess"/*from  w w w.  j  a v  a2 s.c  o  m*/
 */
@Override
public void edit(FieldAccess f) throws CannotCompileException {
    String fieldName = f.getFieldName();
    if (shouldBeEdited(f, fieldName) && editFieldReader(f)) {
        CtClass clazz = f.getEnclosingClass();
        final Optional<String> fieldMarker = getFieldMarker(fieldName);
        if (fieldMarker.isPresent()) {
            clazz.addField(CtField.make(format("private boolean %s = true;", fieldMarker.get()), clazz));
        }
    }
}

From source file:com.github.lukaszbudnik.dqueue.QueueClientIntegrationTest.java

@Test
public void shouldPublishAndConsumeWithManyFilter() throws ExecutionException, InterruptedException {
    // some filters
    Integer routingKey = 3;//from ww  w . ja va 2  s.c  om
    Integer version = 123;
    Integer type = 2;

    ImmutableMap.Builder<String, Object> filters = ImmutableMap.builder();
    filters.put("type", type).put("version", version).put("routing_key", routingKey);

    UUID startTime = UUIDs.timeBased();
    ByteBuffer contents = ByteBuffer.wrap("contents".getBytes());
    Future<UUID> publishFuture = queueClient.publish(new Item(startTime, contents, filters.build()));
    publishFuture.get();

    Future<Optional<Item>> itemFuture = queueClient.consume(filters.build());

    Optional<Item> item = itemFuture.get();

    UUID consumedStartTime = item.get().getStartTime();
    ByteBuffer consumedContents = item.get().getContents();

    assertEquals(startTime, consumedStartTime);
    assertEquals(contents, consumedContents);
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.view.provider.KubernetesV2ManifestProvider.java

@Override
public KubernetesV2Manifest getManifest(String account, String location, String name) {
    Pair<KubernetesKind, String> parsedName;
    try {//from w w w.  j a  v  a2 s.  c om
        parsedName = KubernetesManifest.fromFullResourceName(name);
    } catch (Exception e) {
        return null;
    }

    KubernetesKind kind = parsedName.getLeft();
    String key = Keys.infrastructure(kind, account, location, parsedName.getRight());

    Optional<CacheData> dataOptional = cacheUtils.getSingleEntry(kind.toString(), key);
    if (!dataOptional.isPresent()) {
        return null;
    }

    CacheData data = dataOptional.get();
    KubernetesResourceProperties properties = registry.get(account, kind);
    if (properties == null) {
        return null;
    }

    Function<KubernetesManifest, String> lastEventTimestamp = (
            m) -> (String) m.getOrDefault("lastTimestamp", m.getOrDefault("firstTimestamp", "n/a"));

    List<KubernetesManifest> events = cacheUtils
            .getTransitiveRelationship(kind.toString(), Collections.singletonList(key),
                    KubernetesKind.EVENT.toString())
            .stream().map(KubernetesCacheDataConverter::getManifest)
            .sorted(Comparator.comparing(lastEventTimestamp)).collect(Collectors.toList());

    KubernetesHandler handler = properties.getHandler();

    KubernetesManifest manifest = KubernetesCacheDataConverter.getManifest(data);
    Moniker moniker = KubernetesCacheDataConverter.getMoniker(data);

    return new KubernetesV2Manifest().builder().account(account).location(location).manifest(manifest)
            .moniker(moniker).status(handler.status(manifest)).artifacts(handler.listArtifacts(manifest))
            .events(events).build();
}

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

/**
 * Create a new {@link org.springframework.security.core.userdetails.UserDetails} by uid
 *
 * @param uid         uid/* ww w .  java  2s.  c  o  m*/
 * @param credentials Credentials(always was password)
 * @return {@link org.springframework.security.core.userdetails.UserDetails}
 * @throws org.springframework.security.authentication.BadCredentialsException if credentials invalid
 */
private UserDetails loadUser(String uid, String credentials) {

    // Not empty
    if (CommUtil.isBlank(uid) || CommUtil.isBlank(credentials)) {
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }

    // Load user
    Optional<AuthUser> u = authUserServ.load(uid);

    if (u.filter(x -> x.enabled()).isPresent()) {
        AuthUser user = u.get();
        // Check credentials
        checkCredentials(user.getPassword(), credentials, user.getSalt());

        // After authenticated handler
        afterAuthenticatedHandler(user);

        List<GrantedAuthority> authorities = new LinkedList<>();
        Set<AuthGroup> groups = user.getGroups();
        if (groups != null && groups.size() > 0) {
            groups.forEach(x -> x.getRoles()
                    .forEach(y -> authorities.add(new SimpleGrantedAuthority(y.getName().trim()))));
        }
        return new User(user.getUid(), user.getPassword(), true, true, true, true, authorities);

    } else {
        throw new UsernameNotFoundException(
                messages.getMessage("", new Object[] { uid }, "User {0} has no GrantedAuthority"));
    }

}