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.anhonesteffort.p25.ACAP25.java

private Optional<Double> findActiveControlChannel(Integer systemId, Integer systemWacn, Site site) {
    for (Double channelFreq : site.getControlChannels()) {
        P25ChannelSpec channelSpec = new P25ChannelSpec(channelFreq);
        P25Channel channel = new P25Channel(channelSpec);
        ControlChannelQualifier channelQualifier = new ControlChannelQualifier(controlChannelPool,
                samplesController, channel, systemId, systemWacn);

        try {// ww  w . j a  va2 s  .c o  m

            Future<Optional<Double>> channelQualified = controlChannelPool.submit(channelQualifier);
            Optional<Double> controlFreq = channelQualified.get();

            if (controlFreq.isPresent()) {
                log.info(
                        "found active control channel at " + controlFreq.get() + " for site " + site.getName());
                return Optional.of(controlFreq.get());
            }

        } catch (InterruptedException | ExecutionException e) {
            log.error("error while identifying active control channels, exiting", e);
            java.lang.System.exit(1);
        }
    }

    return Optional.empty();
}

From source file:net.ctalkobt.syllogism.Context.java

/************************************************************************
 * Determines if a given syllogism for an equivalence type is valid.
 *
 * @param memeKey// w ww  . j a v a  2  s  .com
 * @param equivalence
 * @param memeValue
 * @return result if known, otherwise optional.empty(). 
 ***********************************************************************/
public Optional<Boolean> interrogate(Term memeKey, Copula equivalence, Term memeValue) {
    Collection<KeyValue<Copula, Term>> memeRelations = (Collection<KeyValue<Copula, Term>>) memeAssociations
            .get(memeKey);
    if (memeRelations == null || memeRelations.isEmpty()) {
        return Optional.empty();
    }

    Optional<KeyValue<Copula, Term>> result = memeRelations.parallelStream().findFirst()
            .filter((KeyValue<Copula, Term> kv) -> {
                if (kv.getKey().equals(equivalence) && kv.getValue().equals(memeValue)) {
                    return true;
                } else {
                    Optional<Boolean> result1 = interrogate(kv.getValue(), equivalence, memeValue);
                    return result1.isPresent();
                }
            });

    if (result.isPresent()) {
        return Optional.of(equivalence.getTruthEquivalency());
    }
    return Optional.empty();
}

From source file:com.openthinks.webscheduler.service.WebSecurityService.java

public Optional<User> validateUser(String userName, String userPass) {
    User user = getUsers().findByName(userName);
    if (user != null && userPass != null) {
        String encryptPass = DigestUtils.md5Hex(userPass);
        if (user.getPass().equals(encryptPass)) {
            User loginUserInfo = user.clone();//fix second login failed issue
            loginUserInfo.setPass(null);
            return Optional.of(loginUserInfo);
        }//from   ww  w.j  a  va2 s . c o  m
    }
    return Optional.empty();
}

From source file:com.devicehive.resource.DeviceNotificationResourceTest.java

@Test
public void should_get_response_with_status_200_and_notification_when_waitTimeout_is_0_and_polling_for_device() {
    DeviceClassEquipmentVO equipment = DeviceFixture.createEquipmentVO();
    DeviceClassUpdate deviceClass = DeviceFixture.createDeviceClass();
    deviceClass.setEquipment(Optional.of(Collections.singleton(equipment)));
    NetworkVO network = DeviceFixture.createNetwork();
    String guid = UUID.randomUUID().toString();
    DeviceUpdate deviceUpdate = DeviceFixture.createDevice(guid);
    deviceUpdate.setDeviceClass(Optional.of(deviceClass));
    deviceUpdate.setNetwork(Optional.of(network));
    DateTime timeStamp = new DateTime(DateTimeZone.UTC);

    // register device
    Response response = performRequest("/device/" + guid, "PUT", emptyMap(),
            singletonMap(HttpHeaders.AUTHORIZATION, tokenAuthHeader(ACCESS_KEY)), deviceUpdate, NO_CONTENT,
            null);//  w  w w .  j  a v a2  s . c o m
    assertNotNull(response);

    // Create notification
    DeviceNotification notification = DeviceFixture.createDeviceNotification();
    notification = performRequest("/device/" + guid + "/notification", "POST", emptyMap(),
            singletonMap(HttpHeaders.AUTHORIZATION, tokenAuthHeader(ACCESS_KEY)), notification, CREATED,
            DeviceNotification.class);
    assertNotNull(notification.getId());

    // poll notification
    Map<String, Object> params = new HashMap<>();
    params.put("waitTimeout", 0);
    params.put("timestamp", timeStamp);
    ArrayList notifications = new ArrayList();
    notifications = performRequest("/device/" + guid + "/notification/poll", "GET", params,
            singletonMap(HttpHeaders.AUTHORIZATION, tokenAuthHeader(ACCESS_KEY)), null, OK,
            notifications.getClass());
    assertNotNull(notifications);
    assertEquals(1, notifications.size());
}

