Search in sources :

Example 71 with Supplier

use of java.util.function.Supplier in project atlas by alibaba.

the class AwbProguradHook method hookProguardTask.

/**
     * hook混淆的任务,加入awb的混淆配置
     *
     * @param appVariantContext
     */
public void hookProguardTask(final AppVariantContext appVariantContext) {
    final VariantScope variantScope = appVariantContext.getScope();
    List<TransformTask> proguaradTransformTasks = getTransformTaskByTransformType(appVariantContext, ProGuardTransform.class);
    for (TransformTask proguaradTransformTask : proguaradTransformTasks) {
        final ProGuardTransform proGuardTransform = (ProGuardTransform) proguaradTransformTask.getTransform();
        if (null != proGuardTransform) {
            proguaradTransformTask.doFirst(new Action<Task>() {

                @Override
                public void execute(Task task) {
                    GlobalScope globalScope = variantScope.getGlobalScope();
                    File proguardOut = new File(Joiner.on(File.separatorChar).join(String.valueOf(globalScope.getBuildDir()), FD_OUTPUTS, "mapping", variantScope.getVariantConfiguration().getDirName()));
                    //为了方便排查,先把configuration打印到目录
                    proGuardTransform.printconfiguration(new File(proguardOut, "tmp_config.cfg"));
                    final File outConfigFile = new File(proguardOut, "awb_config.cfg");
                    //增加awb的配置
                    AndroidDependencyTree dependencyTree = AtlasBuildContext.androidDependencyTrees.get(variantScope.getVariantConfiguration().getFullName());
                    if (null == dependencyTree) {
                        throw new StopExecutionException("DependencyTree cannot be null!");
                    }
                    if (dependencyTree.getAwbBundles().size() > 0) {
                        BaseVariantOutputData vod = appVariantContext.getVariantData().getOutputs().get(0);
                        AppVariantOutputContext appVariantOutputContext = getAppVariantOutputContext(appVariantContext, vod);
                        File awbObfuscatedDir = new File(globalScope.getIntermediatesDir(), "/classes-proguard/" + variantScope.getVariantConfiguration().getDirName());
                        AwbProguardConfiguration awbProguardConfiguration = new AwbProguardConfiguration(appVariantOutputContext.getAwbTransformMap().values(), awbObfuscatedDir, appVariantOutputContext);
                        try {
                            awbProguardConfiguration.printConfigFile(outConfigFile);
                        } catch (IOException e) {
                            throw new GradleException("", e);
                        }
                        proGuardTransform.setConfigurationFiles(new Supplier<Collection<File>>() {

                            @Override
                            public Collection<File> get() {
                                Set<File> proguardFiles = new HashSet<File>();
                                ((HashSet<File>) proguardFiles).add(outConfigFile);
                                return proguardFiles;
                            }
                        });
                    }
                    File mappingFile = null;
                    if (null != appVariantContext.apContext.getApExploredFolder() && appVariantContext.apContext.getApExploredFolder().exists()) {
                        mappingFile = new File(appVariantContext.apContext.getApExploredFolder(), "mapping.txt");
                    } else {
                        mappingFile = new File(appVariantContext.getScope().getGlobalScope().getProject().getProjectDir(), "mapping.txt");
                    }
                    if (null != mappingFile && mappingFile.exists()) {
                        proGuardTransform.applyTestedMapping(mappingFile);
                    }
                }
            });
        }
    }
}
Also used : GlobalScope(com.android.build.gradle.internal.scope.GlobalScope) VariantScope(com.android.build.gradle.internal.scope.VariantScope) TransformTask(com.android.build.gradle.internal.pipeline.TransformTask) Task(org.gradle.api.Task) AndroidDependencyTree(com.taobao.android.builder.dependency.AndroidDependencyTree) BaseVariantOutputData(com.android.build.gradle.internal.variant.BaseVariantOutputData) AppVariantOutputContext(com.android.build.gradle.internal.api.AppVariantOutputContext) IOException(java.io.IOException) ProGuardTransform(com.android.build.gradle.internal.transforms.ProGuardTransform) StopExecutionException(org.gradle.api.tasks.StopExecutionException) AwbProguardConfiguration(com.taobao.android.builder.tasks.app.bundle.AwbProguardConfiguration) GradleException(org.gradle.api.GradleException) TransformTask(com.android.build.gradle.internal.pipeline.TransformTask) Supplier(java.util.function.Supplier) File(java.io.File)

