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:org.opensingular.form.wicket.mapper.masterdetail.MasterDetailPanel.java

private IBSAction<SInstance> buildShowErrorsAction() {
    return new IBSAction<SInstance>() {
        @Override//w  w w .  ja v  a  2s. c om
        public void execute(AjaxRequestTarget target, IModel<SInstance> model) {
            SInstance baseInstance = model.getObject();
            SDocument doc = baseInstance.getDocument();
            Collection<IValidationError> errors = baseInstance.getNestedValidationErrors();
            if ((errors != null) && !errors.isEmpty()) {
                String alertLevel = errors.stream().map(IValidationError::getErrorLevel)
                        .max(Comparator.naturalOrder())
                        .map(it -> it.le(ValidationErrorLevel.WARNING) ? "alert-warning" : "alert-danger")
                        .orElse(null);

                final StringBuilder sb = new StringBuilder("<div><ul class='list-unstyled alert ")
                        .append(alertLevel).append("'>");
                for (IValidationError error : errors) {
                    Optional<SInstance> inst = doc.findInstanceById(error.getInstanceId());
                    inst.ifPresent(sInstance -> sb.append("<li>")
                            .append(SFormUtil.generateUserFriendlyPath(sInstance, baseInstance)).append(": ")
                            .append(error.getMessage()).append("</li>"));
                }
                sb.append("</ul></div>");

                target.appendJavaScript(
                        ";bootbox.alert('" + JavaScriptUtils.javaScriptEscape(sb.toString()) + "');");
                target.appendJavaScript(Scripts.multipleModalBackDrop());
            }
        }

        @Override
        public boolean isVisible(IModel<SInstance> model) {
            return model != null && model.getObject() != null && model.getObject().hasNestedValidationErrors();
        }
    };
}

From source file:org.pac4j.vertx.StatelessPac4jAuthHandlerIntegrationTest.java

private void testResourceAccess(final String url, final Optional<String> credentialsHeader,
        final int expectedHttpStatus, final Consumer<String> bodyValidator) throws Exception {
    startWebServer();//from   www.  j av  a  2 s  . c  o m
    HttpClient client = vertx.createHttpClient();
    // Attempt to get a private url
    final HttpClientRequest request = client.get(8080, "localhost", url);
    credentialsHeader.ifPresent(header -> request.putHeader(AUTH_HEADER_NAME, header));
    // This should get the desired result straight away rather than operating through redirects
    request.handler(response -> {
        assertEquals(expectedHttpStatus, response.statusCode());
        response.bodyHandler(body -> {
            final String bodyContent = body.toString();
            bodyValidator.accept(bodyContent);
            testComplete();
        });
    });
    request.end();
    await(1, TimeUnit.SECONDS);

}

From source file:org.pentaho.di.ui.trans.step.BaseStreamingDialog.java

