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.todo.backend.security.JWTFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    try {/*from   ww w. j  a  va2  s .c o  m*/
        final HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        final Optional<String> jwtToken = extractToken(httpServletRequest);
        if (jwtToken.isPresent()) {
            final Authentication authentication = JWTUtils.getAuthentication(jwtToken.get(), secretKey);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException e) {
        log.debug("Security exception for user {} - {}. Expired token.", e.getClaims().getSubject(),
                e.getMessage());
        ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Authentication token expired!");
    } catch (JwtException e) {
        log.debug("Authentication token is invalid. {}", e.getMessage());
        ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Authentication token is invalid!");
    }
}

From source file:fi.helsinki.opintoni.integration.unisport.UnisportRestClientTest.java

@Test
public void that404ForUnauthorizedIsHandled() {
    unisportServer.expectAuthorizationFailWith404();
    Optional<UnisportUser> userByPrincipal = unisportRestClient.getUnisportUserByPrincipal(TEACHER_PRINCIPAL);
    assertThat(userByPrincipal.isPresent()).isFalse();
}

From source file:com.rcs.shoe.shop.fx.controller.ui.Controller.java

protected String showChoiseDialog(String title, String header, String content, List<String> choices,
        String selected) {//w  w  w .ja  v a  2 s .  co m
    ChoiceDialog<String> dialog = new ChoiceDialog<>(selected, choices);
    dialog.setTitle(title);
    dialog.setHeaderText(header);
    dialog.setContentText(content);

    Optional<String> result = dialog.showAndWait();
    if (result.isPresent()) {
        return result.get();
    }
    return null;
}

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

@Override
public void populate(final ItemToConvert<CategoryModel> source, final FhCategoryData target)
        throws ConversionException {
    Preconditions.checkArgument(source != null);
    Preconditions.checkArgument(target != null);

    final CategoryModel category = source.getItem();
    final Set<Locale> locales = source.getIndexConfig().getLocales();

    target.setCategoryId(getSanitizeIdStrategy().sanitizeId(category.getCode()));
    target.setNames(mapNames(category, locales));
    final Optional<CategoryModel> parent = parentCategoryResolver.resolve(category);
    if (parent.isPresent()) {
        target.setParentId(getSanitizeIdStrategy().sanitizeId(parent.get().getCode()));
    }/*from www .  j  a v  a2s.  c  om*/
}

From source file:com.rockagen.gnext.test.BaseTest.java

protected void newUser() throws RegisterException {
    AuthUserBO bo = new AuthUserBO();
    bo.setName("test user");
    bo.setUid("test");
    bo.setEmail("test@localhost.com");
    bo.setPhone("15100000000");
    bo.setAddress("USA");
    bo.setCreateUserReferer(UserReferer.LOCAL);
    bo.setType(UserType.GUEST);// w w  w.  j  a va2s .  c o  m
    bo.setPassword("test");
    authUserServ.signup(bo);

    Optional<AuthUser> u = authUserServ.load(uid);
    if (u.isPresent()) {
        user = u.get();
    } else {
        fail("user not exist!");
    }
}

From source file:it.polimi.diceH2020.launcher.service.Validator.java

public boolean validatePrivateCloudParameters(Path pathToFile) {
    Optional<PrivateCloudParameters> sol = objectFromPath(pathToFile, PrivateCloudParameters.class);
    return (sol.isPresent() && sol.get().validate());
}

From source file:io.knotx.mocks.adapter.MockActionAdapterHandler.java

private AdapterResponse replyTransition(ClientRequest request, JsonObject transitions) {
    final Pair<Optional<String>, JsonObject> result = getTransitionResult(request, transitions);

    final JsonObject resultBody = result.getRight().put("form", toJsonObject(request.getFormAttributes()));

    final String data = resultBody.toString();
    final ClientResponse clientResponse = new ClientResponse().setHeaders(headers(request, data))
            .setStatusCode(HttpResponseStatus.OK.code()).setBody(Buffer.buffer(data));

    final AdapterResponse response = new AdapterResponse().setResponse(clientResponse);

    final Optional<String> transition = result.getLeft();
    if (transition.isPresent()) {
        response.setSignal(transition.get());
    }/* w  w  w .ja v a  2  s  .  co  m*/
    return response;
}

