Example usage for java.util Optional isPresent

List of usage examples for java.util Optional isPresent

Introduction

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

Prototype

public boolean isPresent() 

Source Link

Document

If a value is present, returns true , otherwise false .

Usage

From source file:com.intel.podm.client.typeidresolver.ResourceResolver.java

@Override
public JavaType typeFromId(DatabindContext context, String id) {
    for (OdataTypeMatcher matcher : MATCHERS) {
        Optional<Class> matchedClass = matcher.match(id);

        if (matchedClass.isPresent()) {
            return defaultInstance().constructSpecializedType(baseType, matchedClass.get());
        }/*  w w w  . j a  v a2s .com*/
    }

    if (defaultTypeRequired()) {
        return createDefaultType(id);
    }

    LOGGER.e("Encountered an unknown @odata.type: {}", id);
    throw new NotImplementedException(id);
}

From source file:com.minitwit.web.MainController.java

/**
 * Request the Home page.  If the user has authenticated, then then
 * see their full timeline; otherwise the user is redirected to the
 * Public Home page./*from  w w  w  .  ja v a  2 s.co  m*/
 * 
 * @param request
 *   The HTTP request.
 * 
 * @return
 *   The View (with Model) to render in response.
 */
@RequestMapping(value = "/", method = GET)
public ModelAndView userHome(final WebRequest request) {
    final Optional<User> authenticatedUser = getAuthenticatedUser(request);
    if (authenticatedUser.isPresent()) {
        final ModelAndView nav = new ModelAndView("timeline");
        nav.addObject("title", "Timeline");
        nav.addObject("pageTitle", "Timeline");
        nav.addObject("user", authenticatedUser.get());
        List<Message> messages = twitSvc.getUserFullTimelineMessages(authenticatedUser.get());
        nav.addObject("messages", messages);
        return nav;
    } else {
        return new ModelAndView(new RedirectView("/public"));
    }
}

From source file:ch.zweivelo.renderer.simple.shapes.PlaneTest.java

@Test
public void testCalculateIntersectionDistance() throws Exception {

    Optional<Double> doubleOptional = plane.calculateIntersectionDistance(ray);

    assertNotNull(doubleOptional);//from w  ww . j a v  a 2s .  c  o m
    assertTrue(doubleOptional.isPresent());
    assertEquals(1d, doubleOptional.get(), EPSILON);
}

From source file:net.sf.jabref.logic.exporter.CustomExportList.java

private void readPrefs(JabRefPreferences prefs) {
    formats.clear();/*from  w ww  . j  a v  a 2 s  .  c  om*/
    list.clear();
    int i = 0;
    List<String> s;
    while (!((s = prefs.getStringList(JabRefPreferences.CUSTOM_EXPORT_FORMAT + i)).isEmpty())) {
        Optional<ExportFormat> format = createFormat(s);
        if (format.isPresent()) {
            formats.put(format.get().getConsoleName(), format.get());
            list.add(s);
        } else {
            String customExportFormat = prefs.get(JabRefPreferences.CUSTOM_EXPORT_FORMAT + i);
            LOGGER.error("Error initializing custom export format from string " + customExportFormat);
        }
        i++;
    }
}

From source file:com.netflix.spinnaker.orca.clouddriver.tasks.pipeline.MigratePipelineClustersTask.java

@Override
public TaskResult execute(Stage stage) {

    Map<String, Object> context = stage.getContext();
    Optional<Map<String, Object>> pipelineMatch = getPipeline(context);

    if (!pipelineMatch.isPresent()) {
        return pipelineNotFound(context);
    }/*  ww w.j ava2 s .  c  om*/

    List<Map> sources = getSources(pipelineMatch.get());
    List<Map<String, Map>> operations = generateKatoOperation(context, sources);

    TaskId taskId = katoService.requestOperations(getCloudProvider(stage), operations).toBlocking().first();
    Map<String, Object> outputs = new HashMap<>();
    outputs.put("notification.type", "migratepipelineclusters");
    outputs.put("kato.last.task.id", taskId);
    outputs.put("source.pipeline", pipelineMatch.get());
    return new DefaultTaskResult(ExecutionStatus.SUCCEEDED, outputs);
}