Example 72 with Supplier

use of java.util.function.Supplier in project CoreNLP by stanfordnlp.

the class ClauseSplitterSearchProblem method search.

/**
   * The core implementation of the search.
   *
   * @param root The root word to search from. Traditionally, this is the root of the sentence.
   * @param candidateFragments The callback for the resulting sentence fragments.
   *                           This is a predicate of a triple of values.
   *                           The return value of the predicate determines whether we should continue searching.
   *                           The triple is a triple of
   *                           <ol>
   *                             <li>The log probability of the sentence fragment, according to the featurizer and the weights</li>
   *                             <li>The features along the path to this fragment. The last element of this is the features from the most recent step.</li>
   *                             <li>The sentence fragment. Because it is relatively expensive to compute the resulting tree, this is returned as a lazy {@link Supplier}.</li>
   *                           </ol>
   * @param classifier The classifier for whether an arc should be on the path to a clause split, a clause split itself, or neither.
   * @param featurizer The featurizer to use. Make sure this matches the weights!
   * @param actionSpace The action space we are allowed to take. Each action defines a means of splitting a clause on a dependency boundary.
   */
protected void search(// The root to search from
IndexedWord root, // The output specs
final Predicate<Triple<Double, List<Counter<String>>, Supplier<SentenceFragment>>> candidateFragments, // The learning specs
final Classifier<ClauseSplitter.ClauseClassifierLabel, String> classifier, Map<String, ? extends List<String>> hardCodedSplits, final Function<Triple<State, Action, State>, Counter<String>> featurizer, final Collection<Action> actionSpace, final int maxTicks) {
    // (the fringe)
    PriorityQueue<Pair<State, List<Counter<String>>>> fringe = new FixedPrioritiesPriorityQueue<>();
    // (avoid duplicate work)
    Set<IndexedWord> seenWords = new HashSet<>();
    State firstState = new State(null, null, -9000, null, x -> {
    }, // First state is implicitly "done"
    true);
    fringe.add(Pair.makePair(firstState, new ArrayList<>(0)), -0.0);
    int ticks = 0;
    while (!fringe.isEmpty()) {
        if (++ticks > maxTicks) {
            //        log.info("WARNING! Timed out on search with " + ticks + " ticks");
            return;
        }
        // Useful variables
        double logProbSoFar = fringe.getPriority();
        assert logProbSoFar <= 0.0;
        Pair<State, List<Counter<String>>> lastStatePair = fringe.removeFirst();
        State lastState = lastStatePair.first;
        List<Counter<String>> featuresSoFar = lastStatePair.second;
        IndexedWord rootWord = lastState.edge == null ? root : lastState.edge.getDependent();
        // Register thunk
        if (lastState.isDone) {
            if (!candidateFragments.test(Triple.makeTriple(logProbSoFar, featuresSoFar, () -> {
                SemanticGraph copy = new SemanticGraph(tree);
                lastState.thunk.andThen(x -> {
                    for (IndexedWord newTreeRoot : x.getRoots()) {
                        if (newTreeRoot != null) {
                            for (SemanticGraphEdge extraEdge : extraEdgesByGovernor.get(newTreeRoot)) {
                                assert Util.isTree(x);
                                addSubtree(x, newTreeRoot, extraEdge.getRelation().toString(), tree, extraEdge.getDependent(), tree.getIncomingEdgesSorted(newTreeRoot));
                                assert Util.isTree(x);
                            }
                        }
                    }
                }).accept(copy);
                return new SentenceFragment(copy, assumedTruth, false);
            }))) {
                break;
            }
        }
        // Find relevant auxilliary terms
        SemanticGraphEdge subjOrNull = null;
        SemanticGraphEdge objOrNull = null;
        for (SemanticGraphEdge auxEdge : tree.outgoingEdgeIterable(rootWord)) {
            String relString = auxEdge.getRelation().toString();
            if (relString.contains("obj")) {
                objOrNull = auxEdge;
            } else if (relString.contains("subj")) {
                subjOrNull = auxEdge;
            }
        }
        // For each outgoing edge...
        for (SemanticGraphEdge outgoingEdge : tree.outgoingEdgeIterable(rootWord)) {
            // This fires if the governor is an indirect speech verb, and the outgoing edge is a ccomp
            if (outgoingEdge.getRelation().toString().equals("ccomp") && ((outgoingEdge.getGovernor().lemma() != null && INDIRECT_SPEECH_LEMMAS.contains(outgoingEdge.getGovernor().lemma())) || INDIRECT_SPEECH_LEMMAS.contains(outgoingEdge.getGovernor().word()))) {
                continue;
            }
            // Get some variables
            String outgoingEdgeRelation = outgoingEdge.getRelation().toString();
            List<String> forcedArcOrder = hardCodedSplits.get(outgoingEdgeRelation);
            if (forcedArcOrder == null && outgoingEdgeRelation.contains(":")) {
                forcedArcOrder = hardCodedSplits.get(outgoingEdgeRelation.substring(0, outgoingEdgeRelation.indexOf(":")) + ":*");
            }
            boolean doneForcedArc = false;
            // For each action...
            for (Action action : (forcedArcOrder == null ? actionSpace : orderActions(actionSpace, forcedArcOrder))) {
                // Check the prerequisite
                if (!action.prerequisitesMet(tree, outgoingEdge)) {
                    continue;
                }
                if (forcedArcOrder != null && doneForcedArc) {
                    break;
                }
                // 1. Compute the child state
                Optional<State> candidate = action.applyTo(tree, lastState, outgoingEdge, subjOrNull, objOrNull);
                if (candidate.isPresent()) {
                    double logProbability;
                    ClauseClassifierLabel bestLabel;
                    Counter<String> features = featurizer.apply(Triple.makeTriple(lastState, action, candidate.get()));
                    if (forcedArcOrder != null && !doneForcedArc) {
                        logProbability = 0.0;
                        bestLabel = ClauseClassifierLabel.CLAUSE_SPLIT;
                        doneForcedArc = true;
                    } else if (features.containsKey("__undocumented_junit_no_classifier")) {
                        logProbability = Double.NEGATIVE_INFINITY;
                        bestLabel = ClauseClassifierLabel.CLAUSE_INTERM;
                    } else {
                        Counter<ClauseClassifierLabel> scores = classifier.scoresOf(new RVFDatum<>(features));
                        if (scores.size() > 0) {
                            Counters.logNormalizeInPlace(scores);
                        }
                        String rel = outgoingEdge.getRelation().toString();
                        if ("nsubj".equals(rel) || "dobj".equals(rel)) {
                            // Always at least yield on nsubj and dobj
                            scores.remove(ClauseClassifierLabel.NOT_A_CLAUSE);
                        }
                        logProbability = Counters.max(scores, Double.NEGATIVE_INFINITY);
                        bestLabel = Counters.argmax(scores, (x, y) -> 0, ClauseClassifierLabel.CLAUSE_SPLIT);
                    }
                    if (bestLabel != ClauseClassifierLabel.NOT_A_CLAUSE) {
                        Pair<State, List<Counter<String>>> childState = Pair.makePair(candidate.get().withIsDone(bestLabel), new ArrayList<Counter<String>>(featuresSoFar) {

                            {
                                add(features);
                            }
                        });
                        // 2. Register the child state
                        if (!seenWords.contains(childState.first.edge.getDependent())) {
                            //            log.info("  pushing " + action.signature() + " with " + argmax.first.edge);
                            fringe.add(childState, logProbability);
                        }
                    }
                }
            }
        }
        seenWords.add(rootWord);
    }
//    log.info("Search finished in " + ticks + " ticks and " + classifierEvals + " classifier evaluations.");
}
Also used : java.util(java.util) SemanticGraphEdge(edu.stanford.nlp.semgraph.SemanticGraphEdge) GrammaticalRelation(edu.stanford.nlp.trees.GrammaticalRelation) Counters(edu.stanford.nlp.stats.Counters) Predicate(java.util.function.Predicate) Redwood(edu.stanford.nlp.util.logging.Redwood) edu.stanford.nlp.util(edu.stanford.nlp.util) ClauseClassifierLabel(edu.stanford.nlp.naturalli.ClauseSplitter.ClauseClassifierLabel) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Consumer(java.util.function.Consumer) Counter(edu.stanford.nlp.stats.Counter) Stream(java.util.stream.Stream) java.io(java.io) edu.stanford.nlp.classify(edu.stanford.nlp.classify) Language(edu.stanford.nlp.international.Language) edu.stanford.nlp.ling(edu.stanford.nlp.ling) SemanticGraph(edu.stanford.nlp.semgraph.SemanticGraph) ClassicCounter(edu.stanford.nlp.stats.ClassicCounter) PriorityQueue(edu.stanford.nlp.util.PriorityQueue) ClauseClassifierLabel(edu.stanford.nlp.naturalli.ClauseSplitter.ClauseClassifierLabel) Counter(edu.stanford.nlp.stats.Counter) ClassicCounter(edu.stanford.nlp.stats.ClassicCounter) SemanticGraphEdge(edu.stanford.nlp.semgraph.SemanticGraphEdge) SemanticGraph(edu.stanford.nlp.semgraph.SemanticGraph)