From source file:org.openmhealth.shim.misfit.mapper.MisfitPhysicalActivityDataPointMapper.java

@Override
public Optional<DataPoint<PhysicalActivity>> asDataPoint(JsonNode sessionNode) {

    checkNotNull(sessionNode);/*from   w  w  w  . j  a  v a 2  s .  co m*/

    String activityName = asRequiredString(sessionNode, "activityType");

    PhysicalActivity.Builder builder = new PhysicalActivity.Builder(activityName);

    Optional<Double> distance = asOptionalDouble(sessionNode, "distance");

    if (distance.isPresent()) {
        builder.setDistance(new LengthUnitValue(MILE, distance.get()));
    }

    Optional<OffsetDateTime> startDateTime = asOptionalOffsetDateTime(sessionNode, "startTime");
    Optional<Double> durationInSec = asOptionalDouble(sessionNode, "duration");

    if (startDateTime.isPresent() && durationInSec.isPresent()) {
        DurationUnitValue durationUnitValue = new DurationUnitValue(SECOND, durationInSec.get());
        builder.setEffectiveTimeFrame(ofStartDateTimeAndDuration(startDateTime.get(), durationUnitValue));
    }

    asOptionalBigDecimal(sessionNode, "calories")
            .ifPresent(calories -> builder.setCaloriesBurned(new KcalUnitValue(KILOCALORIE, 96.8)));

    PhysicalActivity measure = builder.build();

    Optional<String> externalId = asOptionalString(sessionNode, "id");

    return Optional.of(newDataPoint(measure, RESOURCE_API_SOURCE_NAME, externalId.orElse(null), null));
}

From source file:com.fredhopper.connector.query.populators.response.SearchResponseFacetsPopulator.java

@Override
public void populate(final FhSearchResponse source, final FacetSearchPageData<FhSearchQueryData, I> target)
        throws ConversionException {
    final Optional<Universe> universe = getUniverse(source);
    if (universe.isPresent() && CollectionUtils.isNotEmpty(universe.get().getFacetmap())) {
        final Results results = universe.get().getItemsSection().getResults();
        final int totalNumberResults = results != null ? results.getTotalItems() : 1;
        final List<Facetmap> facetMap = universe.get().getFacetmap();
        final List<FacetData<FhSearchQueryData>> facets = new ArrayList<>();
        for (final Facetmap facet : facetMap) {
            final List<Filter> filters = facet.getFilter();
            for (final Filter filter : filters) {
                final FacetData<FhSearchQueryData> facetData = createFacetData(source, filter,
                        totalNumberResults);
                facets.add(facetData);/*from  w w w  .j a  v a 2s . c  om*/
            }
        }
        target.setFacets(facets);
    } else {
        target.setFacets(Collections.emptyList());
    }
}

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

@Listener
public void onPlayerJoin(ClientConnectionEvent.Join event) {
    Optional<ModifierService> optService = Sponge.getServiceManager().provide(ModifierService.class);
    if (!optService.isPresent()) {
        return;//from www . j ava 2  s.co  m
    }

    ModifierService service = optService.get();

    List<String> messages = new ArrayList<>();
    for (Map.Entry<String, Long> entry : service.getActiveModifiers().entrySet()) {
        String friendlyName = StringUtils.capitalize(entry.getKey().replace("_", " ").toLowerCase());
        String friendlyTime = PrettyText.date(entry.getValue());
        messages.add(" - " + friendlyName + " till " + friendlyTime);
    }
    if (messages.isEmpty())
        return;

    Collections.sort(messages, String.CASE_INSENSITIVE_ORDER);
    messages.add(0, "\n\nThe following donation perks are enabled:");

    Player player = event.getTargetEntity();

    Task.builder().execute(() -> {
        for (String message : messages) {
            player.sendMessage(Text.of(TextColors.GOLD, message));
        }
    }).delay(1, TimeUnit.SECONDS).submit(SkreePlugin.inst());
}