graphql.language.TypeDefinition Java Examples

The following examples show how to use graphql.language.TypeDefinition. 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: GraphQLSchemaDefinition.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Extract GraphQL Types and Fields from given schema
 *
 * @param schema GraphQL Schema
 * @return list of all types and fields
 */
public List<GraphqlSchemaType> extractGraphQLTypeList(String schema) {
    List<GraphqlSchemaType> typeList = new ArrayList<>();
    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry typeRegistry = schemaParser.parse(schema);
    Map<java.lang.String, TypeDefinition> list = typeRegistry.types();
    for (Map.Entry<String, TypeDefinition> entry : list.entrySet()) {
        if (entry.getValue() instanceof ObjectTypeDefinition) {
            GraphqlSchemaType graphqlSchemaType = new GraphqlSchemaType();
            List<String> fieldList = new ArrayList<>();
            graphqlSchemaType.setType(entry.getValue().getName());
            for (FieldDefinition fieldDef : ((ObjectTypeDefinition) entry.getValue()).getFieldDefinitions()) {
                fieldList.add(fieldDef.getName());
            }
            graphqlSchemaType.setFieldList(fieldList);
            typeList.add(graphqlSchemaType);
        }
    }
    return typeList;
}
 
Example #2
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 #3
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 #4
Source File: GraphQLSchemaDefinition.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Extract GraphQL Operations from given schema
 * @param schema graphQL Schema
 * @return the arrayList of APIOperationsDTOextractGraphQLOperationList
 *
 */
public List<URITemplate> extractGraphQLOperationList(String schema, String type) {
    List<URITemplate> operationArray = new ArrayList<>();
    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry typeRegistry = schemaParser.parse(schema);
    Map<java.lang.String, TypeDefinition> operationList = typeRegistry.types();
    for (Map.Entry<String, TypeDefinition> entry : operationList.entrySet()) {
        if (entry.getValue().getName().equals(APIConstants.GRAPHQL_QUERY) ||
                entry.getValue().getName().equals(APIConstants.GRAPHQL_MUTATION)
                || entry.getValue().getName().equals(APIConstants.GRAPHQL_SUBSCRIPTION)) {
            if (type == null) {
                addOperations(entry, operationArray);
            } else if (type.equals(entry.getValue().getName().toUpperCase())) {
                addOperations(entry, operationArray);
            }
        }
    }
    return operationArray;
}
 
Example #5
Source File: GraphQLIntrospectionResultToSchema.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
private TypeDefinition createTypeDefinition(Map<String, Object> type) {
    String kind = (String) type.get("kind");
    String name = (String) type.get("name");
    if (name.startsWith("__")) return null;
    switch (kind) {
        case "INTERFACE":
            return createInterface(type);
        case "OBJECT":
            return createObject(type);
        case "UNION":
            return createUnion(type);
        case "ENUM":
            return createEnum(type);
        case "INPUT_OBJECT":
            return createInputObject(type);
        case "SCALAR":
            return createScalar(type);
        default:
            return assertShouldNeverHappen("unexpected kind %s", kind);
    }
}
 
Example #6
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 5 votes vote down vote up
/**
 * This will print out a runtime graphql schema element using its contained AST type definition.  This
 * must be guarded by a called to {@link #shouldPrintAsAst(TypeDefinition)}
 *
 * @param out        the output writer
 * @param definition the AST type definition
 * @param extensions a list of type definition extensions
 */
private void printAsAst(PrintWriter out, TypeDefinition definition, List<? extends
        TypeDefinition> extensions) {
    out.printf("%s\n", AstPrinter.printAst(definition));
    if (extensions != null) {
        for (TypeDefinition extension : extensions) {
            out.printf("\n%s\n", AstPrinter.printAst(extension));
        }
    }
    out.println();
}
 
Example #7
Source File: GraphQLSchemaDefinition.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param entry Entry
 * @param operationArray operationArray
 */
private void addOperations(Map.Entry<String, TypeDefinition> entry, List<URITemplate> operationArray) {
    for (FieldDefinition fieldDef : ((ObjectTypeDefinition) entry.getValue()).getFieldDefinitions()) {
        URITemplate operation = new URITemplate();
        operation.setHTTPVerb(entry.getKey());
        operation.setUriTemplate(fieldDef.getName());
        operationArray.add(operation);
    }
}
 