Example 73 with Supplier

use of java.util.function.Supplier in project neo4j by neo4j.

the class GraphDatabaseFacade method init.

/**
     * Create a new Core API facade, backed by the given SPI and using pre-resolved dependencies
     */
public void init(SPI spi, Guard guard, ThreadToStatementContextBridge txBridge, Config config) {
    this.spi = spi;
    this.defaultTransactionTimeout = config.get(GraphDatabaseSettings.transaction_timeout);
    Supplier<Statement> statementSupplier = spi::currentStatement;
    Supplier<KernelTransaction> transactionSupplier = spi::currentTransaction;
    ThrowingAction<RuntimeException> assertTransactionOpen = this::assertTransactionOpen;
    this.schema = new SchemaImpl(statementSupplier);
    this.relActions = new StandardRelationshipActions(statementSupplier, transactionSupplier, assertTransactionOpen, (id) -> new NodeProxy(nodeActions, id), this);
    this.nodeActions = new StandardNodeActions(statementSupplier, transactionSupplier, assertTransactionOpen, relActions, this);
    this.indexManager = Suppliers.lazySingleton(() -> {
        IndexProviderImpl idxProvider = new IndexProviderImpl(this, statementSupplier);
        AutoIndexerFacade<Node> nodeAutoIndexer = new AutoIndexerFacade<>(() -> new ReadOnlyIndexFacade<>(idxProvider.getOrCreateNodeIndex(NODE_AUTO_INDEX, null)), spi.autoIndexing().nodes());
        RelationshipAutoIndexerFacade relAutoIndexer = new RelationshipAutoIndexerFacade(() -> new ReadOnlyRelationshipIndexFacade(idxProvider.getOrCreateRelationshipIndex(RELATIONSHIP_AUTO_INDEX, null)), spi.autoIndexing().relationships());
        return new IndexManagerImpl(statementSupplier, idxProvider, nodeAutoIndexer, relAutoIndexer);
    });
    this.contextFactory = Neo4jTransactionalContextFactory.create(spi, guard, txBridge, locker);
}
Also used : InternalIndexState(org.neo4j.kernel.api.index.InternalIndexState) StoreId(org.neo4j.kernel.impl.store.StoreId) RELATIONSHIP_AUTO_INDEX(org.neo4j.kernel.impl.api.legacyindex.InternalAutoIndexing.RELATIONSHIP_AUTO_INDEX) ResourceIterator(org.neo4j.graphdb.ResourceIterator) Suppliers(org.neo4j.function.Suppliers) ResourceClosingIterator(org.neo4j.helpers.collection.ResourceClosingIterator) URL(java.net.URL) ResourceIterable(org.neo4j.graphdb.ResourceIterable) Status(org.neo4j.kernel.api.exceptions.Status) TransactionEventHandler(org.neo4j.graphdb.event.TransactionEventHandler) TopLevelTransaction(org.neo4j.kernel.impl.coreapi.TopLevelTransaction) Statement(org.neo4j.kernel.api.Statement) Property(org.neo4j.kernel.api.properties.Property) RelationshipProxy(org.neo4j.kernel.impl.core.RelationshipProxy) InternalTransaction(org.neo4j.kernel.impl.coreapi.InternalTransaction) RelationshipAutoIndexerFacade(org.neo4j.kernel.impl.coreapi.RelationshipAutoIndexerFacade) IndexNotFoundKernelException(org.neo4j.kernel.api.exceptions.index.IndexNotFoundKernelException) PrimitiveLongIterator(org.neo4j.collection.primitive.PrimitiveLongIterator) NODE_AUTO_INDEX(org.neo4j.kernel.impl.api.legacyindex.InternalAutoIndexing.NODE_AUTO_INDEX) AutoIndexerFacade(org.neo4j.kernel.impl.coreapi.AutoIndexerFacade) Map(java.util.Map) NodePropertyDescriptor(org.neo4j.kernel.api.schema.NodePropertyDescriptor) Transaction(org.neo4j.graphdb.Transaction) TransactionalContextFactory(org.neo4j.kernel.impl.query.TransactionalContextFactory) QueryExecutionException(org.neo4j.graphdb.QueryExecutionException) PrefetchingResourceIterator(org.neo4j.helpers.collection.PrefetchingResourceIterator) KernelEventHandler(org.neo4j.graphdb.event.KernelEventHandler) BidirectionalTraversalDescriptionImpl(org.neo4j.kernel.impl.traversal.BidirectionalTraversalDescriptionImpl) Result(org.neo4j.graphdb.Result) URLAccessValidationError(org.neo4j.graphdb.security.URLAccessValidationError) ThreadToStatementContextBridge(org.neo4j.kernel.impl.core.ThreadToStatementContextBridge) IndexProviderImpl(org.neo4j.kernel.impl.coreapi.IndexProviderImpl) BidirectionalTraversalDescription(org.neo4j.graphdb.traversal.BidirectionalTraversalDescription) InvalidTransactionTypeKernelException(org.neo4j.kernel.api.exceptions.InvalidTransactionTypeKernelException) KernelException(org.neo4j.kernel.api.exceptions.KernelException) StandardRelationshipActions(org.neo4j.kernel.impl.coreapi.StandardRelationshipActions) String.format(java.lang.String.format) Schema(org.neo4j.graphdb.schema.Schema) GraphDatabaseAPI(org.neo4j.kernel.internal.GraphDatabaseAPI) NO_SUCH_LABEL(org.neo4j.kernel.impl.api.operations.KeyReadOperations.NO_SUCH_LABEL) TransactionTerminatedException(org.neo4j.graphdb.TransactionTerminatedException) IndexManager(org.neo4j.graphdb.index.IndexManager) Neo4jTransactionalContextFactory(org.neo4j.kernel.impl.query.Neo4jTransactionalContextFactory) Optional(java.util.Optional) DependencyResolver(org.neo4j.graphdb.DependencyResolver) RelationshipType(org.neo4j.graphdb.RelationshipType) GraphDatabaseSettings(org.neo4j.graphdb.factory.GraphDatabaseSettings) Guard(org.neo4j.kernel.guard.Guard) Label(org.neo4j.graphdb.Label) PlaceboTransaction(org.neo4j.kernel.impl.coreapi.PlaceboTransaction) TransactionalContext(org.neo4j.kernel.impl.query.TransactionalContext) SchemaImpl(org.neo4j.kernel.impl.coreapi.schema.SchemaImpl) EntityType(org.neo4j.storageengine.api.EntityType) StandardNodeActions(org.neo4j.kernel.impl.coreapi.StandardNodeActions) SchemaKernelException(org.neo4j.kernel.api.exceptions.schema.SchemaKernelException) MonoDirectionalTraversalDescription(org.neo4j.kernel.impl.traversal.MonoDirectionalTraversalDescription) NotFoundException(org.neo4j.graphdb.NotFoundException) Supplier(java.util.function.Supplier) SchemaRuleNotFoundException(org.neo4j.kernel.api.exceptions.schema.SchemaRuleNotFoundException) Node(org.neo4j.graphdb.Node) GraphDatabaseQueryService(org.neo4j.kernel.GraphDatabaseQueryService) IndexManagerImpl(org.neo4j.kernel.impl.coreapi.IndexManagerImpl) ConstraintViolationException(org.neo4j.graphdb.ConstraintViolationException) EntityNotFoundException(org.neo4j.kernel.api.exceptions.EntityNotFoundException) SecurityContext(org.neo4j.kernel.api.security.SecurityContext) ReadOnlyRelationshipIndexFacade(org.neo4j.kernel.impl.coreapi.ReadOnlyRelationshipIndexFacade) ThrowingAction(org.neo4j.function.ThrowingAction) NO_SUCH_PROPERTY_KEY(org.neo4j.kernel.impl.api.operations.KeyReadOperations.NO_SUCH_PROPERTY_KEY) TokenAccess(org.neo4j.kernel.impl.api.TokenAccess) AutoIndexing(org.neo4j.kernel.api.legacyindex.AutoIndexing) Config(org.neo4j.kernel.configuration.Config) ReadOnlyIndexFacade(org.neo4j.kernel.impl.coreapi.ReadOnlyIndexFacade) PrimitiveLongCollections(org.neo4j.collection.primitive.PrimitiveLongCollections) ReadOperations(org.neo4j.kernel.api.ReadOperations) IndexQuery(org.neo4j.kernel.api.schema_new.IndexQuery) PrimitiveLongCollections.map(org.neo4j.collection.primitive.PrimitiveLongCollections.map) Iterators.emptyIterator(org.neo4j.helpers.collection.Iterators.emptyIterator) NodeProxy(org.neo4j.kernel.impl.core.NodeProxy) NewIndexDescriptor(org.neo4j.kernel.api.schema_new.index.NewIndexDescriptor) File(java.io.File) PropertyContainerLocker(org.neo4j.kernel.impl.coreapi.PropertyContainerLocker) TimeUnit(java.util.concurrent.TimeUnit) TraversalDescription(org.neo4j.graphdb.traversal.TraversalDescription) Relationship(org.neo4j.graphdb.Relationship) AUTH_DISABLED(org.neo4j.kernel.api.security.SecurityContext.AUTH_DISABLED) KeyReadOperations(org.neo4j.kernel.impl.api.operations.KeyReadOperations) MultipleFoundException(org.neo4j.graphdb.MultipleFoundException) KernelTransaction(org.neo4j.kernel.api.KernelTransaction) ClientConnectionInfo(org.neo4j.kernel.impl.query.clientconnection.ClientConnectionInfo) ConstraintValidationException(org.neo4j.kernel.api.exceptions.schema.ConstraintValidationException) Collections(java.util.Collections) KernelTransaction(org.neo4j.kernel.api.KernelTransaction) RelationshipAutoIndexerFacade(org.neo4j.kernel.impl.coreapi.RelationshipAutoIndexerFacade) Statement(org.neo4j.kernel.api.Statement) RelationshipAutoIndexerFacade(org.neo4j.kernel.impl.coreapi.RelationshipAutoIndexerFacade) AutoIndexerFacade(org.neo4j.kernel.impl.coreapi.AutoIndexerFacade) ReadOnlyRelationshipIndexFacade(org.neo4j.kernel.impl.coreapi.ReadOnlyRelationshipIndexFacade) IndexProviderImpl(org.neo4j.kernel.impl.coreapi.IndexProviderImpl) NodeProxy(org.neo4j.kernel.impl.core.NodeProxy) StandardNodeActions(org.neo4j.kernel.impl.coreapi.StandardNodeActions) IndexManagerImpl(org.neo4j.kernel.impl.coreapi.IndexManagerImpl) SchemaImpl(org.neo4j.kernel.impl.coreapi.schema.SchemaImpl) StandardRelationshipActions(org.neo4j.kernel.impl.coreapi.StandardRelationshipActions) ReadOnlyIndexFacade(org.neo4j.kernel.impl.coreapi.ReadOnlyIndexFacade)

