Search in sources :

Example 1 with DataFetchingEnvironment

use of graphql.schema.DataFetchingEnvironment in project graphql-java by graphql-java.

the class FunWithStringsSchemaFactory method createBatched.

public static FunWithStringsSchemaFactory createBatched(final Map<CallType, AtomicInteger> callCounts) {
    FunWithStringsSchemaFactory factory = new FunWithStringsSchemaFactory();
    factory.setStringObjectValueFetcher(new DataFetcher() {

        @Override
        @Batched
        @SuppressWarnings("unchecked")
        public Object get(DataFetchingEnvironment environment) {
            increment(callCounts, CallType.VALUE);
            List<String> retVal = new ArrayList<>();
            for (String s : (List<String>) environment.getSource()) {
                retVal.add("null".equals(s) ? null : s);
            }
            return retVal;
        }
    });
    factory.setThrowExceptionFetcher(new DataFetcher() {

        @Override
        @Batched
        public Object get(DataFetchingEnvironment environment) {
            throw new RuntimeException("TestException");
        }
    });
    factory.setReturnBadList(new DataFetcher() {

        @Override
        @Batched
        @SuppressWarnings("unchecked")
        public Object get(DataFetchingEnvironment environment) {
            List<String> retVal = new ArrayList<>();
            for (String s : (List<String>) environment.getSource()) {
                retVal.add("null".equals(s) ? null : s);
            }
            retVal.add("badValue");
            return retVal;
        }
    });
    factory.setAnyIterable(new DataFetcher() {

        @Override
        @Batched
        @SuppressWarnings("unchecked")
        public Object get(DataFetchingEnvironment environment) {
            List<Iterable<String>> retVal = new ArrayList<>();
            for (String s : (List<String>) environment.getSource()) {
                retVal.add(new LinkedHashSet<>(Arrays.asList(s, "end")));
            }
            return retVal;
        }
    });
    factory.setAppendFetcher(new DataFetcher() {

        @Override
        @Batched
        @SuppressWarnings("unchecked")
        public Object get(DataFetchingEnvironment environment) {
            increment(callCounts, CallType.APPEND);
            List<String> retVal = new ArrayList<>();
            for (String s : (List<String>) environment.getSource()) {
                retVal.add(s + environment.getArgument("text"));
            }
            // make it an Iterable thing not just List
            return new ArrayDeque<>(retVal);
        }
    });
    factory.setWordsAndLettersFetcher(new DataFetcher() {

        @Batched
        @Override
        @SuppressWarnings("unchecked")
        public Object get(DataFetchingEnvironment environment) {
            increment(callCounts, CallType.WORDS_AND_LETTERS);
            List<String> sources = environment.getSource();
            List<List<List<String>>> retVal = new ArrayList<>();
            for (String source : sources) {
                List<List<String>> sentence = new ArrayList<>();
                splitSentence(source, sentence);
                retVal.add(sentence);
            }
            return retVal.toArray();
        }
    });
    factory.setSplitFetcher(new DataFetcher() {

        @Batched
        @Override
        @SuppressWarnings("unchecked")
        public Object get(DataFetchingEnvironment environment) {
            increment(callCounts, CallType.SPLIT);
            String regex = environment.getArgument("regex");
            List<String> sources = environment.getSource();
            List<List<String>> retVal = new ArrayList<>();
            if (regex == null) {
                for (String ignored : sources) {
                    retVal.add(null);
                }
                return retVal;
            }
            for (String source : sources) {
                List<String> retItem = new ArrayList<>();
                for (String str : source.split(regex)) {
                    if (str.isEmpty()) {
                        retItem.add(null);
                    } else {
                        retItem.add(str);
                    }
                }
                retVal.add(retItem);
            }
            return retVal;
        }
    });
    factory.setShatterFetcher(new DataFetcher() {

        @Batched
        @Override
        @SuppressWarnings("unchecked")
        public Object get(DataFetchingEnvironment environment) {
            increment(callCounts, CallType.SHATTER);
            List<String> sources = environment.getSource();
            List<List<String>> retVal = new ArrayList<>();
            for (String source : sources) {
                List<String> retItem = new ArrayList<>();
                for (char c : source.toCharArray()) {
                    retItem.add(Character.toString(c));
                }
                retVal.add(retItem);
            }
            return retVal;
        }
    });
    return factory;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) GraphQLString(graphql.Scalars.GraphQLString) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) GraphQLObjectType.newObject(graphql.schema.GraphQLObjectType.newObject) ArrayList(java.util.ArrayList) List(java.util.List) GraphQLList(graphql.schema.GraphQLList) DataFetcher(graphql.schema.DataFetcher)

Example 2 with DataFetchingEnvironment

use of graphql.schema.DataFetchingEnvironment in project graphql-java by graphql-java.

