graphql.language.Type Java Examples

The following examples show how to use graphql.language.Type. 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: GraphQLIntrospectionResultToSchema.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Type createTypeIndirection(Map<String, Object> type) {
    String kind = (String) type.get("kind");
    switch (kind) {
        case "INTERFACE":
        case "OBJECT":
        case "UNION":
        case "ENUM":
        case "INPUT_OBJECT":
        case "SCALAR":
            return TypeName.newTypeName().name((String) type.get("name")).build();
        case "NON_NULL":
            return NonNullType.newNonNullType().type(createTypeIndirection((Map<String, Object>) type.get("ofType"))).build();
        case "LIST":
            return ListType.newListType().type(createTypeIndirection((Map<String, Object>) type.get("ofType"))).build();
        default:
            return assertShouldNeverHappen("Unknown kind %s", kind);
    }
}
 
Example #2
Source File: GraphQLIntrospectionResultToSchema.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private List<InputValueDefinition> createInputValueDefinitions(List<Map<String, Object>> args) {
    List<InputValueDefinition> result = new ArrayList<>();
    for (Map<String, Object> arg : args) {
        Type argType = createTypeIndirection((Map<String, Object>) arg.get("type"));
        String valueLiteral = (String) arg.get("defaultValue");
        Value defaultValue = valueLiteral != null ? AstValueHelper.valueFromAst(valueLiteral) : null;
        InputValueDefinition inputValueDefinition = InputValueDefinition.newInputValueDefinition()
                .name((String) arg.get("name"))
                .type(argType)
                .description(getDescription(arg))
                .defaultValue(defaultValue)
                .build();
        result.add(inputValueDefinition);
    }
    return result;
}
 
Example #3
Source File: GraphQLIntrospectionResultToSchema.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
UnionTypeDefinition createUnion(Map<String, Object> input) {
    assertTrue(input.get("kind").equals("UNION"), () -> "wrong input");

    final List<Map<String, Object>> possibleTypes = (List<Map<String, Object>>) input.get("possibleTypes");
    final List<Type> memberTypes = Lists.newArrayList();
    for (Map<String, Object> possibleType : possibleTypes) {
        TypeName typeName = new TypeName((String) possibleType.get("name"));
        memberTypes.add(typeName);
    }

    return UnionTypeDefinition.newUnionTypeDefinition()
            .name((String) input.get("name"))
            .description(getDescription(input))
            .memberTypes(memberTypes)
            .build();
}
 
Example #4
Source File: STModel.java    From graphql-apigen with Apache License 2.0 6 votes vote down vote up
private void addImports(Collection<String> imports, Type type) {
    if ( type instanceof ListType ) {
        imports.add("java.util.List");
        addImports(imports, ((ListType)type).getType());
    } else if ( type instanceof NonNullType ) {
        addImports(imports, ((NonNullType)type).getType());
    } else if ( type instanceof TypeName ) {
        String name = ((TypeName)type).getName();
        if ( BUILTINS.containsKey(name) ) {
            String importName = BUILTINS.get(name);
            if ( null == importName ) return;
            imports.add(importName);
        } else {
            TypeEntry refEntry = referenceTypes.get(name);
            // TODO: scalar name may be different... should read annotations for scalars.
            if ( null == refEntry ) {
                throw new RuntimeException("Unknown type '"+name+"' was not defined in the schema");
            } else {
                imports.add(refEntry.getPackageName() + "." + name);
            }
        }
    } else {
        throw new RuntimeException("Unknown Type="+type.getClass().getName());
    }
}
 
Example #5
Source File: GqlParentType.java    From manifold with Apache License 2.0 6 votes vote down vote up
private Type getType( Node def )
{
  if( def instanceof VariableDefinition )
  {
    return ((VariableDefinition)def).getType();
  }
  if( def instanceof InputValueDefinition )
  {
    return ((InputValueDefinition)def).getType();
  }
  if( def instanceof FieldDefinition )
  {
    return ((FieldDefinition)def).getType();
  }
  throw new IllegalStateException();
}
 
Example #6
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 #7
Source File: STModel.java    From graphql-apigen with Apache License 2.0 6 votes vote down vote up
public List<Interface> getInterfaces() {

        interfaces = new ArrayList<>();

        if (!isObjectType()) {
            return interfaces;
        }

        ObjectTypeDefinition objectTypeDefinition = (ObjectTypeDefinition) typeEntry.getDefinition();

        List<Type> interfaceTypes = objectTypeDefinition.getImplements();

        for (Type anInterfaceType : interfaceTypes) {
            Interface anInterface = new Interface();
            anInterface.type = toJavaTypeName(anInterfaceType);
            interfaces.add(anInterface);
        }

        return interfaces;
    }
 
Example #8
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private ListType getListType( Type type )
{
  if( type instanceof ListType )
  {
    return (ListType)type;
  }
  if( type instanceof TypeName )
  {
    return null;
  }
  return getListType( ((NonNullType)type).getType() );
}
 