public String open() {
    Shell parent = getParent();//from  w  w w  .j  a va  2 s.com
    Display display = parent.getDisplay();

    shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.MIN | SWT.MAX | SWT.RESIZE);
    props.setLook(shell);
    setShellImage(shell, meta);
    shell.setMinimumSize(527, 622);

    lsMod = e -> meta.setChanged();
    changed = meta.hasChanged();

    FormLayout formLayout = new FormLayout();
    formLayout.marginWidth = 15;
    formLayout.marginHeight = 15;

    shell.setLayout(formLayout);
    shell.setText(getDialogTitle());

    Label wicon = new Label(shell, SWT.RIGHT);
    wicon.setImage(getImage());
    FormData fdlicon = new FormData();
    fdlicon.top = new FormAttachment(0, 0);
    fdlicon.right = new FormAttachment(100, 0);
    wicon.setLayoutData(fdlicon);
    props.setLook(wicon);

    wlStepname = new Label(shell, SWT.RIGHT);
    wlStepname.setText(BaseMessages.getString(PKG, "BaseStreamingDialog.Stepname.Label"));
    props.setLook(wlStepname);
    fdlStepname = new FormData();
    fdlStepname.left = new FormAttachment(0, 0);
    fdlStepname.top = new FormAttachment(0, 0);
    wlStepname.setLayoutData(fdlStepname);

    wStepname = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
    wStepname.setText(stepname);
    props.setLook(wStepname);
    wStepname.addModifyListener(lsMod);
    fdStepname = new FormData();
    fdStepname.width = 250;
    fdStepname.left = new FormAttachment(0, 0);
    fdStepname.top = new FormAttachment(wlStepname, 5);
    wStepname.setLayoutData(fdStepname);

    Label spacer = new Label(shell, SWT.HORIZONTAL | SWT.SEPARATOR);
    props.setLook(spacer);
    FormData fdSpacer = new FormData();
    fdSpacer.height = 2;
    fdSpacer.left = new FormAttachment(0, 0);
    fdSpacer.top = new FormAttachment(wStepname, 15);
    fdSpacer.right = new FormAttachment(100, 0);
    fdSpacer.width = 497;
    spacer.setLayoutData(fdSpacer);

    wlTransPath = new Label(shell, SWT.LEFT);
    props.setLook(wlTransPath);
    wlTransPath.setText(BaseMessages.getString(PKG, "BaseStreamingDialog.Transformation"));
    FormData fdlTransPath = new FormData();
    fdlTransPath.left = new FormAttachment(0, 0);
    fdlTransPath.top = new FormAttachment(spacer, 15);
    fdlTransPath.right = new FormAttachment(50, 0);
    wlTransPath.setLayoutData(fdlTransPath);

    wTransPath = new TextVar(transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
    props.setLook(wTransPath);
    wTransPath.addModifyListener(lsMod);
    FormData fdTransPath = new FormData();
    fdTransPath.left = new FormAttachment(0, 0);
    fdTransPath.top = new FormAttachment(wlTransPath, 5);
    fdTransPath.width = 275;
    wTransPath.setLayoutData(fdTransPath);

    wbBrowseTrans = new Button(shell, SWT.PUSH);
    props.setLook(wbBrowseTrans);
    wbBrowseTrans.setText(BaseMessages.getString(PKG, "BaseStreaming.Dialog.Transformation.Browse"));
    FormData fdBrowseTrans = new FormData();
    fdBrowseTrans.left = new FormAttachment(wTransPath, 5);
    fdBrowseTrans.top = new FormAttachment(wlTransPath, 5);
    wbBrowseTrans.setLayoutData(fdBrowseTrans);

    wbBrowseTrans.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            if (repository != null) {
                selectRepositoryTrans();
            } else {
                Optional<String> fileName = selectFile(BaseStreamingDialog.this.wTransPath,
                        Const.STRING_TRANS_FILTER_EXT);
                fileName.ifPresent(fn -> {
                    try {
                        loadFileTrans(fn);
                    } catch (KettleException ex) {
                        ex.printStackTrace();
                    }
                });
            }
        }
    });

    wbCreateSubtrans = new Button(shell, SWT.PUSH);
    props.setLook(wbCreateSubtrans);
    wbCreateSubtrans.setText(BaseMessages.getString(PKG, "BaseStreaming.Dialog.Transformation.CreateSubtrans"));
    FormData fdCreateSubtrans = new FormData();
    fdCreateSubtrans.left = new FormAttachment(wbBrowseTrans, 5);
    fdCreateSubtrans.top = new FormAttachment(wbBrowseTrans, 0, SWT.TOP);
    wbCreateSubtrans.setLayoutData(fdCreateSubtrans);

    wbCreateSubtrans.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            createNewSubtrans();
        }
    });

    // Start of tabbed display
    wTabFolder = new CTabFolder(shell, SWT.BORDER);
    props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
    wTabFolder.setSimple(false);
    wTabFolder.setUnselectedCloseVisible(true);

    wCancel = new Button(shell, SWT.PUSH);
    wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel"));
    FormData fdCancel = new FormData();
    fdCancel.right = new FormAttachment(100, 0);
    fdCancel.bottom = new FormAttachment(100, 0);
    wCancel.setLayoutData(fdCancel);

    wOK = new Button(shell, SWT.PUSH);
    wOK.setText(BaseMessages.getString(PKG, "System.Button.OK"));
    FormData fdOk = new FormData();
    fdOk.right = new FormAttachment(wCancel, -5);
    fdOk.bottom = new FormAttachment(100, 0);
    wOK.setLayoutData(fdOk);

    Label hSpacer = new Label(shell, SWT.HORIZONTAL | SWT.SEPARATOR);
    props.setLook(hSpacer);
    FormData fdhSpacer = new FormData();
    fdhSpacer.height = 2;
    fdhSpacer.left = new FormAttachment(0, 0);
    fdhSpacer.bottom = new FormAttachment(wCancel, -15);
    fdhSpacer.right = new FormAttachment(100, 0);
    hSpacer.setLayoutData(fdhSpacer);

    FormData fdTabFolder = new FormData();
    fdTabFolder.left = new FormAttachment(0, 0);
    fdTabFolder.top = new FormAttachment(wTransPath, 15);
    fdTabFolder.bottom = new FormAttachment(hSpacer, -15);
    fdTabFolder.right = new FormAttachment(100, 0);
    wTabFolder.setLayoutData(fdTabFolder);

    buildSetupTab();
    buildBatchTab();
    createAdditionalTabs();

    lsCancel = e -> cancel();
    lsOK = e -> ok();

    wOK.addListener(SWT.Selection, lsOK);
    wCancel.addListener(SWT.Selection, lsCancel);

    lsDef = new SelectionAdapter() {
        public void widgetDefaultSelected(SelectionEvent e) {
            ok();
        }
    };
    wStepname.addSelectionListener(lsDef);

    shell.addShellListener(new ShellAdapter() {
        public void shellClosed(ShellEvent e) {
            cancel();
        }
    });

    getData();
    setSize();

    wTabFolder.setSelection(0);

    wStepname.selectAll();
    wStepname.setFocus();

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    return stepname;
}