the class UnbatchedDataFetcher method get.

@Override
public CompletableFuture<List<Object>> get(DataFetchingEnvironment environment) {
    List<Object> sources = environment.getSource();
    List<CompletableFuture<Object>> results = new ArrayList<>();
    for (Object source : sources) {
        DataFetchingEnvironment singleEnv = newDataFetchingEnvironment(environment).source(source).build();
        CompletableFuture<Object> cf = Async.toCompletableFuture(delegate.get(singleEnv));
        results.add(cf);
    }
    return Async.each(results);
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) DataFetchingEnvironmentBuilder.newDataFetchingEnvironment(graphql.schema.DataFetchingEnvironmentBuilder.newDataFetchingEnvironment)

Example 3 with DataFetchingEnvironment

use of graphql.schema.DataFetchingEnvironment in project timbuctoo by HuygensING.

the class ViewConfigFetcher method get.

@Override
public Object get(DataFetchingEnvironment env) {
    SubjectReference source = env.getSource();
    final DataSet dataSet = source.getDataSet();
    final QuadStore qs = dataSet.getQuadStore();
    final Map<String, Type> schema = dataSet.getSchemaStore().getStableTypes();
    final TypeNameStore typeNameStore = dataSet.getTypeNameStore();
    try (Stream<CursorQuad> quads = qs.getQuads(source.getSubjectUri(), HAS_VIEW_CONFIG, Direction.OUT, "")) {
        return quads.findFirst().flatMap(q -> {
            try {
                return Optional.ofNullable(objectMapper.readValue(q.getObject(), List.class));
            } catch (IOException e) {
                LOG.error("view config is not a valid JSON object", e);
                return Optional.empty();
            }
        }).orElseGet(() -> makeDefaultViewConfig(source.getSubjectUri(), schema, typeNameStore));
    }
}
Also used : CursorQuad(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.CursorQuad) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) Type(nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.Type) LoggerFactory(org.slf4j.LoggerFactory) QuadStore(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.QuadStore) Predicate(nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.Predicate) SubjectReference(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.SubjectReference) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) HAS_VIEW_CONFIG(nl.knaw.huygens.timbuctoo.v5.util.RdfConstants.HAS_VIEW_CONFIG) Map(java.util.Map) JsonBuilder.jsnA(nl.knaw.huygens.timbuctoo.util.JsonBuilder.jsnA) DataFetcher(graphql.schema.DataFetcher) JsonNode(com.fasterxml.jackson.databind.JsonNode) TypeNameStore(nl.knaw.huygens.timbuctoo.v5.datastores.prefixstore.TypeNameStore) JsonBuilder.jsn(nl.knaw.huygens.timbuctoo.util.JsonBuilder.jsn) Logger(org.slf4j.Logger) ImmutableMap(com.google.common.collect.ImmutableMap) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) List(java.util.List) Stream(java.util.stream.Stream) Optional(java.util.Optional) Direction(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.Direction) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) Type(nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.Type) QuadStore(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.QuadStore) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) CursorQuad(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.CursorQuad) SubjectReference(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.SubjectReference) IOException(java.io.IOException) TypeNameStore(nl.knaw.huygens.timbuctoo.v5.datastores.prefixstore.TypeNameStore)

Example 4 with DataFetchingEnvironment

use of graphql.schema.DataFetchingEnvironment in project nextprot-api by calipho-sib.

the class EntryDataFetcherImpl method get.

