Package org.jboss.errai.codegen.exception

Examples of org.jboss.errai.codegen.exception.GenerationException


      for (MetaParameter mp : mc.getParameters()) {
        if (mp.getType().getErased().isAssignableTo(MetaClassFactory.get(DataBinder.class))
            && mp.isAnnotationPresent(AutoBound.class)) {
          dataModelType = (MetaClass) mp.getType().getParameterizedType().getTypeParameters()[0];
          if (dataBinderRef != null) {
            throw new GenerationException("Multiple @AutoBound data binders found in constructor of " +
                mc.getDeclaringClass());
          }
          dataBinderRef = ctx.getInjectionContext().getInlineBeanReference(mp);
        }
      }
    }

    /*
     * Search for data binder fields annotated with @AutoBound
     */
    MetaField dataBinderField = null;
    for (MetaField field : ctx.getInjector().getInjectedType().getFields()) {
      if (field.getType().getErased().equals(MetaClassFactory.get(DataBinder.class))
          && field.isAnnotationPresent(AutoBound.class)) {
        if (dataBinderField != null) {
          throw new GenerationException("Multiple @AutoBound data binder fields found in class "
              + ctx.getInjector().getInjectedType());
        }
        if (dataBinderRef != null) {
          throw new GenerationException(
              "Multiple @AutoBound data binders found (check constructors and fields) in class "
                  + ctx.getInjector().getInjectedType());
        }
        dataModelType = (MetaClass) field.getType().getParameterizedType().getTypeParameters()[0];
        dataBinderField = field;
        dataBinderRef = Stmt.invokeStatic(ctx.getInjectionContext().getProcessingContext().getBootstrapClass(),
            PrivateAccessUtil.getPrivateFieldInjectorName(dataBinderField),
            Variable.get(ctx.getInjector().getInstanceVarName()));
      }
    }

    /*
     * Create a reference to the composite's data binder
     */
    if (dataBinderRef != null) {
      builder.append(Stmt.declareVariable("binder", DataBinder.class, dataBinderRef));
    }

    /*
     * Merge each field's Widget Element into the DOM in place of the
     * corresponding data-field
     */
    Map<String, Statement> dataFields = DecoratorDataField.aggregateDataFieldMap(ctx, ctx.getType());
    for (Entry<String, Statement> field : dataFields.entrySet()) {
      builder.append(Stmt.invokeStatic(TemplateUtil.class, "compositeComponentReplace", ctx.getType()
          .getFullyQualifiedName(), getTemplateFileName(ctx.getType()), Cast.to(Widget.class, field.getValue()),
          dataFieldElements, field.getKey()));
    }

    /*
     * Add each field to the Collection of children of the new Composite
     * Template
     */
    for (Entry<String, Statement> field : dataFields.entrySet()) {
      builder.append(Stmt.nestedCall(fieldsMap).invoke("put", field.getKey(), field.getValue()));
    }

    /*
     * Bind each widget if data binder is found and has been initialized.
     */
    BlockBuilder<ElseBlockBuilder> binderBlock = If.isNotNull(Variable.get("binder"));
    for (Entry<String, Statement> dataField : dataFields.entrySet()) {
      Bound bound = DecoratorDataField.aggregateDataFieldBoundMap(ctx, ctx.getType()).get(dataField.getKey());
      if (bound != null) {
        if (dataBinderRef != null) {
          String property = bound.property().equals("") ? dataField.getKey() : bound.property();
          // Check if bound property exists in data model type
          if (!dataModelType.getBeanDescriptor().getProperties().contains(property)) {
            throw new GenerationException("Invalid binding of DataField " + dataField.getKey() + " in class "
                + ctx.getInjector().getInjectedType() + "! Property with name " + property + " not found in class "
                + dataModelType);
          }

          Statement converter =
              bound.converter().equals(Bound.NO_CONVERTER.class) ? null : Stmt.newObject(bound.converter());
          binderBlock.append(Stmt.loadVariable("binder").invoke("bind", dataField.getValue(), property, converter));
        }
        else {
          throw new GenerationException("No @AutoBound data binder found for @Bound @DataField " + dataField.getKey()
              + " in class " + ctx.getInjector().getInjectedType());
        }
      }
    }

