Examples of GenerationException


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

      }

      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

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

   *         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

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

            }
            continue;
          }

          if (method.getParameters().length > 0) {
            throw new GenerationException("Method " + method + " in " + typeToSnapshot +
                    " takes parameters. Such methods must be handled by the MethodBodyCallback," +
                    " because they cannot be snapshotted.");
          }

          if (method.getReturnType().equals(void.class)) {
            builder.publicOverridesMethod(method.getName()).finish();
            if (logger.isDebugEnabled()) {
              logger.debug("  finished method " + method.getName());
            }
            continue;
          }
          try {

            final Object retval = typeToExtend.asClass().getMethod(method.getName()).invoke(o);
            methodReturnVals.put(retval, method);

            if (logger.isDebugEnabled()) {
              logger.debug("    retval=" + retval);
            }

            Statement methodBody;
            if (existingSnapshots.containsKey(retval)) {
              logger.debug("    using existing snapshot");
              methodBody = existingSnapshots.get(retval);
            }
            else if (subContext.isLiteralizableClass(method.getReturnType().getErased())) {
              if (unfinishedSnapshots.contains(retval)) {
                throw new CyclicalObjectGraphException(unfinishedSnapshots);
              }

              // use Stmt.create(context) to pass the context along.
              if (logger.isDebugEnabled()) {
                logger.debug("    >> recursing for " + retval);
              }

              methodBody = Stmt.create(subContext).nestedCall(makeSnapshotAsSubclass(
                  retval, method.getReturnType(), method.getReturnType(),
                  methodBodyCallback, typesToRecurseOn, existingSnapshots, unfinishedSnapshots)).returnValue();
            }
            else {
              logger.debug("    relying on literal factory");
              methodBody = Stmt.load(retval).returnValue();
            }

            if (logger.isDebugEnabled()) {
              logger.debug("  finished method " + method.getName());
            }

            builder.publicOverridesMethod(method.getName()).append(methodBody).finish();
            existingSnapshots.put(retval, methodBody);
          }
          catch (GenerationException e) {
            e.appendFailureInfo("In attempt to snapshot return value of "
                + typeToExtend.getFullyQualifiedName() + "." + method.getName() + "()");
            throw e;
          }
          catch (RuntimeException e) {
            throw e;
          }
          catch (Exception e) {
            throw new GenerationException("Failed to extract value for snapshot", e);
          }
        }

        if (logger.isDebugEnabled()) {
          logger.debug("    finished: " + builder);
View Full Code Here

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

      // 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) {
        // TODO log this
      }

      // 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);
    // For each one, generate the code to load the translation and put that generated
    // code in the c'tor of the generated class (GeneratedTranslationService)
    for (MetaClass bundleAnnotatedClass : bundleAnnotatedClasses) {
      String bundlePath = getMessageBundlePath(bundleAnnotatedClass);

      // Skip if we've already processed this bundle.
      if (processedBundles.contains(bundlePath)) {
        continue;
      }

      // Now get all files in the message bundle (all localized versions)
      // TODO optimize this - scan the classpath once and then pull out just the resources we need
      MessageBundleScanner scanner = new MessageBundleScanner(
              new ConfigurationBuilder()
                  .filterInputsBy(new FilterBuilder().include(".*json"))
                  .setUrls(ClasspathHelper.forClassLoader())
                  .setScanners(new MessageBundleResourceScanner(bundlePath)));
      Collection<String> resources = scanner.getStore().get(MessageBundleResourceScanner.class).values();
      // 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.
      for (String resource : resources) {
View Full Code Here

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

   */
  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

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

    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

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

      // Check if the bound property exists in data model type
      Bound bound = ctx.getAnnotation();
      String property = bound.property().equals("") ? ctx.getMemberName() : bound.property();
      if (!DataBindingValidator.isValidPropertyChain(binderLookup.getDataModelType(), property)) {
        throw new GenerationException("Invalid binding of field " + ctx.getMemberName()
            + " in class " + ctx.getInjector().getInjectedType() + "! Property " + property
            + " not resolvable from class " + binderLookup.getDataModelType()
            + "! Hint: Is " + binderLookup.getDataModelType() + " marked as @Bindable? When binding to a "
            + "property chain, all properties but the last in a chain must be of a @Bindable type!");
      }

      Statement widget = ctx.getValueStatement();
      // Ensure the @Bound field or method provides a widget or DOM element
      MetaClass widgetType = ctx.getElementTypeOrMethodReturnType();
      if (widgetType.isAssignableTo(Widget.class)) {
        // Ensure @Bound widget field is initialized
        if (!ctx.isAnnotationPresent(Inject.class) && ctx.getField() != null && widgetType.isDefaultInstantiable()) {
          Statement widgetInit = Stmt.invokeStatic(
              ctx.getInjectionContext().getProcessingContext().getBootstrapClass(),
              PrivateAccessUtil.getPrivateFieldInjectorName(ctx.getField()),
              Refs.get(ctx.getInjector().getInstanceVarName()),
              ObjectBuilder.newInstanceOf(widgetType));

          statements.add(If.isNull(widget).append(widgetInit).finish());
        }
      }
      else if (widgetType.isAssignableTo(Element.class)) {
        widget = Stmt.invokeStatic(ElementWrapperWidget.class, "getWidget", widget);
      }
      else {
        throw new GenerationException("@Bound field or method " + ctx.getMemberName()
            + " in class " + ctx.getInjector().getInjectedType()
            + " must provide a widget or DOM element type but provides: "
            + widgetType.getFullyQualifiedName());
      }

      // Generate the binding
      Statement conv = bound.converter().equals(Bound.NO_CONVERTER.class) ? null : Stmt.newObject(bound.converter());
      statements.add(Stmt.loadVariable("binder").invoke("bind", widget, property, conv));
    }
    else {
      throw new GenerationException("No @Model or @AutoBound data binder found for @Bound field or method "
          + ctx.getMemberName() + " in class " + ctx.getInjector().getInjectedType());
    }

    // The first decorator to run will generate the initialization callback, the subsequent
    // decorators (for other bound widgets of the same class) will just amend the block.
View Full Code Here

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

            .getInjectedType(), Model.class);

    if (!beanMetric.getAllInjectors().isEmpty()) {
      final Collection<Object> allInjectors = beanMetric.getAllInjectors();
      if (allInjectors.size() > 1) {
        throw new GenerationException("Multiple @Models injected in " + inst.getEnclosingType());
      }
      else if (allInjectors.size() == 1) {
        final Object injectorElement = allInjectors.iterator().next();

        if (injectorElement instanceof MetaConstructor || injectorElement instanceof MetaMethod) {
          final MetaParameter mp = beanMetric.getConsolidatedMetaParameters().iterator().next();

          dataModelType = mp.getType();
          assertTypeIsBindable(dataModelType);
          dataBinderRef = inst.getTransientValue(TRANSIENT_BINDER_VALUE, DataBinder.class);
          inst.ensureMemberExposed();
        }
        else {
          final MetaField field = (MetaField) allInjectors.iterator().next();

          dataModelType = field.getType();
          assertTypeIsBindable(dataModelType);

          dataBinderRef = inst.getTransientValue(TRANSIENT_BINDER_VALUE, DataBinder.class);
          inst.getInjectionContext().addExposedField(field, PrivateAccessType.Both);
        }
        return new DataBinderRef(dataModelType, dataBinderRef);
      }
    }
    else {
      List<MetaField> modelFields = inst.getInjector().getInjectedType().getFieldsAnnotatedWith(Model.class);
      if (!modelFields.isEmpty()) {
        throw new GenerationException("Found one or more fields annotated with @Model but missing @Inject "
                + modelFields.toString());
      }

      List<MetaParameter> modelParameters = inst.getInjector().getInjectedType()
              .getParametersAnnotatedWith(Model.class);
      if (!modelParameters.isEmpty()) {
        throw new GenerationException(
                "Found one or more constructor or method parameters annotated with @Model but missing @Inject "
                        + modelParameters.toString());
      }
    }
View Full Code Here

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

    InjectUtil.BeanMetric beanMetric = InjectUtil.getFilteredBeanMetric(inst.getInjectionContext(), inst.getInjector()
            .getInjectedType(), AutoBound.class);

    final Collection<Object> allInjectors = beanMetric.getAllInjectors();
    if (allInjectors.size() > 1) {
      throw new GenerationException("Multiple @AutoBound data binders injected in " + inst.getEnclosingType());
    }
    else if (allInjectors.size() == 1) {
      final Object injectorElement = allInjectors.iterator().next();

      if (injectorElement instanceof MetaConstructor || injectorElement instanceof MetaMethod) {
View Full Code Here

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

   */
  private static void assertTypeIsDataBinder(MetaClass type) {
    final MetaClass databinderMetaClass = MetaClassFactory.get(DataBinder.class);

    if (!databinderMetaClass.isAssignableFrom(type)) {
      throw new GenerationException("Type of @AutoBound element must be " + DataBinder.class.getName() + " but is: "
              + type.getFullyQualifiedName());
    }
  }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.