Package org.jboss.errai.codegen.exception

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


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

      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.");
      }

      MetaClass eventType = method.getParameters()[0].getType();

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

        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 (String name : targetDataFieldNames) {

          if (dataFieldTypes.containsKey(name)) {
            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
             */
            builder.append(Stmt.invokeStatic(TemplateUtil.class, "setupNativeEventListener", component,
                    dataFieldElements.invoke("get", name), listenerInstance, eventsToSink));
          }
        }
      }
      else {
        /*
         * We have a GWT Widget type
         */
        if (method.getParameters().length != 1 || !method.getParameters()[0].getType().isAssignableTo(DomEvent.class)) {
          throw new GenerationException("@EventHandler method [" + method.getName() + "] in class ["
                  + declaringClass.getFullyQualifiedName() + "] must have at least one parameter of a type extending ["
                  + DomEvent.class.getName() + "]");
        }

        MetaClass handlerType = getHandlerForEvent(eventType);
        BlockBuilder<AnonymousClassStructureBuilder> listenerBuiler = ObjectBuilder.newInstanceOf(handlerType).extend()
                .publicOverridesMethod(handlerType.getMethods()[0].getName(), Parameter.of(eventType, "event"));
        listenerBuiler.append(Stmt.nestedCall(component).invoke(method, Stmt.loadVariable("event")));

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

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

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

          if (dataFieldType.isAssignableTo(Element.class)) {
            builder.append(Stmt.invokeStatic(TemplateUtil.class, "setupWrappedElementEventHandler", component, Stmt
                    .nestedCall(fieldsMap).invoke("get", name), listenerInstance, Stmt.invokeStatic(eventType,
                    "getType")));
          }
          else if (dataFieldType.isAssignableTo(hasHandlerType)) {
            Statement widget = Cast.to(hasHandlerType, Stmt.nestedCall(fieldsMap).invoke("get", name));
            builder.append(Stmt.nestedCall(widget).invoke("add" + handlerType.getName(),
                    Cast.to(handlerType, listenerInstance)));
          }
          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() + "]");
    }

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

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

    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

    ctx.ensureMemberExposed();
    Statement instance = ctx.getValueStatement();
    String name = getTemplateDataFieldName(ctx.getAnnotation(), ctx.getMemberName());
    if (ctx.getType().isAssignableTo(Element.class)) {
      if (ctx.isAnnotationPresent(Inject.class)) {
        throw new GenerationException("@DataField [" + name + "] in class ["
                + ctx.getEnclosingType().getFullyQualifiedName() + "] is of type ["
                + ctx.getType().getFullyQualifiedName()
                + "] which does not support @Inject; this instance must be created manually.");
      }
      instance = ObjectBuilder.newInstanceOf(ElementWrapperWidget.class).withParameters(instance);
View Full Code Here

    case HqlSqlTokenTypes.IN: {
      final boolean notIn = ast.getType() == HqlSqlTokenTypes.NOT_IN;
      Statement thingToTest = generateExpression(traverser, dotNodeResolver, containingMethod);
      ast = traverser.next();
      if (ast.getType() != HqlSqlTokenTypes.IN_LIST) {
        throw new GenerationException("Expected IN_LIST node but found " + ast.getText());
      }

      List<Statement> collection = new ArrayList<Statement>(ast.getNumberOfChildren());
      for (int i = 0; i < ast.getNumberOfChildren(); i++) {
        collection.add(Cast.to(Object.class, generateExpression(traverser, dotNodeResolver, containingMethod)));
      }
      Statement callToComparisonsIn = Stmt.invokeStatic(Comparisons.class, "in", thingToTest, collection.toArray());
      return notIn ? Bool.notExpr(callToComparisonsIn) : callToComparisonsIn;
    }

    case HqlSqlTokenTypes.NOT_LIKE:
    case HqlSqlTokenTypes.LIKE: {
      Statement valueExpr = Cast.to(String.class, generateExpression(traverser, dotNodeResolver, containingMethod));
      Statement patternExpr = Cast.to(String.class, generateExpression(traverser, dotNodeResolver, containingMethod));
      Statement escapeCharExpr = Cast.to(String.class, Stmt.loadLiteral(null));
      if (ast.getNumberOfChildren() == 3) {
        traverser.next();
        escapeCharExpr = Cast.to(String.class, generateExpression(traverser, dotNodeResolver, containingMethod));
      }
      Statement likeStmt = Stmt.invokeStatic(
              Comparisons.class, "like", valueExpr, patternExpr, escapeCharExpr);
      return ast.getType() == HqlSqlTokenTypes.LIKE ? likeStmt : Bool.notExpr(likeStmt);
    }

    case HqlSqlTokenTypes.IS_NULL:
      return Bool.isNull(generateExpression(traverser, dotNodeResolver, containingMethod));

    case HqlSqlTokenTypes.IS_NOT_NULL:
      return Bool.isNotNull(generateExpression(traverser, dotNodeResolver, containingMethod));

    case HqlSqlTokenTypes.OR:
      return Bool.or(generateExpression(traverser, dotNodeResolver, containingMethod), generateExpression(traverser, dotNodeResolver, containingMethod));

    case HqlSqlTokenTypes.AND:
      return Bool.and(generateExpression(traverser, dotNodeResolver, containingMethod), generateExpression(traverser, dotNodeResolver, containingMethod));

    case HqlSqlTokenTypes.NOT:
      return Bool.notExpr(generateExpression(traverser, dotNodeResolver, containingMethod));

    //
    // VALUE EXPRESSIONS
    //

    case HqlSqlTokenTypes.DOT:
      DotNode dotNode = (DotNode) ast;
      traverser.fastForwardToNextSiblingOf(dotNode);
      return dotNodeResolver.resolve(dotNode);

    case HqlSqlTokenTypes.NAMED_PARAM:
      ParameterNode paramNode = (ParameterNode) ast;
      NamedParameterSpecification namedParamSpec = (NamedParameterSpecification) paramNode.getHqlParameterSpecification();
      return Stmt.loadVariable("this").invoke("getParameterValue", namedParamSpec.getName());

    case HqlSqlTokenTypes.QUOTED_STRING:
      return Stmt.loadLiteral(SqlUtil.parseStringLiteral(ast.getText()));

    case HqlSqlTokenTypes.UNARY_MINUS:
      return ArithmeticExpressionBuilder.create(ArithmeticOperator.Subtraction, generateExpression(traverser, dotNodeResolver, containingMethod));

    case HqlSqlTokenTypes.NUM_INT:
    case HqlSqlTokenTypes.NUM_DOUBLE:
    case HqlSqlTokenTypes.NUM_FLOAT:
      // all numeric literals (except longs) are generated as doubles
      // (and correspondingly, all "dot nodes" (entity attributes) are retrieved as doubles)
      // this allows us to compare almost any numeric type to any other numeric type
      // (long and char are the exceptions)
      return Stmt.loadLiteral(Double.valueOf(ast.getText()));

    case HqlSqlTokenTypes.NUM_LONG:
      return Stmt.loadLiteral(Long.valueOf(ast.getText()));

    case HqlSqlTokenTypes.TRUE:
    case HqlSqlTokenTypes.FALSE:
      return Stmt.loadLiteral(((BooleanLiteralNode) ast).getValue());

    case HqlSqlTokenTypes.JAVA_CONSTANT:
      return Stmt.loadLiteral(MVEL.eval(ast.getText()));

    case HqlSqlTokenTypes.METHOD_CALL:
      IdentNode methodNameNode = (IdentNode) traverser.next();
      SqlNode exprList = (SqlNode) traverser.next();

      // trim is weird because it can take keywords (IDENT nodes) in its arg list
      if ("trim".equals(methodNameNode.getOriginalText())) {
        String trimType = "BOTH";
        Statement trimChar = Stmt.loadLiteral(' ');
        Statement untrimmedStr;
        ast = traverser.next();
        if (ast.getType() == HqlSqlTokenTypes.IDENT) {
          if (ast.getText().equalsIgnoreCase("BOTH")) {
            trimType = "BOTH";
            ast = traverser.next();
          }
          else if (ast.getText().equalsIgnoreCase("LEADING")) {
            trimType = "LEADING";
            ast = traverser.next();
          }
          else if (ast.getText().equalsIgnoreCase("TRAILING")) {
            trimType = "TRAILING";
            ast = traverser.next();
          }
        }

        if (exprList.getNumberOfChildren() == 4 ||
                (exprList.getNumberOfChildren() == 3 && ast.getType() != HqlSqlTokenTypes.IDENT)) {
          // [[IDENT('LEADING|TRAILING|BOTH')], [<expression:trimchar>], IDENT(FROM),] <expression:untrimmedStr>
          //                                     ^^^ you are here
          Statement trimStr = generateExpression(new AstInorderTraversal(ast), dotNodeResolver, containingMethod);
          trimChar = Stmt.nestedCall(trimStr).invoke("charAt", 0);
          ast = traverser.fastForwardTo(ast.getNextSibling());
        }

        if (ast.getType() == HqlSqlTokenTypes.IDENT) {
          if (ast.getText().equalsIgnoreCase("FROM")) {
            ast = traverser.next();
          }
          else {
            throw new GenerationException("Found unexpected JPQL keyword " + ast.getText() + " in query (expected FROM)");
          }
        }

        untrimmedStr = generateExpression(new AstInorderTraversal(ast), dotNodeResolver, containingMethod);
        traverser.fastForwardToNextSiblingOf(ast);

        // declare a local variable with the regex pattern in it
        int uniq = uniqueNumber.incrementAndGet();
        StringBuilderBuilder trimPattern = Implementations.newStringBuilder();
        trimPattern.append("^");
        if (trimType.equals("LEADING") || trimType.equals("BOTH")) {
          trimPattern.append(Stmt.invokeStatic(Comparisons.class, "escapeRegexChar", trimChar));
          trimPattern.append("*");
        }
        trimPattern.append("(.*?)");
        if (trimType.equals("TRAILING") || trimType.equals("BOTH")) {
          trimPattern.append(Stmt.invokeStatic(Comparisons.class, "escapeRegexChar", trimChar));
          trimPattern.append("*");
        }
        trimPattern.append("$");
        containingMethod.append(
                Stmt.declareFinalVariable(
                        "trimmer" + uniq,
                        RegExp.class,
                        Stmt.invokeStatic(RegExp.class, "compile", Stmt.load(trimPattern).invoke("toString"))));

        return Stmt.nestedCall(
                  Stmt.loadVariable("trimmer" + uniq).invoke("exec", Stmt.castTo(String.class, Stmt.load(untrimmedStr))
               ).invoke("getGroup", 1));
      }

      // for all other functions, we can pre-process the arguments like this:
      Statement[] args = new Statement[exprList.getNumberOfChildren()];
      for (int i = 0; i < args.length; i++) {
        args[i] = generateExpression(traverser, dotNodeResolver, containingMethod);
      }
      if ("lower".equals(methodNameNode.getOriginalText())) {
        return Stmt.castTo(String.class, Stmt.load(args[0])).invoke("toLowerCase");
      }
      else if ("upper".equals(methodNameNode.getOriginalText())) {
        return Stmt.castTo(String.class, Stmt.load(args[0])).invoke("toUpperCase");
      }
      else if ("concat".equals(methodNameNode.getOriginalText())) {
        StringBuilderBuilder sb = Implementations.newStringBuilder();
        for (Statement s : args) {
          sb.append(s);
        }
        return Stmt.load(sb).invoke("toString");
      }
      else if ("substring".equals(methodNameNode.getOriginalText())) {
        int uniq = uniqueNumber.incrementAndGet();
        containingMethod.append(Stmt.declareFinalVariable("substrOrig" + uniq, String.class,
                Cast.to(String.class, args[0])));
        containingMethod.append(Stmt.declareFinalVariable("substrStart" + uniq, int.class,
                Arith.expr(Cast.to(Integer.class, args[1]), ArithmeticOperator.Subtraction, 1)));
        if (args.length == 2) {
          return Stmt.loadVariable("substrOrig" + uniq).invoke("substring", Stmt.loadVariable("substrStart" + uniq));
        }
        else if (args.length == 3) {
          containingMethod.append(Stmt.declareFinalVariable("substrEnd" + uniq, int.class,
                  Arith.expr(Cast.to(Integer.class, args[2]), ArithmeticOperator.Addition, Stmt.loadVariable("substrStart" + uniq))));
          return Stmt.loadVariable("substrOrig" + uniq).invoke(
                  "substring", Stmt.loadVariable("substrStart" + uniq), Stmt.loadVariable("substrEnd" + uniq));
        }
        else {
          throw new GenerationException("Found " + args.length + " arguments to concat() function. Expected 2 or 3.");
        }
      }
      else if ("length".equals(methodNameNode.getOriginalText())) {
        // all numerics must be double for purposes of comparison in this JPQL implementation
        return Stmt.castTo(double.class, Stmt.nestedCall(Stmt.castTo(String.class, Stmt.load(args[0])).invoke("length")));
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

      if (entityListeners != null) {
        for (Class<?> listenerClass : entityListeners.value()) {
          MetaClass listenerMetaClass = MetaClassFactory.get(listenerClass);
          for (MetaMethod callback : listenerMetaClass.getMethodsAnnotatedWith(eventType)) {
            if (callback.getParameters().length != 1) {
              throw new GenerationException("JPA lifecycle listener method " + callback.getName() + " has " +
                      callback.getParameters().length + " parameters (expected 1)");
            }
            if (!callback.getParameters()[0].getType().isAssignableFrom(entityType)) {
              throw new GenerationException("JPA lifecycle listener method " + 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

   *         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

    ConstructorBlockBuilder<?> ctor = classBuilder.publicConstructor();
    final Collection<MetaClass> pages = ClassScanner.getTypesAnnotatedWith(Page.class, context);
    for (MetaClass pageClass : pages) {
      if (!pageClass.isAssignableTo(IsWidget.class)) {
        throw new GenerationException(
            "Class " + pageClass.getFullyQualifiedName() + " is annotated with @Page, so it must implement IsWidget");
      }
      Page annotation = pageClass.getAnnotation(Page.class);
      String pageName = getPageName(pageClass);
      List<Class<? extends PageRole>> annotatedPageRoles = Arrays.asList(annotation.role());

      MetaClass prevPageWithThisName = pageNames.put(pageName, pageClass);
      if (prevPageWithThisName != null) {
        throw new GenerationException(
            "Page names must be unique, but " + prevPageWithThisName + " and " + pageClass +
                " are both named [" + pageName + "]");
      }
      Statement pageImplStmt = generateNewInstanceOfPageImpl(pageClass, pageName);
      if (annotation.startingPage() || annotatedPageRoles.contains(DefaultPage.class)) {
        if (annotation.startingPage()) {
          pageRoles.put(DefaultPage.class, pageClass);
          logger.log(TreeLogger.Type.WARN, "You are using the deprecated statingPage place change to role = DefaultPage.class");
        }

        // need to assign the page impl to a variable and add it to the map twice
        ctor.append(Stmt.declareFinalVariable("defaultPage", PageNode.class, pageImplStmt));
        pageImplStmt = Variable.get("defaultPage");
        ctor.append(
            Stmt.nestedCall(Refs.get("pagesByName"))
                .invoke("put", "", pageImplStmt));
        ctor.append(
                Stmt.nestedCall(Refs.get("pagesByRole"))
                        .invoke("put", DefaultPage.class, pageImplStmt));
      }
      else if (pageName.equals("")) {
        throw new GenerationException(
            "Page " + pageClass.getFullyQualifiedName() + " has an empty path. Only the" +
                " page with startingPage=true is permitted to have an empty path.");
      }

      final String fieldName = StringUtils.uncapitalize(pageClass.getName());
View Full Code Here

  }

  private void validateDefaultPagePresent(Collection<MetaClass> pages, Multimap<Class<?>, MetaClass> pageRoles) {
    Collection<MetaClass> defaultPages = pageRoles.get(DefaultPage.class);
    if (!pages.isEmpty() && defaultPages.isEmpty()) {
      throw new GenerationException(
              "No @Page classes have role = DefaultPage. Exactly one @Page class" +
                      " must be designated as the default starting page.");
    }
  }
View Full Code Here

  private void createValidationError(Collection<MetaClass> pages, Class<?> role) {
    StringBuilder builder = new StringBuilder();
    for (MetaClass mc : pages) {
      builder.append("\n  ").append(mc.getFullyQualifiedName());
    }
    throw new GenerationException(
            "Found more than one @Page with role = '" + role + "': " + builder +
                    "\nExactly one @Page class must be designated with this unique role.");
  }
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.