graphql.language.OperationDefinition Java Examples

The following examples show how to use graphql.language.OperationDefinition. 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: MockDataFetchEnvironment.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: PublicResolverBuilder.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
private Collection<Resolver> buildPropertyAccessors(Stream<Property> properties, ResolverBuilderParams params) {
    MessageBundle messageBundle = params.getEnvironment().messageBundle;
    AnnotatedType beanType = params.getBeanType();
    Predicate<Member> mergedFilters = getFilters().stream().reduce(Predicate::and).orElse(ACCEPT_ALL);

    return properties
            .filter(prop -> isQuery(prop, params))
            .filter(prop -> mergedFilters.test(prop.getField()) && mergedFilters.test(prop.getGetter()))
            .filter(prop -> params.getInclusionStrategy().includeOperation(Arrays.asList(prop.getField(), prop.getGetter()), beanType))
            .map(prop -> {
                TypedElement element = propertyElementReducer.apply(new TypedElement(getFieldType(prop.getField(), params), prop.getField()), new TypedElement(getReturnType(prop.getGetter(), params), prop.getGetter()));
                OperationInfoGeneratorParams infoParams = new OperationInfoGeneratorParams(element, beanType, params.getQuerySourceBeanSupplier(), messageBundle, OperationDefinition.Operation.QUERY);
                return new Resolver(
                        messageBundle.interpolate(operationInfoGenerator.name(infoParams)),
                        messageBundle.interpolate(operationInfoGenerator.description(infoParams)),
                        messageBundle.interpolate(ReservedStrings.decode(operationInfoGenerator.deprecationReason(infoParams))),
                        element.isAnnotationPresent(Batched.class),
                        params.getQuerySourceBeanSupplier() == null ? new MethodInvoker(prop.getGetter(), beanType) : new FixedMethodInvoker(params.getQuerySourceBeanSupplier(), prop.getGetter(), beanType),
                        element,
                        argumentBuilder.buildResolverArguments(new ArgumentBuilderParams(prop.getGetter(), beanType, params.getInclusionStrategy(), params.getTypeTransformer(), params.getEnvironment())),
                        element.isAnnotationPresent(GraphQLComplexity.class) ? element.getAnnotation(GraphQLComplexity.class).value() : null
                );
            })
            .collect(Collectors.toSet());
}
 
Example #3
Source File: Operation.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
public Operation(String name, AnnotatedType javaType, Type contextType, List<OperationArgument> arguments,
                 List<Resolver> resolvers, OperationDefinition.Operation operationType, boolean batched) {

    if (!(resolvers.stream().allMatch(Resolver::isBatched) || resolvers.stream().noneMatch(Resolver::isBatched))) {
        throw new IllegalArgumentException("Operation \"" + name + "\" mixes regular and batched resolvers");
    }
    
    this.name = name;
    this.description = resolvers.stream().map(Resolver::getOperationDescription).filter(Utils::isNotEmpty).findFirst().orElse(null);
    this.deprecationReason = resolvers.stream().map(Resolver::getOperationDeprecationReason).filter(Objects::nonNull).findFirst().orElse(null);
    this.typedElement = new TypedElement(javaType, resolvers.stream()
            .flatMap(resolver -> resolver.getTypedElement().getElements().stream())
            .distinct().collect(Collectors.toList()));
    this.contextType = contextType;
    this.resolversByFingerprint = collectResolversByFingerprint(resolvers);
    this.arguments = arguments;
    this.operationType = operationType;
    this.batched = batched;
}
 
Example #4
Source File: PublicResolverBuilder.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
private Collection<Resolver> buildFieldAccessors(ResolverBuilderParams params) {
    MessageBundle messageBundle = params.getEnvironment().messageBundle;
    AnnotatedType beanType = params.getBeanType();

    return Arrays.stream(ClassUtils.getRawType(beanType.getType()).getFields())
            .filter(field -> isQuery(field, params))
            .filter(getFilters().stream().reduce(Predicate::and).orElse(ACCEPT_ALL))
            .filter(field -> params.getInclusionStrategy().includeOperation(Collections.singletonList(field), beanType))
            .map(field -> {
                TypedElement element = new TypedElement(getFieldType(field, params), field);
                OperationInfoGeneratorParams infoParams = new OperationInfoGeneratorParams(element, beanType, params.getQuerySourceBeanSupplier(), messageBundle, OperationDefinition.Operation.QUERY);
                return new Resolver(
                        messageBundle.interpolate(operationInfoGenerator.name(infoParams)),
                        messageBundle.interpolate(operationInfoGenerator.description(infoParams)),
                        messageBundle.interpolate(ReservedStrings.decode(operationInfoGenerator.deprecationReason(infoParams))),
                        false,
                        new FieldAccessor(field, beanType),
                        element,
                        Collections.emptyList(),
                        field.isAnnotationPresent(GraphQLComplexity.class) ? field.getAnnotation(GraphQLComplexity.class).value() : null
                );
            })
            .collect(Collectors.toSet());
}
 