@Override
public Entry get(DataFetchingEnvironment environment) {
    // TODO THIS IS A POC (Proof of Concept)
    // If we decide to go ahead with GraphQL please try to adapt this terrible function using EntryQueryResolver that implements GraphQLQueryResolver
    // graphql java tools allows to do newSchemaParser().file(schemaFile).resolvers(...).getSchemaObjects.getGraphqlSchema
    String accession = environment.getArgument("accession");
    Integer publicationLimit = -1;
    Integer annotationLimit = -1;
    String category = "";
    // Searching for publication limit
    Optional<Selection> publicationField = environment.getFields().get(0).getSelectionSet().getSelections().stream().filter(f -> ((Field) f).getName().equals("publications")).findAny();
    if (publicationField.isPresent()) {
        Optional<Argument> publicationLimitArg = ((Field) publicationField.get()).getArguments().stream().filter(f -> f.getName().equals("limit")).findAny();
        if (publicationLimitArg.isPresent()) {
            publicationLimit = Integer.valueOf(publicationLimitArg.get().getValue().toString().replace("IntValue{value=", "").replace("}", ""));
        }
    }
    // Searching for annotation field
    Optional<Selection> annotationField = environment.getFields().get(0).getSelectionSet().getSelections().stream().filter(f -> ((Field) f).getName().equals("annotations")).findAny();
    if (annotationField.isPresent()) {
        Optional<Argument> publicationLimitArg = ((Field) annotationField.get()).getArguments().stream().filter(f -> f.getName().equals("category")).findAny();
        if (publicationLimitArg.isPresent()) {
            category = publicationLimitArg.get().getValue().toString().replace("StringValue{value='", "").replace("'}", "");
        }
        Optional<Argument> annotationLimitArg = ((Field) annotationField.get()).getArguments().stream().filter(f -> f.getName().equals("limit")).findAny();
        if (annotationLimitArg.isPresent()) {
            annotationLimit = Integer.valueOf(annotationLimitArg.get().getValue().toString().replace("IntValue{value=", "").replace("}", ""));
        }
    }
    Entry entry = entryBuilderService.build(EntryConfig.newConfig(accession).with(category).withPublications().withOverview().withTargetIsoforms());
    if (publicationLimit != -1) {
        List<Publication> publications = entry.getPublications();
        List<Publication> publicationSubset = publications.subList(0, publicationLimit);
        entry.setPublications(publicationSubset);
    }
    if (annotationLimit != -1) {
        String cat = entry.getAnnotationsByCategory().keySet().iterator().next();
        entry.setAnnotations(entry.getAnnotationsByCategory(AnnotationCategory.getDecamelizedAnnotationTypeName(cat)).subList(0, annotationLimit));
    }
    return entry;
}
Also used : DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) Entry(org.nextprot.api.core.domain.Entry) Autowired(org.springframework.beans.factory.annotation.Autowired) Field(graphql.language.Field) EntryBuilderService(org.nextprot.api.core.service.EntryBuilderService) Argument(graphql.language.Argument) Selection(graphql.language.Selection) Publication(org.nextprot.api.core.domain.Publication) Component(org.springframework.stereotype.Component) List(java.util.List) AnnotationCategory(org.nextprot.api.commons.constants.AnnotationCategory) EntryConfig(org.nextprot.api.core.service.fluent.EntryConfig) DataFetcher(graphql.schema.DataFetcher) Optional(java.util.Optional) Entry(org.nextprot.api.core.domain.Entry) Argument(graphql.language.Argument) Selection(graphql.language.Selection) Publication(org.nextprot.api.core.domain.Publication)

Example 5 with DataFetchingEnvironment

use of graphql.schema.DataFetchingEnvironment in project ontrack by nemerosa.

the class GitChangeLogBranchGraphQLFieldContributor method gitChangeLogFetcher.

private DataFetcher gitChangeLogFetcher() {
    return fetcher(Branch.class, (DataFetchingEnvironment environment, Branch branch) -> {
        String from = GraphqlUtils.getStringArgument(environment, "from").orElseThrow(() -> new IllegalStateException("From argument is required."));
        String to = GraphqlUtils.getStringArgument(environment, "to").orElseThrow(() -> new IllegalStateException("To argument is required."));
        Build fromBuild = structureService.findBuildByName(branch.getProject().getName(), branch.getName(), from).orElseThrow(() -> new BuildNotFoundException(branch.getProject().getName(), branch.getName(), from));
        Build toBuild = structureService.findBuildByName(branch.getProject().getName(), branch.getName(), to).orElseThrow(() -> new BuildNotFoundException(branch.getProject().getName(), branch.getName(), to));
        return gitService.changeLog(new BuildDiffRequest(fromBuild.getId(), toBuild.getId()));
    });
}
Also used : BuildDiffRequest(net.nemerosa.ontrack.extension.api.model.BuildDiffRequest) BuildNotFoundException(net.nemerosa.ontrack.model.exceptions.BuildNotFoundException) GraphQLString(graphql.Scalars.GraphQLString) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment)

Aggregations

DataFetchingEnvironment (graphql.schema.DataFetchingEnvironment)16 DataFetcher (graphql.schema.DataFetcher)12 List (java.util.List)9 Field (graphql.language.Field)7 Optional (java.util.Optional)7 Map (java.util.Map)6 Logger (org.slf4j.Logger)6 LoggerFactory (org.slf4j.LoggerFactory)6 Argument (graphql.language.Argument)5 Selection (graphql.language.Selection)5 Collectors (java.util.stream.Collectors)5 ArrayValue (graphql.language.ArrayValue)4 BooleanValue (graphql.language.BooleanValue)4 FloatValue (graphql.language.FloatValue)4 FragmentDefinition (graphql.language.FragmentDefinition)4 FragmentSpread (graphql.language.FragmentSpread)4 InlineFragment (graphql.language.InlineFragment)4 IntValue (graphql.language.IntValue)4 ObjectField (graphql.language.ObjectField)4 ObjectValue (graphql.language.ObjectValue)4