From source file:org.rapidpm.microservice.optionals.cli.CmdLineParser.java

private void initWithArgs() {
    try {/*from  www . j  ava  2  s . co  m*/
        final Field cliArguments = Main.class.getDeclaredField("cliArguments");
        final boolean accessible = cliArguments.isAccessible();
        cliArguments.setAccessible(true);
        final Optional<String[]> cliOptional = (Optional<String[]>) cliArguments.get(null);
        if (cliOptional != null) {
            cliOptional.ifPresent(args -> this.args = args);
        }
        cliArguments.setAccessible(accessible);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        e.printStackTrace();
    }
}

From source file:org.roda.core.plugins.plugins.PluginHelper.java

public static void fixParents(IndexService index, ModelService model, Optional<String> jobId,
        Optional<String> computedSearchScope)
        throws GenericException, RequestNotValidException, AuthorizationDeniedException, NotFoundException {

    // collect all ghost ids
    Map<String, List<String>> aipIdToGhost = new HashMap<>();
    Map<String, List<String>> sipIdToGhost = new HashMap<>();

    Filter ghostsFilter = new Filter(
            new SimpleFilterParameter(RodaConstants.AIP_GHOST, Boolean.TRUE.toString()));
    jobId.ifPresent(id -> ghostsFilter.add(new SimpleFilterParameter(RodaConstants.INGEST_JOB_ID, id)));
    IterableIndexResult<IndexedAIP> ghosts = index.findAll(IndexedAIP.class, ghostsFilter,
            Arrays.asList(RodaConstants.INDEX_UUID, RodaConstants.INGEST_SIP_IDS));

    for (IndexedAIP aip : ghosts) {
        if (aip.getIngestSIPIds() != null && !aip.getIngestSIPIds().isEmpty()) {
            List<String> temp = new ArrayList<>();
            String firstIngestSIPId = aip.getIngestSIPIds().get(0);
            if (sipIdToGhost.containsKey(firstIngestSIPId)) {
                temp = sipIdToGhost.get(firstIngestSIPId);
            }/*from   ww  w . j av a2 s .c  o  m*/
            temp.add(aip.getId());
            sipIdToGhost.put(firstIngestSIPId, temp);
        } else {
            List<String> temp = new ArrayList<>();
            if (aipIdToGhost.containsKey(aip.getId())) {
                temp = aipIdToGhost.get(aip.getId());
            }
            temp.add(aip.getId());
            aipIdToGhost.put(aip.getId(), temp);
        }
    }

    for (Map.Entry<String, List<String>> entry : sipIdToGhost.entrySet()) {
        Filter nonGhostsFilter = new Filter(
                new OneOfManyFilterParameter(RodaConstants.INGEST_SIP_IDS, Arrays.asList(entry.getKey())),
                new SimpleFilterParameter(RodaConstants.AIP_GHOST, Boolean.FALSE.toString()));

        computedSearchScope.ifPresent(
                id -> nonGhostsFilter.add(new SimpleFilterParameter(RodaConstants.AIP_ANCESTORS, id)));

        IndexResult<IndexedAIP> result = index.find(IndexedAIP.class, nonGhostsFilter, Sorter.NONE,
                new Sublist(0, 1), Arrays.asList(RodaConstants.INDEX_UUID));

        if (result.getTotalCount() > 1) {
            LOGGER.debug("Couldn't find non-ghost AIP with ingest SIP ids {}", entry.getKey());
        } else if (result.getTotalCount() == 1) {
            IndexedAIP newParentIAIP = result.getResults().get(0);
            for (String id : entry.getValue()) {
                moveChildrenAIPsAndDelete(index, model, id, newParentIAIP.getId(), computedSearchScope);
            }
        } else if (result.getTotalCount() == 0) {
            String ghostIdToKeep = entry.getValue().get(0);
            AIP ghostToKeep = model.retrieveAIP(ghostIdToKeep);
            ghostToKeep.setGhost(false);
            model.updateAIP(ghostToKeep, "test");
            if (entry.getValue().size() > 1) {
                for (int i = 1; i < entry.getValue().size(); i++) {
                    updateParent(index, model, entry.getValue().get(i), ghostIdToKeep, computedSearchScope);
                }
            }
        }
    }
}