Example #5
Source File: GqlParentType.java    From manifold with Apache License 2.0 6 votes vote down vote up
private void addInnerOperations( SrcLinkedClass srcClass )
{
  for( OperationDefinition operation: _operations.values() )
  {
    switch( operation.getOperation() )
    {
      case QUERY:
      case MUTATION:
        // Queries and mutations are the same thing -- web requests
        addQueryType( operation, srcClass );
        break;
      case SUBSCRIPTION:
        // todo:
        break;
    }
  }
}
 
Example #6
Source File: GqlParentType.java    From manifold with Apache License 2.0 6 votes vote down vote up
private List<? extends NamedNode> getDefinitions( Definition def )
{
  if( def instanceof OperationDefinition )
  {
    return ((OperationDefinition)def).getVariableDefinitions();
  }
  if( def instanceof InputObjectTypeDefinition )
  {
    return ((InputObjectTypeDefinition)def).getInputValueDefinitions();
  }
  if( def instanceof ObjectTypeDefinition )
  {
    return ((ObjectTypeDefinition)def).getFieldDefinitions();
  }
  throw new IllegalStateException();
}
 
Example #7
Source File: GqlParentType.java    From manifold with Apache License 2.0 6 votes vote down vote up
private TypeDefinition getRoot( OperationDefinition.Operation operation )
{
  TypeDefinition root = null;
  SchemaDefinition schemaDefinition = findSchemaDefinition();
  if( schemaDefinition != null )
  {
    Optional<OperationTypeDefinition> rootQueryType =
      schemaDefinition.getOperationTypeDefinitions().stream()
        .filter( e -> e.getName().equals( getOperationKey( operation ) ) ).findFirst();
    if( rootQueryType.isPresent() )
    {
      Type type = rootQueryType.get().getTypeName();
      root = findTypeDefinition( type );
    }
  }
  if( root == null )
  {
    // e.g., by convention a 'type' named "Query" is considered the root query type
    // if one is not specified in the 'schema'
    root = _gqlManifold.findTypeDefinition( getOperationDefaultTypeName( operation ) );
  }
  return root;
}
 
Example #8
Source File: GqlParentType.java    From manifold with Apache License 2.0 6 votes vote down vote up
private void addQueryResultType( OperationDefinition operation, TypeDefinition ctx, SrcLinkedClass enclosingType )
{
  String fqn = enclosingType.getName() + ".Result";
  SrcLinkedClass srcClass = new SrcLinkedClass( fqn, enclosingType, Interface )
    .addInterface( GqlQueryResult.class.getSimpleName() )
    .addAnnotation( new SrcAnnotationExpression( Structural.class.getSimpleName() )
      .addArgument( "factoryClass", Class.class, "Result.ProxyFactory.class" ) )
    .modifiers( Modifier.PUBLIC );

  addProxyFactory( srcClass );

  for( Selection member: operation.getSelectionSet().getSelections() )
  {
    addQuerySelection( srcClass, ctx, member );
  }

  enclosingType.addInnerClass( srcClass );
}
 
Example #9
Source File: PublicResolverBuilder.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Resolver> buildQueryResolvers(ResolverBuilderParams params) {
    Set<Property> properties = ClassUtils.getProperties(ClassUtils.getRawType(params.getBeanType().getType()));
    Collection<Resolver> propertyAccessors = buildPropertyAccessors(properties.stream(), params);
    Collection<Resolver> methodInvokers = buildMethodInvokers(params, (method, par) -> isQuery(method, par) && properties.stream().noneMatch(prop -> prop.getGetter().equals(method)), OperationDefinition.Operation.QUERY, true);
    Collection<Resolver> fieldAccessors = buildFieldAccessors(params);
    return Utils.concat(methodInvokers.stream(), propertyAccessors.stream(), fieldAccessors.stream()).collect(Collectors.toSet());
}
 