Example #8
Source File: GraphQLIntrospectionResultToSchema.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
private TypeDefinition createScalar(Map<String, Object> input) {
    String name = (String) input.get("name");
    if (ScalarInfo.isGraphqlSpecifiedScalar(name)) {
        return null;
    }
    return ScalarTypeDefinition.newScalarTypeDefinition().name(name).description(getDescription(input)).build();
}
 
Example #9
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 #10
Source File: GqlManifold.java    From manifold with Apache License 2.0 5 votes vote down vote up
TypeDefinition findTypeDefinition( String simpleName )
{
  return getAllTypeNames().stream()
    .map( fqn -> {
      GqlModel model = getModel( fqn );
      return model == null ? null : model.getTypeDefinition( simpleName );
    } )
    .filter( Objects::nonNull )
    .findFirst().orElse( null );
}
 
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: 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 #13
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private String findLub( UnionTypeDefinition typeDef )
{
  Set<Set<InterfaceTypeDefinition>> ifaces = new HashSet<>();
  for( Type t: typeDef.getMemberTypes() )
  {
    TypeDefinition td = findTypeDefinition( t );
    if( td instanceof ObjectTypeDefinition )
    {
      ifaces.add( ((ObjectTypeDefinition)td).getImplements().stream()
        .map( type -> (InterfaceTypeDefinition)findTypeDefinition( type ) )
        .collect( Collectors.toSet() ) );
    }
    else if( td instanceof InterfaceTypeDefinition )
    {
      ifaces.add( Collections.singleton( (InterfaceTypeDefinition)td ) );
    }
  }
  //noinspection OptionalGetWithoutIsPresent
  Set<InterfaceTypeDefinition> intersection =
    ifaces.stream().reduce( ( p1, p2 ) -> {
      p1.retainAll( p2 );
      return p1;
    } ).get();
  if( intersection.isEmpty() )
  {
    // no common interface
    return null;
  }
  else
  {
    // can only use one
    return intersection.iterator().next().getName();
  }
}
 
Example #14
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
/**
 * Searches globally for a type i.e., across all .graphql files.
 */
private TypeDefinition findTypeDefinition( Type type )
{
  TypeName componentType = (TypeName)getComponentType( type );
  TypeDefinition typeDefinition = _registry.getType( componentType ).orElse( null );
  if( typeDefinition != null )
  {
    return typeDefinition;
  }

  return _gqlManifold.findTypeDefinition( componentType.getName() );
}
 
Example #15
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void addIntersectionMethods( SrcLinkedClass srcClass, UnionTypeDefinition union )
{
  Set<Pair<String, String>> fieldDefs = new HashSet<>();
  Map<String, FieldDefinition> nameToFieldDef = new HashMap<>();
  for( Type memberType: union.getMemberTypes() )
  {
    TypeDefinition typeDef = findTypeDefinition( memberType );
    if( typeDef instanceof ObjectTypeDefinition )
    {
      if( fieldDefs.isEmpty() )
      {
        fieldDefs.addAll( ((ObjectTypeDefinition)typeDef).getFieldDefinitions()
          .stream().map( e -> {
            nameToFieldDef.put( e.getName(), e );
            return new Pair<>( e.getName(), e.getType().toString() );
          } ).collect( Collectors.toSet() ) );
      }
      else
      {
        fieldDefs.retainAll( ((ObjectTypeDefinition)typeDef).getFieldDefinitions()
          .stream().map( e -> new Pair<>( e.getName(), e.getType().toString() ) ).collect( Collectors.toSet() ) );
      }
    }
  }
  fieldDefs.forEach(
    fieldDef -> addMember( srcClass, null, nameToFieldDef.get( fieldDef.getFirst() ).getType(), fieldDef.getFirst(),
      name -> fieldDefs.stream().anyMatch( f -> f.getFirst().equals( name ) ) ) );
}
 
Example #16
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void addUnionInterfaces( TypeDefinition type, SrcLinkedClass srcClass )
{
  Set<UnionTypeDefinition> unions = _typeToUnions.get( type );
  if( unions != null )
  {
    unions.forEach( union -> srcClass.addInterface( makeIdentifier( union.getName(), false ) ) );
  }
}
 
