Java Code Examples for graphql.schema.DataFetchingEnvironment#getContext()

The following examples show how to use graphql.schema.DataFetchingEnvironment#getContext() . 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: ResolutionEnvironment.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
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 2
Source File: FetchParams.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
public FetchParams(DataFetchingEnvironment environment, HGQLSchema hgqlSchema)
        throws HGQLConfigurationException {

    final String predicate = extractPredicate(environment);
    predicateURI = extractPredicateUri(hgqlSchema, predicate);
    targetURI = extractTargetURI(environment, hgqlSchema, predicate);
    subjectResource = environment.getSource();
    client = environment.getContext();
}
 
Example 3
Source File: SetCustomProvenanceMutation.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object executeAction(DataFetchingEnvironment environment) {
  ImmutableContextData contextData = environment.getContext();
  Optional<User> userOpt = contextData.getUser();
  if (!userOpt.isPresent()) {
    throw new RuntimeException("User should be logged in.");
  }
  User user = userOpt.get();
  Optional<DataSet> dataSetOpt = dataSetRepository.getDataSet(user, ownerId, dataSetName);
  if (!dataSetOpt.isPresent()) {
    throw new RuntimeException("Data set is not available.");
  }

  DataSet dataSet = dataSetOpt.get();
  if (!contextData.getUserPermissionCheck().hasPermission(dataSet.getMetadata(), Permission.SET_CUSTOM_PROV)) {
    throw new RuntimeException("User should have permissions to set the custom provenance.");
  }

  TreeNode customProvenanceNode = OBJECT_MAPPER.valueToTree(environment.getArgument("customProvenance"));
  try {
    CustomProvenance customProvenance = OBJECT_MAPPER.treeToValue(customProvenanceNode, CustomProvenance.class);
    validateCustomProvenance(customProvenance);
    dataSet.setCustomProvenance(customProvenance);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }

  return ImmutableMap.of("message", "Custom provenance is set.");
}
 
Example 4
Source File: DefaultIndexConfigMutation.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Object executeAction(DataFetchingEnvironment env) {
  final User user = MutationHelpers.getUser(env);
  Optional<DataSet> dataSetOpt = dataSetRepository.getDataSet(user, ownerId, dataSetName);
  if (!dataSetOpt.isPresent()) {
    throw new RuntimeException("Dataset does not exist");
  }

  final DataSet dataSet = dataSetOpt.get();
  ImmutableContextData contextData = env.getContext();
  if (!contextData.getUserPermissionCheck().hasPermission(dataSet.getMetadata(), Permission.CONFIG_INDEX)) {
    throw new RuntimeException("User has no permissions to change the index configuration.");
  }

  final ReadOnlyChecker readOnlyChecker = dataSet.getReadOnlyChecker();
  final PredicateMutation predicateMutation = new PredicateMutation();
  final TypeNameStore typeNameStore = dataSet.getTypeNameStore();
  final PredicateMutation[] resetIndexPredicates = dataSet
      .getSchemaStore().getStableTypes().values().stream()
      .map(Type::getName)
      // The read-only data is non user data, where we do not need an search index for.
      .filter(uri -> !readOnlyChecker.isReadonlyType(uri))
      .map(collectionUri -> createIndexPredicate(predicateMutation, typeNameStore, collectionUri))
      .toArray(PredicateMutation[]::new);

  try {
    MutationHelpers.addMutations(dataSet, resetIndexPredicates);
  } catch (LogStorageFailedException | ExecutionException | InterruptedException e) {
    throw new RuntimeException(e);
  }

  return ImmutableMap.of("message", "Index is rest.");
}
 
