Search in sources :

Example 76 with Objects

use of java.util.Objects in project cxf by apache.

the class OpenApiParseUtils method getUserApplicationFromJson.

public static UserApplication getUserApplicationFromJson(String json, ParseConfiguration cfg) {
    JsonMapObjectReaderWriter reader = new JsonMapObjectReaderWriter();
    Map<String, Object> map = reader.fromJson(json);
    UserApplication app = new UserApplication();
    app.setBasePath("/");
    List<Map<String, Object>> servers = CastUtils.cast((List<?>) map.get("servers"));
    if (servers != null && !servers.isEmpty()) {
        final String url = (String) servers.get(0).get("url");
        if (url != null) {
            app.setBasePath(url);
        }
    }
    Map<String, List<UserOperation>> userOpsMap = new LinkedHashMap<String, List<UserOperation>>();
    Set<String> tags = new HashSet<>();
    List<Map<String, Object>> tagsProp = CastUtils.cast((List<?>) map.get("tags"));
    if (tagsProp != null) {
        for (Map<String, Object> tagProp : tagsProp) {
            tags.add((String) tagProp.get("name"));
        }
    } else {
        tags.add("");
    }
    for (String tag : tags) {
        userOpsMap.put(tag, new LinkedList<UserOperation>());
    }
    Map<String, Map<String, Object>> paths = CastUtils.cast((Map<?, ?>) map.get("paths"));
    for (Map.Entry<String, Map<String, Object>> pathEntry : paths.entrySet()) {
        String operPath = pathEntry.getKey();
        Map<String, Object> operations = pathEntry.getValue();
        for (Map.Entry<String, Object> operEntry : operations.entrySet()) {
            UserOperation userOp = new UserOperation();
            userOp.setVerb(operEntry.getKey().toUpperCase());
            Map<String, Object> oper = CastUtils.cast((Map<?, ?>) operEntry.getValue());
            userOp.setPath(operPath);
            userOp.setName((String) oper.get("operationId"));
            Map<String, Object> responses = CastUtils.cast((Map<?, ?>) oper.get("responses"));
            if (responses != null) {
                userOp.setProduces(listToString(responses.entrySet().stream().map(entry -> CastUtils.cast((Map<?, ?>) entry.getValue())).map(value -> CastUtils.cast((Map<?, ?>) value.get("content"))).filter(Objects::nonNull).flatMap(content -> content.keySet().stream().map(type -> (String) type)).collect(Collectors.toList())));
            }
            Map<String, Object> payloads = CastUtils.cast((Map<?, ?>) oper.get("requestBody"));
            if (payloads != null) {
                userOp.setConsumes(listToString(payloads.entrySet().stream().map(entry -> CastUtils.cast((Map<?, ?>) entry.getValue())).map(value -> CastUtils.cast((Map<?, ?>) value.get("content"))).filter(Objects::nonNull).flatMap(content -> content.keySet().stream().map(type -> (String) type)).collect(Collectors.toList())));
            }
            List<Parameter> userOpParams = new LinkedList<Parameter>();
            List<Map<String, Object>> params = CastUtils.cast((List<?>) oper.get("parameters"));
            if (params != null) {
                for (Map<String, Object> param : params) {
                    String name = (String) param.get("name");
                    // "query", "header", "path" or "cookie".
                    String paramType = (String) param.get("in");
                    ParameterType pType = null;
                    if ("query".equals(paramType)) {
                        pType = ParameterType.QUERY;
                    } else if ("header".equals(paramType)) {
                        pType = ParameterType.HEADER;
                    } else if ("path".equals(paramType)) {
                        pType = ParameterType.PATH;
                    } else if ("cookie".equals(paramType)) {
                        pType = ParameterType.COOKIE;
                    } else {
                        pType = ParameterType.REQUEST_BODY;
                    }
                    Parameter userParam = new Parameter(pType, name);
                    setJavaType(userParam, (String) param.get("type"));
                    userOpParams.add(userParam);
                }
            }
            if (!userOpParams.isEmpty()) {
                userOp.setParameters(userOpParams);
            }
            List<String> opTags = CastUtils.cast((List<?>) oper.get("tags"));
            if (opTags == null) {
                opTags = Collections.singletonList("");
            }
            for (String opTag : opTags) {
                userOpsMap.get(opTag).add(userOp);
            }
        }
    }
    List<UserResource> resources = new LinkedList<UserResource>();
    for (Map.Entry<String, List<UserOperation>> entry : userOpsMap.entrySet()) {
        UserResource ur = new UserResource();
        ur.setPath("/");
        ur.setOperations(entry.getValue());
        ur.setName(entry.getKey());
        resources.add(ur);
    }
    app.setResources(resources);
    return app;
}
Also used : Bus(org.apache.cxf.Bus) UserApplication(org.apache.cxf.jaxrs.model.UserApplication) HashMap(java.util.HashMap) UserResource(org.apache.cxf.jaxrs.model.UserResource) Parameter(org.apache.cxf.jaxrs.model.Parameter) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) ParameterType(org.apache.cxf.jaxrs.model.ParameterType) LogUtils(org.apache.cxf.common.logging.LogUtils) Map(java.util.Map) ResourceUtils(org.apache.cxf.jaxrs.utils.ResourceUtils) LinkedList(java.util.LinkedList) UserOperation(org.apache.cxf.jaxrs.model.UserOperation) CastUtils(org.apache.cxf.helpers.CastUtils) IOUtils(org.apache.cxf.helpers.IOUtils) Set(java.util.Set) IOException(java.io.IOException) Logger(java.util.logging.Logger) ClassLoaderUtils(org.apache.cxf.common.classloader.ClassLoaderUtils) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) BusFactory(org.apache.cxf.BusFactory) Collections(java.util.Collections) InputStream(java.io.InputStream) JsonMapObjectReaderWriter(org.apache.cxf.jaxrs.json.basic.JsonMapObjectReaderWriter) LinkedHashMap(java.util.LinkedHashMap) LinkedList(java.util.LinkedList) List(java.util.List) HashSet(java.util.HashSet) ParameterType(org.apache.cxf.jaxrs.model.ParameterType) JsonMapObjectReaderWriter(org.apache.cxf.jaxrs.json.basic.JsonMapObjectReaderWriter) UserResource(org.apache.cxf.jaxrs.model.UserResource) LinkedList(java.util.LinkedList) UserApplication(org.apache.cxf.jaxrs.model.UserApplication) UserOperation(org.apache.cxf.jaxrs.model.UserOperation) Objects(java.util.Objects) Parameter(org.apache.cxf.jaxrs.model.Parameter) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 77 with Objects

