graphql.language.Definition Java Examples

The following examples show how to use graphql.language.Definition. 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: STModel.java    From graphql-apigen with Apache License 2.0 6 votes vote down vote up
public synchronized List<Field> getFields() {
    if ( null == fields ) {
        Definition def = typeEntry.getDefinition();
        if ( isObjectType() ) {
            fields = getFields((ObjectTypeDefinition)def);
        } else if ( isInterfaceType() ) {
            fields = getFields((InterfaceTypeDefinition)def);
        } else if ( isInputObjectType() ) {
            fields = getFields((InputObjectTypeDefinition)def);
        } else if ( isUnionType() ) {
            fields = getFields((UnionTypeDefinition)def);
        } else if ( isEnumType() ) {
            fields = getFields((EnumTypeDefinition)def);
        } else if ( isSchemaType() ) {
            fields = getFields((SchemaDefinition)def);
        } else {
            fields = Collections.emptyList();
        }
    }
    return fields;
}
 
Example #2
Source File: GqlParentType.java    From manifold with Apache License 2.0 6 votes vote down vote up
private void addBuilderMethod( SrcLinkedClass srcClass, Definition definition )
{
  SrcMethod method = new SrcMethod( srcClass )
    .modifiers( Modifier.STATIC )
    .name( "builder" )
    .returns( new SrcType( "Builder" ) );
  addRequiredParameters( srcClass, definition, method );
  srcClass.addMethod( method );

  StringBuilder sb = new StringBuilder();
  sb.append( "return new Builder(" );
  int count = 0;
  for( SrcParameter param: method.getParameters() )
  {
    if( count++ > 0 )
    {
      sb.append( ", " );
    }
    //noinspection unused
    sb.append( makeIdentifier( param.getSimpleName(), false ) );
  }
  sb.append( ");" );
  method.body( sb.toString() );
}
 
Example #3
Source File: STModel.java    From graphql-apigen with Apache License 2.0 6 votes vote down vote up
public synchronized List<String> getImports() {
    if ( null == imports ) {
        Definition def = typeEntry.getDefinition();
        Set<String> names = new TreeSet<String>();
        if ( isObjectType() ) {
            addImports(names, (ObjectTypeDefinition)def);
        } else if ( isInterfaceType() ) {
            addImports(names, (InterfaceTypeDefinition)def);
        } else if ( isInputObjectType() ) {
            addImports(names, (InputObjectTypeDefinition)def);
        } else if ( isUnionType() ) {
            addImports(names, (UnionTypeDefinition)def);
        } else if ( isEnumType() ) {
            addImports(names, (EnumTypeDefinition)def);
        } else if ( isSchemaType() ) {
            addImports(names, (SchemaDefinition)def);
        }
        imports = new ArrayList<>(names);
    }
    return imports;
}
 
Example #4
Source File: GqlParentType.java    From manifold with Apache License 2.0 6 votes vote down vote up
private void addBuilder( SrcLinkedClass enclosingType, Definition definition )
{
  SrcConstructor ctor;
  String fqn = enclosingType.getName() + ".Builder";
  SrcLinkedClass srcClass = new SrcLinkedClass( fqn, enclosingType, Class )
    .modifiers( Modifier.STATIC )
    .addField( new SrcField( "_result", new SrcType( enclosingType.getSimpleName() ) )
      .modifiers( Modifier.PRIVATE | Modifier.FINAL ) )
    .addConstructor( ctor = new SrcConstructor()
      .modifiers( Modifier.PRIVATE ) )
    .addMethod( new SrcMethod()
      .modifiers( Modifier.PUBLIC )
      .name( "build" )
      .returns( enclosingType.getSimpleName() )
      .body( "return _result;" ) );
  enclosingType.addInnerClass( srcClass );

  addRequiredParameters( enclosingType, definition, ctor );
  ctor.body( addBuilderConstructorBody( ctor ) );

  addWithMethods( srcClass, definition );
}
 
Example #5
Source File: GqlParentType.java    From manifold with Apache License 2.0 6 votes vote down vote up
private void addCopier( SrcLinkedClass enclosingType, Definition definition )
{
  String fqn = enclosingType.getName() + ".Copier";
  SrcLinkedClass srcClass = new SrcLinkedClass( fqn, enclosingType, Class )
    .addField( new SrcField( "_result", enclosingType.getSimpleName() )
      .modifiers( Modifier.PRIVATE | Modifier.FINAL ) )
    .addConstructor( new SrcConstructor()
      .modifiers( Modifier.PRIVATE )
      .addParam( "from", enclosingType.getSimpleName() )
      .body( "_result = from.copy();" ) )
    .addMethod( new SrcMethod()
      .modifiers( Modifier.PUBLIC )
      .name( "copy" )
      .returns( enclosingType.getSimpleName() )
      .body( "return _result;" ) );
  addWithMethods( srcClass, definition );
  enclosingType.addInnerClass( srcClass );
}
 
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: TypeEntry.java    From graphql-apigen with Apache License 2.0 6 votes vote down vote up
private static List<Directive> getDirectives(Definition def) {
    if ( def instanceof ObjectTypeDefinition ) {
        return ((ObjectTypeDefinition)def).getDirectives();
    } if ( def instanceof InterfaceTypeDefinition ) {
        return ((InterfaceTypeDefinition)def).getDirectives();
    } if ( def instanceof EnumTypeDefinition ) {
        return ((EnumTypeDefinition)def).getDirectives();
    } if ( def instanceof ScalarTypeDefinition ) {
        return ((ScalarTypeDefinition)def).getDirectives();
    } if ( def instanceof UnionTypeDefinition ) {
        return ((UnionTypeDefinition)def).getDirectives();
    } if ( def instanceof InputObjectTypeDefinition ) {
        return ((InputObjectTypeDefinition)def).getDirectives();
    } if ( def instanceof SchemaDefinition ) {
        return ((SchemaDefinition)def).getDirectives();
    }
    return Collections.emptyList();
}
 
