Search in sources :

Example 91 with Supplier

use of java.util.function.Supplier in project aic-praise by aic-sri-international.

the class AbstractPerspective method newModel.

@Override
public void newModel(ExamplePages examples) {
    newModel(() -> {
        List<ModelPage> pages = examples.getPages();
        Map<Integer, Supplier<ModelPageEditor>> newModelPageIdxs = new HashMap<>();
        for (int i = 0; i < pages.size(); i++) {
            ModelPage page = pages.get(i);
            newModelPageIdxs.put(i, new ModelPageEditorSupplier(page.getModel(), page.getDefaultQueriesToRun()));
        }
        return FXCollections.observableMap(newModelPageIdxs);
    });
    modelFile.set(null);
}
Also used : ModelPage(com.sri.ai.praise.model.common.io.ModelPage) HashMap(java.util.HashMap) Supplier(java.util.function.Supplier)

Example 92 with Supplier

use of java.util.function.Supplier in project indy by Commonjava.

the class DeprecatedFoloContentAccessResource method doCreate.

@ApiOperation("Store and track file/artifact content under the given artifact store (type/name) and path.")
@ApiResponses({ @ApiResponse(code = 201, message = "Content was stored successfully"), @ApiResponse(code = 400, message = "No appropriate storage location was found in the specified store (this store, or a member if a group is specified).") })
@PUT
@Path("/{path: (.*)}")
public Response doCreate(@ApiParam("User-assigned tracking session key") @PathParam("id") final String id, @ApiParam(allowableValues = "hosted,group,remote", required = true) @PathParam("type") final String type, @PathParam("name") final String name, @PathParam("path") final String path, @Context final HttpServletRequest request, @Context final UriInfo uriInfo) {
    final TrackingKey tk = new TrackingKey(id);
    EventMetadata metadata = new EventMetadata().set(TRACKING_KEY, tk).set(ACCESS_CHANNEL, AccessChannel.MAVEN_REPO);
    final Supplier<URI> uriSupplier = () -> uriInfo.getBaseUriBuilder().path(getClass()).path(path).build(id, type, name);
    final Consumer<Response.ResponseBuilder> deprecation = builder -> {
        String alt = Paths.get("/api/folo/track/", id, MAVEN_PKG_KEY, type, name, path).toString();
        markDeprecated(builder, alt);
    };
    return handler.doCreate(MAVEN_PKG_KEY, type, name, path, request, metadata, uriSupplier, deprecation);
}
Also used : PathParam(javax.ws.rs.PathParam) IndyDeployment(org.commonjava.indy.bind.jaxrs.IndyDeployment) CHECK_CACHE_ONLY(org.commonjava.indy.IndyContentConstants.CHECK_CACHE_ONLY) GET(javax.ws.rs.GET) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) ApiParam(io.swagger.annotations.ApiParam) ApiResponses(io.swagger.annotations.ApiResponses) Supplier(java.util.function.Supplier) Inject(javax.inject.Inject) ApiOperation(io.swagger.annotations.ApiOperation) TrackingKey(org.commonjava.indy.folo.model.TrackingKey) HttpServletRequest(javax.servlet.http.HttpServletRequest) QueryParam(javax.ws.rs.QueryParam) Api(io.swagger.annotations.Api) URI(java.net.URI) ACCESS_CHANNEL(org.commonjava.indy.folo.ctl.FoloConstants.ACCESS_CHANNEL) MAVEN_PKG_KEY(org.commonjava.indy.pkg.maven.model.MavenPackageTypeDescriptor.MAVEN_PKG_KEY) Logger(org.slf4j.Logger) Context(javax.ws.rs.core.Context) ContentAccessHandler(org.commonjava.indy.core.bind.jaxrs.ContentAccessHandler) IndyResources(org.commonjava.indy.bind.jaxrs.IndyResources) AccessChannel(org.commonjava.indy.model.core.AccessChannel) StreamingOutput(javax.ws.rs.core.StreamingOutput) ResponseUtils.markDeprecated(org.commonjava.indy.bind.jaxrs.util.ResponseUtils.markDeprecated) Consumer(java.util.function.Consumer) ContentController(org.commonjava.indy.core.ctl.ContentController) Response(javax.ws.rs.core.Response) Paths(java.nio.file.Paths) TRACKING_KEY(org.commonjava.indy.folo.ctl.FoloConstants.TRACKING_KEY) ApiResponse(io.swagger.annotations.ApiResponse) EventMetadata(org.commonjava.maven.galley.event.EventMetadata) PUT(javax.ws.rs.PUT) UriInfo(javax.ws.rs.core.UriInfo) HEAD(javax.ws.rs.HEAD) URI(java.net.URI) TrackingKey(org.commonjava.indy.folo.model.TrackingKey) EventMetadata(org.commonjava.maven.galley.event.EventMetadata) Path(javax.ws.rs.Path) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses) PUT(javax.ws.rs.PUT)