From source file:net.sf.jabref.exporter.CustomExportList.java

private void readPrefs() {
    formats.clear();//  www.  j  a  va  2s  . com
    list.clear();
    int i = 0;
    List<String> s;
    while (!((s = Globals.prefs.getStringList(JabRefPreferences.CUSTOM_EXPORT_FORMAT + i)).isEmpty())) {
        Optional<ExportFormat> format = createFormat(s);
        if (format.isPresent()) {
            formats.put(format.get().getConsoleName(), format.get());
            list.add(s);
        } else {
            String customExportFormat = Globals.prefs.get(JabRefPreferences.CUSTOM_EXPORT_FORMAT + i);
            LOGGER.error("Error initializing custom export format from string " + customExportFormat);
        }
        i++;
    }
}

From source file:com.javaeeeee.repositories.UsersRepositoryTest.java

/**
 * A method to test that findByUsername returns a user.
 *///from  w ww  .ja v  a2s  .com
@Test
public void findByUsernameShouldReturnAUser() {
    final String name = "Phil";
    entityManager.persist(new User(name, "1"));
    Optional<User> optional = usersRepository.findByUsername(name);

    Assert.assertTrue(optional.isPresent());
    User user = optional.get();

    Assert.assertEquals(name, user.getUsername());
}

From source file:com.skelril.skree.content.modifier.ModExtendCommand.java

@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    Optional<ModifierService> optService = Sponge.getServiceManager().provide(ModifierService.class);
    if (!optService.isPresent()) {
        src.sendMessage(Text.of(TextColors.DARK_RED, "Modifier service not found."));
        return CommandResult.empty();
    }//from  w  ww  .  j a  v a 2  s. c om
    ModifierService service = optService.get();

    String modifier = args.<String>getOne("modifier").get();
    int minutes = args.<Integer>getOne("minutes").get();

    boolean wasActive = service.isActive(modifier);

    service.extend(modifier, TimeUnit.MINUTES.toMillis(minutes));

    String friendlyName = StringUtils.capitalize(modifier.replace("_", " ").toLowerCase());
    String friendlyTime = PrettyText.date(service.expiryOf(modifier));

    String change = wasActive ? " extended" : " enabled";
    String rawMessage = friendlyName + change + " till " + friendlyTime + "!";

    MessageChannel.TO_ALL.send(Text.of(TextColors.GOLD, rawMessage));
    GameChatterPlugin.inst().sendSystemMessage(rawMessage);

    return CommandResult.success();
}

From source file:net.pkhsolutions.pecsapp.control.ScalingPictureFileStorage.java

@NotNull
public Optional<BufferedImage> loadForLayout(@NotNull PictureDescriptor descriptor, @NotNull PageLayout layout)
        throws IOException {
    @NotNull
    Optional<BufferedImage> image = pictureFileStorage.load(descriptor, Optional.of(layout));
    if (!image.isPresent()) {
        LOGGER.debug("Could not find image for descriptor {} and layout {}, trying to find raw image",
                descriptor, layout);//from  w  ww.j a v a2s  . co  m
        // Try with the raw image
        image = pictureFileStorage.load(descriptor, Optional.empty());
        if (image.isPresent()) {
            LOGGER.debug("Found raw image, scaling it to layout {} and storing it", layout);
            // We don't have a size for this layout, so let's create one
            image = image.map(img -> pictureTransformer.scaleIfNecessary(img, layout));
            pictureFileStorage.store(descriptor, Optional.of(layout), image.get());
        }
    }
    return image;
}

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

/************************************************************************
 * Determines if a given syllogism for an equivalence type is valid.
 *
 * @param memeKey/*from   w  w  w .  j a  v a2s .c o  m*/
 * @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();
}