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:com.rcs.shoe.shop.fx.controller.ui.Controller.java

protected String showChoiseDialog(String title, String header, String content, List<String> choices,
        String selected) {/*from w  w  w .  j av a 2s.  co m*/
    ChoiceDialog<String> dialog = new ChoiceDialog<>(selected, choices);
    dialog.setTitle(title);
    dialog.setHeaderText(header);
    dialog.setContentText(content);

    Optional<String> result = dialog.showAndWait();
    if (result.isPresent()) {
        return result.get();
    }
    return null;
}

From source file:de.rnd7.urlcache.URLCacheLoader.java

@Override
public CachedElement load(final URLCacheKey key) throws Exception {
    final Optional<CachedElement> fromDisk = this.loadFromDisk(key);
    if (fromDisk.isPresent()) {
        return fromDisk.get();
    }/*  w w w. j  av a 2 s.c om*/

    final CachedElement element = this.loadFromURL(key);
    this.saveToDisk(element, key);

    return element;
}

From source file:bg.vitkinov.edu.services.JokeCategoryService.java

@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT })
public ResponseEntity<?> insert(@RequestParam String name, @RequestParam String keywords) {
    Optional<Category> category = repository.findByName(name);
    if (category.isPresent()) {
        return new ResponseEntity<>(category.get(), HttpStatus.CONFLICT);
    }/*w ww . j  a  va2 s.co m*/
    Category newCateogry = new Category();
    newCateogry.setName(name);
    newCateogry.setKeyWords(getKewWors(keywords));
    return new ResponseEntity<>(repository.save(newCateogry), HttpStatus.CREATED);
}

From source file:com.facebook.presto.accumulo.AccumuloClient.java

private static void validateColumns(ConnectorTableMetadata meta) {
    // Check all the column types, and throw an exception if the types of a map are complex
    // While it is a rare case, this is not supported by the Accumulo connector
    ImmutableSet.Builder<String> columnNameBuilder = ImmutableSet.builder();
    for (ColumnMetadata column : meta.getColumns()) {
        if (Types.isMapType(column.getType())) {
            if (Types.isMapType(Types.getKeyType(column.getType()))
                    || Types.isMapType(Types.getValueType(column.getType()))
                    || Types.isArrayType(Types.getKeyType(column.getType()))
                    || Types.isArrayType(Types.getValueType(column.getType()))) {
                throw new PrestoException(INVALID_TABLE_PROPERTY,
                        "Key/value types of a MAP column must be plain types");
            }//w  w w. jav a2  s .  c o m
        }

        columnNameBuilder.add(column.getName().toLowerCase(Locale.ENGLISH));
    }

    // Validate the columns are distinct
    if (columnNameBuilder.build().size() != meta.getColumns().size()) {
        throw new PrestoException(INVALID_TABLE_PROPERTY, "Duplicate column names are not supported");
    }

    Optional<Map<String, Pair<String, String>>> columnMapping = AccumuloTableProperties
            .getColumnMapping(meta.getProperties());
    if (columnMapping.isPresent()) {
        // Validate there are no duplicates in the column mapping
        long distinctMappings = columnMapping.get().values().stream().distinct().count();
        if (distinctMappings != columnMapping.get().size()) {
            throw new PrestoException(INVALID_TABLE_PROPERTY,
                    "Duplicate column family/qualifier pair detected in column mapping, check the value of "
                            + AccumuloTableProperties.COLUMN_MAPPING);
        }

        // Validate no column is mapped to the reserved entry
        String reservedRowIdColumn = AccumuloPageSink.ROW_ID_COLUMN.toString();
        if (columnMapping.get().values().stream().filter(pair -> pair.getKey().equals(reservedRowIdColumn)
                && pair.getValue().equals(reservedRowIdColumn)).count() > 0) {
            throw new PrestoException(INVALID_TABLE_PROPERTY,
                    format("Column familiy/qualifier mapping of %s:%s is reserved", reservedRowIdColumn,
                            reservedRowIdColumn));
        }
    } else if (AccumuloTableProperties.isExternal(meta.getProperties())) {
        // Column mapping is not defined (i.e. use column generation) and table is external
        // But column generation is for internal tables only
        throw new PrestoException(INVALID_TABLE_PROPERTY,
                "Column generation for external tables is not supported, must specify "
                        + AccumuloTableProperties.COLUMN_MAPPING);
    }
}

From source file:com.teradata.benchto.driver.BenchmarkPropertiesTest.java

@Test
public void parseActiveVariables() {
    Optional<Map<String, String>> activeVariables = activeVariables("ala=kot,tola=pies");
    assertThat(activeVariables).isPresent();
    assertThat(activeVariables.get()).containsOnly(entry("ala", "kot"), entry("tola", "pies"));
}

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 ww  w  .  j  a  va  2  s  . c om
    }
    return true;
}

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  a v  a2  s .  c o  m
    }
    return true;
}

From source file:fi.helsinki.opintoni.security.CustomAuthenticationSuccessHandler.java

private void syncUserWithDatabase(AppUser appUser) {
    Optional<User> user = getUserFromDb(appUser);
    if (user.isPresent()) {
        updateExistingUser(appUser, user.get());
    } else {//from  ww  w .j  a v  a 2s  .c  o  m
        createNewUser(appUser);
    }
}

From source file:spring.travel.site.services.UserServiceTest.java

@Test
public void shouldReturnUserWithNoAddress() throws Exception {
    stubGet("/user?id=123", new User("123", "Fred", "Flintstone", "freddyf", Optional.<Address>empty()));

    HandOff<Optional<User>> handOff = new HandOff<>();

    userService.user(Optional.of("123")).whenComplete((user, t) -> handOff.put(user));

    Optional<User> optionalUser = handOff.get(1);
    assertNotEquals(Optional.empty(), optionalUser);

    User user = optionalUser.get();
    assertEquals("Fred", user.getFirstName());
    assertEquals(Optional.empty(), user.getAddress());
}

From source file:com.arpnetworking.configuration.jackson.JsonNodeUriSourceTest.java

@Test
public void test() throws MalformedURLException {
    final WireMockServer server = new WireMockServer(0);
    server.start();//w w  w.  j av a2 s  .  co  m
    final WireMock wireMock = new WireMock(server.port());

    wireMock.register(WireMock.get(WireMock.urlEqualTo("/configuration"))
            .willReturn(WireMock.aResponse().withStatus(200)
                    .withHeader("Content-Type", "application/json; charset=utf-8")
                    .withBody("{\"values\":[\"foo\",\"bar\"]}")));

    final JsonNodeUriSource jsonNodeUriSource = new JsonNodeUriSource.Builder()
            .setUri(URI.create("http://localhost:" + server.port() + "/configuration")).build();

    final Optional<JsonNode> jsonNode = jsonNodeUriSource.getJsonNode();
    Assert.assertTrue(jsonNode.isPresent());
    Assert.assertTrue(jsonNode.get().isObject());
    Assert.assertEquals(1, Iterators.size(((ObjectNode) jsonNode.get()).fieldNames()));

    final Optional<JsonNode> valuesJsonNode = jsonNodeUriSource.getValue("values");
    Assert.assertTrue(valuesJsonNode.isPresent());
    Assert.assertTrue(valuesJsonNode.get().isArray());
    Assert.assertEquals(2, ((ArrayNode) valuesJsonNode.get()).size());
    Assert.assertEquals("foo", ((ArrayNode) valuesJsonNode.get()).get(0).textValue());
    Assert.assertEquals("bar", ((ArrayNode) valuesJsonNode.get()).get(1).textValue());

    server.stop();
}