Example #10
Source File: DefaultOperationBuilder.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private Operation buildOperation(Type contextType, List<Resolver> resolvers, OperationDefinition.Operation operationType, GlobalEnvironment environment) {
    String name = resolveName(resolvers);
    AnnotatedType javaType = resolveJavaType(name, resolvers, environment.messageBundle);
    List<OperationArgument> arguments = collectArguments(name, resolvers);
    boolean batched = isBatched(resolvers);
    return new Operation(name, javaType, contextType, arguments, resolvers, operationType, batched);
}
 
Example #11
Source File: PublicResolverBuilder.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private Collection<Resolver> buildMethodInvokers(ResolverBuilderParams params, BiPredicate<Method, ResolverBuilderParams> filter, OperationDefinition.Operation operation, boolean batchable) {
    MessageBundle messageBundle = params.getEnvironment().messageBundle;
    AnnotatedType beanType = params.getBeanType();
    Supplier<Object> querySourceBean = params.getQuerySourceBeanSupplier();
    Class<?> rawType = ClassUtils.getRawType(beanType.getType());
    if (rawType.isArray() || rawType.isPrimitive()) return Collections.emptyList();

    return Arrays.stream(rawType.getMethods())
            .filter(method -> filter.test(method, params))
            .filter(method -> params.getInclusionStrategy().includeOperation(Collections.singletonList(method), beanType))
            .filter(getFilters().stream().reduce(Predicate::and).orElse(ACCEPT_ALL))
            .map(method -> {
                TypedElement element = new TypedElement(getReturnType(method, params), method);
                OperationInfoGeneratorParams infoParams = new OperationInfoGeneratorParams(element, beanType, querySourceBean, messageBundle, operation);
                return new Resolver(
                        messageBundle.interpolate(operationInfoGenerator.name(infoParams)),
                        messageBundle.interpolate(operationInfoGenerator.description(infoParams)),
                        messageBundle.interpolate(ReservedStrings.decode(operationInfoGenerator.deprecationReason(infoParams))),
                        batchable && method.isAnnotationPresent(Batched.class),
                        querySourceBean == null ? new MethodInvoker(method, beanType) : new FixedMethodInvoker(querySourceBean, method, beanType),
                        element,
                        argumentBuilder.buildResolverArguments(
                                new ArgumentBuilderParams(method, beanType, params.getInclusionStrategy(), params.getTypeTransformer(), params.getEnvironment())),
                        method.isAnnotationPresent(GraphQLComplexity.class) ? method.getAnnotation(GraphQLComplexity.class).value() : null
                );
            })
            .collect(Collectors.toList());
}
 
Example #12
Source File: ComplexityAnalyzer.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private GraphQLObjectType getRootType(GraphQLSchema schema, OperationDefinition operationDefinition) {
    if (operationDefinition.getOperation() == OperationDefinition.Operation.MUTATION) {
        return Objects.requireNonNull(schema.getMutationType());
    } else if (operationDefinition.getOperation() == OperationDefinition.Operation.QUERY) {
        return Objects.requireNonNull(schema.getQueryType());
    } else if (operationDefinition.getOperation() == OperationDefinition.Operation.SUBSCRIPTION) {
        return Objects.requireNonNull(schema.getSubscriptionType());
    } else {
        throw new IllegalStateException("Unknown operation type encountered. Incompatible graphql-java version?");
    }
}
 
Example #13
Source File: Generator.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private void generateQueryMethod(Document query) {
    List<OperationDefinition> definitions = query.getDefinitionsOfType(OperationDefinition.class);
    if (definitions.size() != 1)
        throw new GraphQlGeneratorException("expected exactly one definition but found "
                + definitions.stream().map(this::operationInfo).collect(listString()));
    OperationDefinition operation = definitions.get(0);
    List<Field> fields = operation.getSelectionSet().getSelectionsOfType(Field.class);
    if (fields.size() != 1)
        throw new GraphQlGeneratorException("expected exactly one field but got "
                + fields.stream().map(Field::getName).collect(listString()));
    Field field = fields.get(0);
    body.append(new MethodGenerator(operation, field));
}
 