Example #9
Source File: STModel.java    From graphql-apigen with Apache License 2.0 5 votes vote down vote up
private String toJavaTypeName(Type type) {
    if ( type instanceof ListType ) {
        return "List<" + toJavaTypeName(((ListType)type).getType()) + ">";
    } else if ( type instanceof NonNullType ) {
        return toJavaTypeName(((NonNullType)type).getType());
    } else if ( type instanceof TypeName ) {
        String name = ((TypeName)type).getName();
        String rename = RENAME.get(name);
        // TODO: scalar type directive to get implementation class...
        if ( null != rename ) return rename;
        return name;
    } else {
        throw new UnsupportedOperationException("Unknown Type="+type.getClass().getName());
    }
}
 
Example #10
Source File: STModel.java    From graphql-apigen with Apache License 2.0 5 votes vote down vote up
private String toGraphQLType(Type type) {
    if ( type instanceof ListType ) {
        return "new GraphQLList(" + toGraphQLType(((ListType)type).getType()) + ")";
    } else if ( type instanceof NonNullType ) {
        return toGraphQLType(((NonNullType)type).getType());
    } else if ( type instanceof TypeName ) {
        String name = ((TypeName)type).getName();
        if ( BUILTINS.containsKey(name) ) {
            return "Scalars.GraphQL" + name;
        }
        return "new GraphQLTypeReference(\""+name+"\")";
    } else {
        throw new UnsupportedOperationException("Unknown Type="+type.getClass().getName());
    }
}
 
Example #11
Source File: STModel.java    From graphql-apigen with Apache License 2.0 5 votes vote down vote up
private List<Field> getFields(UnionTypeDefinition def) {
    List<Field> fields = new ArrayList<Field>();
    for ( Type type : def.getMemberTypes() ) {
        fields.add(new Field(null, toJavaTypeName(type)));
    }
    return fields;
}
 
Example #12
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private SrcType makeSrcType( SrcLinkedClass owner, Type type, boolean typeParam )
{
  SrcType srcType;
  if( type instanceof ListType )
  {
    srcType = new SrcType( "List" );
    srcType.addTypeParam( makeSrcType( owner, ((ListType)type).getType(), true ) );
  }
  else if( type instanceof TypeName )
  {
    String typeName = getJavaClassName( owner, (TypeName)type, typeParam );
    srcType = new SrcType( typeName );
    if( !typeParam )
    {
      Class<?> javaClass = getJavaClass( (TypeName)type, false );
      srcType.setPrimitive( javaClass != null && javaClass.isPrimitive() );
    }
  }
  else if( type instanceof NonNullType )
  {
    Type theType = ((NonNullType)type).getType();
    srcType = makeSrcType( owner, theType, typeParam );
    if( !typeParam && !srcType.isPrimitive() )
    {
      srcType.addAnnotation( new SrcAnnotationExpression( NotNull.class.getSimpleName() ) );
    }
  }
  else
  {
    throw new IllegalStateException( "Unhandled type: " + type.getClass().getTypeName() );
  }
  return srcType;
}
 
Example #13
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private SrcType convertSrcType( SrcLinkedClass owner, Type type, String component )
{
  SrcType srcType = new SrcType( convertType( owner, type, component ) );
  if( type instanceof NonNullType )
  {
    srcType.addAnnotation( new SrcAnnotationExpression( NotNull.class.getSimpleName() ) );
  }
  return srcType;
}
 
Example #14
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private String convertType( SrcLinkedClass owner, Type type, String component )
{
  ListType listType = getListType( type );
  if( listType != null )
  {
    return List.class.getSimpleName() + '<' + convertType( owner, listType.getType(), component ) + '>';
  }
  return owner.getDisambiguatedNameInNest( component );
}
 
Example #15
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private Type getComponentType( Type type )
{
  if( type instanceof ListType )
  {
    return getComponentType( ((ListType)type).getType() );
  }
  if( type instanceof NonNullType )
  {
    return getComponentType( ((NonNullType)type).getType() );
  }
  return type;
}
 
Example #16
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void addInnerObjectType( ObjectTypeDefinition type, SrcLinkedClass enclosingType )
{
  String identifier = makeIdentifier( type.getName(), false );
  String fqn = getFqn() + '.' + identifier;
  SrcLinkedClass srcClass = new SrcLinkedClass( fqn, enclosingType, Interface )
    .addInterface( IJsonBindingsBacked.class.getSimpleName() )
    .addAnnotation( new SrcAnnotationExpression( Structural.class.getSimpleName() )
      .addArgument( "factoryClass", Class.class, identifier + ".ProxyFactory.class" ) )
    .modifiers( Modifier.PUBLIC );
  addUnionInterfaces( type, srcClass );
  addActualNameAnnotation( srcClass, type.getName(), false );
  addSourcePositionAnnotation( srcClass, type, srcClass );
  List<Type> interfaces = type.getImplements();
  addInterfaces( srcClass, interfaces );
  addProxyFactory( srcClass );
  addBuilder( srcClass, type );
  addCreateMethod( srcClass, type );
  addBuilderMethod( srcClass, type );
  addLoadMethod( srcClass );
  addCopier( srcClass, type );
  addCopierMethod( srcClass );
  addCopyMethod( srcClass );

  List<FieldDefinition> fieldDefinitions = type.getFieldDefinitions();
  for( FieldDefinition member: fieldDefinitions )
  {
    addMember( srcClass, member, name -> fieldDefinitions.stream().anyMatch( f -> f.getName().equals( name ) ) );
  }
  addObjectExtensions( type, srcClass );
  enclosingType.addInnerClass( srcClass );
}
 
