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

The following examples show how to use graphql.schema.DataFetchingEnvironment#getArgument() . 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: PersistEntityMutation.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object executeAction(DataFetchingEnvironment env) {
  User user = MutationHelpers.getUser(env);
  String entityUri = env.getArgument("entityUri");
  URI uri;
  try {
    uri = GetEntity.makeUrl(ownerId, dataSetName, entityUri);
  } catch (UnsupportedEncodingException e) {
    return ImmutableMap.of("message", "Request for presistent Uri failed.");
  }
  URI fullUri = uriHelper.fromResourceUri(uri);

  EntityLookup entityLookup = ImmutableEntityLookup.builder().dataSetId(dataSetId).uri(entityUri).user(user).build();
  redirectionService.add(fullUri, entityLookup);

  return ImmutableMap.of("message", "Request for presistent Uri accepted");
}
 
Example 2
Source File: NotificationDataFetcher.java    From notification with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: ResourceSyncImportMutation.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@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 4
Source File: LookUpSubjectByUriFetcherWrapper.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object get(DataFetchingEnvironment environment) {
  final DatabaseResult source = environment.getSource();
  ParsedURI baseUri = new ParsedURI(source.getDataSet().getMetadata().getBaseUri());
  String uri = environment.getArgument(uriArgument);
  return lookUpSubjectByUriFetcher.getItem(
    baseUri.resolve(uri).toString(),
    source.getDataSet()
  );
}
 
Example 5
Source File: HelloDataFetcher.java    From micronaut-graphql with Apache License 2.0 5 votes vote down vote up
@Override
public String get(DataFetchingEnvironment env) {
    String name = env.getArgument("name");
    if (name == null || name.trim().length() == 0) {
        name = "World";
    }
    return String.format("Hello %s!", name);
}
 
Example 6
Source File: CompleteToDoDataFetcher.java    From micronaut-graphql with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean get(DataFetchingEnvironment env) {
    String id = env.getArgument("id");
    ToDo toDo = toDoRepository.findById(id);
    if (toDo != null) {
        toDo.setCompleted(true);
        toDoRepository.save(toDo);
        return true;
    } else {
        return false;
    }
}
 
Example 7
Source File: MutationHelpers.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
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"));
}
 
Example 8
Source File: LogAdapter.java    From besu with Apache License 2.0 5 votes vote down vote up
public Optional<AccountAdapter> getAccount(final DataFetchingEnvironment environment) {
  final BlockchainQueries query = getBlockchainQueries(environment);
  long blockNumber = logWithMetadata.getBlockNumber();
  final Long bn = environment.getArgument("block");
  if (bn != null) {
    blockNumber = bn;
  }

  return query
      .getWorldState(blockNumber)
      .map(ws -> new AccountAdapter(ws.get(logWithMetadata.getLogger())));
}
 
Example 9
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 10
Source File: UrlTransformDataFetcher.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object doGet(final DataFetchingEnvironment environment) {
    String fieldName = environment.getField().getName();
    Map<String, Object> source = environment.getSource();
    if (source.containsKey(fieldName) && nonNull(source.get(fieldName))) {
        String transformerName = environment.getArgument(ARG_NAME_TRANSFORM);
        if (isNotEmpty(transformerName)) {
            return urlTransformationService.transform(transformerName, source.get(fieldName).toString());
        }
    }
    return source.get(fieldName);
}
 
Example 11
Source File: BlockAdapterBase.java    From besu with Apache License 2.0 5 votes vote down vote up
public Optional<AccountAdapter> getMiner(final DataFetchingEnvironment environment) {

    final BlockchainQueries query = getBlockchainQueries(environment);
    long blockNumber = header.getNumber();
    final Long bn = environment.getArgument("block");
    if (bn != null) {
      blockNumber = bn;
    }
    return Optional.of(
        new AccountAdapter(query.getWorldState(blockNumber).get().get(header.getCoinbase())));
  }
 