Example #14
Source File: PublisherAdapter.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public GraphQLFieldDefinition transformField(GraphQLFieldDefinition field, Operation operation, OperationMapper operationMapper, BuildContext buildContext) {
    //Publisher returned from a subscription must be mapped as singular result (i.e. not a list)
    if (operation.getOperationType() == OperationDefinition.Operation.SUBSCRIPTION) {
        return field.transform(builder -> builder.type(unwrapList(field.getType())));
    }
    //In other operations, a Publisher is effectively equivalent to a list
    return field;
}
 
Example #15
Source File: GqlManifold.java    From manifold with Apache License 2.0 5 votes vote down vote up
private Definition getChildDefinition( Definition def, String name )
{
  for( Node child: def.getNamedChildren().getChildren( name ) )
  {
    if( child instanceof TypeDefinition || child instanceof OperationDefinition )
    {
      return (Definition)child;
    }
  }
  return null;
}
 
Example #16
Source File: GqlModel.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void buildRegistry( Document document )
{
  TypeDefinitionRegistry typeRegistry = new TypeDefinitionRegistry();
  List<Definition> definitions = document.getDefinitions();
  Map<String, OperationDefinition> operations = new LinkedHashMap<>();
  Map<String, FragmentDefinition> fragments = new LinkedHashMap<>();
  List<GraphQLError> errors = new ArrayList<>();
  for( Definition definition: definitions )
  {
    if( definition instanceof SchemaDefinition )
    {
      _schemaDefinition = (SchemaDefinition)definition;
    }
    else if( definition instanceof SDLDefinition )
    {
      // types, interfaces, unions, inputs, scalars, extensions
      typeRegistry.add( (SDLDefinition)definition ).ifPresent( errors::add );
      if( definition instanceof ScalarTypeDefinition )
      {
        // register scalar type
        typeRegistry.scalars().put( ((ScalarTypeDefinition)definition).getName(), (ScalarTypeDefinition)definition );
      }
    }
    else if( definition instanceof OperationDefinition )
    {
      // queries, mutations, subscriptions
      operations.put( ((OperationDefinition)definition).getName(), (OperationDefinition)definition );
    }
    else if( definition instanceof FragmentDefinition )
    {
      // fragments
      fragments.put( ((FragmentDefinition)definition).getName(), (FragmentDefinition)definition );
    }
  }
  _issues = new GqlIssueContainer( errors, getFile() );
  _typeRegistry = typeRegistry;
  _operations = operations;
  _fragments = fragments;
}
 
Example #17
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
private String getStartSymbol( Node node )
{
  String start = "";
  if( node instanceof TypeDefinition )
  {
    if( node instanceof ObjectTypeDefinition )
    {
      start = "type";
    }
    else if( node instanceof EnumTypeDefinition )
    {
      start = "enum";
    }
    else if( node instanceof InputObjectTypeDefinition )
    {
      start = "input";
    }
    else if( node instanceof InterfaceTypeDefinition )
    {
      start = "interface";
    }
    else if( node instanceof ScalarTypeDefinition )
    {
      start = "scalar";
    }
    else if( node instanceof UnionTypeDefinition )
    {
      start = "union";
    }
  }
  else if( node instanceof OperationDefinition )
  {
    start = ((OperationDefinition)node).getOperation().name().toLowerCase();
  }
  return start;
}
 
Example #18
Source File: OperationInfoGeneratorParams.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
OperationInfoGeneratorParams(TypedElement element, AnnotatedType declaringType, Supplier<Object> instanceSupplier,
                             MessageBundle messageBundle, OperationDefinition.Operation operationType) {
    this.element = Objects.requireNonNull(element);
    this.declaringType = Objects.requireNonNull(declaringType);
    this.instanceSupplier = instanceSupplier;
    this.messageBundle = messageBundle != null ? messageBundle : EmptyMessageBundle.INSTANCE;
    this.operationType = operationType;
}
 
