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.arpnetworking.configuration.jackson.JsonNodePaginatedUrlSourceTest.java

@Test
public void test() throws MalformedURLException {
    final WireMockServer server = new WireMockServer(0);
    server.start();/*from w ww .j  a  v  a  2s  .  c  o m*/
    final WireMock wireMock = new WireMock(server.port());

    wireMock.register(WireMock.get(WireMock.urlEqualTo("/animals?offset=0&limit=1"))
            .willReturn(WireMock.aResponse().withStatus(200)
                    .withHeader("Content-Type", "application/json; charset=utf-8")
                    .withBody("{\"metadata\":{\"next\":\"animals?offset=1&limit=1\"},\"data\":[\"cat\"]}")));

    wireMock.register(WireMock.get(WireMock.urlEqualTo("/animals?offset=1&limit=1"))
            .willReturn(WireMock.aResponse().withStatus(200)
                    .withHeader("Content-Type", "application/json; charset=utf-8")
                    .withBody("{\"metadata\":{\"next\":\"animals?offset=2&limit=1\"},\"data\":[\"dog\"]}")));

    wireMock.register(WireMock.get(WireMock.urlEqualTo("/animals?offset=2&limit=1"))
            .willReturn(WireMock.aResponse().withStatus(200)
                    .withHeader("Content-Type", "application/json; charset=utf-8")
                    .withBody("{\"metadata\":{\"next\":null},\"data\":[\"mouse\"]}")));

    final JsonNodePaginatedUriSource jsonNodePaginatedUrlSource = new JsonNodePaginatedUriSource.Builder()
            .setUri(URI.create("http://localhost:" + server.port() + "/animals?offset=0&limit=1"))
            .setDataKeys(ImmutableList.of("data")).setNextPageKeys(ImmutableList.of("metadata", "next"))
            .build();

    final Optional<JsonNode> jsonNode = jsonNodePaginatedUrlSource.getJsonNode();
    Assert.assertTrue(jsonNode.isPresent());
    Assert.assertTrue(jsonNode.get().isArray());
    Assert.assertEquals(3, ((ArrayNode) jsonNode.get()).size());
    Assert.assertEquals("cat", ((ArrayNode) jsonNode.get()).get(0).textValue());
    Assert.assertEquals("dog", ((ArrayNode) jsonNode.get()).get(1).textValue());
    Assert.assertEquals("mouse", ((ArrayNode) jsonNode.get()).get(2).textValue());

    server.stop();
}

From source file:com.hortonworks.registries.storage.impl.jdbc.provider.sql.query.AbstractStorableUpdateQuery.java

public AbstractStorableUpdateQuery(Storable storable) {
    super(storable);
    Map<String, Object> columnsToValues = storable.toMap();
    columns.forEach(col -> bindings.add(Pair.of(col, columnsToValues.get(col.getName()))));
    primaryKey.getFieldsToVal().forEach((f, o) -> {
        bindings.add(Pair.of(f, o));//w  ww  .  j  ava 2s.co  m
        whereFields.add(f);
    });
    try {
        Optional<Pair<Field, Long>> versionFieldValue = StorageUtils.getVersionFieldValue(storable);
        if (versionFieldValue.isPresent()) {
            Pair<Field, Long> fv = versionFieldValue.get();
            Schema.Field versionField = Schema.Field.of(fv.getKey().getName(),
                    Schema.fromJavaType(fv.getValue().getClass()));
            whereFields.add(versionField);
            // update only if its the previous
            bindings.add(Pair.of(versionField, fv.getValue() - 1));
        }
    } catch (Exception ex) {
        LOG.error("Got exception", ex);
    }
}

From source file:com.synopsys.integration.blackduck.api.LicenseDataServiceTestIT.java

@Test
public void testGettingLicenseFromComponentVersion() throws Exception {
    BlackDuckServicesFactory blackDuckServicesFactory = intHttpClientTestHelper
            .createBlackDuckServicesFactory();
    LicenseService licenseService = blackDuckServicesFactory.createLicenseService();

    SimpleBdioFactory simpleBdioFactory = new SimpleBdioFactory();
    ExternalId guavaExternalId = simpleBdioFactory.createMavenExternalId("com.google.guava", "guava", "20.0");
    Optional<ComplexLicenseView> optionalComplexLicense = licenseService
            .getComplexLicenseItemFromComponent(guavaExternalId);
    ComplexLicenseView complexLicense = optionalComplexLicense.get();

    assertEquals("Apache License 2.0", complexLicense.getLicenseDisplay());
    assertEquals(ComplexLicenseType.DISJUNCTIVE, complexLicense.getType());
    assertEquals(1, complexLicense.getLicenses().size());

    ComplexLicenseView embeddedLicense = complexLicense.getLicenses().get(0);
    assertTrue(StringUtils.isNotBlank(embeddedLicense.getLicense()));
    assertEquals("Apache License 2.0", embeddedLicense.getLicenseDisplay());
    assertEquals("Apache License 2.0", embeddedLicense.getName());
    assertEquals("OPEN_SOURCE", embeddedLicense.getOwnership());
    assertNull(embeddedLicense.getType());
    assertEquals(0, embeddedLicense.getLicenses().size());

    System.out.println(complexLicense);
}