Example 5
Source File: EditMutation.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object executeAction(DataFetchingEnvironment environment) {
  final String uri = environment.getArgument("uri");
  final Map entity = environment.getArgument("entity");
  ImmutableContextData contextData = environment.getContext();
  Optional<User> userOpt = contextData.getUser();
  if (!userOpt.isPresent()) {
    throw new RuntimeException("User should be logged in.");
  }

  User user = userOpt.get();
  Optional<DataSet> dataSetOpt = dataSetRepository.getDataSet(user, ownerId, dataSetName);
  if (!dataSetOpt.isPresent()) {
    throw new RuntimeException("Data set is not available.");
  }

  DataSet dataSet = dataSetOpt.get();
  if (!contextData.getUserPermissionCheck().hasPermission(dataSet.getMetadata(), Permission.WRITE)) {
    throw new RuntimeException("User should have permissions to edit entities of the data set.");
  }

  try (Stream<CursorQuad> quads = dataSet.getQuadStore().getQuads(uri)) {
    if (!quads.findAny().isPresent()) {
      throw new RuntimeException("Subject with uri '" + uri + "' does not exist");
    }
  }

  try {
    dataSet.getImportManager().generateLog(
      dataSet.getMetadata().getBaseUri(),
      dataSet.getMetadata().getGraph(),
      new GraphQlToRdfPatch(uri, userUriCreator.create(user), new EditMutationChangeLog(uri, entity))
    ).get(); // Wait until the data is processed
  } catch (LogStorageFailedException | JsonProcessingException | InterruptedException | ExecutionException e) {
    throw new RuntimeException(e);
  }

  return subjectFetcher.getItem(uri, dataSet);
}
 
Example 6
Source File: DeleteMutation.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object executeAction(DataFetchingEnvironment environment) {
  final String uri = environment.getArgument("uri");
  final Map entity = environment.getArgument("entity");
  ImmutableContextData contextData = environment.getContext();
  Optional<User> userOpt = contextData.getUser();
  if (!userOpt.isPresent()) {
    throw new RuntimeException("User should be logged in.");
  }

  User user = userOpt.get();
  Optional<DataSet> dataSetOpt = dataSetRepository.getDataSet(user, ownerId, dataSetName);
  if (!dataSetOpt.isPresent()) {
    throw new RuntimeException("Data set is not available.");
  }

  DataSet dataSet = dataSetOpt.get();
  if (!contextData.getUserPermissionCheck().hasPermission(dataSet.getMetadata(), Permission.DELETE)) {
    throw new RuntimeException("User should have permissions to delete entities of the data set.");
  }

  try (Stream<CursorQuad> quads = dataSet.getQuadStore().getQuads(uri)) {
    if (!quads.findAny().isPresent()) {
      throw new RuntimeException("Subject with uri '" + uri + "' does not exist");
    }
  }

  try {
    dataSet.getImportManager().generateLog(
      dataSet.getMetadata().getBaseUri(),
      dataSet.getMetadata().getGraph(),
      new GraphQlToRdfPatch(uri, userUriCreator.create(user), new DeleteMutationChangeLog(uri, entity))
    ).get(); // Wait until the data is processed
  } catch (LogStorageFailedException | JsonProcessingException | InterruptedException | ExecutionException e) {
    throw new RuntimeException(e);
  }

  return new RemovedEntity(uri);
}
 
Example 7
Source File: CreateMutation.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object executeAction(DataFetchingEnvironment environment) {
  final String uri = environment.getArgument("uri");
  final Map entity = environment.getArgument("entity");
  ImmutableContextData contextData = environment.getContext();
  Optional<User> userOpt = contextData.getUser();
  if (!userOpt.isPresent()) {
    throw new RuntimeException("User should be logged in.");
  }

  User user = userOpt.get();
  Optional<DataSet> dataSetOpt = dataSetRepository.getDataSet(user, ownerId, dataSetName);
  if (!dataSetOpt.isPresent()) {
    throw new RuntimeException("Data set is not available.");
  }

  DataSet dataSet = dataSetOpt.get();
  if (!contextData.getUserPermissionCheck().hasPermission(dataSet.getMetadata(), Permission.CREATE)) {
    throw new RuntimeException("User should have permissions to create entities of the data set.");
  }

  try (Stream<CursorQuad> quads = dataSet.getQuadStore().getQuads(uri)) {
    if (quads.findAny().isPresent()) {
      throw new RuntimeException("Subject with uri '" + uri + "' already exists");
    }
  }

  try {
    dataSet.getImportManager().generateLog(
      dataSet.getMetadata().getBaseUri(),
      dataSet.getMetadata().getGraph(),
      new GraphQlToRdfPatch(uri, userUriCreator.create(user), new CreateMutationChangeLog(uri, typeUri, entity))
    ).get(); // Wait until the data is processed
  } catch (LogStorageFailedException | JsonProcessingException | InterruptedException | ExecutionException e) {
    throw new RuntimeException(e);
  }

  return subjectFetcher.getItem(uri, dataSet);
}
 