Example 93 with Supplier

use of java.util.function.Supplier in project alchemy-test by SirWellington.

the class MoreAnswersTest method testReturnFirst.

@Test
public void testReturnFirst() {
    System.out.println("testReturnFirst");
    Answer instance = MoreAnswers.returnFirst();
    assertNotNull(instance);
    BiFunction<String, String, String> function = mock(BiFunction.class);
    when(function.apply(anyString(), anyString())).then(instance);
    String expected = "arg1";
    String result = function.apply(expected, "arg2");
    assertThat(result, is(expected));
    Supplier supplier = mock(Supplier.class);
    when(supplier.get()).then(instance);
    assertThrows(() -> supplier.get()).isInstanceOf(IllegalArgumentException.class);
}
Also used : Answer(org.mockito.stubbing.Answer) Supplier(java.util.function.Supplier) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.junit.Test)

Example 94 with Supplier

use of java.util.function.Supplier in project lucene-solr by apache.

the class StatsCollectorSupplierFactory method create.

/**
   * Builds a Supplier that will generate identical arrays of new StatsCollectors.
   * 
   * @param schema The Schema being used.
   * @param exRequests The expression requests to generate a StatsCollector[] from.
   * @return A Supplier that will return an array of new StatsCollector.
   */
@SuppressWarnings("unchecked")
public static Supplier<StatsCollector[]> create(IndexSchema schema, List<ExpressionRequest> exRequests) {
    final Map<String, Set<String>> collectorStats = new TreeMap<>();
    final Map<String, Set<Integer>> collectorPercs = new TreeMap<>();
    final Map<String, ValueSource> collectorSources = new TreeMap<>();
    // and statistics that need to be calculated on those ValueSources.
    for (ExpressionRequest expRequest : exRequests) {
        String statExpression = expRequest.getExpressionString();
        Set<String> statistics = getStatistics(statExpression);
        if (statistics == null) {
            continue;
        }
        for (String statExp : statistics) {
            String stat;
            String operands;
            try {
                stat = statExp.substring(0, statExp.indexOf('(')).trim();
                operands = statExp.substring(statExp.indexOf('(') + 1, statExp.lastIndexOf(')')).trim();
            } catch (Exception e) {
                throw new SolrException(ErrorCode.BAD_REQUEST, "Unable to parse statistic: [" + statExpression + "]", e);
            }
            String[] arguments = ExpressionFactory.getArguments(operands);
            String source = arguments[0];
            if (stat.equals(AnalyticsParams.STAT_PERCENTILE)) {
                // The statistic is a percentile, extra parsing is required
                if (arguments.length < 2) {
                    throw new SolrException(ErrorCode.BAD_REQUEST, "Too few arguments given for " + stat + "() in [" + statExp + "].");
                } else if (arguments.length > 2) {
                    throw new SolrException(ErrorCode.BAD_REQUEST, "Too many arguments given for " + stat + "() in [" + statExp + "].");
                }
                source = arguments[1];
                Set<Integer> percs = collectorPercs.get(source);
                if (percs == null) {
                    percs = new HashSet<>();
                    collectorPercs.put(source, percs);
                }
                try {
                    int perc = Integer.parseInt(arguments[0]);
                    if (perc > 0 && perc < 100) {
                        percs.add(perc);
                    } else {
                        throw new SolrException(ErrorCode.BAD_REQUEST, "The percentile in [" + statExp + "] is not between 0 and 100, exculsive.");
                    }
                } catch (NumberFormatException e) {
                    throw new SolrException(ErrorCode.BAD_REQUEST, "\"" + arguments[0] + "\" cannot be converted into a percentile.", e);
                }
            } else if (arguments.length > 1) {
                throw new SolrException(ErrorCode.BAD_REQUEST, "Too many arguments given for " + stat + "() in [" + statExp + "].");
            } else if (arguments.length == 0) {
                throw new SolrException(ErrorCode.BAD_REQUEST, "No arguments given for " + stat + "() in [" + statExp + "].");
            }
            // Only unique ValueSources will be made; therefore statistics must be accumulated for
            // each ValueSource, even across different expression requests
            Set<String> stats = collectorStats.get(source);
            if (stats == null) {
                stats = new HashSet<>();
                collectorStats.put(source, stats);
            }
            if (AnalyticsParams.STAT_PERCENTILE.equals(stat)) {
                stats.add(stat + "_" + arguments[0]);
            } else {
                stats.add(stat);
            }
        }
    }
    String[] keys = collectorStats.keySet().toArray(new String[0]);
    for (String sourceStr : keys) {
        // Build one ValueSource for each unique value source string
        ValueSource source = buildSourceTree(schema, sourceStr);
        if (source == null) {
            throw new SolrException(ErrorCode.BAD_REQUEST, "The statistic [" + sourceStr + "] could not be parsed.");
        }
        String builtString = source.toString();
        collectorSources.put(builtString, source);
        // Replace the user given string with the correctly built string
        if (!builtString.equals(sourceStr)) {
            Set<String> stats = collectorStats.remove(sourceStr);
            if (stats != null) {
                collectorStats.put(builtString, stats);
            }
            Set<Integer> percs = collectorPercs.remove(sourceStr);
            if (percs != null) {
                collectorPercs.put(builtString, percs);
            }
            for (ExpressionRequest er : exRequests) {
                er.setExpressionString(er.getExpressionString().replace(sourceStr, builtString));
            }
        }
    }
    if (collectorSources.size() == 0) {
        return new Supplier<StatsCollector[]>() {

            @Override
            public StatsCollector[] get() {
                return new StatsCollector[0];
            }
        };
    }
    log.info("Stats objects: " + collectorStats.size() + " sr=" + collectorSources.size() + " pr=" + collectorPercs.size());
    // All information is stored in final arrays so that nothing 
    // has to be computed when the Supplier's get() method is called.
    final Set<String>[] statsArr = collectorStats.values().toArray(new Set[0]);
    final ValueSource[] sourceArr = collectorSources.values().toArray(new ValueSource[0]);
    final boolean[] uniqueBools = new boolean[statsArr.length];
    final boolean[] medianBools = new boolean[statsArr.length];
    final boolean[] numericBools = new boolean[statsArr.length];
    final boolean[] dateBools = new boolean[statsArr.length];
    final double[][] percsArr = new double[statsArr.length][];
    final String[][] percsNames = new String[statsArr.length][];
    for (int count = 0; count < sourceArr.length; count++) {
        uniqueBools[count] = statsArr[count].contains(AnalyticsParams.STAT_UNIQUE);
        medianBools[count] = statsArr[count].contains(AnalyticsParams.STAT_MEDIAN);
        numericBools[count] = statsArr[count].contains(AnalyticsParams.STAT_SUM) || statsArr[count].contains(AnalyticsParams.STAT_SUM_OF_SQUARES) || statsArr[count].contains(AnalyticsParams.STAT_MEAN) || statsArr[count].contains(AnalyticsParams.STAT_STANDARD_DEVIATION);
        dateBools[count] = (sourceArr[count] instanceof DateFieldSource) | (sourceArr[count] instanceof MultiDateFunction) | (sourceArr[count] instanceof ConstDateSource);
        Set<Integer> ps = collectorPercs.get(sourceArr[count].toString());
        if (ps != null) {
            percsArr[count] = new double[ps.size()];
            percsNames[count] = new String[ps.size()];
            int percCount = 0;
            for (int p : ps) {
                percsArr[count][percCount] = p / 100.0;
                percsNames[count][percCount++] = AnalyticsParams.STAT_PERCENTILE + "_" + p;
            }
        }
    }
    // Making the Supplier
    return new Supplier<StatsCollector[]>() {

        public StatsCollector[] get() {
            StatsCollector[] collectors = new StatsCollector[statsArr.length];
            for (int count = 0; count < statsArr.length; count++) {
                if (numericBools[count]) {
                    StatsCollector sc = new NumericStatsCollector(sourceArr[count], statsArr[count]);
                    if (uniqueBools[count])
                        sc = new UniqueStatsCollector(sc);
                    if (medianBools[count])
                        sc = new MedianStatsCollector(sc);
                    if (percsArr[count] != null)
                        sc = new PercentileStatsCollector(sc, percsArr[count], percsNames[count]);
                    collectors[count] = sc;
                } else if (dateBools[count]) {
                    StatsCollector sc = new MinMaxStatsCollector(sourceArr[count], statsArr[count]);
                    if (uniqueBools[count])
                        sc = new UniqueStatsCollector(sc);
                    if (medianBools[count])
                        sc = new DateMedianStatsCollector(sc);
                    if (percsArr[count] != null)
                        sc = new PercentileStatsCollector(sc, percsArr[count], percsNames[count]);
                    collectors[count] = sc;
                } else {
                    StatsCollector sc = new MinMaxStatsCollector(sourceArr[count], statsArr[count]);
                    if (uniqueBools[count])
                        sc = new UniqueStatsCollector(sc);
                    if (medianBools[count])
                        sc = new MedianStatsCollector(sc);
                    if (percsArr[count] != null)
                        sc = new PercentileStatsCollector(sc, percsArr[count], percsNames[count]);
                    collectors[count] = sc;
                }
            }
            return collectors;
        }
    };
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) MultiDateFunction(org.apache.solr.analytics.util.valuesource.MultiDateFunction) ExpressionRequest(org.apache.solr.analytics.request.ExpressionRequest) DateFieldSource(org.apache.solr.analytics.util.valuesource.DateFieldSource) ConstDateSource(org.apache.solr.analytics.util.valuesource.ConstDateSource) Supplier(java.util.function.Supplier) SolrException(org.apache.solr.common.SolrException) TreeMap(java.util.TreeMap) SolrException(org.apache.solr.common.SolrException) ValueSource(org.apache.lucene.queries.function.ValueSource)