Example 74 with Supplier

use of java.util.function.Supplier in project spring-framework by spring-projects.

the class BodyExtractorsTests method createContext.

@Before
public void createContext() {
    final List<HttpMessageReader<?>> messageReaders = new ArrayList<>();
    messageReaders.add(new DecoderHttpMessageReader<>(new ByteBufferDecoder()));
    messageReaders.add(new DecoderHttpMessageReader<>(new StringDecoder()));
    messageReaders.add(new DecoderHttpMessageReader<>(new Jaxb2XmlDecoder()));
    messageReaders.add(new DecoderHttpMessageReader<>(new Jackson2JsonDecoder()));
    messageReaders.add(new FormHttpMessageReader());
    this.context = new BodyExtractor.Context() {

        @Override
        public Supplier<Stream<HttpMessageReader<?>>> messageReaders() {
            return messageReaders::stream;
        }

        @Override
        public Map<String, Object> hints() {
            return hints;
        }
    };
    this.hints = new HashMap<String, Object>();
}
Also used : Jackson2JsonDecoder(org.springframework.http.codec.json.Jackson2JsonDecoder) ArrayList(java.util.ArrayList) Jaxb2XmlDecoder(org.springframework.http.codec.xml.Jaxb2XmlDecoder) StringDecoder(org.springframework.core.codec.StringDecoder) ByteBufferDecoder(org.springframework.core.codec.ByteBufferDecoder) FormHttpMessageReader(org.springframework.http.codec.FormHttpMessageReader) HttpMessageReader(org.springframework.http.codec.HttpMessageReader) DecoderHttpMessageReader(org.springframework.http.codec.DecoderHttpMessageReader) FormHttpMessageReader(org.springframework.http.codec.FormHttpMessageReader) Supplier(java.util.function.Supplier) HashMap(java.util.HashMap) Map(java.util.Map) MultiValueMap(org.springframework.util.MultiValueMap) Before(org.junit.Before)