use of java.util.Objects in project winery by eclipse.

the class Showcases method convert.

public MultiException convert(String path, String namespace, Stream<String> files) throws Exception {
    MultiException exception = new MultiException();
    files.map(name -> {
        try {
            return new LinkedHashMap.SimpleEntry<>(name, readServiceTemplate(path + File.separator + name));
        } catch (Exception e) {
            exception.add(e);
        }
        return null;
    }).filter(Objects::nonNull).map(entry -> new LinkedHashMap.SimpleEntry<>(entry.getKey(), convert(entry.getValue(), entry.getKey(), namespace))).forEach(entry -> WriterUtils.saveDefinitions(entry.getValue(), outPath, namespace, entry.getKey()));
    if (exception.hasException()) {
        throw exception.getException();
    }
    return exception;
}
Also used : ServiceTemplateId(org.eclipse.winery.common.ids.definitions.ServiceTemplateId) Test(org.junit.Test) FileInputStream(java.io.FileInputStream) XmlId(org.eclipse.winery.common.ids.XmlId) RepositoryFactory(org.eclipse.winery.repository.backend.RepositoryFactory) File(java.io.File) TServiceTemplate(org.eclipse.winery.model.tosca.TServiceTemplate) LinkedHashMap(java.util.LinkedHashMap) Objects(java.util.Objects) Stream(java.util.stream.Stream) Ignore(org.junit.Ignore) Paths(java.nio.file.Paths) MultiException(org.eclipse.winery.yaml.common.exception.MultiException) Namespaces(org.eclipse.winery.yaml.common.Namespaces) AbstractTestY2X(org.eclipse.winery.yaml.converter.yaml.support.AbstractTestY2X) Namespace(org.eclipse.winery.common.ids.Namespace) WriterUtils(org.eclipse.winery.yaml.common.writer.WriterUtils) Assert(org.junit.Assert) Converter(org.eclipse.winery.yaml.converter.Converter) InputStream(java.io.InputStream) Objects(java.util.Objects) MultiException(org.eclipse.winery.yaml.common.exception.MultiException) MultiException(org.eclipse.winery.yaml.common.exception.MultiException) LinkedHashMap(java.util.LinkedHashMap)

Example 78 with Objects

use of java.util.Objects in project pravega by pravega.

the class AsyncStorageWrapper method supplyAsync.

/**
 * Executes the given Callable asynchronously and returns a CompletableFuture that will be completed with the result.
 * @param operation    The Callable to execute.
 * @param segmentNames The names of the Segments involved in this operation (for sequencing purposes).
 */
