Example usage for java.util.function Supplier get

List of usage examples for java.util.function Supplier get

Introduction

In this page you can find the example usage for java.util.function Supplier get.

Prototype

T get();

Source Link

Document

Gets a result.

Usage

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

private <T extends SilverpeasComponentInstance> T checkComponentInstanceById(final T componentInstance,
        final String componentId, final Supplier<T> nullComponentInstance) {
    if (componentInstance != null) {
        if (componentInstance.getId().equals(componentId) || "-1".equals(componentInstance.getId())
                || isLong(componentId)) {
            return componentInstance;
        }/* www.ja v a  2  s.  c  o  m*/
        SilverLogger.getLogger(this).error("{0}. Wrong component {1} has been found!!",
                failureOnGetting(COMPONENT, componentId), componentInstance.getId());
        return nullComponentInstance != null ? nullComponentInstance.get() : null;
    }
    return null;
}

From source file:org.sleuthkit.autopsy.timeline.actions.SaveSnapshotAsReport.java

/**
 * Constructor//from w w  w  .  j  a  v a  2  s  .c o  m
 *
 * @param controller   The controller for this timeline action
 * @param nodeSupplier The Supplier of the node to snapshot.
 */
@NbBundle.Messages({ "Timeline.ModuleName=Timeline", "SaveSnapShotAsReport.action.dialogs.title=Timeline",
        "SaveSnapShotAsReport.action.name.text=Snapshot Report",
        "SaveSnapShotAsReport.action.longText=Save a screen capture of the current view of the timeline as a report.",
        "# {0} - report file path", "SaveSnapShotAsReport.ReportSavedAt=Report saved at [{0}]",
        "SaveSnapShotAsReport.Success=Success",
        "SaveSnapShotAsReport.FailedToAddReport=Failed to add snaphot to case as a report.",
        "# {0} - report path", "SaveSnapShotAsReport.ErrorWritingReport=Error writing report to disk at {0}.",
        "# {0} - generated default report name",
        "SaveSnapShotAsReport.reportName.prompt=leave empty for default report name: {0}.",
        "SaveSnapShotAsReport.reportName.header=Enter a report name for the Timeline Snapshot Report.",
        "SaveSnapShotAsReport.duplicateReportNameError.text=A report with that name already exists." })
public SaveSnapshotAsReport(TimeLineController controller, Supplier<Node> nodeSupplier) {
    super(Bundle.SaveSnapShotAsReport_action_name_text());
    setLongText(Bundle.SaveSnapShotAsReport_action_longText());
    setGraphic(new ImageView(SNAP_SHOT));

    this.controller = controller;
    this.currentCase = controller.getAutopsyCase();

    setEventHandler(actionEvent -> {
        //capture generation date and use to make default report name
        Date generationDate = new Date();
        final String defaultReportName = FileUtil.escapeFileName(currentCase.getName() + " "
                + new SimpleDateFormat("MM-dd-yyyy-HH-mm-ss").format(generationDate)); //NON_NLS
        BufferedImage snapshot = SwingFXUtils.fromFXImage(nodeSupplier.get().snapshot(null, null), null);

        //prompt user to pick report name
        TextInputDialog textInputDialog = new TextInputDialog();
        PromptDialogManager.setDialogIcons(textInputDialog);
        textInputDialog.setTitle(Bundle.SaveSnapShotAsReport_action_dialogs_title());
        textInputDialog.getEditor()
                .setPromptText(Bundle.SaveSnapShotAsReport_reportName_prompt(defaultReportName));
        textInputDialog.setHeaderText(Bundle.SaveSnapShotAsReport_reportName_header());

        //keep prompt even if text field has focus, until user starts typing.
        textInputDialog.getEditor()
                .setStyle("-fx-prompt-text-fill: derive(-fx-control-inner-background, -30%);");//NON_NLS 

        /*
         * Create a ValidationSupport to validate that a report with the
         * entered name doesn't exist on disk already. Disable ok button if
         * report name is not validated.
         */
        ValidationSupport validationSupport = new ValidationSupport();
        validationSupport.registerValidator(textInputDialog.getEditor(), false, new Validator<String>() {
            @Override
            public ValidationResult apply(Control textField, String enteredReportName) {
                String reportName = StringUtils.defaultIfBlank(enteredReportName, defaultReportName);
                boolean exists = Files.exists(Paths.get(currentCase.getReportDirectory(), reportName));
                return ValidationResult.fromErrorIf(textField,
                        Bundle.SaveSnapShotAsReport_duplicateReportNameError_text(), exists);
            }
        });
        textInputDialog.getDialogPane().lookupButton(ButtonType.OK).disableProperty()
                .bind(validationSupport.invalidProperty());

        //show dialog and handle result
        textInputDialog.showAndWait().ifPresent(enteredReportName -> {
            //reportName defaults to case name + timestamp if left blank
            String reportName = StringUtils.defaultIfBlank(enteredReportName, defaultReportName);
            Path reportFolderPath = Paths.get(currentCase.getReportDirectory(), reportName,
                    "Timeline Snapshot"); //NON_NLS
            Path reportMainFilePath;

            try {
                //generate and write report
                reportMainFilePath = new SnapShotReportWriter(currentCase, reportFolderPath, reportName,
                        controller.getEventsModel().getZoomParamaters(), generationDate, snapshot)
                                .writeReport();
            } catch (IOException ex) {
                LOGGER.log(Level.SEVERE, "Error writing report to disk at " + reportFolderPath, ex); //NON_NLS
                new Alert(Alert.AlertType.ERROR,
                        Bundle.SaveSnapShotAsReport_ErrorWritingReport(reportFolderPath)).show();
                return;
            }

            try {
                //add main file as report to case
                Case.getCurrentCase().addReport(reportMainFilePath.toString(), Bundle.Timeline_ModuleName(),
                        reportName);
            } catch (TskCoreException ex) {
                LOGGER.log(Level.WARNING,
                        "Failed to add " + reportMainFilePath.toString() + " to case as a report", ex); //NON_NLS
                new Alert(Alert.AlertType.ERROR, Bundle.SaveSnapShotAsReport_FailedToAddReport()).show();
                return;
            }

            //notify user of report location
            final Alert alert = new Alert(Alert.AlertType.INFORMATION, null, OPEN, OK);
            alert.setTitle(Bundle.SaveSnapShotAsReport_action_dialogs_title());
            alert.setHeaderText(Bundle.SaveSnapShotAsReport_Success());

            //make action to open report, and hyperlinklable to invoke action
            final OpenReportAction openReportAction = new OpenReportAction(reportMainFilePath);
            HyperlinkLabel hyperlinkLabel = new HyperlinkLabel(
                    Bundle.SaveSnapShotAsReport_ReportSavedAt(reportMainFilePath.toString()));
            hyperlinkLabel.setOnAction(openReportAction);
            alert.getDialogPane().setContent(hyperlinkLabel);

            alert.showAndWait().filter(OPEN::equals).ifPresent(buttonType -> openReportAction.handle(null));
        });
    });
}