Example #19
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void addRequestMethods( SrcLinkedClass srcClass, OperationDefinition operation )
{
  String query = ManEscapeUtil.escapeForJavaStringLiteral( AstPrinter.printAstCompact( operation ) );
  String fragments = getFragments( srcClass );
  //noinspection UnusedAssignment
  query += " " + fragments;
  srcClass.addMethod( new SrcMethod()
    .addAnnotation( new SrcAnnotationExpression( DisableStringLiteralTemplates.class.getSimpleName() ) )
    .modifiers( Flags.DEFAULT )
    .name( "request" )
    .addParam( "url", String.class )
    .returns( new SrcType( "Executor<Result>" ) )
    .body( "return new Executor<Result>(url, \"${operation.getOperation().name().toLowerCase()}\", \"$query\", getBindings(), Result.class);"
    ) );
  srcClass.addMethod( new SrcMethod()
    .addAnnotation( new SrcAnnotationExpression( DisableStringLiteralTemplates.class.getSimpleName() ) )
    .modifiers( Flags.DEFAULT )
    .name( "request" )
    .addParam( "endpoint", Endpoint.class )
    .returns( new SrcType( "Executor<Result>" ) )
    .body( "return new Executor<Result>(endpoint, \"${operation.getOperation().name().toLowerCase()}\", \"$query\", getBindings(), Result.class);"
    ) );
  srcClass.addMethod( new SrcMethod()
    .addAnnotation( new SrcAnnotationExpression( DisableStringLiteralTemplates.class.getSimpleName() ) )
    .modifiers( Flags.DEFAULT )
    .name( "request" )
    .addParam( "requester", new SrcType( "Supplier<Requester<Bindings>>" ) )
    .returns( new SrcType( "Executor<Result>" ) )
    .body( "return new Executor<Result>(requester, \"${operation.getOperation().name().toLowerCase()}\", \"$query\", getBindings(), Result.class);"
    ) );
}
 
Example #20
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void addValueMethodForOperation( OperationDefinition operation, SrcLinkedClass srcClass )
{
  String identifier = makeIdentifier( operation.getName(), false );

  SrcMethod method = new SrcMethod( srcClass )
    .modifiers( Flags.PUBLIC )
    .name( "builder" )
    .returns( new SrcType( identifier + ".Builder" ) );
  addRequiredParameters( srcClass, operation, method );
  StringBuilder sb = new StringBuilder();
  sb.append( "return $identifier.builder(" );
  int count = 0;
  for( SrcParameter param: method.getParameters() )
  {
    if( count++ > 0 )
    {
      sb.append( ", " );
    }
    //noinspection unused
    sb.append( param.getSimpleName() );
  }
  sb.append( ");" );
  method.body( sb.toString() );
  srcClass.addMethod( method );


  SrcMethod valueMethod = new SrcMethod( srcClass )
    .modifiers( Modifier.PUBLIC | Modifier.STATIC )
    .name( "fragmentValue" )
    .returns( srcClass.getSimpleName() )
    .body( "return new ${srcClass.getSimpleName()}();" );
  srcClass.addMethod( valueMethod );
}
 
Example #21
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void addFragmentValueMethod( SrcLinkedClass srcClass )
{
  if( !(_file instanceof IFileFragment) )
  {
    return;
  }

  switch( ((IFileFragment)_file).getHostKind() )
  {
    case DOUBLE_QUOTE_LITERAL:
    case TEXT_BLOCK_LITERAL:
      break;

    default:
      return;
  }

  for( OperationDefinition operation: _operations.values() )
  {
    switch( operation.getOperation() )
    {
      case QUERY:
      case MUTATION:
        // Queries and mutations are the same thing -- web requests
        addValueMethodForOperation( operation, srcClass );
        break;
      case SUBSCRIPTION:
        // todo:
        break;
    }
  }
}
 
Example #22
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
GqlParentType( String fqn, SchemaDefinition schemaDefinition, TypeDefinitionRegistry registry,
               Map<String, OperationDefinition> operations, Map<String, FragmentDefinition> fragments,
               IFile file, GqlManifold gqlManifold )
{
  _fqn = fqn;
  _schemaDefinition = schemaDefinition;
  _registry = registry;
  _operations = operations;
  _fragments = fragments;
  _file = file;
  _gqlManifold = gqlManifold;
  _typeToUnions = new HashMap<>();
}
 
Example #23
Source File: ExecutionForestFactory.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
private SelectionSet selectionSet(final Document queryDocument) {

        final Definition definition = queryDocument.getDefinitions().get(0);

        if(definition.getClass().isAssignableFrom(FragmentDefinition.class)) {

            return getFragmentSelectionSet(queryDocument);

        } else if(definition.getClass().isAssignableFrom(OperationDefinition.class)) {
            final OperationDefinition operationDefinition = (OperationDefinition)definition;
            return operationDefinition.getSelectionSet();
        }
        throw new IllegalArgumentException(queryDocument.getClass().getName() + " is not supported");
    }
 
