Class HostAccess.Builder

java.lang.Object
org.graalvm.polyglot.HostAccess.Builder
Enclosing class:
HostAccess

public final class HostAccess.Builder extends Object
Builder to create a custom host access policy.
Since:
19.0
  • Method Details

    • allowAccessAnnotatedBy

      public HostAccess.Builder allowAccessAnnotatedBy(Class<? extends Annotation> annotation)
      Allows access to public constructors, methods or fields of public classes that were annotated by the given annotation class.
      Since:
      19.0
    • allowPublicAccess

      public HostAccess.Builder allowPublicAccess(boolean allow)
      Allows unrestricted access to all public constructors, methods or fields of public classes. Note that this policy allows unrestricted access to reflection. It is highly discouraged from using this option in environments where the guest application is not fully trusted.
      Since:
      19.0
    • allowAccess

      public HostAccess.Builder allowAccess(Executable element)
      Allows access to a given constructor or method. Note that the method or constructor must be public in order to have any effect.
      Since:
      19.0
    • allowAccess

      public HostAccess.Builder allowAccess(Field element)
      Allows access to a given field. Note that the field must be public in order to have any effect.
      Since:
      19.0
    • denyAccess

      public HostAccess.Builder denyAccess(Class<?> clazz)
      Prevents access to members of given class and its subclasses.
      Parameters:
      clazz - the class to deny access to
      Returns:
      this builder
      Since:
      19.0
    • denyAccess

      public HostAccess.Builder denyAccess(Class<?> clazz, boolean includeSubclasses)
      Prevents access to members of given class.
      Parameters:
      clazz - the class to deny access to
      includeSubclasses - should subclasses be excuded as well?
      Returns:
      this builder
      Since:
      19.0
    • allowAllImplementations

      public HostAccess.Builder allowAllImplementations(boolean allow)
      Allow guest languages to implement any Java interface.

      Note that implementations implicitly export all their methods, i.e., allowing implementations of a type implies allowing access its methods via its implementations, regardless of whether the methods have been explicitly exported.

      Since:
      19.0
      See Also:
    • allowAllClassImplementations

      public HostAccess.Builder allowAllClassImplementations(boolean allow)
      Allow guest languages to implement (extend) any Java class. Note that the default host type mappings and Value.as(Class) only implement abstract classes.

      Note that implementations implicitly export all their methods, i.e., allowing implementations of a type implies allowing access its methods via its implementations, regardless of whether the methods have been explicitly exported.

      Since:
      20.3.0
      See Also:
    • allowImplementationsAnnotatedBy

      public HostAccess.Builder allowImplementationsAnnotatedBy(Class<? extends Annotation> annotation)
      Allow implementations of types annotated with the given annotation. For the explicit host access present the HostAccess.Implementable annotation is configured for this purpose. Applies to interfaces and classes.

      Note that implementations implicitly export all their methods, i.e., allowing implementations of a type implies allowing access its methods via its implementations, regardless of whether the methods have been explicitly exported.

      Since:
      19.0
      See Also:
    • allowImplementations

      public HostAccess.Builder allowImplementations(Class<?> type)
      Allow implementations of this type by the guest language.

      Note that implementations implicitly export all their methods, i.e., allowing implementations of a type implies allowing access its methods via its implementations, regardless of whether the methods have been explicitly exported.

      Parameters:
      type - an interface that may be implemented or a class that may be extended.
      Since:
      19.0
      See Also:
    • allowArrayAccess

      public HostAccess.Builder allowArrayAccess(boolean arrayAccess)
      Allows the guest application to access arrays as values with array elements. By default no array access is allowed.
      Since:
      19.0
      See Also:
    • allowListAccess

      public HostAccess.Builder allowListAccess(boolean listAccess)
      Allows the guest application to access lists as values with array elements and iterators. By default no array access is allowed. Allowing list access implies also allowing of iterables and iterators.
      Since:
      19.0
      See Also:
    • allowIterableAccess

      public HostAccess.Builder allowIterableAccess(boolean iterableAccess)
      Allows the guest application to access iterables as values with iterators. By default no iterable access is allowed. Allowing iterable access implies also allowing of iterators.
      Since:
      21.1
      See Also:
    • allowIteratorAccess

      public HostAccess.Builder allowIteratorAccess(boolean iteratorAccess)
      Allows the guest application to access iterators as iterator values. By default no iterator access is allowed.
      Since:
      21.1
      See Also:
    • allowMapAccess

      public HostAccess.Builder allowMapAccess(boolean mapAccess)
      Allows the guest application to access map as hash values. By default no map access is allowed. Allowing map access implies also allowing of iterators.
      Since:
      21.1
      See Also:
    • allowBigIntegerNumberAccess

      public HostAccess.Builder allowBigIntegerNumberAccess(boolean bigIntegerNumberAccess)
      Allows the guest application to access BigInteger as a number. By default BigInteger number access is allowed.
      Since:
      23.0
      See Also:
    • allowBufferAccess

      public HostAccess.Builder allowBufferAccess(boolean bufferAccess)
      Allows the guest application to access ByteBuffers as values with buffer elements. By default no buffer access is allowed.
      Since:
      21.1
      See Also:
    • allowAccessInheritance

      public HostAccess.Builder allowAccessInheritance(boolean inheritAccess)
      Allows the guest application to inherit access to allowed methods, i.e. implementations of allowed abstract and interface methods and overrides of allowed concrete methods. If access inheritance is disabled, all method implementations need to be explicitly allowed (either by an annotation or using reflection) to be available. Consequently, attempting to allow abstract methods has no effect in this access mode. Rationale: Requiring explicit vetting of all method implementations prevents unintentional exporting of newly added or overridden methods. When a user annotates an abstract (or concrete) method as exported, they might still know what that means when they write the code and know of all its implementations; but they might forget it later and other contributors to the codebase might not be aware of what is exported through an interface or superclass. So when someone introduces a new implementation or overrides the method in a subclass, perhaps a few levels down, they could be accidentally exporting it to the guest application.
      Since:
      22.2
      See Also:
    • allowMutableTargetMappings

      public HostAccess.Builder allowMutableTargetMappings(HostAccess.MutableTargetMapping... mapping)
      Allows host object mappings of mutable target types, such as List, Map, Iterator and Iterable based on the HostAccess.MutableTargetMapping. Mapping guest objects to well-known host object types such as Map is convenient on one hand. On the other hand it can lead to bugs as the guest code is free to provide an arbitrary backing implementation of such objects, which may not behave as expected of a Map.
      Since:
      23.0
    • targetTypeMapping

      public <S, T> HostAccess.Builder targetTypeMapping(Class<S> sourceType, Class<T> targetType, Predicate<S> accepts, Function<S,T> converter)
      Adds a custom source to target type mapping for Java host calls, host field assignments and explicit value conversions. Method is equivalent to calling the targetTypeMapping method with precedence HostAccess.TargetMappingPrecedence.HIGH.
      Since:
      19.0
    • targetTypeMapping

      public <S, T> HostAccess.Builder targetTypeMapping(Class<S> sourceType, Class<T> targetType, Predicate<S> accepts, Function<S,T> converter, HostAccess.TargetMappingPrecedence precedence)
      Adds a custom source to target type mapping for Java host calls, host field assignments and explicit value conversions. The source type specifies the static source type for the conversion. The target type specifies the exact and static target type of the mapping. Sub or base target types won't trigger the mapping. Custom target type mappings always have precedence over default mappings specified in Value.as(Class), therefore allow to customize their behavior. The provided converter takes a value of the source type and converts it to the target type. If the mapping is only conditionally applicable then an accepts predicate may be specified. If the mapping is applicable for all source values with the specified source type then a null accepts predicate should be specified. The converter may throw a ClassCastException if the mapping is not applicable. It is recommended to return false in the accepts predicate if the mapping is not applicable instead of throwing an exception. Implementing the accepts predicate instead of throwing an exception also allows the implementation to perform better overload selection when a method with multiple overloads is invoked.

      All type mappings are applied recursively to generic types. A type mapping with the target type String.class will also be applied to the elements of a List mapping. This works for lists, maps, arrays and varargs parameters.

      The source type uses the semantics of Value.as(Class) to convert to the source value. Custom type mappings are not applied there. If the source type is not applicable to a value then the mapping will not be applied. For conversions that may accept any value the Value should be used as source type.

      Multiple mappings may be added for a source or target class. Multiple mappings are applied in the order they were added, grouped by the priority where the highest priority group is applied first. See Value.as(Class) for a detailed ordered list of the conversion order used. The first mapping that accepts the source value will be used. If the default priority is used then all custom target type mappings use the same precedence when an overloaded method is selected. This means that if two methods with a custom target type mapping are applicable for a set of arguments, an IllegalArgumentException is thrown at runtime. Using a non-default priority for the mapping allows to configure whether the method will be prioritized or deprioritized depending on the precedence.

      For example take a configured target mapping from String to int and two overloaded methods that takes an int or a String parameter. If this method is invoked with a String value then there are three possible outcomes depending on the precedence that was used for the custom mapping:

      Primitive boxed target types will be applied to the primitive and boxed values. It is therefore enough to specify a target mapping to Integer to also map to the target type int.class. Primitive target types can not be used as target types. They throw an IllegalArgumentException if used.

      If the converter function or the accepts predicate calls Value.as(Class) recursively then custom target mappings are applied. Special care must be taken in order to not trigger stack overflow errors. It is recommended to use a restricted source type instead of Value.as(Class) where possible. It is strongly discouraged that accept predicates or converter cause any side-effects or escape values for permanent storage.

      Usage example:

       public static class MyClass {
      
           @HostAccess.Export
           public void json(JsonObject c) {
           }
      
           @HostAccess.Export
           public String intToString(String c) {
               return c;
           }
       }
      
       public static class JsonObject {
           JsonObject(Value v) {
           }
       }
      
       public static void main(String[] args) {
           HostAccess.Builder builder = HostAccess.newBuilder();
           builder.allowAccessAnnotatedBy(HostAccess.Export.class);
           builder.targetTypeMapping(Value.class, JsonObject.class,
                           (v) -> v.hasMembers() || v.hasArrayElements(),
                           (v) -> new JsonObject(v)).build();
      
           builder.targetTypeMapping(Integer.class, String.class, null,
                           (v) -> v.toString());
      
           HostAccess access = builder.build();
           try (Context c = Context.newBuilder().allowHostAccess(access).build()) {
               c.getBindings("js").putMember("javaObject", new MyClass());
               c.eval("js", "javaObject.json({})"); // works!
               c.eval("js", "javaObject.json([])"); // works!
               try {
                   c.eval("js", "javaObject.json(42)"); // fails!
               } catch (PolyglotException e) {
               }
      
               c.eval("js", "javaObject.intToString(42)"); // returns "42"
           }
       }
       
      Parameters:
      sourceType - the static source type to convert from with this mapping. The source type must be applicable for a mapping to be accepted.
      targetType - the exact and static target type to convert to with this mapping.
      accepts - the predicate to check whether a mapping is applicable. Returns true if the mapping is applicable else false. If set to null then all values of a given source type are applicable.
      converter - a function that produces the converted value of the mapping. May return null. May throw ClassCastException if the source value is not convertible.
      precedence - the precedence of the defined mapping which influences conversion order and precedence with default mappings and other target type mappings.
      Throws:
      IllegalArgumentException - for primitive target types.
      Since:
      20.3
    • methodScoping

      public HostAccess.Builder methodScoping(boolean scopingDefault)
      Sets the default scoping of callback function parameters. Parameters escape from the scope of a function, if a reference to them is kept after the function returns. To use a value beyond the method scope Value.pin() may be used.
      Since:
      21.3
      See Also:
    • disableMethodScopingAnnotatedBy

      public HostAccess.Builder disableMethodScopingAnnotatedBy(Class<? extends Annotation> annotation)
      Function parameters of a method annotated with the specified annotation are not scoped.
      Since:
      21.3
    • disableMethodScoping

      public HostAccess.Builder disableMethodScoping(Executable e)
      Function parameters of the specified executable escape the executable's scope.
      Since:
      21.3
    • useModuleLookup

      public HostAccess.Builder useModuleLookup(MethodHandles.Lookup lookup)
      Sets the lookup the guest application should use to find and access classes on the host side in modularized host applications. This allows guest applications to find and access public classes that are not directly exported by the lookup module, or public classes that are exported to the module only through qualified exports. Access to classes in the unnamed module is not affected by the use of this method.

      Pass MethodHandles.lookup() from a named module to export its access privileges to the guest application.

      It is requited that the lookup module is a named module, i.e., lookup.lookupClass().getModule().isNamed() must be true.

      Note that even though the provided lookup may provide access to non-public classes or members, the access will be restricted to classes or members with public visibility.

      By default, MethodHandles.publicLookup() is used to access host classes which can only access classes from the unnamed module and classes exported to the unnamed module.

      MethodHandles.publicLookup() is also used for classes from the unnamed module even if another lookup is specified by this method. Therefore, the guest application can still add classes to the classpath and access them even though a custom lookup from a named module is specified.

      Parameters:
      lookup - lookup from a named module to be used for host access.
      Throws:
      IllegalArgumentException - if the passed lookup is not from a named module.
      Since:
      23.1
    • build

      public HostAccess build()
      Creates an instance of the custom host access configuration.
      Since:
      19.0