Example 12
Source File: ResourceSyncUpdateMutation.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object executeAction(DataFetchingEnvironment env) {
  User user = MutationHelpers.getUser(env);

  String combinedId = env.getArgument("dataSetId");
  // the user-specified authorization token for remote server:
  String authString = env.getArgument("authorization");
  Tuple<String, String> userAndDataSet = DataSetMetaData.splitCombinedId(combinedId);
  Optional<DataSet> dataSetOpt;

  ResourceSyncImport.ResourceSyncReport resourceSyncReport;

  try {
    dataSetOpt = dataSetRepository.getDataSet(user, userAndDataSet.getLeft(), userAndDataSet.getRight());
    if (!dataSetOpt.isPresent()) {
      LOG.error("DataSet does not exist.");
      throw new RuntimeException("DataSet does not exist.");
    }
    DataSet dataSet = dataSetOpt.get();
    MutationHelpers.checkPermission(env, dataSet.getMetadata(), Permission.UPDATE_RESOURCESYNC);
    ResourceSyncImport resourceSyncImport = new ResourceSyncImport(
      resourceSyncFileLoader, dataSet, false);
    String capabilityListUri = dataSet.getMetadata().getImportInfo().get(0).getImportSource();
    resourceSyncReport = resourceSyncImport.filterAndImport(capabilityListUri, null, true,
      authString);
  } catch (IOException | CantRetrieveFileException | CantDetermineDataSetException e) {
    LOG.error("Failed to do a resource sync import. ", e);
    throw new RuntimeException(e);
  }

  return resourceSyncReport;
}
 
Example 13
Source File: ProductDeleteFetcher.java    From research-graphql with MIT License 5 votes vote down vote up
@Override
public ProductDto get(DataFetchingEnvironment environment) {
    log.info("getArguments {}", environment.getArguments());
    String productId = environment.getArgument("productId");
    ProductDto deletedProduct = productAdaptor.deleteProduct(productId);
    log.info("deleted product={}", deletedProduct);
    return deletedProduct;
}
 
Example 14
Source File: ApolloTestsServer.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
private Object getAllLinks(DataFetchingEnvironment env) {
  boolean secureOnly = env.getArgument("secureOnly");
  return testData.links.stream()
    .filter(link -> !secureOnly || link.getUrl().startsWith("https://"))
    .collect(toList());
}
 
Example 15
Source File: BookDataFetcher.java    From sfg-blog-posts with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Book get(DataFetchingEnvironment dataFetchingEnvironment) {
    String isn = dataFetchingEnvironment.getArgument("id");
    return bookRepository.findById(isn).orElse(null);
}
 
Example 16
Source File: CreateToDoDataFetcher.java    From micronaut-graphql with Apache License 2.0 4 votes vote down vote up
@Override
public ToDo get(DataFetchingEnvironment env) {
    String title = env.getArgument("title");
    ToDo toDo = new ToDo(title);
    return toDoRepository.save(toDo);
}
 
Example 17
Source File: DataSetMetadataMutation.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Object executeAction(DataFetchingEnvironment env) {
  DataSet dataSet = MutationHelpers.getDataSet(env, dataSetRepository::getDataSet);
  MutationHelpers.checkPermission(env, dataSet.getMetadata(),Permission.EDIT_DATASET_METADATA);

  try {
    Map md = env.getArgument("metadata");
    final String baseUri = dataSet.getMetadata().getBaseUri().endsWith("/") ?
      dataSet.getMetadata().getBaseUri() :
      dataSet.getMetadata().getBaseUri() + "/";
    addMutation(
      dataSet,
      new PredicateMutation()
        .entity(
          baseUri,
          this.<String>parseProp(md, "title", v -> replace("http://purl.org/dc/terms/title", value(v))),
          this.<String>parseProp(md, "description", v -> replace("http://purl.org/dc/terms/description", value(v,
            MARKDOWN))),
          this.<String>parseProp(md, "imageUrl", v -> replace("http://xmlns.com/foaf/0.1/depiction", value(v))),
          this.<Map>parseProp(md, "license", v -> this.<String>parseProp(v, "uri",
            uri -> replace("http://purl.org/dc/terms/license", subject(uri))
          )),
          this.<Map>parseProp(md, "owner", owner -> getOrCreate(
            "http://purl.org/dc/terms/rightsHolder",
            baseUri + "rightsHolder",
            this.<String>parseProp(owner, "name", v -> replace("http://schema.org/name", value(v))),
            this.<String>parseProp(owner, "email", v -> replace("http://schema.org/email", value(v)))
          )),
          this.<Map>parseProp(md, "contact", owner -> getOrCreate(
            "http://schema.org/ContactPoint",
            baseUri + "ContactPoint",
            this.<String>parseProp(owner, "name", v -> replace("http://schema.org/name", value(v))),
            this.<String>parseProp(owner, "email", v -> replace("http://schema.org/email", value(v)))
          )),
          this.<Map>parseProp(md, "provenanceInfo", owner -> getOrCreate(
            "http://purl.org/dc/terms/provenance",
            baseUri + "Provenance",
            this.<String>parseProp(owner, "title", v -> replace("http://purl.org/dc/terms/title", value(v))),
            this.<String>parseProp(owner, "body", v -> replace("http://purl.org/dc/terms/description", value(v,
              MARKDOWN)))
          ))
        )
    );

    return new DataSetWithDatabase(dataSet, env.<ContextData>getContext().getUserPermissionCheck());
  } catch (LogStorageFailedException | InterruptedException | ExecutionException e) {
    throw new RuntimeException(e);
  }
}
 