From source file:org.sonar.java.se.MethodYield.java

public Stream<ProgramState> statesAfterInvocation(List<SymbolicValue> invocationArguments,
        List<Type> invocationTypes, ProgramState programState, Supplier<SymbolicValue> svSupplier) {
    Set<ProgramState> results = new LinkedHashSet<>();
    for (int index = 0; index < invocationArguments.size(); index++) {
        Constraint constraint = getConstraint(index, invocationTypes);
        if (constraint == null) {
            // no constraint on this parameter, let's try next one.
            continue;
        }//  w w  w  . j  ava  2s  . co  m

        SymbolicValue invokedArg = invocationArguments.get(index);
        Set<ProgramState> programStates = programStatesForConstraint(
                results.isEmpty() ? Lists.newArrayList(programState) : results, invokedArg, constraint);
        if (programStates.isEmpty()) {
            // constraint can't be satisfied, no need to process things further, this yield is not applicable.
            // TODO there might be some issue to report in this case.
            return Stream.empty();
        }
        results = programStates;
    }

    // resulting program states can be empty if all constraints on params are null or if method has no arguments.
    // That means that this yield is still possible and we need to stack a returned SV with its eventual constraints.
    if (results.isEmpty()) {
        results.add(programState);
    }

    // applied all constraints from parameters, stack return value
    SymbolicValue sv;
    if (resultIndex < 0) {
        sv = svSupplier.get();
    } else {
        // returned SV is the same as one of the arguments.
        sv = invocationArguments.get(resultIndex);
    }
    Stream<ProgramState> stateStream = results.stream().map(s -> s.stackValue(sv));
    if (resultConstraint != null) {
        stateStream = stateStream.map(s -> s.addConstraint(sv, resultConstraint));
    }
    return stateStream.distinct();
}

From source file:org.sonar.java.se.symbolicvalues.RelationalSymbolicValueTest.java