Example 8
Source File: MutationHelpers.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
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 9
Source File: OtherDataSetFetcher.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<Map> get(DataFetchingEnvironment env) {
  if (env.getSource() instanceof SubjectReference) {
    final Set<String> dataSetIds = new HashSet<>();
    SubjectReference source = env.getSource();
    ContextData contextData = env.getContext();
    Stream<DataSet> dataSets = contextData.getUser()
      .map(user -> repo.getDataSetsWithReadAccess(user).stream())
      .orElseGet(() -> repo.getDataSets().stream().filter(d -> d.getMetadata().isPublished()));

    if (env.containsArgument("dataSetIds")) {
      dataSetIds.addAll(env.getArgument("dataSetIds"));
      dataSets = dataSets.filter(d -> dataSetIds.contains(d.getMetadata().getCombinedId()));
    }
    final String ownId = source.getDataSet().getMetadata().getCombinedId();
    return dataSets
      .filter(d -> !ownId.equals(d.getMetadata().getCombinedId()))
      .map(d -> {
        try (Stream<CursorQuad> quads = d.getQuadStore().getQuads(source.getSubjectUri())) {
          return tuple(d, quads.findAny());
        }
      })
      .filter(i -> i.getRight().isPresent())
      .map(i -> ImmutableMap.of(
        "metadata", new DataSetWithDatabase(i.getLeft(), env.<ContextData>getContext().getUserPermissionCheck()),
        "entity", new LazyTypeSubjectReference(i.getRight().get().getSubject(), i.getLeft())
      ))
      .collect(toList());

  }
  return Lists.newArrayList();
}
 
Example 10
Source File: QueryDataFetcher.java    From barleydb with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void breakQuery(DataFetchingEnvironment graphEnv, QueryObject<Object> query) {
 GraphQLContext graphCtx = graphEnv.getContext();	  
 for (QJoin join: new ArrayList<>(query.getJoins())) {
  if (graphCtx.getQueryCustomizations().shouldBreakJoin(join, graphCtx)) {
	  query.removeJoin(join);
	  GraphQLContext gctx = graphEnv.getContext();
	  gctx.registerJoinBreak(join);
  }
breakQuery(graphEnv, (QueryObject<Object>)join.getTo());
 }
}
 
Example 11
Source File: FetchParams.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
public FetchParams(DataFetchingEnvironment environment, HGQLSchema hgqlschema) {

        subjectResource = environment.getSource();
        String predicate = ((Field) environment.getFields().toArray()[0]).getName();
        predicateURI = hgqlschema.getFields().get(predicate).getId();
        client = environment.getContext();
        if (!environment.getParentType().getName().equals("Query")) {
            String targetName = hgqlschema.getTypes().get(environment.getParentType().getName()).getField(predicate).getTargetName();
            if (hgqlschema.getTypes().containsKey(targetName) && hgqlschema.getTypes().get(targetName).getId()!=null) {
                targetURI=hgqlschema.getTypes().get(targetName).getId();
            }
        }
    }
 
Example 12
Source File: UserListFetcher.java    From research-graphql with MIT License 5 votes vote down vote up
@Override
public List<UserDto> get(DataFetchingEnvironment environment) {
    HttpHeaders headers = environment.getContext();
    log.info("getContext() {}", headers);
    log.info("getArguments {}", environment.getArguments());
    List<UserDto> allUsers = userAdaptor.getAllUsers();
    return allUsers;
}
 
