Example usage for java.util Optional ifPresent

List of usage examples for java.util Optional ifPresent

Introduction

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

Prototype

public void ifPresent(Consumer<? super T> action) 

Source Link

Document

If a value is present, performs the given action with the value, otherwise does nothing.

Usage

From source file:pzalejko.iot.hardware.home.core.service.sender.MqttDataSender.java

@Override
public void send(Object object, EventType type) {
    checkNotNull(object);//from   w ww.j  a v  a  2s  .  co  m
    checkNotNull(type);

    final Optional<String> topic = Optional.ofNullable(topicMapper.getTopic(type));
    topic.ifPresent(t -> sendEvent(object, type, t));
}

From source file:alfio.util.TemplateResource.java

public static Map<String, Object> buildModelForTicketPDF(Organization organization, Event event,
        TicketReservation ticketReservation, TicketCategory ticketCategory, Ticket ticket,
        Optional<ImageData> imageData, String reservationId) {
    String qrCodeText = ticket.ticketCode(event.getPrivateKey());
    ///*w ww. j  a v  a 2s.c  o  m*/
    Map<String, Object> model = new HashMap<>();
    model.put("ticket", ticket);
    model.put("reservation", ticketReservation);
    model.put("ticketCategory", ticketCategory);
    model.put("event", event);
    model.put("organization", organization);
    model.put("reservationId", reservationId);
    fillTicketValidity(event, ticketCategory, model);

    model.put("qrCodeDataUri",
            "data:image/png;base64," + Base64.getEncoder().encodeToString(createQRCode(qrCodeText)));

    imageData.ifPresent(iData -> {
        model.put("eventImage", iData.getEventImage());
        model.put("imageWidth", iData.getImageWidth());
        model.put("imageHeight", iData.getEventImage());
    });

    model.put("deskPaymentRequired", Optional.ofNullable(ticketReservation.getPaymentMethod())
            .orElse(PaymentProxy.STRIPE).isDeskPaymentRequired());
    return model;
}

From source file:acmi.l2.clientmod.xdat.Controller.java

private static TreeItem<Object> createTreeItem(IOEntity o) {
    TreeItem<Object> item = new TreeItem<>(o);

    List<Field> fields = new ArrayList<>();
    Class<?> clazz = o.getClass();
    while (clazz != Object.class) {
        Arrays.stream(clazz.getDeclaredFields()).filter(field -> !field.isSynthetic())
                .filter(field -> List.class.isAssignableFrom(field.getType())
                        || IOEntity.class.isAssignableFrom(field.getType()))
                .forEach(fields::add);/*from   w  w w .j  av  a 2 s  .c o  m*/
        clazz = clazz.getSuperclass();
    }
    fields.forEach(field -> {
        field.setAccessible(true);

        Optional<Object> obj = Optional.empty();
        try {
            obj = Optional.ofNullable(field.get(o));
        } catch (IllegalAccessException e) {
            log.log(Level.WARNING, String.format("%s.%s is not accessible", o.getClass(), field.getName()), e);
            Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null,
                    String.format("%s.%s is not accessible", o.getClass(), field.getName()));
        }

        obj.ifPresent(val -> {
            if (List.class.isAssignableFrom(field.getType())) {
                if (!field.isAnnotationPresent(Type.class)) {
                    log.log(Level.WARNING,
                            String.format("%s.%s: @Type not defined", o.getClass().getName(), field.getName()));
                    Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null,
                            String.format("%s.%s: @Type not defined", o.getClass().getName(), field.getName()));
                } else {
                    List<IOEntity> list = (List<IOEntity>) val;
                    Class<? extends IOEntity> type = field.getAnnotation(Type.class).value()
                            .asSubclass(IOEntity.class);
                    TreeItem<Object> listItem = new TreeItem<>(new ListHolder(o, list, field.getName(), type));

                    item.getChildren().add(listItem);

                    listItem.getChildren()
                            .addAll(list.stream().map(Controller::createTreeItem).collect(Collectors.toList()));
                }
            } else if (IOEntity.class.isAssignableFrom(field.getType())) {
                IOEntity ioEntity = (IOEntity) val;

                item.getChildren().add(createTreeItem(ioEntity));
            }
        });
    });
    return item;
}

From source file:de.hybris.platform.consignmenttrackingaddon.controllers.pages.misc.ConsignmentTrackingController.java

@RequireHardLogIn
@RequestMapping(value = ORDER_CODE_PATH_VARIABLE_PATTERN + CONSIGNMENT_CODE_PATH_VARIABLE_PATTERN
        + "/tracking", method = RequestMethod.GET)
public String retrieveTrackingEvents(@PathVariable("orderCode") final String orderCode,
        @PathVariable("consignmentCode") final String consignmentCode, final Model model) {
    final Optional<ConsignmentData> optional = consignmentTrackingFacade.getConsignmentByCode(orderCode,
            consignmentCode);/* ww  w . j a  v  a 2 s .  c  om*/
    optional.ifPresent(consignment -> {
        model.addAttribute("consignment", consignment);
        model.addAttribute("statusCode", Integer.valueOf(getConsignmentStatusCode(consignment)));
        model.addAttribute("trackingUrl",
                consignmentTrackingFacade.getTrackingUrlForConsignmentCode(orderCode, consignmentCode));
    });

    return ControllerConstants.Views.Pages.Consignment.TrackPackagePage;
}

From source file:io.kamax.mxisd.controller.profile.v1.ProfileController.java

