Example usage for java.util Optional of

List of usage examples for java.util Optional of

Introduction

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

Prototype

public static <T> Optional<T> of(T value) 

Source Link

Document

Returns an Optional describing the given non- null value.

Usage

From source file:jobhunter.api.infojobs.Client.java

public <T> Optional<T> get(Class<T> clazz, String url) throws InfoJobsAPIException {
    HttpGet httpGet = new HttpGet(url);
    try (CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(provider).build()) {
        try (CloseableHttpResponse response = client.execute(httpGet)) {
            if (response.getStatusLine().getStatusCode() == 200) {
                T entity = mapper.readValue(response.getEntity().getContent(), clazz);
                return Optional.of(entity);
            } else {
                Error error = mapper.readValue(response.getEntity().getContent(), Error.class);
                throw new InfoJobsAPIException(error);
            }//from  w  ww  . j ava  2s .  c om
        }
    } catch (IOException e) {
        l.error("Failed to GET {} from {}", clazz.getCanonicalName(), url, e);
        throw new InfoJobsAPIException(e.getLocalizedMessage());
    }
}

From source file:tds.assessment.web.endpoints.AssessmentControllerTest.java

@Test
public void shouldFindAssessmentByKey() {
    final String clientName = "SBAC_PT";
    final String assessmentKey = "theKey";
    Assessment assessment = new Assessment();
    assessment.setKey(assessmentKey);/*  w  w  w .j av a2  s .  com*/

    when(service.findAssessment(clientName, assessmentKey)).thenReturn(Optional.of(assessment));
    ResponseEntity<Assessment> response = controller.findAssessment(clientName, assessmentKey);
    verify(service).findAssessment(clientName, assessmentKey);

    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(response.getBody().getKey()).isEqualTo("theKey");
}

From source file:org.hawkular.services.rest.test.InventoryHelper.java

private static Optional<ExtendedInventoryStructure> rebuildFromChunks(JsonNode dataNode) {
    if (!dataNode.has(0)) {
        return Optional.empty();
    }/*ww w  . jav a  2s  .c om*/
    try {
        JsonNode masterNode = dataNode.get(0);
        final byte[] all;
        if (masterNode.has("tags") && masterNode.get("tags").has("chunks")) {
            int nbChunks = masterNode.get("tags").get("chunks").asInt();
            int totalSize = masterNode.get("tags").get("size").asInt();
            byte[] master = masterNode.get("value").binaryValue();
            if (master.length == 0) {
                return Optional.empty();
            }
            all = new byte[totalSize];
            int pos = 0;
            System.arraycopy(master, 0, all, pos, master.length);
            pos += master.length;
            for (int i = 1; i < nbChunks; i++) {
                JsonNode slaveNode = dataNode.get(i);
                byte[] slave = slaveNode.get("value").binaryValue();
                System.arraycopy(slave, 0, all, pos, slave.length);
                pos += slave.length;
            }
        } else {
            // Not chunked
            all = masterNode.get("value").binaryValue();
        }
        String decompressed = decompress(all);
        ExtendedInventoryStructure structure = MAPPER.readValue(decompressed, ExtendedInventoryStructure.class);
        return Optional.of(structure);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.bekwam.resignator.NewPasswordController.java

@FXML
public void ok(ActionEvent evt) {
    if (logger.isDebugEnabled()) {
        logger.debug("[OK]");
    }//  w  w w  .jav  a2  s .co m

    String errMsg = validate();

    if (StringUtils.isEmpty(errMsg)) {
        confirmedPassword = Optional.of(pfPassword.getText());

        if (logger.isDebugEnabled()) {
            logger.debug("[OK] password is present?="
                    + (confirmedPassword.isPresent() && !StringUtils.isEmpty(confirmedPassword.get())));
        }

        if (logger.isDebugEnabled()) {
            logger.debug("[OK] npc id={}", this.hashCode());
        }

        synchronized (this) {
            notify();
        }

        ((Button) evt.getSource()).getScene().getWindow().hide();

    } else {
        lblError.setVisible(true);
        lblError.setText(errMsg);
    }
}

From source file:com.ikanow.aleph2.security.service.IkanowV1UserGroupRoleProvider.java

@SuppressWarnings("unchecked")
protected void initDb() {
    if (_core_management_db == null) {
        _core_management_db = _context.getCoreManagementDbService();
    }/*  w  w  w .ja  va  2  s .c om*/
    if (_underlying_management_db == null) {
        _underlying_management_db = _context.getService(IManagementDbService.class, Optional.empty()).get();
    }
    String personOptions = "social.person";
    personDb = _underlying_management_db
            .getUnderlyingPlatformDriver(ICrudService.class, Optional.of(personOptions)).get();
}

From source file:io.github.lxgaming.teleportbow.commands.AbstractCommand.java

@Override
public final Optional<Text> getShortDescription(CommandSource commandSource) {
    if (StringUtils.length(getDescription()) > 53) {
        return Optional.of(Text.of(StringUtils.substring(getDescription(), 0, 50), "..."));
    }//from  www.j  a v  a2  s . c o  m

    return Optional.of(Text.of(StringUtils.defaultIfBlank(getDescription(), "No description provided")));
}

From source file:de.mas.wiiu.jnus.utils.FSTUtils.java

public static Optional<FSTEntry> getChildOfDirectory(FSTEntry root, String filename) {
    for (FSTEntry cur : root.getChildren()) {
        if (cur.getFilename().equalsIgnoreCase(filename)) {
            return Optional.of(cur);
        }//from  w ww .  j a  v a2s .co  m
    }
    return Optional.empty();
}

From source file:org.lendingclub.mercator.aws.RouteTableScanner.java

@Override
public Optional<String> computeArn(JsonNode n) {
    return Optional.of(createEc2Arn("route-table", n.path("aws_routeTableId").asText()));
}

From source file:org.dswarm.graph.gdm.test.GDMResource3Test.java

@Ignore
@Test/*from  ww w .  ja va2 s .c om*/
public void mabxmlVersioningTest() throws IOException {

    final ObjectNode requestJson = getMABXMLContentSchema();

    // 157, 149
    readGDMFromDBThatWasWrittenAsGDM(Optional.of(requestJson), "versioning/mabxml_dmp.gson",
            "versioning/mabxml_dmp2.gson", "http://data.slub-dresden.de/resources/1",
            "http://www.ddb.de/professionell/mabxml/mabxml-1.xsd#datensatzType", 157, 149, false,
            Optional.empty());
}

From source file:com.vsct.dt.hesperides.indexation.model.ElasticSearchEntity.java

public Optional<T> getEntity() {
    if (this.get != null && this.get.isFound()) {
        return Optional.of(this.get.getSource());
    } else {/*from www.  ja v  a 2 s  . c  om*/
        return Optional.empty();
    }
}