Example 18
Source File: ApolloTestsServer.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
private Object staticCounter(DataFetchingEnvironment env) {
  int count = env.getArgument("num");
  Map<String, Object> counter = new HashMap<>();
  counter.put("count", count);
  return counter;
}
 
Example 19
Source File: CreateNotificationMutation.java    From notification with Apache License 2.0 4 votes vote down vote up
@Override
public Notification get(DataFetchingEnvironment environment) {
  final String username = environment.getArgument("username");
  if (Strings.isNullOrEmpty(username)) {
    throw new GraphQLValidationError("username cannot be empty");
  }

  final Map<String, Object> input = environment.getArgument("notification");
  if (input == null || input.isEmpty()) {
    throw new GraphQLValidationError("notification cannot be empty");
  }

  final String category = String.valueOf(input.get("category")).trim();
  if (Strings.isNullOrEmpty(category) || "null".equals(category)) {
    throw new GraphQLValidationError("category cannot be empty");
  }

  final int categoryLength = category.codePointCount(0, category.length());

  if (categoryLength < Notification.CATEGORY_MIN_LENGTH
      || categoryLength > Notification.CATEGORY_MAX_LENGTH) {
    throw new GraphQLValidationError(
        String.format(
            "category must be between %d and %d characters",
            Notification.CATEGORY_MIN_LENGTH, Notification.CATEGORY_MAX_LENGTH));
  }

  final String message = String.valueOf(input.get("message")).trim();
  if (Strings.isNullOrEmpty(message) || "null".equals(message)) {
    throw new GraphQLValidationError("message cannot be empty");
  }

  final int messageLength = message.codePointCount(0, message.length());

  if (messageLength < Notification.MESSAGE_MIN_LENGTH
      || messageLength > Notification.MESSAGE_MAX_LENGTH) {
    throw new GraphQLValidationError(
        String.format(
            "message must be between %d and %d characters",
            Notification.MESSAGE_MIN_LENGTH, Notification.MESSAGE_MAX_LENGTH));
  }

  final Notification.Builder builder = Notification.builder(category, message);

  final Object properties = input.get("properties");
  if (properties != null && properties instanceof Map) {
    builder.withProperties(convertToMap(properties));
  }

  final Notification notification = builder.build();

  try {
    return store.store(username, notification);
  } catch (NotificationStoreException e) {
    LOGGER.error(String.format("Unable to create notification for %s", username), e);
    throw new GraphQLValidationError("Unable to create notification");
  }
}
 
Example 20
Source File: AccountAdapter.java    From besu with Apache License 2.0 4 votes vote down vote up
public Optional<Bytes32> getStorage(final DataFetchingEnvironment environment) {
  final Bytes32 slot = environment.getArgument("slot");
  return Optional.of(account.getStorageValue(UInt256.fromBytes(slot)).toBytes());
}