Example #8
Source File: GqlManifold.java    From manifold with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isInnerType( String topLevel, String relativeInner )
{
  GqlModel model = getModel( topLevel );
  GqlParentType type = model == null ? null : model.getType();
  if( type == null )
  {
    return false;
  }

  Definition typeDef = null;
  for( StringTokenizer tokenizer = new StringTokenizer( relativeInner, "." ); tokenizer.hasMoreTokens(); )
  {
    String innerName = tokenizer.nextToken();
    typeDef = typeDef == null ? type.getChild( innerName ) : getChildDefinition( typeDef, innerName );
    if( typeDef == null )
    {
      // special case so Builder classes can have extension methods applied
      return innerName.equals( "Builder" ) && !tokenizer.hasMoreTokens();
    }
  }
  return typeDef != null;
}
 
Example #9
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
Definition getChild( String childName )
{
  Definition def = _registry.getType( childName ).orElse( null );
  if( def == null )
  {
    def = _operations.get( childName );
  }
  return def;
}
 
Example #10
Source File: ApiGen.java    From graphql-apigen with Apache License 2.0 5 votes vote down vote up
private void add(Map<String, TypeEntry> types, URL path) throws IOException {
    String content = slurp(path);
    try {
        Document doc = parser.parseDocument(content);
        for ( Definition definition : doc.getDefinitions() ) {
            if ( definition instanceof SchemaDefinition ) {
                if ( generatedTypes == types ) {
                    schemaDefinitions.add(new TypeEntry(definition, path, defaultPackageName));
                }
                continue;
            } else if ( ! (definition instanceof TypeDefinition) ) {
                // TODO: What about @definition types?
                throw new RuntimeException(
                    "GraphQL schema documents must only contain schema type definitions, got "+
                    definition.getClass().getSimpleName() + " [" +
                    definition.getSourceLocation().getLine() + "," +
                    definition.getSourceLocation().getColumn() + "]");
            }
            TypeEntry newEntry = new TypeEntry(definition, path, defaultPackageName);
            TypeEntry oldEntry = referenceTypes.get(newEntry.getName());

            if ( null != oldEntry ) {
                // TODO: Support the extend type?
                throw new RuntimeException(
                    "Duplicate type definition for '" + newEntry.getName() + "'" +
                    " defined both in " + oldEntry.getSourceLocation() + " and " +
                    newEntry.getSourceLocation());
            }

            types.put(newEntry.getName(), newEntry);
            if ( types != referenceTypes ) {
                // All types should be added to reference types...
                referenceTypes.put(newEntry.getName(), newEntry);
            }
        }
    } catch ( Exception ex ) {
        throw new RuntimeException(ex.getMessage() + " when parsing '"+path+"'", ex);
    }
}
 
Example #11
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 #12
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 #13
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void addWithMethods( SrcLinkedClass srcClass, Definition definition )
{
  for( NamedNode node: getDefinitions( definition ) )
  {
    if( isRequiredVar( node ) )
    {
      continue;
    }

    Type type = getType( node );
    String propName = makeIdentifier( node.getName(), true );
    addWithMethod( srcClass, node, propName, makeSrcType( srcClass, type, false ) );
  }
}
 
Example #14
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void addRequiredParameters( SrcLinkedClass owner, Definition definition, AbstractSrcMethod method )
{
  for( NamedNode node: getDefinitions( definition ) )
  {
    if( isRequiredVar( node ) )
    {
      Type type = getType( node );
      SrcType srcType = makeSrcType( owner, type, false );
      method.addParam( makeIdentifier( remove$( node.getName() ), false ), srcType );
    }
  }
}
 
Example #15
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 #16
Source File: TypeEntry.java    From graphql-apigen with Apache License 2.0 4 votes vote down vote up
public TypeEntry(Definition definition, URL source, String defaultPackageName) {
    this.source = source;
    this.definition = definition;
    this.packageName = getPackageName(getDirectives(definition), defaultPackageName);
}
 
Example #17
Source File: TypeEntry.java    From graphql-apigen with Apache License 2.0 4 votes vote down vote up
public Definition getDefinition() {
    return definition;
}
 
Example #18
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;
}