@RequestMapping("/{userId:.+}")
public String getProfile(HttpServletRequest req, HttpServletResponse res, @PathVariable String userId) {
    Optional<String> accessTokenOpt = findAccessToken(req);
    HttpGet reqOut = new HttpGet(resolveProxyUrl(req));
    accessTokenOpt.ifPresent(accessToken -> reqOut.addHeader("Authorization", "Bearer " + accessToken));

    try (CloseableHttpResponse hsResponse = client.execute(reqOut)) {
        res.setStatus(hsResponse.getStatusLine().getStatusCode());
        JsonElement el = parser.parse(EntityUtils.toString(hsResponse.getEntity()));
        List<_ThreePid> list = mgr.getThreepids(MatrixID.asAcceptable(userId));
        if (!list.isEmpty() && el.isJsonObject()) {
            JsonObject obj = el.getAsJsonObject();
            obj.add("threepids", GsonUtil.build().toJsonTree(list));
        }/*from w  w w .  j a  va  2 s .c o  m*/
        return gson.toJson(el);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.tesshu.subsonic.client.sample4_music_andmovie.StreamDownloadAndPlayApplication.java

@Override
public void start(Stage stage) throws Exception {

    Search2Controller search2 = context.getBean(Search2Controller.class);

    StreamController streamController = context.getBean(StreamController.class);

    SuccessObserver callback = context.getBean(SuccessObserver.class);

    File tmpDirectory = new File(tmpPath);
    tmpDirectory.mkdir();//from   w w w.  ja  va2s  .c  o  m

    Optional<SearchResult2> result2 = search2.getOf("e", null, null, null, null, 1, null, null);

    result2.ifPresent(result -> {
        Optional<Child> maybeSong = result.getSongs().stream().findFirst();
        maybeSong.ifPresent(song -> {

            streamController.stream(song, maxBitRate, format, null, null, null, null,
                    (subject, inputStream, contentLength) -> {

                        File dir = new File(
                                tmpPath + "/" + song.getPath().replaceAll("([^/]+?)?$", StringUtils.EMPTY));
                        dir.mkdirs();

                        File file = new File(tmpPath + "/"
                                + song.getPath().replaceAll("([^.]+?)?$", StringUtils.EMPTY) + format);

                        try {
                            BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
                            BufferedInputStream reader = new BufferedInputStream(inputStream);

                            byte buf[] = new byte[256];
                            int len;
                            while ((len = reader.read(buf)) != -1) {
                                fos.write(buf, 0, len);
                            }
                            fos.flush();
                            fos.close();
                            reader.close();
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        String path = Paths.get(file.getPath()).toUri().toString();
                        Group root = new Group();
                        Scene scene = new Scene(root, 640, 480);
                        Media media = new Media(path);
                        MediaPlayer player = new MediaPlayer(media);
                        MediaView view = new MediaView(player);
                        ((Group) scene.getRoot()).getChildren().add(view);
                        stage.setScene(scene);
                        stage.show();

                        player.play();

                    }, callback);

        });

    });
}

From source file:org.obiba.mica.micaConfig.service.EntityConfigService.java

public void publish() {
    Optional<T> networkForm = findPartial();
    networkForm.ifPresent(d -> getRepository().save(d));
}

From source file:com.rockagen.gnext.service.spring.aspect.OpLogAspect.java

/**
 * Register request info/*ww w.  j a  va  2s  .  c  o m*/
 * @param action action
 * @param startAt start at
 * @param result result 0,1
 * @param message message
 */
private void register(String action, Date startAt, int result, String message) {

    Date endAt = new Date();
    OpLog l = new OpLog();

    l.setAction(action);
    l.setStartAt(startAt);
    l.setEndAt(endAt);
    l.setIp(getIp());
    l.setTimes(l.getEndAt().getTime() - l.getStartAt().getTime());
    l.setMessage(message);
    l.setResult(result);
    l.setUsername(getUsername());

    Optional<AuthUser> au = authUserServ.load(getUsername());

    au.ifPresent(x -> {
        Optional.ofNullable(x.getLastUserReferer()).ifPresent(y -> l.setUserReferer(y.value()));
        Optional.ofNullable(x.getType()).ifPresent(y -> l.setUserType(y.value()));
    });

    mongoTemplate.save(l);

}

From source file:com.watchrabbit.crawler.executor.service.CrawlExecutorServiceImpl.java

private void enableSession(RemoteWebDriver driver, CrawlForm form, Collection<Cookie> session) {
    driver.get(form.getUrl());//from   ww w. j  av  a  2  s .  c  o m
    loaderService.waitFor(driver);
    if (!session.isEmpty()) {
        driver.manage().deleteAllCookies();
        session.forEach(driver.manage()::addCookie);

        driver.get(form.getUrl());
        loaderService.waitFor(driver);
    }
    if (StringUtils.isNotEmpty(form.getKeyword())) {
        Optional<SearchForm> searchFormOptional = findSearchInput(driver);
        searchFormOptional.ifPresent(searchForm -> {
            searchForm.input.sendKeys(form.getKeyword());
            loaderService.waitFor(driver);
            searchForm.submit.click();
            loaderService.waitFor(driver);
        });

    }
}

From source file:com.epam.reportportal.auth.AuthProvidersInfoContributor.java

@Override
public void contribute(Info.Builder builder) {
    Optional<Set<String>> loginDetails = Optional.ofNullable(settingsRepository.findOne("default"))
            .flatMap(settings -> Optional.ofNullable(settings.getoAuth2LoginDetails())).map(Map::keySet);
    loginDetails.ifPresent(it -> builder.withDetail("auth_extensions", it));
}