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:org.owasp.webgoat.controller.StartLesson.java

@RequestMapping(value = { "*.lesson" }, produces = "text/html")
public ModelAndView lessonPage(HttpServletRequest request) {
    // I will set here the thymeleaf fragment location based on the resource requested.
    ModelAndView model = new ModelAndView();
    SecurityContext context = SecurityContextHolder.getContext(); //TODO this should work with the security roles of Spring
    GrantedAuthority authority = context.getAuthentication().getAuthorities().iterator().next();
    String path = request.getServletPath(); // we now got /a/b/c/AccessControlMatrix.lesson
    String lessonName = path.substring(path.lastIndexOf('/') + 1, path.indexOf(".lesson"));
    List<AbstractLesson> lessons = course.getLessons();
    Optional<AbstractLesson> lesson = lessons.stream().filter(l -> l.getId().equals(lessonName)).findFirst();
    ws.setCurrentLesson(lesson.get());
    model.setViewName("lesson_content");
    model.addObject("lesson", lesson.get());
    return model;
}

From source file:com.googlesource.gerrit.plugins.lfs.fs.LfsFsContentServlet.java

@Override
protected void doHead(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
    String verifyId = req.getHeader(HttpHeaders.IF_NONE_MATCH);
    if (Strings.isNullOrEmpty(verifyId)) {
        doGet(req, rsp);//ww  w .jav a 2 s .  c om
        return;
    }

    Optional<AnyLongObjectId> obj = validateGetRequest(req, rsp);
    if (obj.isPresent() && obj.get().getName().equalsIgnoreCase(verifyId)) {
        rsp.addHeader(HttpHeaders.ETAG, obj.get().getName());
        rsp.setStatus(HttpStatus.SC_NOT_MODIFIED);
        return;
    }

    getObject(req, rsp, obj);
}

From source file:com.macrossx.wechat.impl.WechatUserHelper.java

public Optional<WechatUserGet> userGet(String nextOpenid) {
    try {/*from w ww. ja  v  a 2s  . com*/
        Optional<WechatAccessToken> token = helper.getAccessToken();
        if (token.isPresent()) {
            WechatAccessToken accessToken = token.get();
            HttpGet httpGet = new HttpGet();

            httpGet.setURI(new URI(MessageFormat.format(WechatConstants.USER_GET_URL,
                    accessToken.getAccess_token(), nextOpenid == null ? "" : nextOpenid)));
            return new WechatHttpClient().send(httpGet, WechatUserGet.class);
        }
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        log.info(e.getMessage());
    }
    return Optional.empty();
}

From source file:com.macrossx.wechat.impl.WechatUserHelper.java

public Optional<WechatUserInfo> userInfo(String openid) {
    try {/*from   w  w w.  ja  v a  2s. com*/
        Optional<WechatAccessToken> token = helper.getAccessToken();
        if (token.isPresent()) {
            WechatAccessToken accessToken = token.get();
            HttpGet httpGet = new HttpGet();

            httpGet.setURI(new URI(MessageFormat.format(WechatConstants.USER_INFO_URL,
                    accessToken.getAccess_token(), openid)));
            return new WechatHttpClient().send(httpGet, WechatUserInfo.class);
        }
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        log.info(e.getMessage());
    }
    return Optional.empty();
}

From source file:org.apache.solr.client.solrj.impl.PreemptiveBasicAuthClientBuilderFactory.java

@Override
public SolrHttpClientBuilder getHttpClientBuilder(Optional<SolrHttpClientBuilder> builder) {
    return builder.isPresent() ? initHttpClientBuilder(builder.get())
            : initHttpClientBuilder(SolrHttpClientBuilder.create());
}

From source file:io.kamax.mxisd.lookup.provider.BridgeFetcher.java

@Override
public Optional<SingleLookupReply> find(SingleLookupRequest request) {
    Optional<String> mediumUrl = Optional.ofNullable(cfg.getMappings().get(request.getType()));
    if (mediumUrl.isPresent() && !StringUtils.isBlank(mediumUrl.get())) {
        log.info("Using specific medium bridge lookup URL {}", mediumUrl.get());

        return fetcher.find(mediumUrl.get(), request);
    } else if (!StringUtils.isBlank(cfg.getServer())) {
        log.info("Using generic bridge lookup URL {}", cfg.getServer());

        return fetcher.find(cfg.getServer(), request);
    } else {/*from ww  w . ja  v  a 2  s.c  o  m*/
        log.info("No bridge lookup URL found/configured, skipping");

        return Optional.empty();
    }
}