Example #17
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void addInnerTypes( SrcLinkedClass srcClass )
{
  mapUnionMemberToUnions();

  for( TypeDefinition type: _registry.types().values() )
  {
    if( type instanceof ObjectTypeDefinition )
    {
      addInnerObjectType( (ObjectTypeDefinition)type, srcClass );
    }
    else if( type instanceof InterfaceTypeDefinition )
    {
      addInnerInterfaceType( (InterfaceTypeDefinition)type, srcClass );
    }
    else if( type instanceof EnumTypeDefinition )
    {
      addInnerEnumType( (EnumTypeDefinition)type, srcClass );
    }
    else if( type instanceof InputObjectTypeDefinition )
    {
      addInnerInputType( (InputObjectTypeDefinition)type, srcClass );
    }
    else if( type instanceof UnionTypeDefinition )
    {
      addInnerUnionType( (UnionTypeDefinition)type, srcClass );
    }
  }
}
 
Example #18
Source File: GqlModel.java    From manifold with Apache License 2.0 4 votes vote down vote up
TypeDefinition getTypeDefinition( String simpleName )
{
  return _typeRegistry.getType( simpleName ).orElse( null );
}
 
Example #19
Source File: TypeEntry.java    From graphql-apigen with Apache License 2.0 4 votes vote down vote up
public String getName() {
    if ( definition instanceof TypeDefinition ) {
        return ((TypeDefinition)definition).getName();
    }
    return "";
}
 
Example #20
Source File: GraphQLIntrospectionResultToSchema.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
/**
 * Returns a IDL Document that represents the schema as defined by the introspection result map
 *
 * @param introspectionResult the result of an introspection query on a schema
 *
 * @return a IDL Document of the schema
 */
@SuppressWarnings("unchecked")
public Document createSchemaDefinition(Map<String, Object> introspectionResult) {
    assertTrue(introspectionResult.get("__schema") != null, () -> "__schema expected");
    Map<String, Object> schema = (Map<String, Object>) introspectionResult.get("__schema");


    Map<String, Object> queryType = (Map<String, Object>) schema.get("queryType");
    assertNotNull(queryType, () -> "queryType expected");
    TypeName query = TypeName.newTypeName().name((String) queryType.get("name")).build();
    boolean nonDefaultQueryName = !"Query".equals(query.getName());

    SchemaDefinition.Builder schemaDefinition = SchemaDefinition.newSchemaDefinition();
    schemaDefinition.operationTypeDefinition(OperationTypeDefinition.newOperationTypeDefinition().name("query").typeName(query).build());

    Map<String, Object> mutationType = (Map<String, Object>) schema.get("mutationType");
    boolean nonDefaultMutationName = false;
    if (mutationType != null) {
        TypeName mutation = TypeName.newTypeName().name((String) mutationType.get("name")).build();
        nonDefaultMutationName = !"Mutation".equals(mutation.getName());
        schemaDefinition.operationTypeDefinition(OperationTypeDefinition.newOperationTypeDefinition().name("mutation").typeName(mutation).build());
    }

    Map<String, Object> subscriptionType = (Map<String, Object>) schema.get("subscriptionType");
    boolean nonDefaultSubscriptionName = false;
    if (subscriptionType != null) {
        TypeName subscription = TypeName.newTypeName().name(((String) subscriptionType.get("name"))).build();
        nonDefaultSubscriptionName = !"Subscription".equals(subscription.getName());
        schemaDefinition.operationTypeDefinition(OperationTypeDefinition.newOperationTypeDefinition().name("subscription").typeName(subscription).build());
    }

    Document.Builder document = Document.newDocument();
    if (nonDefaultQueryName || nonDefaultMutationName || nonDefaultSubscriptionName) {
        document.definition(schemaDefinition.build());
    }

    List<Map<String, Object>> types = (List<Map<String, Object>>) schema.get("types");
    for (Map<String, Object> type : types) {
        TypeDefinition typeDefinition = createTypeDefinition(type);
        if (typeDefinition == null) continue;
        document.definition(typeDefinition);
    }

    return document.build();
}
 
Example #21
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 2 votes vote down vote up
/**
 * This will return true if the options say to use the AST and we have an AST element
 *
 * @param definition the AST type definition
 * @return true if we should print using AST nodes
 */
private boolean shouldPrintAsAst(TypeDefinition definition) {
    return options.isUseAstDefinitions() && definition != null;
}