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:fi.helsinki.opintoni.security.CustomAuthenticationSuccessHandlerTest.java

@Test
public void thatMissingOodiPersonIdIsUpdated() throws Exception {
    Optional<User> user = Optional.of(new User());
    when(userService.findFirstByEduPersonPrincipalName(EDU_PRINCIPAL_NAME)).thenReturn(user);

    handler.onAuthenticationSuccess(mock(HttpServletRequest.class), mockResponse(), authentication);

    verify(userService, times(1)).save(argThat(new UserMatcher()));
}

From source file:com.uber.hoodie.common.TestRawTripPayload.java

@Override
public Optional<IndexedRecord> getInsertValue(Schema schema) throws IOException {
    if (isDeleted) {
        return Optional.empty();
    } else {//  w ww .  j  a  va2s.  co  m
        MercifulJsonConverter jsonConverter = new MercifulJsonConverter(schema);
        return Optional.of(jsonConverter.convert(getJsonData()));
    }
}

From source file:io.gravitee.gateway.http.core.endpoint.impl.tenant.MultiTenantAwareEndpointLifecycleManagerTest.java

@Test
public void shouldNotStartEndpoint_backup() throws Exception {
    io.gravitee.definition.model.Endpoint endpoint = mock(io.gravitee.definition.model.Endpoint.class);

    when(endpoint.isBackup()).thenReturn(true);
    when(proxy.getEndpoints()).thenReturn(Collections.singletonList(endpoint));

    when(gatewayConfiguration.tenant()).thenReturn(Optional.of("europe"));
    endpointLifecycleManager.start();// w  w w .ja v  a2  s. co  m

    verify(applicationContext, never()).getBean(eq(HttpClient.class), any(Endpoint.class));

    assertTrue(endpointLifecycleManager.targetByEndpoint().isEmpty());
    assertTrue(endpointLifecycleManager.endpoints().isEmpty());
}

From source file:io.kamax.mxisd.util.GsonParser.java

public <T> Optional<T> parseOptional(HttpResponse res, String memberName, Class<T> type) throws IOException {
    try {//ww w  .  j a v a 2s  .co m
        return Optional.of(parse(res.getEntity().getContent(), memberName, type));
    } catch (JsonMemberNotFoundException e) {
        return Optional.empty();
    }
}

From source file:com.okta.scim.SingleUserController.java

/**
 * Update via Patch {@link User} attributes
 *
 * @param payload Payload from HTTP request
 * @param id {@link User#id}/*www.  j a  v  a 2  s.  c  o m*/
 *
 * @return {@link #scimError(String, Optional)} / JSON {@link Map} of {@link User}
 */
@RequestMapping(method = RequestMethod.PATCH)
public @ResponseBody Map singleUserPatch(@RequestBody Map<String, Object> payload, @PathVariable String id) {
    List schema = (List) payload.get("schemas");
    List<Map> operations = (List) payload.get("Operations");

    if (schema == null) {
        return scimError("Payload must contain schema attribute.", Optional.of(400));
    }
    if (operations == null) {
        return scimError("Payload must contain operations attribute.", Optional.of(400));
    }

    //Verify schema
    String schemaPatchOp = "urn:ietf:params:scim:api:messages:2.0:PatchOp";
    if (!schema.contains(schemaPatchOp)) {
        return scimError("The 'schemas' type in this request is not supported.", Optional.of(501));
    }

    //Find user for update
    User user = db.findById(id).get(0);

    for (Map map : operations) {
        if (map.get("op") == null && !map.get("op").equals("replace")) {
            continue;
        }
        Map<String, Object> value = (Map) map.get("value");

        // Use Java reflection to find and set User attribute
        if (value != null) {
            for (Map.Entry key : value.entrySet()) {
                try {
                    Field field = user.getClass().getDeclaredField(key.getKey().toString());
                    field.set(user, key.getValue());
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    // Error - Do not update field
                }
            }
        }
    }
    return user.toScimResource();
}

From source file:org.sonarqube.shell.commands.SonarSession.java

<T> Optional<T> get(String path, Class<T> clazz, Optional<Map<String, String>> params) {
    try {/*from   w  w w.ja va2  s.  c  om*/
        WebTarget resource = rootContext.path(path);
        if (params.isPresent()) {
            for (Map.Entry<String, String> entry : params.get().entrySet()) {
                resource = resource.queryParam(entry.getKey(), entry.getValue());
            }
        }
        return Optional.of(resource.request(MediaType.APPLICATION_JSON_TYPE).get(clazz));
    } catch (ProcessingException | NotFoundException e) {
        LOGGER.error("Failed to get the resource {} and convert it to {}", path, clazz.getName());
    }
    return empty();
}

From source file:org.ng200.openolympus.services.ContestService.java

public Instant getContestEndIncludingAllTimeExtensions(final Contest contest) {
    return contest.getStartTime().toInstant().plusMillis(contest.getDuration())
            .plusMillis(this.contestTimeExtensionRepository.findByContest(contest).stream()
                    .collect(Collectors.groupingBy(timeExtension -> timeExtension.getContest())).values()
                    .stream()// w  w w . ja v a2s.  com
                    .map(group -> group.stream().map(timeExtension -> timeExtension.getDuration())
                            .reduce((l, r) -> l + r))
                    .max((l, r) -> l.orElse(0l).compareTo(r.orElse(0l))).orElse(Optional.of(0l)).orElse(0l));
}

From source file:com.yodle.vantage.component.service.ComponentServiceTest.java

@Test
public void givenVersionHasResolvedDependencies_createOrUpdateVersion_createsResolvedDependencyVersions() {
    when(versionDao.getVersion(COMPONENT, VERSION)).thenReturn(Optional.of(new Version(COMPONENT, VERSION)));

    Version version = new Version(COMPONENT, VERSION);
    Dependency dependency = createDependency();
    version.setResolvedDependencies(Sets.newHashSet(dependency));

    componentService.createOrUpdateVersion(version);

    verify(componentDao).ensureCreated(dependency.getVersion().getComponent());
    verify(versionDao).createResolvedDependency(version, dependency.getVersion(), dependency.getProfiles());
}

From source file:com.todo.backend.security.JWTFilter.java

private Optional<String> extractToken(HttpServletRequest request) {
    final String bearerToken = request.getHeader(AUTHORIZATION);
    if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(BEARER)) {
        final String jwtToken = bearerToken.substring(BEARER.length(), bearerToken.length());
        return Optional.of(jwtToken);
    }/* ww w  .  ja v  a 2 s . c  o m*/
    return Optional.empty();
}

From source file:com.ikanow.aleph2.analytics.storm.utils.TestStormControllerUtil.java

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

    try {//from  w  w  w  .  j  a  va  2s  . co  m
        _app_injector = ModuleUtils.createTestInjector(Arrays.asList(), Optional.of(config));
    } catch (Exception e) {
        try {
            e.printStackTrace();
        } catch (Exception ee) {
            System.out.println(ErrorUtils.getLongForm("{0}", e));
        }
    }
}