Example #17
Source File: Generator.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private Type<?> type(Argument argument) {
    Value<?> value = argument.getValue();
    if (value instanceof VariableReference)
        return resolve(((VariableReference) value).getName());
    throw new GraphQlGeneratorException(
            "unsupported type " + value + " for argument '" + argument.getName() + "'");
}
 
Example #18
Source File: Generator.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private Type<?> resolve(String name) {
    return variableDefinitions.stream()
            .filter(var -> var.getName().equals(name))
            .findAny()
            .map(VariableDefinition::getType)
            .orElseThrow(() -> new GraphQlGeneratorException("no definition found for parameter '" + name
                    + "' in "
                    + variableDefinitions.stream().map(VariableDefinition::getName).collect(listString())));
}
 
Example #19
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 #20
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 #21
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 #22
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 #23
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void addInterfaces( SrcLinkedClass srcClass, List<Type> interfaces )
{
  for( Type iface: interfaces )
  {
    if( iface instanceof TypeName )
    {
      srcClass.addInterface( makeIdentifier( ((TypeName)iface).getName(), false ) );
    }
  }
}
 
Example #24
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 #25
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void addMember( SrcLinkedClass srcClass, NamedNode member, Type type, String name,
                        Predicate<String> duplicateChecker )
{
  SrcType srcType = makeSrcType( srcClass, type, false );
  String propName = makeIdentifier( name, true );
  if( !propName.equals( name ) && duplicateChecker.test( propName ) )
  {
    // There are two fields that differ in name only by the case of the first character "Foo" v. "foo".
    // Since the get/set methods capitalize the name, we must differentiate the method names
    // e.g., getFoo() and get_foo()
    propName = '_' + makeIdentifier( name, false );
  }
  //noinspection unused
  StringBuilder propertyType = srcType.render( new StringBuilder(), 0, false );
  //noinspection unused
  StringBuilder componentType = getComponentType( srcType ).render( new StringBuilder(), 0, false );
  SrcGetProperty getter = new SrcGetProperty( propName, srcType )
    .modifiers( Flags.DEFAULT )
    .body( "return ($propertyType)" + RuntimeMethods.class.getSimpleName() + ".coerce(getBindings().get(\"$name\"), ${componentType}.class);" );
  if( member != null )
  {
    addActualNameAnnotation( getter, name, true );
    addSourcePositionAnnotation( srcClass, member, name, getter );
  }
  srcClass.addGetProperty( getter ).modifiers( Modifier.PUBLIC );

  SrcSetProperty setter = new SrcSetProperty( propName, srcType )
    .modifiers( Flags.DEFAULT )
    .body( "getBindings().put(\"$name\", " + RuntimeMethods.class.getSimpleName() + ".coerceToBindingValue(${'$'}value));\n" );
  if( member != null )
  {
    addActualNameAnnotation( setter, name, true );
    addSourcePositionAnnotation( srcClass, member, name, setter );
  }
  srcClass.addSetProperty( setter ).modifiers( Modifier.PUBLIC );
}
 
Example #26
Source File: GqlParentType.java    From manifold with Apache License 2.0 4 votes vote down vote up
private boolean isRequiredVar( NamedNode node )
{
  Type type = getType( node );
  return type instanceof NonNullType &&
         (!(node instanceof VariableDefinition) || ((VariableDefinition)node).getDefaultValue() == null);
}
 
Example #27
Source File: STModel.java    From graphql-apigen with Apache License 2.0 4 votes vote down vote up
private void addImports(Collection<String> imports, UnionTypeDefinition def) {
    for ( Type type : def.getMemberTypes() ) {
        addImports(imports, type);
    }
}
 
Example #28
Source File: GqlParentType.java    From manifold with Apache License 2.0 4 votes vote down vote up
private void addMember( SrcLinkedClass srcClass, FieldDefinition member, Predicate<String> duplicateChecker )
{
  Type type = member.getType();
  String name = makeIdentifier( member.getName(), false );
  addMember( srcClass, member, type, name, duplicateChecker );
}
 
Example #29
Source File: GlitrFieldDefinition.java    From glitr with MIT License 4 votes vote down vote up
public GlitrFieldDefinition(String name, Type type) {
    super(name, type);
}
 
Example #30
Source File: GlitrFieldDefinition.java    From glitr with MIT License 4 votes vote down vote up
public GlitrFieldDefinition(String name, Type type, Set<GlitrMetaDefinition> metaDefinitions) {
    super(name, type);
    this.metaDefinitions = metaDefinitions;
}