graphql.schema.DataFetchingEnvironment Java Examples
The following examples show how to use
graphql.schema.DataFetchingEnvironment.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FetchParamsTest.java From hypergraphql with Apache License 2.0 | 6 votes |
@Test @DisplayName("schema must not have empty config") void schema_must_have_config_2() { DataFetchingEnvironment environment = mock(DataFetchingEnvironment.class); when(environment.getFields()).thenReturn(Collections.singletonList(mock(Field.class))); HGQLSchema schema = mock(HGQLSchema.class); when(schema.getFields()).thenReturn(Collections.emptyMap()); Executable executable = () -> new FetchParams( environment, schema ); assertThrows(NullPointerException.class, executable); }
Example #2
Source File: TransactionAdapter.java From besu with Apache License 2.0 | 6 votes |
public Optional<AccountAdapter> getCreatedContract(final DataFetchingEnvironment environment) { final boolean contractCreated = transactionWithMetadata.getTransaction().isContractCreation(); if (contractCreated) { final Optional<Address> addr = transactionWithMetadata.getTransaction().getTo(); if (addr.isPresent()) { final BlockchainQueries query = getBlockchainQueries(environment); final Optional<Long> txBlockNumber = transactionWithMetadata.getBlockNumber(); final Optional<Long> bn = Optional.ofNullable(environment.getArgument("block")); if (!txBlockNumber.isPresent() && !bn.isPresent()) { return Optional.empty(); } final long blockNumber = bn.orElseGet(txBlockNumber::get); final Optional<MutableWorldState> ws = query.getWorldState(blockNumber); if (ws.isPresent()) { return Optional.of(new AccountAdapter(ws.get().get(addr.get()))); } } } return Optional.empty(); }
Example #3
Source File: TransactionAdapter.java From besu with Apache License 2.0 | 6 votes |
public List<LogAdapter> getLogs(final DataFetchingEnvironment environment) { final BlockchainQueries query = getBlockchainQueries(environment); final Hash hash = transactionWithMetadata.getTransaction().getHash(); final Optional<TransactionReceiptWithMetadata> maybeTransactionReceiptWithMetadata = query.transactionReceiptByTransactionHash(hash); final List<LogAdapter> results = new ArrayList<>(); if (maybeTransactionReceiptWithMetadata.isPresent()) { final List<LogWithMetadata> logs = LogWithMetadata.generate( maybeTransactionReceiptWithMetadata.get().getReceipt(), transactionWithMetadata.getBlockNumber().get(), transactionWithMetadata.getBlockHash().get(), hash, transactionWithMetadata.getTransactionIndex().get(), false); for (final LogWithMetadata log : logs) { results.add(new LogAdapter(log)); } } return results; }
Example #4
Source File: EntityDataFetcher.java From barleydb with GNU Lesser General Public License v3.0 | 6 votes |
private void setProjection(DataFetchingEnvironment graphEnv, EntityType entityType, QueryObject<Object> query) { /* * set the projection */ List<SelectedField> selectedFields = graphEnv.getSelectionSet().getFields(); if (selectedFields != null) { for (SelectedField sf: selectedFields) { String parts[] = sf.getQualifiedName().split("/"); QueryObject<Object> q = getQueryForPath(query, entityType, Arrays.asList(parts).subList(0, parts.length - 1)); QProperty<Object> qprop = createProperty(q, parts[ parts.length - 1]); q.andSelect(qprop); LOG.debug("Added {} to select for {}", qprop.getName(), qprop.getQueryObject().getTypeName()); } } forceSelectForeignKeysAndSortNodes(query); }
Example #5
Source File: EntityImageFetcher.java From timbuctoo with GNU General Public License v3.0 | 6 votes |
@Override public TypedValue get(DataFetchingEnvironment env) { if (env.getSource() instanceof SubjectReference) { SubjectReference source = env.getSource(); DataSet dataSet = source.getDataSet(); if (env.getParentType() instanceof GraphQLObjectType) { String type = getDirectiveArgument((GraphQLObjectType) env.getParentType(), "rdfType", "uri").orElse(null); Optional<TypedValue> summaryProperty = summaryPropDataRetriever.createSummaryProperty(source, dataSet, type); if (summaryProperty.isPresent()) { return summaryProperty.get(); } } } return null; }
Example #6
Source File: AbstractDataFetcher.java From smallrye-graphql with Apache License 2.0 | 6 votes |
protected final DataFetcherResult.Builder<Object> appendPartialResult( DataFetcherResult.Builder<Object> resultBuilder, DataFetchingEnvironment dfe, GraphQLException graphQLException) { DataFetcherExceptionHandlerParameters handlerParameters = DataFetcherExceptionHandlerParameters .newExceptionParameters() .dataFetchingEnvironment(dfe) .exception(graphQLException) .build(); SourceLocation sourceLocation = handlerParameters.getSourceLocation(); ExecutionPath path = handlerParameters.getPath(); GraphQLExceptionWhileDataFetching error = new GraphQLExceptionWhileDataFetching(path, graphQLException, sourceLocation); return resultBuilder .data(graphQLException.getPartialResults()) .error(error); }
Example #7
Source File: FetchParamsTest.java From hypergraphql with Apache License 2.0 | 6 votes |
@Test @DisplayName("Environment must have a parent type") void environment_must_have_parent_type() { String uri = "abc123"; HGQLSchema schema = mock(HGQLSchema.class); DataFetchingEnvironment environment = mock(DataFetchingEnvironment.class); Field field1 = mock(Field.class); List<Field> fields = Collections.singletonList(field1); when(environment.getFields()).thenReturn(fields); when(field1.getName()).thenReturn("field1"); FieldConfig fieldConfig = mock(FieldConfig.class); Map<String, FieldConfig> schemaFields = Collections.singletonMap("field1", fieldConfig); when(schema.getFields()).thenReturn(schemaFields); when(fieldConfig.getId()).thenReturn(uri); Executable executable = () -> new FetchParams(environment, schema); assertThrows(NullPointerException.class, executable); }
Example #8
Source File: ResolutionEnvironment.java From graphql-spqr with Apache License 2.0 | 6 votes |
public ResolutionEnvironment(Resolver resolver, DataFetchingEnvironment env, ValueMapper valueMapper, GlobalEnvironment globalEnvironment, ConverterRegistry converters, DerivedTypeRegistry derivedTypes) { this.context = env.getSource(); this.rootContext = env.getContext(); this.resolver = resolver; this.valueMapper = valueMapper; this.globalEnvironment = globalEnvironment; this.converters = converters; this.fieldType = env.getFieldType(); this.parentType = (GraphQLNamedType) env.getParentType(); this.graphQLSchema = env.getGraphQLSchema(); this.dataFetchingEnvironment = env; this.derivedTypes = derivedTypes; this.arguments = new HashMap<>(); }
Example #9
Source File: NotificationDataFetcher.java From notification with Apache License 2.0 | 6 votes |
@Nullable @Override public SortedSet<Notification> get(DataFetchingEnvironment environment) { final String username = environment.getArgument("username"); if (Strings.isNullOrEmpty(username)) { return null; } final Optional<UserNotifications> notifications; try { notifications = store.fetch(username); } catch (NotificationStoreException e) { LOGGER.error("Unable to fetch notifications", e); return null; } if (!notifications.isPresent()) { return Collections.emptySortedSet(); } return notifications.get().getNotifications(); }
Example #10
Source File: IndexConfigMutation.java From timbuctoo with GNU General Public License v3.0 | 6 votes |
@Override public Object executeAction(DataFetchingEnvironment env) { String collectionUri = env.getArgument("collectionUri"); Object indexConfig = env.getArgument("indexConfig"); DataSet dataSet = MutationHelpers.getDataSet(env, dataSetRepository::getDataSet); MutationHelpers.checkPermission(env, dataSet.getMetadata(), Permission.CONFIG_INDEX); try { MutationHelpers.addMutation( dataSet, new PredicateMutation() .entity( collectionUri, replace(TIM_HASINDEXERCONFIG, value(OBJECT_MAPPER.writeValueAsString(indexConfig))) ) ); return indexConfig; } catch (LogStorageFailedException | InterruptedException | ExecutionException | JsonProcessingException e) { throw new RuntimeException(e); } }
Example #11
Source File: OpenTracingDecoratorTest.java From smallrye-graphql with Apache License 2.0 | 6 votes |
@Test public void testTracingWorks() throws Exception { OpenTracingDecorator decorator = new OpenTracingDecorator(); DataFetchingEnvironment dfe = MockDataFetchEnvironment.myFastQueryDfe("Query", "myFastQuery", "someOperation", "1"); MockExecutionContext mockExecutionContext = new MockExecutionContext(); mockExecutionContext.setDataFetchingEnvironment(dfe); mockExecutionContext.setNewGraphQLContext(GraphQLContext.newContext().build()); decorator.execute(mockExecutionContext); assertOneSpanIsFinished(); MockSpan span = MockTracerOpenTracingService.MOCK_TRACER.finishedSpans().get(0); assertContainsGraphQLTags(span, "Query", "myFastQuery", "someOperation", "1"); assertNoErrorLogged(span); }
Example #12
Source File: OpenTracingDecoratorTest.java From smallrye-graphql with Apache License 2.0 | 6 votes |
@Test public void testAsyncWorks() throws Exception { OpenTracingDecorator decorator = new OpenTracingDecorator(); DataFetchingEnvironment dfe = MockDataFetchEnvironment.myFastQueryDfe("Query", "myFastQuery", "someOperation", "1"); MockExecutionContext mockExecutionContext = new MockExecutionContext(); mockExecutionContext.setDataFetchingEnvironment(dfe); mockExecutionContext.setNewGraphQLContext(GraphQLContext.newContext().build()); final CompletableFuture<Object> result = new CompletableFuture<>(); mockExecutionContext.setResult(result); decorator.execute(mockExecutionContext); assertNoSpanIsFinished(); result.complete(""); assertOneSpanIsFinished(); MockSpan span = MockTracerOpenTracingService.MOCK_TRACER.finishedSpans().get(0); assertContainsGraphQLTags(span, "Query", "myFastQuery", "someOperation", "1"); assertNoErrorLogged(span); }
Example #13
Source File: OpenTracingDecoratorTest.java From smallrye-graphql with Apache License 2.0 | 6 votes |
@Test public void testSpanOverMultipleThreadsWorks() throws Exception { OpenTracingDecorator decorator = new OpenTracingDecorator(); DataFetchingEnvironment dfe = MockDataFetchEnvironment.myFastQueryDfe("Query", "myFastQuery", "someOperation", "1"); MockExecutionContext mockExecutionContext = new MockExecutionContext(); mockExecutionContext.setDataFetchingEnvironment(dfe); mockExecutionContext.setNewGraphQLContext(GraphQLContext.newContext().build()); CompletableFuture<String> future = new CompletableFuture<>(); CompletableFuture<String> asyncFutur = future.thenApplyAsync(Function.identity());//Let future complete in different Thread mockExecutionContext.setResult(asyncFutur); CompletableFuture<String> result = (CompletableFuture<String>) decorator.execute(mockExecutionContext); assertNoSpanIsFinished(); future.complete("Result"); assertEquals("Result", result.get()); assertOneSpanIsFinished(); MockSpan span = MockTracerOpenTracingService.MOCK_TRACER.finishedSpans().get(0); assertContainsGraphQLTags(span, "Query", "myFastQuery", "someOperation", "1"); assertNoErrorLogged(span); }
Example #14
Source File: MetricDecoratorTest.java From smallrye-graphql with Apache License 2.0 | 6 votes |
@Test public void testAsyncWorks() throws Exception { MetricDecorator decorator = new MetricDecorator(); DataFetchingEnvironment dfe = myFastQueryDfe(); MockExecutionContext mockExecutionContext = new MockExecutionContext(); mockExecutionContext.setDataFetchingEnvironment(dfe); mockExecutionContext.setNewGraphQLContext(GraphQLContext.newContext().build()); final CompletableFuture<Object> result = new CompletableFuture<>(); mockExecutionContext.setResult(result); decorator.execute(mockExecutionContext); TestMetricsServiceImpl.MockMetricsRegistry registry = TestMetricsServiceImpl.vendorRegistry; assertEquals(0, registry.simpleTimers.size()); result.complete(""); assertEquals(1, registry.simpleTimers.size()); assertEquals(1, registry.simpleTimers.get("mp_graphql_Query_myFastQuery").getCount()); }
Example #15
Source File: ViewConfigMutation.java From timbuctoo with GNU General Public License v3.0 | 6 votes |
@Override public Object executeAction(DataFetchingEnvironment env) { String collectionUri = env.getArgument("collectionUri"); Object viewConfig = env.getArgument("viewConfig"); DataSet dataSet = MutationHelpers.getDataSet(env, dataSetRepository::getDataSet); MutationHelpers.checkPermission(env, dataSet.getMetadata(), Permission.CONFIG_VIEW); try { MutationHelpers.addMutation( dataSet, new PredicateMutation() .entity( collectionUri, replace(HAS_VIEW_CONFIG, value(OBJECT_MAPPER.writeValueAsString(viewConfig))) ) ); return viewConfig; } catch (LogStorageFailedException | InterruptedException | ExecutionException | JsonProcessingException e) { throw new RuntimeException(e); } }
Example #16
Source File: ViewConfigFetcher.java From timbuctoo with GNU General Public License v3.0 | 6 votes |
@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)); } }
Example #17
Source File: SelectorToFieldMask.java From rejoiner with Apache License 2.0 | 6 votes |
public static Builder getFieldMaskForProto( DataFetchingEnvironment environment, Descriptor descriptor, String startAtFieldName) { Map<String, FragmentDefinition> fragmentsByName = environment.getFragmentsByName(); Builder maskFromSelectionBuilder = FieldMask.newBuilder(); for (Field field : environment.getFields()) { for (Selection<?> selection1 : field.getSelectionSet().getSelections()) { if (selection1 instanceof Field) { Field field2 = (Field) selection1; if (field2.getName().equals(startAtFieldName)) { for (Selection<?> selection : field2.getSelectionSet().getSelections()) { maskFromSelectionBuilder.addAllPaths( getPathsForProto("", selection, descriptor, fragmentsByName)); } } } } } return maskFromSelectionBuilder; }
Example #18
Source File: MockDataFetchEnvironment.java From smallrye-graphql with Apache License 2.0 | 6 votes |
public static DataFetchingEnvironment myFastQueryDfe(String typeName, String fieldName, String operationName, String executionId) { GraphQLNamedType query = mock(GraphQLNamedType.class); when(query.getName()).thenReturn(typeName); Field field = mock(Field.class); when(field.getName()).thenReturn(fieldName); OperationDefinition operationDefinition = mock(OperationDefinition.class); when(operationDefinition.getName()).thenReturn(operationName); ExecutionPath executionPath = mock(ExecutionPath.class); when(executionPath.toString()).thenReturn("/" + typeName + "/" + fieldName); ExecutionStepInfo executionStepInfo = mock(ExecutionStepInfo.class); when(executionStepInfo.getPath()).thenReturn(executionPath); DataFetchingEnvironment dfe = mock(DataFetchingEnvironment.class); when(dfe.getParentType()).thenReturn(query); when(dfe.getField()).thenReturn(field); when(dfe.getOperationDefinition()).thenReturn(operationDefinition); when(dfe.getExecutionStepInfo()).thenReturn(executionStepInfo); when(dfe.getExecutionId()).thenReturn(ExecutionId.from(executionId)); return dfe; }
Example #19
Source File: TransactionAdapter.java From besu with Apache License 2.0 | 6 votes |
public Optional<AccountAdapter> getTo(final DataFetchingEnvironment environment) { final BlockchainQueries query = getBlockchainQueries(environment); final Optional<Long> txBlockNumber = transactionWithMetadata.getBlockNumber(); final Optional<Long> bn = Optional.ofNullable(environment.getArgument("block")); if (!txBlockNumber.isPresent() && !bn.isPresent()) { return Optional.empty(); } return query .getWorldState(bn.orElseGet(txBlockNumber::get)) .flatMap( ws -> transactionWithMetadata .getTransaction() .getTo() .map(addr -> new AccountAdapter(ws.get(addr)))); }
Example #20
Source File: SelectorToFieldMask.java From rejoiner with Apache License 2.0 | 6 votes |
public static Builder getFieldMaskForProto( DataFetchingEnvironment environment, Descriptor descriptor) { Map<String, FragmentDefinition> fragmentsByName = environment.getFragmentsByName(); Builder maskFromSelectionBuilder = FieldMask.newBuilder(); for (Field field : Optional.ofNullable(environment.getMergedField()) .map(MergedField::getFields) .orElse(ImmutableList.of())) { for (Selection<?> selection : field.getSelectionSet().getSelections()) { maskFromSelectionBuilder.addAllPaths( getPathsForProto("", selection, descriptor, fragmentsByName)); } } return maskFromSelectionBuilder; }
Example #21
Source File: VertxPropertyDataFetcher.java From vertx-web with Apache License 2.0 | 5 votes |
@GenIgnore(PERMITTED_TYPE) static PropertyDataFetcher<Object> create(String propertyName) { return new PropertyDataFetcher<Object>(propertyName) { @Override public Object get(DataFetchingEnvironment environment) { Object source = environment.getSource(); if (source instanceof JsonObject) { JsonObject jsonObject = (JsonObject) source; return jsonObject.getValue(getPropertyName()); } return super.get(environment); } }; }
Example #22
Source File: MutationHelpers.java From timbuctoo with GNU General Public License v3.0 | 5 votes |
public static void checkPermission(DataFetchingEnvironment env, DataSetMetaData dataSetMetaData, Permission permission) throws RuntimeException { ContextData contextData = env.getContext(); UserPermissionCheck userPermissionCheck = contextData.getUserPermissionCheck(); if (!userPermissionCheck.hasPermission(dataSetMetaData, permission)) { throw new RuntimeException("You do not have permission '" + permission + "' for this data set."); } }
Example #23
Source File: OverrideDataFetcher.java From glitr with MIT License | 5 votes |
private Method findMethod(String name, Class clazz) { try { //noinspection unchecked return clazz.getMethod(name, DataFetchingEnvironment.class); } catch (NoSuchMethodException e) { logger.debug("Couldn't find method for name {} and class {}", name, clazz, e.getMessage()); } return null; }
Example #24
Source File: UserQuery.java From tutorials with MIT License | 5 votes |
@GraphQLField public static User retrieveUser(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.ID) final String id) { final Optional<User> any = getUsers(env).stream() .filter(c -> c.getId() == Long.parseLong(id)) .findFirst(); return any.orElse(null); }
Example #25
Source File: MetricDecoratorTest.java From smallrye-graphql with Apache License 2.0 | 5 votes |
@Test public void testSimpleTimerCountWorks() throws Exception { MetricDecorator decorator = new MetricDecorator(); DataFetchingEnvironment dfe = myFastQueryDfe(); MockExecutionContext mockExecutionContext = new MockExecutionContext(); mockExecutionContext.setDataFetchingEnvironment(dfe); mockExecutionContext.setNewGraphQLContext(GraphQLContext.newContext().build()); decorator.execute(mockExecutionContext); decorator.execute(mockExecutionContext); decorator.execute(mockExecutionContext); DataFetchingEnvironment dfe2 = myOtherQueryDfe(); MockExecutionContext mockExecutionContext2 = new MockExecutionContext(); mockExecutionContext2.setDataFetchingEnvironment(dfe2); mockExecutionContext2.setNewGraphQLContext(GraphQLContext.newContext().build()); decorator.execute(mockExecutionContext2); decorator.execute(mockExecutionContext2); TestMetricsServiceImpl.MockMetricsRegistry registry = TestMetricsServiceImpl.vendorRegistry; assertEquals(2, registry.simpleTimers.size()); assertEquals(3, registry.simpleTimers.get("mp_graphql_Query_myFastQuery").getCount()); assertEquals(2, registry.simpleTimers.get("mp_graphql_Query_myOtherQuery").getCount()); }
Example #26
Source File: ResourceSyncImportMutation.java From timbuctoo with GNU General Public License v3.0 | 5 votes |
@Override public Object executeAction(DataFetchingEnvironment env) { User user = MutationHelpers.getUser(env); String dataSetName = env.getArgument("dataSetName"); String capabilityListUri = env.getArgument("capabilityListUri"); String userSpecifiedDataSet = env.getArgument("userSpecifiedDataSet"); String authString = env.getArgument("authorization"); try { ImportInfo importInfo = new ImportInfo(capabilityListUri, Date.from(Instant.now())); DataSet dataSet = dataSetRepository.createDataSet(user, dataSetName, Lists.newArrayList(importInfo)); MutationHelpers.checkPermission(env, dataSet.getMetadata(), Permission.IMPORT_RESOURCESYNC); ResourceSyncImport resourceSyncImport = new ResourceSyncImport(resourceSyncFileLoader, dataSet, false); return resourceSyncImport.filterAndImport( capabilityListUri, userSpecifiedDataSet, false, authString ); } catch (DataStoreCreationException | IllegalDataSetNameException | IOException | CantRetrieveFileException | CantDetermineDataSetException | DataSetCreationException e) { LOG.error("Failed to do a resource sync import. ", e); throw new RuntimeException(e); } }
Example #27
Source File: OrderItemProductFetcher.java From research-graphql with MIT License | 5 votes |
@Override public ProductDto get(DataFetchingEnvironment environment) { log.info("getSource {}", (Object)environment.getSource()); OrderItemDto orderItemDto = environment.getSource(); ProductDto product = productAdaptor.getProduct(orderItemDto.getProductId()); return product; }
Example #28
Source File: QueryDataFetcher.java From barleydb with GNU Lesser General Public License v3.0 | 5 votes |
private EntityType getEntityTypeForQuery(DataFetchingEnvironment graphEnv) { String entityName = graphEnv.getExecutionStepInfo().getType().getName(); if (entityName == null) { entityName = graphEnv.getExecutionStepInfo().getType().getChildren().get(0).getName(); } EntityType et = env.getDefinitionsSet().getFirstEntityTypeByInterfaceName(namespace + ".model." + entityName); requireNonNull(et, "EntityType must exist"); return et; }
Example #29
Source File: MethodDataFetcher.java From graphql-apigen with Apache License 2.0 | 5 votes |
@Override public Object get(DataFetchingEnvironment env) { Object source = ( null != impl ) ? impl : env.getSource(); if (source == null) return null; if (source instanceof ResolveDataFetchingEnvironment) { source = ((ResolveDataFetchingEnvironment)source).resolve(env); } return getMethodViaGetter(source, env.getFieldType(), getFieldType(env.getParentType()), env.getArguments()); }
Example #30
Source File: MutationHelpers.java From timbuctoo with GNU General Public License v3.0 | 5 votes |
public static DataSet getDataSet(DataFetchingEnvironment env, DataSetFetcher fetcher) { String dataSetId = env.getArgument("dataSetId"); Tuple<String, String> userAndDataSet = DataSetMetaData.splitCombinedId(dataSetId); User user = getUser(env); String ownerId = userAndDataSet.getLeft(); String dataSetName = userAndDataSet.getRight(); return fetcher.getDataSet(user, ownerId, dataSetName) .orElseThrow(() -> new RuntimeException("Dataset does not exist")); }