From source file:org.roda.core.plugins.plugins.PluginHelper.java

private static void updateParent(IndexService index, ModelService model, String aipId, String newParentId,
        Optional<String> searchScope)
        throws GenericException, AuthorizationDeniedException, RequestNotValidException {
    Filter parentFilter = new Filter(new SimpleFilterParameter(RodaConstants.AIP_PARENT_ID, aipId));
    searchScope.ifPresent(id -> parentFilter.add(new SimpleFilterParameter(RodaConstants.AIP_ANCESTORS, id)));
    index.execute(IndexedAIP.class, parentFilter, Arrays.asList(RodaConstants.INDEX_UUID), child -> {
        try {/*from   w w  w.j a va 2 s  .c  o m*/
            AIP aip = model.retrieveAIP(child.getId());
            aip.setParentId(newParentId);
            model.updateAIP(aip, "test");
        } catch (NotFoundException e) {
            LOGGER.debug("Can't move child. It wasn't found.", e);
        }
    });
    try {
        model.deleteAIP(aipId);
    } catch (NotFoundException e) {
        LOGGER.debug("Can't delete ghost or move node. It wasn't found.", e);
    }
}

From source file:org.roda.core.plugins.plugins.PluginHelper.java

private static void moveChildrenAIPsAndDelete(IndexService index, ModelService model, String aipId,
        String newParentId, Optional<String> searchScope)
        throws GenericException, AuthorizationDeniedException, RequestNotValidException {
    Filter parentFilter = new Filter(new SimpleFilterParameter(RodaConstants.AIP_PARENT_ID, aipId));
    searchScope.ifPresent(id -> parentFilter.add(new SimpleFilterParameter(RodaConstants.AIP_ANCESTORS, id)));
    index.execute(IndexedAIP.class, parentFilter, Arrays.asList(RodaConstants.INDEX_UUID), child -> {
        try {/*w w  w . ja v  a 2s .co m*/
            model.moveAIP(child.getId(), newParentId);
        } catch (NotFoundException e) {
            LOGGER.debug("Can't move child. It wasn't found.", e);
        }
    });
    try {
        model.deleteAIP(aipId);
    } catch (NotFoundException e) {
        LOGGER.debug("Can't delete ghost or move node. It wasn't found.", e);
    }
}

From source file:org.sakaiproject.assignment.persistence.AssignmentRepositoryImpl.java