Example #24
Source File: GraphQLAPIHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method used to extract operation List
 * @param messageContext messageContext
 * @param operation operation
 * @return operationList
 */
private String getOperationList(MessageContext messageContext,OperationDefinition operation) {
    String operationList = "";
    GraphQLSchemaDefinition graphql = new GraphQLSchemaDefinition();
    ArrayList<String> operationArray = new ArrayList<>();

    List<URITemplate> list = graphql.extractGraphQLOperationList(schemaDefinition,
            operation.getOperation().toString());
    ArrayList<String> supportedFields = getSupportedFields(list);

    getNestedLevelOperations(operation.getSelectionSet().getSelections(), supportedFields, operationArray);
    operationList = String.join(",", operationArray);
    return operationList;
}
 
Example #25
Source File: OperationInfoGeneratorParams.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
public OperationDefinition.Operation getOperationType() {
    return operationType;
}
 
Example #26
Source File: OperationInfoGeneratorParams.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
public Builder withOperationType(OperationDefinition.Operation operationType) {
    this.operationType = operationType;
    return this;
}
 
Example #27
Source File: GraphQLAPIHandler.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public boolean handleRequest(MessageContext messageContext) {
    try {
        String payload;
        Parser parser = new Parser();

        org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).
                getAxis2MessageContext();
        String requestPath = messageContext.getProperty(REST_SUB_REQUEST_PATH).toString();
        if (requestPath != null && !requestPath.isEmpty()) {
            String[] queryParams = ((Axis2MessageContext) messageContext).getProperties().
                    get(REST_SUB_REQUEST_PATH).toString().split(QUERY_PATH_STRING);
            if (queryParams.length > 1) {
                payload = URLDecoder.decode(queryParams[1], UNICODE_TRANSFORMATION_FORMAT);
            } else {
                RelayUtils.buildMessage(axis2MC);
                OMElement body = axis2MC.getEnvelope().getBody().getFirstElement();
                if (body != null && body.getFirstElement() != null) {
                    payload = body.getFirstElement().getText();
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Invalid query parameter " + queryParams[0]);
                    }
                    handleFailure(messageContext, "Invalid query parameter");
                    return false;
                }
            }
            messageContext.setProperty(APIConstants.GRAPHQL_PAYLOAD, payload);
        } else {
            handleFailure(messageContext, "Request path cannot be empty");
            return false;
        }

        // Validate payload with graphQLSchema
        Document document = parser.parseDocument(payload);

        if (validatePayloadWithSchema(messageContext, document)) {
            supportForBasicAndAuthentication(messageContext);

            // Extract the operation type and operations from the payload
            for (Definition definition : document.getDefinitions()) {
                if (definition instanceof OperationDefinition) {
                    OperationDefinition operation = (OperationDefinition) definition;
                    if (operation.getOperation() != null) {
                        String httpVerb = ((Axis2MessageContext) messageContext).getAxis2MessageContext().
                                getProperty(HTTP_METHOD).toString();
                        messageContext.setProperty(HTTP_VERB, httpVerb);
                        ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty(HTTP_METHOD,
                                operation.getOperation().toString());
                        String operationList = getOperationList(messageContext, operation);
                        messageContext.setProperty(APIConstants.API_ELECTED_RESOURCE, operationList);
                        if (log.isDebugEnabled()) {
                            log.debug("Operation list has been successfully added to elected property");
                        }
                        return true;
                    }
                } else {
                    handleFailure(messageContext, "Operation definition cannot be empty");
                    return false;
                }
            }
        } else {
            return false;
        }
    } catch (IOException | XMLStreamException | InvalidSyntaxException e) {
        log.error(e.getMessage());
        handleFailure(messageContext, e.getMessage());
    }
    return false;
}
 
Example #28
Source File: PublicResolverBuilder.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<Resolver> buildSubscriptionResolvers(ResolverBuilderParams params) {
    return buildMethodInvokers(params, this::isSubscription, OperationDefinition.Operation.SUBSCRIPTION, false);
}
 
Example #29
Source File: PublicResolverBuilder.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<Resolver> buildMutationResolvers(ResolverBuilderParams params) {
    return buildMethodInvokers(params, this::isMutation, OperationDefinition.Operation.MUTATION, false);
}
 
Example #30
Source File: RelayDataFetchingEnvironmentDecorator.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public OperationDefinition getOperationDefinition() {
    return delegate.getOperationDefinition();
}