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:org.jhk.pulsing.web.dao.prod.db.redis.RedisPulseDao.java

@Override
public Optional<Pulse> getPulse(PulseId pulseId) {
    _LOGGER.debug("RedisPulseDao.getPulse: " + pulseId);

    String pulseJson = getJedis().get(PULSE_.toString() + pulseId.getId());
    Optional<Pulse> pulse = Optional.empty();

    if (pulseJson != null) {
        try {// w ww  . ja va 2  s .com
            pulse = Optional.of(SerializationHelper.deserializeFromJSONStringToAvro(Pulse.class,
                    Pulse.getClassSchema(), pulseJson));
        } catch (IOException dException) {
            dException.printStackTrace();
        }
    }

    return pulse;
}

From source file:se.omegapoint.facepalm.infrastructure.FilePolicyRepository.java

@Override
public Optional<Policy> retrievePolicyWith(final String filename) {
    notBlank(filename);//w ww .  j  a  va 2s.c  om

    final ExecutorService executorService = Executors.newSingleThreadExecutor();
    final Command command = commandBasedOnOperatingSystem(filename);
    final Future<String> future = executorService.submit(command);

    try {
        eventService.publish(new GenericEvent(format("About to execute command[%s]", command.command)));
        return Optional.of(new Policy(future.get(TIMEOUT, TimeUnit.SECONDS)));
    } catch (Exception e) {
        return Optional.empty();
    }
}

From source file:net.cyphoria.cylus.web.controller.KontoBearbeitenControllerTest.java

@Test
public void kontoModellObjektWirdberKontoNummerGeladen() throws ResourceNotFoundException {
    when(kontoService.findeKontoMitKontoNummer(KONTO_NUMMER)).thenReturn(Optional.of(KONTO));

    assertThat(controller.getKonto(KONTO_NUMMER), is(KONTO));
}

From source file:net.sf.jabref.logic.util.io.FileUtil.java

/**
 * Returns the extension of a file name or Optional.empty() if the file does not have one (no . in name).
 *
 * @param fileName//from w w w . j  av  a 2 s. c  o m
 * @return The extension, trimmed and in lowercase.
 */
public static Optional<String> getFileExtension(String fileName) {
    int pos = fileName.lastIndexOf('.');
    if ((pos > 0) && (pos < (fileName.length() - 1))) {
        return Optional.of(fileName.substring(pos + 1).trim().toLowerCase());
    } else {
        return Optional.empty();
    }
}

From source file:org.ulyssis.ipp.config.Config.java

/**
 * Create a configuration from the given JSON configuration string.
 *///from   www.  jav  a 2s.  co m
public static Optional<Config> fromConfigurationString(String configuration) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.findAndRegisterModules();
    try {
        Config result = mapper.readValue(configuration, Config.class);
        return Optional.of(result);
    } catch (IOException e) {
        LOG.error("Error reading configuration", e);
        return Optional.empty();
    }
}

From source file:com.example.config.WithAccessTokenSecurityContextFactory.java

@Override
public SecurityContext createSecurityContext(final WithAccessToken annotation) {
    final SecurityContext context = SecurityContextHolder.createEmptyContext();
    final GivenAccessToken accessToken = new GivenAccessToken(annotation);
    final OAuth2Authentication oauth2 = accessToken.oauth2();

    final MockingDetails mockingDetails = Mockito.mockingDetails(accessTokenRepository);
    if (mockingDetails.isMock()) {
        when(accessTokenRepository.findByAccessToken(accessToken.accessToken))
                .thenReturn(Optional.of(accessToken.accessTokenEntity()));
    }/* w  ww .j  a v a  2 s . c o m*/

    context.setAuthentication(oauth2);
    return context;
}

From source file:com.liferay.blade.cli.util.Prompter.java