Example 75 with Supplier

use of java.util.function.Supplier in project spring-framework by spring-projects.

the class BodyInsertersTests method createContext.

@Before
public void createContext() {
    final List<HttpMessageWriter<?>> messageWriters = new ArrayList<>();
    messageWriters.add(new EncoderHttpMessageWriter<>(new ByteBufferEncoder()));
    messageWriters.add(new EncoderHttpMessageWriter<>(new CharSequenceEncoder()));
    messageWriters.add(new ResourceHttpMessageWriter());
    messageWriters.add(new EncoderHttpMessageWriter<>(new Jaxb2XmlEncoder()));
    Jackson2JsonEncoder jsonEncoder = new Jackson2JsonEncoder();
    messageWriters.add(new EncoderHttpMessageWriter<>(jsonEncoder));
    messageWriters.add(new ServerSentEventHttpMessageWriter(Collections.singletonList(jsonEncoder)));
    messageWriters.add(new FormHttpMessageWriter());
    this.context = new BodyInserter.Context() {

        @Override
        public Supplier<Stream<HttpMessageWriter<?>>> messageWriters() {
            return messageWriters::stream;
        }

        @Override
        public Map<String, Object> hints() {
            return hints;
        }
    };
    this.hints = new HashMap<>();
}
Also used : ByteBufferEncoder(org.springframework.core.codec.ByteBufferEncoder) ResourceHttpMessageWriter(org.springframework.http.codec.ResourceHttpMessageWriter) EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) ServerSentEventHttpMessageWriter(org.springframework.http.codec.ServerSentEventHttpMessageWriter) FormHttpMessageWriter(org.springframework.http.codec.FormHttpMessageWriter) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) ArrayList(java.util.ArrayList) ServerSentEventHttpMessageWriter(org.springframework.http.codec.ServerSentEventHttpMessageWriter) Jaxb2XmlEncoder(org.springframework.http.codec.xml.Jaxb2XmlEncoder) Jackson2JsonEncoder(org.springframework.http.codec.json.Jackson2JsonEncoder) ResourceHttpMessageWriter(org.springframework.http.codec.ResourceHttpMessageWriter) Supplier(java.util.function.Supplier) FormHttpMessageWriter(org.springframework.http.codec.FormHttpMessageWriter) CharSequenceEncoder(org.springframework.core.codec.CharSequenceEncoder) HashMap(java.util.HashMap) Map(java.util.Map) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Before(org.junit.Before)

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