Example 13
Source File: MySubscriptionResolver.java    From samples with MIT License 5 votes vote down vote up
Publisher<Integer> hello(DataFetchingEnvironment env) {
  GraphQLWebSocketContext context = env.getContext();
  Optional<Authentication> authentication = Optional.ofNullable(context.getSession())
      .map(Session::getUserProperties)
      .map(props -> props.get("CONNECT_TOKEN"))
      .map(Authentication.class::cast);
  log.info("Subscribe to publisher with token: {}", authentication);
  authentication.ifPresent(SecurityContextHolder.getContext()::setAuthentication);
  log.info("Security context principal: {}", SecurityContextHolder.getContext().getAuthentication().getPrincipal());
  return publisher;
}
 
Example 14
Source File: OpenTracingDecorator.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private Span getParentSpan(Tracer tracer, final DataFetchingEnvironment env) {
    final GraphQLContext localContext = env.getLocalContext();
    if (localContext != null && localContext.hasKey(PARENT_SPAN_KEY)) {
        return localContext.get(PARENT_SPAN_KEY);
    }

    final GraphQLContext rootContext = env.getContext();
    if (rootContext != null && rootContext.hasKey(PARENT_SPAN_KEY)) {
        return rootContext.get(PARENT_SPAN_KEY);
    }

    return tracer.activeSpan();
}
 
Example 15
Source File: EntityDataFetcher.java    From barleydb with GNU Lesser General Public License v3.0 4 votes vote down vote up
private QueryObject<Object> getJoinAt(DataFetchingEnvironment graphEnv, Entity entity, String property) {
	GraphQLContext gctx = graphEnv.getContext();
	QJoin join = gctx.getJoinBreakFor(entity, property);
    return (QueryObject<Object> )(join != null ? join.getTo() : null);
}
 
Example 16
Source File: QueryDataFetcher.java    From barleydb with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public Object get(DataFetchingEnvironment graphEnv) throws Exception {
  EntityContext ctx = new EntityContext(env, namespace);

  QueryObject<Object> query = null;
  if (customQueries != null) {
    query = (QueryObject<Object>)customQueries.getQuery(graphEnv.getField().getName());
  }
  if (query == null) {
    EntityType entityType = getEntityTypeForQuery(graphEnv);
    query = buildQuery(graphEnv, entityType);
  }
  else {
    buildQuery(graphEnv, query);
  }
  LOG.debug("Built full query which will be broken into chunks, query => {}", ctx.debugQueryString(query));
  
  breakQuery(graphEnv, query);
  
  GraphQLContext gctx = graphEnv.getContext();
  QueryResult<Object> queryResult = ctx.performQuery(query);
  
  List<Entity> result = queryResult.getEntityList();
  LOG.debug("Processed {} rows", ctx.getStatistics().getNumberOfRowsRead());
  if (graphEnv.getExecutionStepInfo().getType() instanceof GraphQLList) {
    if (gctx.isBatchFetchEnabled()) {
  	  ctx.batchFetchDescendants(result);
    }
    return result; //Entity2Map.toListOfMaps(result);
  }
  else if (result.size() == 1) {
    Entity e = result.get(0);//Entity2Map.toMap(result.get(0));
    if (gctx.isBatchFetchEnabled()) {
      ctx.batchFetchDescendants(e);
    }
    return e;
  }
  else if (result.size() == 0) {
  	return null;
  }
  throw new IllegalStateException("too many results");
}
 
Example 17
Source File: MutationHelpers.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
public static User getUser(DataFetchingEnvironment env) {
  ContextData contextData = env.getContext();

  return contextData.getUser().orElseThrow(() -> new RuntimeException("You are not logged in"));
}
 
Example 18
Source File: GraphQlStreamObserver.java    From rejoiner with Apache License 2.0 4 votes vote down vote up
public GraphQlStreamObserver(DataFetchingEnvironment dataFetchingEnvironment) {
  this.dataFetchingEnvironment = dataFetchingEnvironment;
  rejoinerStreamingContext = dataFetchingEnvironment.getContext();
  rejoinerStreamingContext.startStream();
}
 
Example 19
Source File: ChatDataFetcher.java    From micronaut-graphql with Apache License 2.0 4 votes vote down vote up
@Override
public ChatMessage get(DataFetchingEnvironment env) {
    String text = env.getArgument("text");
    String from = env.getContext();
    return chatRepository.save(text, from);
}