From source file:com.ikanow.aleph2.security.db.AbstractDb.java

public Object loadById(Object id) {
    Session s = null;/*from   w  ww.  j  a  v  a  2  s  .  co  m*/
    try {
        Optional<JsonNode> ojs = getStore().getObjectById(id).get();
        if (ojs.isPresent()) {
            s = (Session) deserialize(ojs.get());
        }
    } catch (Exception e) {
        logger.error("Caught Exception loading from db:", e);
    }
    return s;
}

From source file:com.epam.training.service.impl.DefaultSergiiService.java

@Override
public void createLogo(final String logoCode) {
    final Optional<CatalogUnawareMediaModel> existingLogo = findExistingLogo(logoCode);

    final CatalogUnawareMediaModel media = existingLogo.isPresent() ? existingLogo.get()
            : modelService.create(CatalogUnawareMediaModel.class);
    media.setCode(logoCode);//ww w.j a  va 2  s. co  m
    media.setRealFileName("sap-hybris-platform.png");
    modelService.save(media);

    mediaService.setStreamForMedia(media, getImageStream());
}

From source file:org.onebusaway.alexa.MainSpeechlet.java

public SpeechletResponse onIntent(final IntentRequest request, final Session session)
        throws SpeechletException {
    try {/*from www  . j  a  v a  2s  .c o  m*/
        Optional<ObaUserDataItem> optUserData = obaDao.getUserData(session);
        if (optUserData.isPresent()) {
            return getAuthedSpeechlet(optUserData.get()).onIntent(request, session);
        } else {
            return anonSpeechlet.onIntent(request, session);
        }
    } catch (URISyntaxException e) {
        log.error("Intent exception: " + e.getMessage());
        log.error("Backtrace:\n" + e.getStackTrace());
        throw new SpeechletException("Error creating user data on Intent using ObaBaseUrl: " + e);
    } catch (Exception e) {
        log.error("Intent exception: " + e.getMessage());
        log.error("Backtrace:\n" + e.getStackTrace());
        throw e;
    }
}

From source file:io.dfox.junit.http.example.ExampleTest.java

private void assertNoteExists(final String notePath) throws IOException {
    JsonNode notesFixture = getTestData("notes.json");
    JsonNode noteFixture = notesFixture.path(notePath);
    String name = noteFixture.path("name").asText();
    String expectedContents = noteFixture.path("contents").asText();

    Optional<InputStream> note = repository.getNote(name);
    assertTrue(note.isPresent());/*from  w w  w .j a  va2  s. c  om*/
    try (InputStream stream = note.get()) {
        String contents = IOUtils.toString(stream);
        assertEquals(expectedContents, contents);
    }
}

From source file:no.asgari.civilization.server.model.PBF.java

/**
 * Returns the username of the player who is start of turn
 *///  ww w.j a  va2 s  .  c  o m
@JsonIgnore
public String getNameOfUsersTurn() {
    Optional<Playerhand> optional = players.stream().filter(Playerhand::isYourTurn).findFirst();

    if (optional.isPresent()) {
        return optional.get().getUsername();
    }

    return "";
}

From source file:com.devicehive.dao.rdbms.RdbmsGenericDao.java

public void cacheQuery(Query query, Optional<CacheConfig> cacheConfig) {
    if (cacheConfig.isPresent()) {
        query.setHint(CACHEABLE, true);//from  w ww. j  a  v a2  s.  c  o m
        query.setHint(RETRIEVE_MODE, cacheConfig.get().getRetrieveMode());
        query.setHint(STORE_MODE, cacheConfig.get().getStoreMode());
    }
}

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

@GET
public Mica.DataAccessFormDto get() {
    Optional<DataAccessForm> d = dataAccessFormService.find();

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

    return dtos.asDto(d.get());
}