2

I'm writing an E2E Test for my REST-Application. So the test, that is located in the frontend, calls the deployed backend, this is working perfectly fine except for one tiny problem: When the readEntity Method on the received Response is called, an java.lang.ArrayStoreException occurs. My observations show that the Problem lies within a self written Constraint Annotation:

I've written my own Constraint-Annotation @Future for Bean-Validation, my POJO uses this Annotation to validate that a LocalDateTime is in the future. I've also provided two simple Interfaces, which are used as Validation-Groups:

public interface ExistingInstance extends Default {

}

and

public interface NewInstance extends Default {

}

When i use one of these Interfaces as a validation group in my custom Constraint Annotation like follows:

public class Book {

   @Future(groups=NewInstance.class)
   private LocalDateTime validFrom;

   private LocalDateTime validTo;

   // Getters & Setters...
}

I receive this Exception:

java.lang.ArrayStoreException
    at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:736)
    at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:543)
    at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:367)
    at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:298)
    at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:132)
    at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:84)
    at java.lang.reflect.AccessibleObject.getAnnotationsFromCache(AccessibleObject.java:313)
    at java.lang.reflect.Field.declaredAnnotations(Field.java:1167)
    at java.lang.reflect.Field.getDeclaredAnnotations(Field.java:1160)
    at com.fasterxml.jackson.databind.introspect.AnnotatedFieldCollector._findFields(AnnotatedFieldCollector.java:86)
    at com.fasterxml.jackson.databind.introspect.AnnotatedFieldCollector._findFields(AnnotatedFieldCollector.java:71)
    at com.fasterxml.jackson.databind.introspect.AnnotatedFieldCollector.collect(AnnotatedFieldCollector.java:48)
    at com.fasterxml.jackson.databind.introspect.AnnotatedFieldCollector.collectFields(AnnotatedFieldCollector.java:43)
    at com.fasterxml.jackson.databind.introspect.AnnotatedClass._fields(AnnotatedClass.java:371)
    at com.fasterxml.jackson.databind.introspect.AnnotatedClass.fields(AnnotatedClass.java:343)
    at com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector._addFields(POJOPropertiesCollector.java:493)
    at com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector.collectAll(POJOPropertiesCollector.java:421)
    at com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector.getPropertyMap(POJOPropertiesCollector.java:386)
    at com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector.getProperties(POJOPropertiesCollector.java:233)
    at com.fasterxml.jackson.databind.introspect.BasicBeanDescription._properties(BasicBeanDescription.java:164)
    at com.fasterxml.jackson.databind.introspect.BasicBeanDescription.findProperties(BasicBeanDescription.java:239)
    at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory._findCreatorsFromProperties(BasicDeserializerFactory.java:328)
    at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory._constructDefaultValueInstantiator(BasicDeserializerFactory.java:272)
    at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.findValueInstantiator(BasicDeserializerFactory.java:223)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.buildBeanDeserializer(BeanDeserializerFactory.java:261)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:150)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:414)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:349)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
    at com.fasterxml.jackson.databind.DeserializationContext.findContextualValueDeserializer(DeserializationContext.java:558)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.createContextual(CollectionDeserializer.java:188)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.createContextual(CollectionDeserializer.java:28)
    at com.fasterxml.jackson.databind.DeserializationContext.handlePrimaryContextualization(DeserializationContext.java:765)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.resolve(BeanDeserializerBase.java:535)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:293)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
    at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:591)
    at com.fasterxml.jackson.databind.ObjectReader._prefetchRootDeserializer(ObjectReader.java:2340)
    at com.fasterxml.jackson.databind.ObjectReader.forType(ObjectReader.java:723)
    at com.fasterxml.jackson.jaxrs.base.ProviderBase.readFrom(ProviderBase.java:804)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:233)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:212)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:132)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1072)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:885)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:845)
    at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:340)
    at org.glassfish.jersey.client.InboundJaxrsResponse$2.call(InboundJaxrsResponse.java:104)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:292)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:274)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:205)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:365)
    at org.glassfish.jersey.client.InboundJaxrsResponse.runInScopeIfPossible(InboundJaxrsResponse.java:244)
    at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:101)
    at my.package.structure.books.BooksClient.readEntityFromResponse(BooksClient.java:309)
    at my.package.structure.books.BooksClient.getBooks(BooksClient.java:95)
    at my.package.structure.books.BooksClientTest.getBooks_Test(BooksClientTest.java:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:90)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
    at java.lang.reflect.Method.invoke(Method.java:508)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:436)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:170)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor$$Lambda$251.00000000126A8D40.execute(Unknown Source)
    at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:166)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:113)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:112)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$143.000000001120E090.execute(Unknown Source)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$146.000000001148A600.accept(Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:195)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:186)
    at java.util.Iterator.forEachRemaining(Iterator.java:127)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1812)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:523)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:513)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:162)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:185)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:245)
    at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:429)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$143.000000001120E090.execute(Unknown Source)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$146.000000001148A600.accept(Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:195)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:186)
    at java.util.Iterator.forEachRemaining(Iterator.java:127)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1812)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:523)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:513)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:162)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:185)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:245)
    at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:429)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$143.000000001120E090.execute(Unknown Source)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