Example 95 with Supplier

use of java.util.function.Supplier in project JGroups by belaban.

the class ClassConfigurator method init.

protected static void init() throws Exception {
    // make sure we have a class for DocumentBuilderFactory
    Util.loadClass("javax.xml.parsers.DocumentBuilderFactory", ClassConfigurator.class);
    String magic_number_file = null, protocol_id_file = null;
    try {
        // PropertyPermission not granted if running in an untrusted environment with JNLP
        magic_number_file = Util.getProperty(new String[] { Global.MAGIC_NUMBER_FILE, "org.jgroups.conf.magicNumberFile" }, null, null, MAGIC_NUMBER_FILE);
        protocol_id_file = Util.getProperty(new String[] { Global.PROTOCOL_ID_FILE, "org.jgroups.conf.protocolIDFile" }, null, null, PROTOCOL_ID_FILE);
    } catch (SecurityException ex) {
    }
    // Read jg-magic-map.xml
    List<Triple<Short, String, Boolean>> mapping = readMappings(magic_number_file);
    for (Triple<Short, String, Boolean> tuple : mapping) {
        short m = tuple.getVal1();
        if (m >= MAX_MAGIC_VALUE)
            throw new IllegalArgumentException("ID " + m + " is bigger than MAX_MAGIC_VALUE (" + MAX_MAGIC_VALUE + "); increase MAX_MAGIC_VALUE");
        boolean external = tuple.getVal3();
        if (external) {
            if (magicMap[m] != null)
                alreadyInMagicMap(m, tuple.getVal2());
            continue;
        }
        Class clazz = Util.loadClass(tuple.getVal2(), ClassConfigurator.class);
        if (magicMap[m] != null)
            alreadyInMagicMap(m, clazz.getName());
        if (Constructable.class.isAssignableFrom(clazz)) {
            Constructable obj = (Constructable) clazz.newInstance();
            magicMap[m] = obj.create();
        } else {
            Supplier<? extends Object> supplier = (Supplier<Object>) () -> {
                try {
                    return clazz.newInstance();
                } catch (Throwable throwable) {
                    return null;
                }
            };
            magicMap[m] = supplier;
        }
        Object inst = magicMap[m].get();
        if (inst == null)
            continue;
        // test to confirm that the Constructable impl returns an instance of the correct type
        if (!inst.getClass().equals(clazz))
            throw new IllegalStateException(String.format("%s.create() returned the wrong class: %s\n", clazz.getSimpleName(), inst.getClass().getSimpleName()));
        // check that the IDs are the same
        if (inst instanceof Header)
            checkSameId((Header) inst, m);
        classMap.put(clazz, m);
    }
    // Read jg-protocol-ids.xml
    mapping = readMappings(protocol_id_file);
    for (Triple<Short, String, Boolean> tuple : mapping) {
        short m = tuple.getVal1();
        boolean external = tuple.getVal3();
        if (external) {
            if (protocol_names.containsKey(m))
                alreadyInProtocolsMap(m, tuple.getVal2());
            continue;
        }
        Class clazz = Util.loadClass(tuple.getVal2(), ClassConfigurator.class);
        if (protocol_ids.containsKey(clazz))
            alreadyInProtocolsMap(m, clazz.getName());
        protocol_ids.put(clazz, m);
        protocol_names.put(m, clazz);
    }
}
Also used : Constructable(org.jgroups.Constructable) Triple(org.jgroups.util.Triple) Header(org.jgroups.Header) Supplier(java.util.function.Supplier)

Aggregations

Supplier (java.util.function.Supplier)104 Test (org.junit.Test)43 List (java.util.List)41 ArrayList (java.util.ArrayList)28 Map (java.util.Map)24 Collectors (java.util.stream.Collectors)23 HashMap (java.util.HashMap)21 Function (java.util.function.Function)20 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)19 IOException (java.io.IOException)17 Arrays (java.util.Arrays)16 TimeUnit (java.util.concurrent.TimeUnit)14 Consumer (java.util.function.Consumer)14 Assert (org.junit.Assert)14 Collections (java.util.Collections)13 CompletableFuture (java.util.concurrent.CompletableFuture)13 Rule (org.junit.Rule)13 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)12 Cleanup (lombok.Cleanup)12 Timeout (org.junit.rules.Timeout)11