@Override
@Transactional/* w w w  .  ja  v a2 s  .  c om*/
public void newSubmission(Assignment assignment, AssignmentSubmission submission,
        Optional<Set<AssignmentSubmissionSubmitter>> submitters, Optional<Set<String>> feedbackAttachments,
        Optional<Set<String>> submittedAttachments, Optional<Map<String, String>> properties) {
    if (!existsSubmission(submission.getId()) && exists(assignment.getId())) {
        submission.setDateCreated(Date.from(Instant.now()));
        submitters.ifPresent(submission::setSubmitters);
        submitters.ifPresent(s -> s.forEach(submitter -> submitter.setSubmission(submission)));
        feedbackAttachments.ifPresent(submission::setFeedbackAttachments);
        submittedAttachments.ifPresent(submission::setAttachments);
        properties.ifPresent(submission::setProperties);

        submission.setAssignment(assignment);
        assignment.getSubmissions().add(submission);

        sessionFactory.getCurrentSession().persist(assignment);
    }
}

From source file:org.silverpeas.components.mydb.web.MyDBWebController.java

@POST
@Path("AddRow")
@RedirectToInternalJsp("mydb.jsp")
@LowestRoleAccess(value = SilverpeasRole.publisher)
public void addNewTableRow(final MyDBWebRequestContext context) {
    try {/*from  w  w w  .  j  av  a 2s  .c om*/
        if (tableView.isDefined()) {
            final HttpRequest request = context.getRequest();
            final Enumeration<String> params = request.getParameterNames();
            final Map<String, TableFieldValue> tuples = new HashMap<>();
            while (params.hasMoreElements()) {
                final String paramName = params.nextElement();
                final Optional<DbColumn> column = tableView.getColumn(paramName);
                column.ifPresent(c -> {
                    final String paramValue = request.getParameter(paramName);
                    if (paramValue == null || (paramValue.isEmpty() && !c.isOfTypeText())) {
                        throwInvalidValueType(paramName, c.getType());
                    }
                    final TableFieldValue value = TableFieldValue.fromString(paramValue, c.getType());
                    tuples.put(paramName, value);
                });
            }
            if (!tuples.isEmpty()) {
                tableView.addRow(new TableRow(tuples));
            } else {
                context.getMessager().addError(getMultilang().getString("mydb.error.invalidRow"));
            }
        } else {
            context.getMessager().addError(getMultilang().getString(ERROR_NO_SELECTED_TABLE));
        }
    } catch (IllegalArgumentException | MyDBRuntimeException e) {
        context.getMessager().addError(e.getLocalizedMessage());
    }
    viewTableContent(context);
}

From source file:org.silverpeas.core.admin.service.Admin.java

@Override
public String updateSpaceInst(SpaceInst spaceInstNew) throws AdminException {
    try {//w  ww .  j  a va 2 s  .com
        SpaceInst oldSpace = getSpaceInstById(spaceInstNew.getId());
        // Update the space in tables
        spaceManager.updateSpaceInst(spaceInstNew);
        if (useProfileInheritance && (oldSpace.isInheritanceBlocked() != spaceInstNew.isInheritanceBlocked())) {
            updateSpaceInheritance(oldSpace, spaceInstNew.isInheritanceBlocked());
        }
        cache.opUpdateSpace(spaceInstNew);
        Optional<SpaceInstLight> spaceInCache = treeCache.getSpaceInstLight(spaceInstNew.getLocalId());
        spaceInCache.ifPresent(s -> s.setInheritanceBlocked(spaceInstNew.isInheritanceBlocked()));
        // Update space in TreeCache
        SpaceInstLight spaceLight = spaceManager.getSpaceInstLightById(getDriverSpaceId(spaceInstNew.getId()));
        spaceLight.setInheritanceBlocked(spaceInstNew.isInheritanceBlocked());
        treeCache.updateSpace(spaceLight);

        // indexation de l'espace

        createSpaceIndex(spaceLight);
        return spaceInstNew.getId();
    } catch (Exception e) {
        throw new AdminException(failureOnUpdate(SPACE, spaceInstNew.getId()), e);
    }
}