Now the Confusing Part:

If i use my Validation-Group Interfaces on an Existing Annotation, provided by Java, like @NotNull:

public class Book {
   
   @NotNull(groups=NewInstance.class)
   private LocalDateTime validFrom;

   private LocalDateTime validTo;

   // Getters & Setters...
}

It works like perfectly fine. Even if i use a class provided in the JDK, like Default.class as a group on my Custom Annotation:

public class Book {
   
   @NotNull(groups=Default.class)
   private LocalDateTime validFrom;

   private LocalDateTime validTo;

   // Getters & Setters...
}

It works!

What am i missing?

I use:

  • Java v8
  • JavaEE v7
  • Jersey Client v2.33
  • Jersey HK2 v2.33
  • Hibernate Validator v5.4.3

Note: I know that the Annotation `@Future` is already provided, but in Java 8 with JavaEE 7 it does not support the 'new' Time-API.

Edit Here is my code to reproduce the error:

Server-Side: Wrapper for Returned Entities

public class Wrapper<T> {
   
   private T returnValue;
   private String exception;
   private Integer processingState;
   private String processingMessage;

   //Getter & Setter
}
@Path("books")
public class BookService {

   @EJB
   private BookRepo repository;

   @Path("all")
   public Response getAllBooks() {
      Response response = null;
      try {
         // findAll returns a List wrapped inside the above shown Wrapper class
         response = Response.status(200).entity(new GenericEntity<Wrapper<List<Book>>>(repository.findAll()){}).build();
      } catch (Exception e) {
         response = Response.status(500).build();
      }

      return response;
   }

}

Client Side:

public class BooksClient {

   private ObjectMapper mapper;
   private Client client;
   private WebTarget baseTarget;
   
   public BooksClient(String endpointAdress) {
      this.mapper = new ObjectMapper();
      this.mapper.registerModule(new JavaTimeModule());
      this.mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

      JacksonJsonProvider provider = new JacksonJsonProvider(this.mapper);

      this.client = ClientBuilder.newClient(new ClientConfig().register(provider));

      this.baseTarget = this.client.target(endpointAdress);
   }

   public Wrapper<List<Book>> getBooks() {
      WebTarget bookTarget = baseTarget.path("all");
      
      Response response = bookTarget.request(MediaType.APPLICATION_JSON).get();

      return this.readEntityFromResponse(response);

   }

   private Wrapper<List<Book>> readEntityFromResponse(Response response) {
      Wrapper<List<Book>> result = null;

      GenericType<List<Book>> responseType = new GenericType<Wrapper<List<Book>>>(){};

      result = response.readEntity(responseType); // <--- root of Exception

      return result;
   }

}

Test Class

public class BooksClientTest {

   @Spy
   private BooksClient client = new BooksClient("http://localhost:1234/ws/books");

   @Test
   public void getBooks_Test() {
      Wrapper<List<Book>> result = this.client.getBooks();
      assertThat(result).isNotNull();
   }

}

Custom-Annotation:

/**
 * Validates a Time Value.
 */
@Documented
@Retention(RUNTIME)
@Target(FIELD)
@Constraint(validatedBy = { FutureLocalDateTimeValidator.class, FutureLocalDateValidator.class,
    FutureLocalTimeValidator.class, FutureZonedDateTimeValidator.class })
public @interface Future {

  String message() default "Error while validating the date!";