private <R> CompletableFuture<R> supplyAsync(Callable<R> operation, String... segmentNames) {
    Exceptions.checkNotClosed(this.closed.get(), this);
    CompletableFuture<R> result;
    synchronized (this.lastTasks) {
        // Collect all futures this is dependent on.
        val futures = Arrays.stream(segmentNames).map(this.lastTasks::get).filter(Objects::nonNull).map(t -> t.task).toArray(CompletableFuture[]::new);
        int taskId = this.currentTaskId++;
        if (futures.length == 0) {
            // Nothing to depend on - free to execute now.
            result = CompletableFuture.supplyAsync(() -> execute(operation, taskId, segmentNames), this.executor);
        } else {
            // We need to wait on these futures to complete before executing ours.
            result = CompletableFuture.allOf(futures).handleAsync((r, ex) -> execute(operation, taskId, segmentNames), this.executor);
        }
        // Update the last task for each involved segment to be this so that future tasks can be properly sequenced.
        RunningTask t = new RunningTask(taskId, result);
        for (String s : segmentNames) {
            this.lastTasks.put(s, t);
        }
    }
    return result;
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) RunnableWithException(io.pravega.common.function.RunnableWithException) Executor(java.util.concurrent.Executor) SneakyThrows(lombok.SneakyThrows) Exceptions(io.pravega.common.Exceptions) RequiredArgsConstructor(lombok.RequiredArgsConstructor) lombok.val(lombok.val) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) ThreadSafe(javax.annotation.concurrent.ThreadSafe) GuardedBy(javax.annotation.concurrent.GuardedBy) SegmentProperties(io.pravega.segmentstore.contracts.SegmentProperties) Objects(java.util.Objects) Duration(java.time.Duration) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) InputStream(java.io.InputStream) Objects(java.util.Objects)

Example 79 with Objects

use of java.util.Objects in project drools by kiegroup.

the class DroolsObjectInputStream method bindAllExtractors.

public void bindAllExtractors(InternalKnowledgeBase kbase) {
    extractorBinders.forEach((k, l) -> {
        ClassFieldReader extractor = kbase.getPackagesMap().values().stream().map(pkg -> pkg.getClassFieldAccessorStore().getReader(k)).filter(Objects::nonNull).findFirst().orElseThrow(() -> new RuntimeException("Unknown extractor for " + k));
        l.forEach(binder -> binder.accept(extractor));
    });
}
Also used : OutputStream(java.io.OutputStream) ClassFieldAccessorStore(org.drools.core.base.ClassFieldAccessorStore) ClassFieldReader(org.drools.core.base.ClassFieldReader) ClassUtils(org.drools.core.util.ClassUtils) ObjectInputStream(java.io.ObjectInputStream) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) IOException(java.io.IOException) ObjectStreamClass(java.io.ObjectStreamClass) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) InvalidClassException(java.io.InvalidClassException) Objects(java.util.Objects) Consumer(java.util.function.Consumer) List(java.util.List) AccessorKey(org.drools.core.base.AccessorKey) Map(java.util.Map) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) InputStream(java.io.InputStream) ClassFieldReader(org.drools.core.base.ClassFieldReader) Objects(java.util.Objects)

Example 80 with Objects

use of java.util.Objects in project grakn by graknlabs.

the class ReasonerQueryImpl method getSubstitution.

/**
 * @return substitution obtained from all id predicates (including internal) in the query
 */