private static Optional<Boolean> _getBooleanAnswer(String questionWithPrompt, InputStream inputStream,
        PrintStream printStream, Optional<Boolean> defaultAnswer) {

    Optional<Boolean> answer = null;

    try (CloseShieldInputStream closeShieldInputStream = new CloseShieldInputStream(inputStream);
            Scanner scanner = new Scanner(closeShieldInputStream)) {

        while ((answer == null) || !answer.isPresent()) {
            printStream.println(questionWithPrompt);

            String readLine = null;

            while (((answer == null) || !answer.isPresent()) && !Objects.equals(answer, defaultAnswer)
                    && scanner.hasNextLine()) {

                readLine = scanner.nextLine();

                if (readLine != null) {
                    readLine = readLine.toLowerCase();

                    switch (readLine.trim()) {
                    case "y":
                    case "yes":
                        answer = Optional.of(true);

                        break;
                    case "n":
                    case "no":
                        answer = Optional.of(false);

                        break;
                    default:
                        if (defaultAnswer.isPresent()) {
                            answer = defaultAnswer;
                        } else {
                            printStream.println("Unrecognized input: " + readLine);

                            continue;
                        }//from   www  .j ava  2s. co m

                        break;
                    }
                } else {
                    answer = defaultAnswer;
                }
            }
        }
    } catch (IllegalStateException ise) {
        throw new RuntimeException(ise);
    } catch (Exception exception) {
        if (defaultAnswer.isPresent()) {
            answer = defaultAnswer;
        }
    }

    return answer;
}

From source file:org.onosproject.sdxl3.config.SdxParticipantsConfig.java

/**
 * Gets the set of configured BGP peers.
 *
 * @return BGP peers/*from  ww  w.j a  va  2s  .  co m*/
 */
public Set<PeerConfig> bgpPeers() {
    Set<PeerConfig> peers = Sets.newHashSet();

    JsonNode peersNode = object.get(PEERS);

    if (peersNode == null) {
        return peers;
    }
    peersNode.forEach(jsonNode -> {
        Optional<String> name;
        if (jsonNode.get(NAME) == null) {
            name = Optional.empty();
        } else {
            name = Optional.of(jsonNode.get(NAME).asText());
        }

        peers.add(new PeerConfig(name, IpAddress.valueOf(jsonNode.path(IP).asText()),
                ConnectPoint.deviceConnectPoint(jsonNode.path(CONN_POINT).asText()),
                jsonNode.path(INTF_NAME).asText()));
    });

    return peers;
}

From source file:com.github.cbismuth.fdupes.collect.PathAnalyser.java

public Optional<Path> getTimestampPath(final Path destination, final Path path) {
    final Optional<Path> result;

    final String name = FilenameUtils.getName(path.toString());

    final Matcher matcher_1 = PATTERN_1.matcher(name);
    if (matcher_1.matches()) {
        result = Optional.of(onMatch(destination, matcher_1));
    } else {/*from   ww w  .  j a v a 2 s .com*/
        final Matcher matcher_2 = PATTERN_2.matcher(name);
        if (matcher_2.matches()) {
            result = Optional.of(onMatch(destination, matcher_2));
        } else {
            LOGGER.warn("File [{}] doesn't match pattern", path);

            result = Optional.empty();
        }
    }

    return result;
}

From source file:alfio.controller.support.TemplateProcessorTest.java

private void assertDimensionsUnder300x150(Pair<String, String> p) {
    Map<String, String> parameters = new HashMap<>();
    parameters.put(FileBlobMetadata.ATTR_IMG_WIDTH, p.getLeft());
    parameters.put(FileBlobMetadata.ATTR_IMG_HEIGHT, p.getRight());
    FileBlobMetadata metadata = mock(FileBlobMetadata.class);
    when(metadata.getAttributes()).thenReturn(parameters);
    Event e = mock(Event.class);
    when(e.getFileBlobIdIsPresent()).thenReturn(true);
    FileUploadManager fileUploadManager = mock(FileUploadManager.class);
    when(fileUploadManager.findMetadata(e.getFileBlobId())).thenReturn(Optional.of(metadata));
    TemplateProcessor.extractImageModel(e, fileUploadManager).ifPresent(imageData -> {
        assertTrue(imageData.getImageWidth() <= 300);
        assertTrue(imageData.getImageHeight() <= 150);
    });//from  w  w w. ja va  2  s . c om
}