  Class<?>[] groups() default {};

  Class<? extends Payload>[] payload() default {};
}

Corresponding Validator:

public class FutureLocalDateTimeValidator implements ConstraintValidator<Future, LocalDateTime> {

  @Override
  public void initialize(Future constraintAnnotation) {
    // not needed.
  }

  @Override
  public boolean isValid(LocalDateTime value, ConstraintValidatorContext context) {
    if (value == null) {
      return true;
    }

    LocalDateTime today = LocalDateTime.now();
    return value.isAfter(today);
  }

}

I've tried different self written Annotations with the exact same result.

The Application is deployed on a WAS 9.0

If i use the actual frontend no error occurs.

Hope this helps, thanks in advance!

4
  • 1
    Looks like you could reproduce the error at a lower level by calling Field#getDeclaredAnnotations() on that particular field. If you want to allow others to be able to reproduce it, you should post all the necessary code. Feb 10, 2021 at 17:32
  • You're still missing the custom annotation and validator to go with it. That was what I was referring to in the previous comment. Feb 11, 2021 at 15:17
  • You are right, sorry, I will update my Post!
    – Dignity
    Feb 11, 2021 at 15:44
  • Do you know how to use reflection? I tried to reproduce the problem just using reflection and calling Field#getDeclaredAnnotations() on the field, as I mentioned, and I cannot reproduce the problem. I was wondering if you could reproduce it on your side simple using reflection (based on the stack trace) Feb 11, 2021 at 16:50

2 Answers 2

4

I could not find the exact version (the line numbers do not match), but the code found on docjar.com is plausible enough to explain what happens.

private static Object parseClassArray(int length,
                                      ByteBuffer buf,
                                      ConstantPool constPool,
                                      Class<?> container) {
    Object[] result = new Class<?>[length];
    boolean typeMismatch = false;
    int tag = 0;

    for (int i = 0; i < length; i++) {
        tag = buf.get();
        if (tag == 'c') {
            result[i] = parseClassValue(buf, constPool, container);
        } else {
            skipMemberValue(tag, buf);
            typeMismatch = true;
        }
    }
    return typeMismatch ? exceptionProxy(tag) : result;
}
private static Object parseClassValue(ByteBuffer buf,
                                      ConstantPool constPool,
                                      Class<?> container) {
    int classIndex = buf.getShort() & 0xFFFF;
    try {
        try {
            String sig = constPool.getUTF8At(classIndex);
            return parseSig(sig, container);
        } catch (IllegalArgumentException ex) {
            // support obsolete early jsr175 format class files
            return constPool.getClassAt(classIndex);
        }
    } catch (NoClassDefFoundError e) {
        return new TypeNotPresentExceptionProxy("[unknown]", e);
    }
    catch (TypeNotPresentException e) {
        return new TypeNotPresentExceptionProxy(e.typeName(), e.getCause());
    }
}

The interesting aspect is that the method parseClassValue does not always return a Class<?>; when a NoClassDefFoundError or TypeNotPresentException occurs, it will return a TypeNotPresentExceptionProxy instance instead.

Since parseClassArray does not check for this special return value but unconditionally stores the result into a Class<?>[] array, an ArrayStoreException may occur.

This is a bug, obviously, but it also provides a hint why you are not always encountering this specific problem (and apparently, not many developers in general).

It only occurs when an absent type is referenced in an annotation value that has an array of Class type. So you may focus on the question which type is not available in the failing environment. One way to check this, is to enforce an earlier termination in the erroneous case, e.g.

public class Book {
    // now, it will fail at class initialization time if the type is missing
   static final Class<?> DUMMY = NewInstance.class;

   @Future(groups=NewInstance.class)
   private LocalDateTime validFrom;

   private LocalDateTime validTo;

   // Getters & Setters...
}
1
  • Thanks for the explanation! I added that line of code and now the Error says: java.lang.NoClassDefFoundError: javax.validation.groups.Default (Can't post the whole stacktrace
    – Dignity
    Feb 15, 2021 at 6:50
0

I found the problem. I'm using

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>5.4.3.Final</version>
    </dependency>

and

    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>1.1.0.Final</version>
    </dependency>

these are incompatible according to this answer.
I upgraded the version to:

    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>2.0.1.Final</version>
    </dependency>

And now everything works fine. Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.