From source file:com.fredhopper.connector.index.populator.CategoryPopulatorTest.java

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);

    final IndexConfig config = mock(IndexConfig.class);

    when(config.getLocales()).thenReturn(localesEnDe);
    when(source1.getIndexConfig()).thenReturn(config);
    when(source2.getIndexConfig()).thenReturn(config);

    final CategoryModel category1 = mock(CategoryModel.class);
    mockCategory(category1, 1);/*  ww  w  .  ja va2  s .  c om*/
    when(source1.getItem()).thenReturn(category1);
    when(parentResolver.resolve(category1)).thenReturn(Optional.empty());

    final CategoryModel category2 = mock(CategoryModel.class);
    mockCategory(category2, 2);
    when(source2.getItem()).thenReturn(category2);
    when(parentResolver.resolve(category2)).thenReturn(Optional.of(category1));

    when(sanitizeIdStrategy.sanitizeId("cat1")).thenReturn("cat1");
    when(sanitizeIdStrategy.sanitizeId("cat2")).thenReturn("cat2");

    categoryPopulator = new CategoryPopulator();
    categoryPopulator.setParentCategoryResolver(parentResolver);

    categoryPopulator.setSanitizeIdStrategy(sanitizeIdStrategy);

}

From source file:org.mytms.common.data.Pageable.java

/**
 * Returns an {@link Optional} so that it can easily be mapped on.
 * /*from www .j  a  va2  s .  c  o m*/
 * @return
 */
default Optional<Pageable> toOptional() {
    return isUnpaged() ? Optional.empty() : Optional.of(this);
}

From source file:org.ow2.proactive.workflow_catalog.rest.controller.WorkflowRevisionControllerTest.java

@Test
public void testGet() throws Exception {
    workflowRevisionController.get(BUCKET_ID, WF_ID, REV_ID, Optional.empty());
    verify(workflowRevisionService, times(1)).getWorkflow(BUCKET_ID, WF_ID, Optional.of(REV_ID),
            Optional.empty());//  www. ja  v  a  2s.co  m
}

From source file:com.ikanow.aleph2.storm.samples.TestJavaScriptTopology.java

@Before
public void injectModules() throws Exception {
    final Config config = ConfigFactory
            .parseFile(new File("./example_config_files/context_local_test.properties"));

    try {/*  w  w  w .j  av a2 s  . co  m*/
        _app_injector = ModuleUtils.createTestInjector(Arrays.asList(), Optional.of(config));
        _local_cluster = new LocalCluster();
        this.ips = readIps();

        _app_injector.injectMembers(this);
    } catch (Exception e) {
        try {
            e.printStackTrace();
        } catch (Exception ee) {
            System.out.println(ErrorUtils.getLongForm("{0}", e));
        }
    }
}

From source file:org.springsource.restbucks.payment.PaymentServiceImplUnitTest.java

@Test
public void throwsOrderPaidEventOnPayment() {

    CreditCard creditCard = new CreditCard(NUMBER, "Oliver Gierke", Month.JANUARY, Year.of(2020));
    when(creditCardRepository.findByNumber(NUMBER)).thenReturn(Optional.of(creditCard));

    Order order = new Order();
    ReflectionTestUtils.setField(order, "id", 1L);

    paymentService.pay(order, NUMBER);/*from  ww w. java 2s .  co m*/

    verify(publisher).publishEvent(Mockito.any((OrderPaidEvent.class)));
}

From source file:de.Keyle.MyPet.util.Updater.java

protected Optional<Update> check() {
    try {//from w w w  . j a  v a2 s .  c o  m
        String parameter = "";
        parameter += "&package=" + MyPetApi.getCompatUtil().getInternalVersion();
        parameter += "&build=" + MyPetVersion.getBuild();
        parameter += "&dev=" + MyPetVersion.isDevBuild();

        String url = "http://update.mypet-plugin.de/" + plugin + "?" + parameter;

        // no data will be saved on the server
        String content = Util.readUrlContent(url);
        JSONParser parser = new JSONParser();
        JSONObject result = (JSONObject) parser.parse(content);

        if (result.containsKey("latest")) {
            String version = result.get("latest").toString();
            int build = ((Long) result.get("build")).intValue();
            return Optional.of(new Update(version, build));
        }
    } catch (Exception ignored) {
        ignored.printStackTrace();
    }
    return Optional.empty();
}