private List<String> resolveRelationStateForAllKinds(RelationalSymbolicValue known,
        Supplier<String> knownAsString) {
    List<String> actual = new ArrayList<>();
    for (Tree.Kind operator : operators) {
        RelationalSymbolicValue test = relationalSV(operator, b, a);
        RelationState relationState = test.resolveRelationState(Collections.singleton(known));
        actual.add(String.format("given %s when %s -> %s", knownAsString.get(),
                relationToString(operator, a, b), relationState));
    }//from w  ww  . j a v a  2  s.c om
    RelationalSymbolicValue eq = new RelationalSymbolicValue(RelationalSymbolicValue.Kind.METHOD_EQUALS, a, b);
    Stream.of(eq, eq.inverse()).forEach(rel -> {
        RelationState relationState = rel.resolveRelationState(Collections.singleton(known));
        actual.add(String.format("given %s when %s -> %s", knownAsString.get(), rel, relationState));
    });
    return actual;
}

From source file:org.sonar.java.se.symbolicvalues.RelationalSymbolicValueTest.java

private List<String> combineWithAll(RelationalSymbolicValue relation, Supplier<String> relationAsString) {
    List<String> actual = new ArrayList<>();
    for (Tree.Kind r : operators) {
        actual.add(String.format("%s && %s => %s", relationAsString.get(), relationToString(r, b, c),
                nullableToCollection(relation.deduceTransitiveOrSimplified(relationalSV(r, c, b)))));
    }//from w  w w.  j av a  2  s. c o m
    RelationalSymbolicValue eq = new RelationalSymbolicValue(RelationalSymbolicValue.Kind.METHOD_EQUALS, b, c);
    Stream.of(eq, eq.inverse()).forEach(rel -> actual.add(String.format("%s && %s => %s",
            relationAsString.get(), rel, nullableToCollection(relation.deduceTransitiveOrSimplified(rel)))));
    return actual;
}

From source file:org.sonar.java.se.xproc.ExceptionalYield.java

@Override
public Stream<ProgramState> statesAfterInvocation(List<SymbolicValue> invocationArguments,
        List<Type> invocationTypes, ProgramState programState, Supplier<SymbolicValue> svSupplier) {
    return parametersAfterInvocation(invocationArguments, invocationTypes, programState)
            .map(s -> s.stackValue(svSupplier.get())).distinct();
}

From source file:org.sonar.java.se.xproc.HappyPathYield.java

@Override
public Stream<ProgramState> statesAfterInvocation(List<SymbolicValue> invocationArguments,
        List<Type> invocationTypes, ProgramState programState, Supplier<SymbolicValue> svSupplier) {
    Stream<ProgramState> results = parametersAfterInvocation(invocationArguments, invocationTypes,
            programState);/*  w w w . j  a  v a  2 s. co m*/

    // applied all constraints from parameters, stack return value
    SymbolicValue sv;
    if (resultIndex < 0 || resultIndex == invocationArguments.size()) {
        // if returnIndex is the size of invocationArguments : returning vararg parameter on a call with no elements specified
        sv = svSupplier.get();
    } else {
        // returned SV is the same as one of the arguments.
        sv = invocationArguments.get(resultIndex);
    }
    results = results.map(s -> s.stackValue(sv));
    if (resultConstraint != null) {
        results = results.map(s -> s.addConstraints(sv, resultConstraint));
    }
    return results.distinct();
}

From source file:org.sonar.server.webhook.WebhookQGChangeEventListenerTest.java

private void mockPayloadSupplierConsumedByWebhooks() {
    Mockito.doAnswer(invocationOnMock -> {
        Supplier<WebhookPayload> supplier = (Supplier<WebhookPayload>) invocationOnMock.getArguments()[2];
        supplier.get();
        return null;
    }).when(webHooks).sendProjectAnalysisUpdate(Matchers.any(Configuration.class), Matchers.any(),
            Matchers.any());//from  w  w  w.j a  v a 2 s  . c  o m
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Obtain a bean instance from the given supplier.
 * @param instanceSupplier the configured supplier
 * @param beanName the corresponding bean name
 * @return a BeanWrapper for the new instance
 * @since 5.0//from  w w  w  . j a  v  a  2  s . c o m
 * @see #getObjectForBeanInstance
 */
protected BeanWrapper obtainFromSupplier(Supplier<?> instanceSupplier, String beanName) {
    Object instance;

    String outerBean = this.currentlyCreatedBean.get();
    this.currentlyCreatedBean.set(beanName);
    try {
        instance = instanceSupplier.get();
    } finally {
        if (outerBean != null) {
            this.currentlyCreatedBean.set(outerBean);
        } else {
            this.currentlyCreatedBean.remove();
        }
    }

    if (instance == null) {
        instance = new NullBean();
    }
    BeanWrapper bw = new BeanWrapperImpl(instance);
    initBeanWrapper(bw);
    return bw;
}

From source file:org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.java

private void stop(Timer.Sample timerSample, Supplier<Iterable<Tag>> tags, Builder builder) {
    timerSample.stop(builder.tags(tags.get()).register(this.registry));
}