View Full Code Here


                Stmt.loadLiteral(namedQuery.name()),
                generatedFactory));
      }
      catch (Exception ex) {
        // catch-and-rethrow to attach information about the query that failed
        GenerationException wrapperException =
            new GenerationException("Unable to translate JPQL named query.\n" +
                "Name: " + namedQuery.name() + "\n" +
                "Query: " + namedQuery.query(),
                ex);
        logger.log(com.google.gwt.core.ext.TreeLogger.Type.ERROR, "Translation Failed", ex);
        throw wrapperException;
View Full Code Here

      }

      for (MetaClass listenerMetaClass : listenerClasses) {
        for (MetaMethod callback : listenerMetaClass.getMethodsAnnotatedWith(eventType)) {
          if (callback.getParameters().length != 1) {
            throw new GenerationException("JPA lifecycle listener method " + listenerMetaClass.getName() +
                    "." + callback.getName() + " has " + callback.getParameters().length + " parameters (expected 1)");
          }
          if (!callback.getParameters()[0].getType().isAssignableFrom(entityType)) {
            throw new GenerationException("JPA lifecycle listener method " + listenerMetaClass.getName() +
                    "." + callback.getName() + " parameter type " + callback.getParameters()[0].getType().getName() +
                    " is incompatible with the entity type " + entityType.getName());
          }
          if (!callback.isPublic()) {
            PrivateAccessUtil.addPrivateAccessStubs("jsni", classBuilder, callback, new Modifier[]{});
View Full Code Here

   *         OneToMany, OneToOne).
   */
  private static CascadeType[] extractCascadeTypes(Member javaMember) {
    if (!(javaMember instanceof AccessibleObject)) {
      Class<? extends Member> memberType = javaMember == null ? null : javaMember.getClass();
      throw new GenerationException(
          "Found a SingularAttribute whose Java Member is not a field or a method (it is a " + memberType + ")");
    }
    AccessibleObject member = (AccessibleObject) javaMember;

    if (member.getAnnotation(ManyToMany.class) != null) {
View Full Code Here

      // Figure out the translation key name
      String name = null;
      String fieldName = metaField.getName();
      String defaultName = metaField.getDeclaringClass().getFullyQualifiedName() + "." + fieldName;
      if (!metaField.getType().isAssignableFrom(String.class)) {
        throw new GenerationException("Translation key fields must be of type java.lang.String: " + defaultName);
      }
      try {
        Class<?> asClass = metaField.getDeclaringClass().asClass();
        Field field = asClass.getField(fieldName);
        Object fieldVal = field.get(null);
        if (fieldVal == null) {
          throw new GenerationException("Translation key fields cannot be null: " + defaultName);
        }
        name = fieldVal.toString();
      }
      catch (Exception e) {
        log.warn("There was an error while processing a TranslationKey", e);
      }

      // Figure out the translation key value (for the null locale).
      String value = null;
      TranslationKey annotation = metaField.getAnnotation(TranslationKey.class);
      String defaultValue = annotation.defaultValue();
      if (defaultValue != null) {
        value = defaultValue;
      }
      else {
        value = "!!" + defaultName + "!!";
      }

      // Generate code to register the null locale mapping
      if (translationKeyFieldMap.containsKey(name)) {
        throw new GenerationException("Duplicate translation key found: " + defaultName);
      }
      translationKeyFieldMap.put(name, value);
      ctor.append(Stmt.loadVariable("this").invoke("registerTranslation", name, value, null));
    }

    // Scan for all @Bundle annotations.
    final Collection<MetaClass> bundleAnnotatedClasses = ClassScanner.getTypesAnnotatedWith(Bundle.class, context);

    Set<String> bundlePaths = new HashSet<String>();
    for (MetaClass bundleAnnotatedClass : bundleAnnotatedClasses) {
      String bundlePath = getMessageBundlePath(bundleAnnotatedClass);
      bundlePaths.add(bundlePath);
    }

    // Now get all files in the message bundle (all localized versions)
    final Collection<URL> scannableUrls = getScannableUrls(bundleAnnotatedClasses);
    log.info("Preparing to scan for i18n bundle files.");
    MessageBundleScanner scanner = new MessageBundleScanner(
            new ConfigurationBuilder()
                .filterInputsBy(new FilterBuilder().include(".*json"))
                .setUrls(scannableUrls)
                .setScanners(new MessageBundleResourceScanner(bundlePaths)));

    // For each one, generate the code to load the translation and put that generated
    // code in the c'tor of the generated class (GeneratedTranslationService)
    Collection<String> resources = scanner.getStore().get(MessageBundleResourceScanner.class).values();
    for (String bundlePath : bundlePaths) {
      // If we didn't find at least the specified root bundle file, that's a problem.
      if (!resources.contains(bundlePath)) {
        throw new GenerationException("Missing i18n bundle (specified in @Bundle): " + bundlePath);
      }
    }

    // Now generate code to load up each of the JSON files and register them
    // with the translation service.
View Full Code Here

    for (final MetaClass bundleClass : bundleAnnotatedClasses) {
      final String bundlePath = getMessageBundlePath(bundleClass);
      if (bundlePath != null && !completedPaths.contains(bundlePath)) {
        final URL resource = getClass().getClassLoader().getResource(bundlePath);
        if (resource == null) {
          throw new GenerationException("Failed to load bundle " + bundlePath +
                  " defined on class " + bundleClass.getFullyQualifiedName());
        }
       
        final URL classpathElement;
        final String pathRoot = getPathRoot(bundleClass, resource);
View Full Code Here

   */
  private String getMessageBundlePath(MetaClass bundleAnnotatedClass) {
    Bundle annotation = bundleAnnotatedClass.getAnnotation(Bundle.class);
    String name = annotation.value();
    if (name == null) {
      throw new GenerationException("@Bundle: bundle name must not be null].");
    }
    // Absolute path vs. relative path.
    if (name.startsWith("/")) {
      return name.substring(1);
    }
View Full Code Here

  @Override
  public List<? extends Statement> generateDecorator(final InjectableInstance<Templated> ctx) {
    final MetaClass declaringClass = ctx.getEnclosingType();

    if (!declaringClass.isAssignableTo(Composite.class)) {
      throw new GenerationException("@Templated class [" + declaringClass.getFullyQualifiedName()
          + "] must extend base class [" + Composite.class.getName() + "].");
    }

    for (final MetaField field : declaringClass.getFields()) {
      if (field.isAnnotationPresent(DataField.class)) {
View Full Code Here

    for (final MetaMethod method : declaringClass.getMethodsAnnotatedWith(EventHandler.class)) {

      final String[] targetDataFieldNames = method.getAnnotation(EventHandler.class).value();

      if (targetDataFieldNames.length == 0) {
        throw new GenerationException("@EventHandler annotation on method ["
            + declaringClass.getFullyQualifiedName()
            + "." + method.getName() + "] must specify at least one data-field target.");
      }

      final MetaClass eventType = (method.getParameters().length == 1) ? method.getParameters()[0].getType() : null;
      if (eventType == null || (!eventType.isAssignableTo(Event.class)) && !eventType.isAssignableTo(DomEvent.class)) {
        throw new GenerationException("@EventHandler method [" + method.getName() + "] in class ["
            + declaringClass.getFullyQualifiedName()
            + "] must have exactly one parameter of a type extending either ["
            + DomEvent.class.getName() + "] or [" + NativeEvent.class.getName() + "].");
      }

      if (eventType.isAssignableTo(Event.class)) {
        /*
         * Generate native DOM event handlers.
         */
        final MetaClass handlerType = MetaClassFactory.get(EventListener.class);
        final BlockBuilder<AnonymousClassStructureBuilder> listenerBuiler = ObjectBuilder.newInstanceOf(handlerType)
            .extend()
            .publicOverridesMethod(handlerType.getMethods()[0].getName(), Parameter.of(eventType, "event"));
        listenerBuiler.append(InjectUtil.invokePublicOrPrivateMethod(ctx.getInjectionContext(), component,
            method, Stmt.loadVariable("event")));

        final ObjectBuilder listenerInstance = listenerBuiler.finish().finish();

        int eventsToSink =
            Event.FOCUSEVENTS | Event.GESTUREEVENTS | Event.KEYEVENTS | Event.MOUSEEVENTS | Event.TOUCHEVENTS;
        if (method.isAnnotationPresent(SinkNative.class)) {
          eventsToSink = method.getAnnotation(SinkNative.class).value();
        }

        for (final String name : targetDataFieldNames) {

          if (processedNativeHandlers.contains(name) || processedEventHandlers.contains(name)) {
            throw new GenerationException(
                "Cannot specify more than one @EventHandler method when @SyncNative is used for data-field ["
                    + name + "] in class ["
                    + declaringClass.getFullyQualifiedName()
                    + "].");
          }
          else {
            processedNativeHandlers.add(name);
          }

          if (dataFieldTypes.containsKey(name)) {
            final MetaClass dataFieldType = dataFieldTypes.get(name);
            if (!dataFieldType.isAssignableTo(Element.class)) {
              /*
               * We have a GWT or other Widget type.
               */
              throw new GenerationException("@DataField [" + name + "] of type [" + dataFieldType.getName()
                  + "] in class [" + declaringClass.getFullyQualifiedName() + "] is not assignable to ["
                  + Element.class.getName() + "] specified by @EventHandler method " + method.getName()
                  + "("
                  + eventType.getName() + ")]");
            }
            else {
              /*
               * We have a wrapped native Element reference
               */
              throw new GenerationException("Cannot attach native DOM events to @DataField [" + name
                  + "] of type ["
                  + dataFieldType.getName() + "] in class [" + declaringClass.getFullyQualifiedName()
                  + "] specified by @EventHandler method " + method.getName() + "(" + eventType.getName()
                  + ")] - Use the corresponding GWT 'EventHandler' types instead.");
            }
          }
          else {
            /*
             * We are completely native and have no reference to this data-field
             * Element in Java
             */
            initStmts.add(Stmt.invokeStatic(TemplateUtil.class, "setupNativeEventListener", component,
                Stmt.loadVariable(dataFieldElementsVarName).invoke("get", name), listenerInstance,
                eventsToSink));
          }
        }
      }
      else {
        /*
         * We have a GWT Widget type
         */
        final MetaClass handlerType;
        try {
          handlerType = getHandlerForEvent(eventType);
        }
        catch (GenerationException e) {
          /*
           *  see ERRAI-373 for details on this crazy inference (without this message, the cause of the
           *  problem is nearly impossible to diagnose)
           */
          if (declaringClass.getClass() == JavaReflectionClass.class) {
            throw new GenerationException(
                "The type " + declaringClass.getFullyQualifiedName() + " looks like a client-side" +
                    " @Templated class, but it is not known to GWT. This probably means that " +
                    declaringClass.getName() + " or one of its supertypes contains non-translatable code." +
                    " Run the GWT compiler with logLevel=DEBUG to pinpoint the problem.", e);
          }
          throw e;
        }

        final BlockBuilder<AnonymousClassStructureBuilder> listenerBuiler = ObjectBuilder.newInstanceOf(handlerType)
            .extend()
            .publicOverridesMethod(handlerType.getMethods()[0].getName(), Parameter.of(eventType, "event"));


        listenerBuiler.append(InjectUtil.invokePublicOrPrivateMethod(ctx.getInjectionContext(),
            component, method, Stmt.loadVariable("event")));

        final ObjectBuilder listenerInstance = listenerBuiler.finish().finish();

        final MetaClass hasHandlerType = MetaClassFactory.get("com.google.gwt.event.dom.client.Has"
            + handlerType.getName()
            + "s");

        for (final String name : targetDataFieldNames) {
          final MetaClass dataFieldType = dataFieldTypes.get(name);

          if (dataFieldType == null) {
            throw new GenerationException("@EventHandler method [" + method.getName() + "] in class ["
                + declaringClass.getFullyQualifiedName()
                + "] handles a GWT event type but the specified @DataField [" + name + "] was not found.");
          }

          if (processedNativeHandlers.contains(name)) {
            throw new GenerationException(
                "Cannot specify more than one @EventHandler method when @SinkNative is used for data-field ["
                    + name + "] in class [" + declaringClass.getFullyQualifiedName()
                    + "].");
          }

          processedEventHandlers.add(name);

          // Where will the event come from? It could be a @DataField member, or it could be the templated widget itself!
          final Statement eventSource;
          if ("this".equals(name)) {
            eventSource = Stmt.loadVariable("obj");
          }
          else {
            eventSource = Stmt.nestedCall(fieldsMap).invoke("get", name);
          }

          if (dataFieldType.isAssignableTo(Element.class)) {
            initStmts.add(Stmt.invokeStatic(TemplateUtil.class, "setupWrappedElementEventHandler", component,
                eventSource, listenerInstance,
                Stmt.invokeStatic(eventType, "getType")));
          }
          else if (dataFieldType.isAssignableTo(hasHandlerType)) {
            final Statement widget = Cast.to(hasHandlerType, eventSource);
            initStmts.add(Stmt.nestedCall(widget).invoke("add" + handlerType.getName(),
                Cast.to(handlerType, listenerInstance)));
          }
          else if (dataFieldType.isAssignableTo(Widget.class)) {
            final Statement widget = Cast.to(Widget.class, eventSource);
            initStmts.add(Stmt.nestedCall(widget).invoke("addDomHandler",
                listenerInstance, Stmt.invokeStatic(eventType, "getType")));
          }
          else {
            throw new GenerationException("@DataField [" + name + "] of type [" + dataFieldType.getName()
                + "] in class [" + declaringClass.getFullyQualifiedName()
                + "] does not implement required interface [" + hasHandlerType.getName()
                + "] specified by @EventHandler method " + method.getName() + "(" + eventType.getName()
                + ")]");
          }
View Full Code Here

        }
      }
    }

    if (method == null) {
      throw new GenerationException("Method 'getAssociatedType()' could not be found in the event ["
          + eventType.getName() + "]");
    }

    final MetaType returnType = method.getGenericReturnType();
    if (returnType == null) {
      throw new GenerationException("The method 'getAssociatedType()' in the event [" + eventType.getName()
          + "] returns void.");
    }

    logger.debug("eventType: " + eventType.getClass() + " -- " + eventType);
    logger.debug("method: " + method.getClass() + " -- " + method);
    logger.debug("genericReturnType: " + returnType.getClass() + " -- " + returnType);

    if (!(returnType instanceof MetaParameterizedType)) {
      throw new GenerationException("The method 'getAssociatedType()' in the event [" + eventType.getName()
          + "] does not return Type<? extends EventHandler>..");
    }

    final MetaParameterizedType parameterizedType = (MetaParameterizedType) returnType;
    logger.debug("parameterizedType: " + parameterizedType.getClass() + " -- " + parameterizedType);

    final MetaType[] argTypes = parameterizedType.getTypeParameters();
    if ((argTypes.length != 1) && argTypes[0] instanceof MetaClass
        && !((MetaClass) argTypes[0]).isAssignableTo(EventHandler.class)) {
      throw new GenerationException("The method 'getAssociatedType()' in the event [" + eventType.getName()
          + "] does not return Type<? extends EventHandler>..");
    }

    return (MetaClass) argTypes[0];
  }
View Full Code Here

TOP

Related Classes of org.jboss.errai.codegen.exception.GenerationException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.