public Answer getSubstitution() {
    if (substitution == null) {
        Set<Var> varNames = getVarNames();
        Set<IdPredicate> predicates = getAtoms(IsaAtomBase.class).map(IsaAtomBase::getTypePredicate).filter(Objects::nonNull).filter(p -> varNames.contains(p.getVarName())).collect(Collectors.toSet());
        getAtoms(IdPredicate.class).forEach(predicates::add);
        HashMap<Var, Concept> answerMap = new HashMap<>();
        predicates.forEach(p -> {
            Concept concept = tx().getConcept(p.getPredicate());
            if (concept == null)
                throw GraqlQueryException.idNotFound(p.getPredicate());
            answerMap.put(p.getVarName(), concept);
        });
        substitution = new QueryAnswer(answerMap);
    }
    return substitution;
}
Also used : PatternAdmin(ai.grakn.graql.admin.PatternAdmin) Pair(ai.grakn.graql.internal.reasoner.utils.Pair) Atom(ai.grakn.graql.internal.reasoner.atom.Atom) LoggerFactory(org.slf4j.LoggerFactory) Type(ai.grakn.concept.Type) ResolutionIterator(ai.grakn.graql.internal.reasoner.ResolutionIterator) QueryStateBase(ai.grakn.graql.internal.reasoner.state.QueryStateBase) MultiUnifierImpl(ai.grakn.graql.internal.reasoner.MultiUnifierImpl) ResolutionState(ai.grakn.graql.internal.reasoner.state.ResolutionState) QueryAnswerStream.join(ai.grakn.graql.internal.reasoner.query.QueryAnswerStream.join) Map(java.util.Map) IsaAtom(ai.grakn.graql.internal.reasoner.atom.binary.IsaAtom) RuleUtils(ai.grakn.graql.internal.reasoner.rule.RuleUtils) ConceptId(ai.grakn.concept.ConceptId) Graql.var(ai.grakn.graql.Graql.var) ImmutableSet(com.google.common.collect.ImmutableSet) NeqPredicate(ai.grakn.graql.internal.reasoner.atom.predicate.NeqPredicate) Conjunction(ai.grakn.graql.admin.Conjunction) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) ConjunctiveState(ai.grakn.graql.internal.reasoner.state.ConjunctiveState) QueryAnswerStream.joinWithInverse(ai.grakn.graql.internal.reasoner.query.QueryAnswerStream.joinWithInverse) Set(java.util.Set) IdPredicate(ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate) Collectors(java.util.stream.Collectors) LazyQueryCache(ai.grakn.graql.internal.reasoner.cache.LazyQueryCache) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) Atomic(ai.grakn.graql.admin.Atomic) List(java.util.List) Cache(ai.grakn.graql.internal.reasoner.cache.Cache) Stream(java.util.stream.Stream) InferenceRule(ai.grakn.graql.internal.reasoner.rule.InferenceRule) Var(ai.grakn.graql.Var) AtomicBase(ai.grakn.graql.internal.reasoner.atom.AtomicBase) UnifierType(ai.grakn.graql.internal.reasoner.UnifierType) Concept(ai.grakn.concept.Concept) HashMap(java.util.HashMap) Answer(ai.grakn.graql.admin.Answer) CumulativeState(ai.grakn.graql.internal.reasoner.state.CumulativeState) JoinExplanation(ai.grakn.graql.internal.reasoner.explanation.JoinExplanation) Iterators(com.google.common.collect.Iterators) QueryAnswerStream.nonEqualsFilter(ai.grakn.graql.internal.reasoner.query.QueryAnswerStream.nonEqualsFilter) HashSet(java.util.HashSet) Lists(com.google.common.collect.Lists) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) LinkedList(java.util.LinkedList) RelationshipAtom(ai.grakn.graql.internal.reasoner.atom.binary.RelationshipAtom) Nullable(javax.annotation.Nullable) LinkedHashSet(java.util.LinkedHashSet) QueryCache(ai.grakn.graql.internal.reasoner.cache.QueryCache) Patterns(ai.grakn.graql.internal.pattern.Patterns) GraqlQueryException(ai.grakn.exception.GraqlQueryException) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) AnswerState(ai.grakn.graql.internal.reasoner.state.AnswerState) MultiUnifier(ai.grakn.graql.admin.MultiUnifier) IsaAtomBase(ai.grakn.graql.internal.reasoner.atom.binary.IsaAtomBase) GetQuery(ai.grakn.graql.GetQuery) AtomicFactory(ai.grakn.graql.internal.reasoner.atom.AtomicFactory) ReasonerQuery(ai.grakn.graql.admin.ReasonerQuery) UnifierComparison(ai.grakn.graql.admin.UnifierComparison) EmbeddedGraknTx(ai.grakn.kb.internal.EmbeddedGraknTx) VarPatternAdmin(ai.grakn.graql.admin.VarPatternAdmin) Schema(ai.grakn.util.Schema) Unifier(ai.grakn.graql.admin.Unifier) ResolutionPlan(ai.grakn.graql.internal.reasoner.plan.ResolutionPlan) Collections(java.util.Collections) Concept(ai.grakn.concept.Concept) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) IdPredicate(ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate) HashMap(java.util.HashMap) Var(ai.grakn.graql.Var) Objects(java.util.Objects)

Aggregations

Objects (java.util.Objects)83 List (java.util.List)45 Map (java.util.Map)37 Collectors (java.util.stream.Collectors)32 ArrayList (java.util.ArrayList)30 Set (java.util.Set)30 IOException (java.io.IOException)22 HashMap (java.util.HashMap)21 Optional (java.util.Optional)19 Collections (java.util.Collections)18 LoggerFactory (org.slf4j.LoggerFactory)17 Stream (java.util.stream.Stream)16 Logger (org.slf4j.Logger)16 HashSet (java.util.HashSet)14 Collection (java.util.Collection)13 InputStream (java.io.InputStream)12 ImmutableSet (com.google.common.collect.ImmutableSet)10 Result (ddf.catalog.data.Result)9 TimeUnit (java.util.concurrent.TimeUnit)9 Metacard (ddf.catalog.data.Metacard)8