From source file:com.galenframework.ide.controllers.DomSnapshotController.java

public void initRoutes() {
    post("/api/dom-snapshots", (req, res) -> {
        String url = req.params().get("url");
        String source = req.params().get("source");
        if (url == null || source == null) {
            DomSnapshotRequest snapshotRequest = mapper.readValue(req.body(), DomSnapshotRequest.class);
            url = snapshotRequest.getUrl();
            source = snapshotRequest.getSource();
        }//w ww  .jav a  2s  .  c  o m
        return domSnapshotService.createSnapshot(source, url);
    });

    get("/api/dom-snapshots/:domId/snapshot.html", (req, res) -> {
        res.header("Content-Type", "text/html");
        String domId = req.params("domId");
        if (domId != null && !domId.trim().isEmpty()) {
            Optional<DomSnapshot> domSnapshot = domSnapshotService.getDomSnapshot(domId);
            if (domSnapshot.isPresent()) {
                return domSnapshot.get().getOriginSource();
            } else {
                return "Can't find DOM snapshot for key: " + domId;
            }
        } else
            throw new RuntimeException("Incorrect request, missing domId");
    });
}

From source file:spring.travel.site.services.UserServiceTest.java

@Test
public void shouldReturnUserWithAnAddress() throws Exception {
    stubGet("/user?id=123",
            new User("123", "Fred", "Flintstone", "freddyf", Optional.of(new Address("345 Stonecave Road",
                    "Bedrock", "70777", "US", new Location(5290307, 36.128551, -112.036070)))));

    HandOff<Optional<User>> handOff = new HandOff<>();

    userService.user(Optional.of("123")).whenComplete((user, t) -> handOff.put(user));

    Optional<User> optionalUser = handOff.get(1);
    assertNotEquals(Optional.empty(), optionalUser);

    User user = optionalUser.get();
    assertEquals("Fred", user.getFirstName());
    assertNotEquals(Optional.empty(), user.getAddress());

    Address address = user.getAddress().get();
    assertEquals("345 Stonecave Road", address.getFirstLine());
    assertEquals(5290307, address.getLocation().getCityId());
}

From source file:de.bytefish.elasticutils.elasticsearch2.utils.JsonUtilitiesTest.java

@Test
public void json_is_generated_when_serialization_succeeds() throws Exception {

    TestEntity entity = new TestEntity();

    entity.val = "Test";

    Optional<byte[]> resultBytes = JsonUtilities.convertJsonToBytes(entity);

    Assert.assertEquals(true, resultBytes.isPresent());
    Assert.assertEquals("{\"val\":\"Test\"}", new String(resultBytes.get()));
}

From source file:com.facebook.presto.accumulo.AccumuloClient.java

private static void validateLocalityGroups(ConnectorTableMetadata meta) {
    // Validate any configured locality groups
    Optional<Map<String, Set<String>>> groups = AccumuloTableProperties.getLocalityGroups(meta.getProperties());
    if (!groups.isPresent()) {
        return;/*w w  w  .ja  v a  2s . c  om*/
    }

    String rowIdColumn = getRowIdColumn(meta);

    // For each locality group
    for (Map.Entry<String, Set<String>> g : groups.get().entrySet()) {
        if (g.getValue().contains(rowIdColumn)) {
            throw new PrestoException(INVALID_TABLE_PROPERTY, "Row ID column cannot be in a locality group");
        }

        // Validate the specified column names exist in the table definition,
        // incrementing a counter for each matching column
        int matchingColumns = 0;
        for (ColumnMetadata column : meta.getColumns()) {
            if (g.getValue().contains(column.getName().toLowerCase(Locale.ENGLISH))) {
                ++matchingColumns;

                // Break out early if all columns are found
                if (matchingColumns == g.getValue().size()) {
                    break;
                }
            }
        }

        // If the number of matched columns does not equal the defined size,
        // then a column was specified that does not exist
        // (or there is a duplicate column in the table DDL, which is also an issue but has been checked before in validateColumns).
        if (matchingColumns != g.getValue().size()) {
            throw new PrestoException(INVALID_TABLE_PROPERTY,
                    "Unknown Presto column defined for locality group " + g.getKey());
        }
    }
}