Exemplo n.º 1
0
    public boolean apply() throws GenerationFailureException, GenerationCanceledException {
      try {
        DefaultTemplateContext context = new DefaultTemplateContext(myEnv, myApplicableNode, null);
        final QueryExecutionContext queryExecutor = myEnv.getQueryExecutor();
        SNode outputContextNode = queryExecutor.getContextNode(myRule, context);
        if (!checkContext(outputContextNode)) {
          return false;
        }

        try {
          queryExecutor.applyRule(myRule, context, outputContextNode);
        } catch (DismissTopMappingRuleException e) {
          myEnv
              .getLogger()
              .error(
                  myRule.getRuleNode(),
                  "wrong template: dismiss in weaving rule is not supported",
                  GeneratorUtil.describeInput(context));
        } catch (TemplateProcessingFailureException e) {
          myEnv
              .getLogger()
              .error(
                  myRule.getRuleNode(),
                  "weaving rule: error processing template fragment",
                  GeneratorUtil.describeInput(context));
        }
      } catch (GenerationCanceledException ex) {
        throw ex;
      } catch (GenerationFailureException ex) {
        throw ex;
      } catch (GenerationException e) {
        myEnv.getLogger().error(myRule.getRuleNode(), "internal error: " + e.toString());
      }
      return true; // original code did myGenerator.setChanged once checkContext had passed.
    }
Exemplo n.º 2
0
  // Note this is a bit of a integration test not a strict unit test
  @Test
  public void testFillingAMoreComplicatedBoundingRectangle() throws Exception {
    double xStart = 0.0;
    double xStop = 25.5;
    double yStart = 0.0;
    double yStop = 33.33;

    double xStep = 0.4;
    double yStep = 0.6;

    RectangularROI roi = new RectangularROI();
    roi.setPoint(Math.min(xStart, xStop), Math.min(yStart, yStop));
    roi.setLengths(Math.abs(xStop - xStart), Math.abs(yStop - yStart));

    RasterModel model = new RasterModel();
    model.setxStep(xStep);
    model.setyStep(yStep);

    // Get the point list
    IPointGenerator<RasterModel, Point> gen = service.createGenerator(model, roi);
    List<Point> pointList = gen.createPoints();

    int rows = (int) (Math.floor((xStop - xStart) / xStep) + 1);
    int cols = (int) (Math.floor((yStop - yStart) / yStep) + 1);
    // Check the list size
    assertEquals("Point list size should be correct", rows * cols, pointList.size());

    // Check some points
    assertEquals(new Point(0, xStart, 0, yStart), pointList.get(0));
    assertEquals(xStart + 3 * xStep, pointList.get(3).getX(), 1e-8);
    // TODO more

    GeneratorUtil.testGeneratorPoints(gen);
  }
Exemplo n.º 3
0
  @Test
  public void testFillingBoundingRectangle() throws Exception {
    // Create a simple bounding rectangle
    RectangularROI boundingRectangle = new RectangularROI(0, 0, 3, 3, 0);

    // Create a raster scan path
    RasterModel model = new RasterModel();
    model.setxStep(1);
    model.setyStep(1);

    // Get the point list
    IPointGenerator<RasterModel, Point> gen = service.createGenerator(model, boundingRectangle);
    List<Point> pointList = gen.createPoints();

    // Check correct number of points
    assertEquals(16, pointList.size());

    // Check some random points are correct
    assertEquals(0.0, pointList.get(0).getX(), 1e-8);
    assertEquals(0.0, pointList.get(0).getY(), 1e-8);

    assertEquals(3.0, pointList.get(3).getX(), 1e-8);
    assertEquals(0.0, pointList.get(3).getY(), 1e-8);

    assertEquals(3.0, pointList.get(7).getX(), 1e-8);
    assertEquals(1.0, pointList.get(7).getY(), 1e-8);

    assertEquals(3.0, pointList.get(11).getX(), 1e-8);
    assertEquals(2.0, pointList.get(11).getY(), 1e-8);

    GeneratorUtil.testGeneratorPoints(gen);
  }
Exemplo n.º 4
0
  public static void main(String[] args) {

    PropertyManager manager = PropertyManager.newInstance(args[0]);
    try {
      Generator generator = new JspToFaceletsTLD21Generator(manager);
      generator.generate(GeneratorUtil.getConfigBean(args[1]));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  } // END main
Exemplo n.º 5
0
  private ModifiersTree handleModifiersAndAnnotations(
      TreeMaker make,
      WorkingCopy workingCopy,
      String annotationType,
      Map<String, Object> annotationArguments)
      throws Exception {
    Set<Modifier> modifierSet = EnumSet.of(Modifier.PRIVATE);

    List<ExpressionTree> annoArgList = new ArrayList<ExpressionTree>();
    if (annotationArguments != null) {
      for (String key : annotationArguments.keySet()) {
        Object val = annotationArguments.get(key);
        ExpressionTree annoArg = GeneratorUtil.createAnnotationArgument(make, key, val);
        annoArgList.add(annoArg);
      }
    }
    AnnotationTree annotationTree =
        GeneratorUtil.createAnnotation(make, workingCopy, annotationType, annoArgList);

    return make.Modifiers(modifierSet, Collections.singletonList(annotationTree));
  }
Exemplo n.º 6
0
  // Note this is a bit of a integration test not a strict unit test
  @Test
  public void testFillingACircle() throws Exception {
    double xCentre = 0;
    double yCentre = 0;
    double radius = 1;

    CircularROI roi = new CircularROI();
    roi.setPoint(xCentre, yCentre);
    roi.setRadius(radius);

    RasterModel model = new RasterModel();
    model.setxStep(1);
    model.setyStep(1);

    // Get the point list
    IPointGenerator<RasterModel, Point> gen = service.createGenerator(model, roi);
    List<Point> pointList = gen.createPoints();

    // Check the length of the lists are equal
    assertEquals(5, pointList.size());

    // Check the points are correct and the order is maintained
    // 0
    assertEquals(0, pointList.get(0).getX(), 1e-8);
    assertEquals(-1, pointList.get(0).getY(), 1e-8);
    // 1
    assertEquals(-1, pointList.get(1).getX(), 1e-8);
    assertEquals(0, pointList.get(1).getY(), 1e-8);
    // 2
    assertEquals(0, pointList.get(2).getX(), 1e-8);
    assertEquals(0, pointList.get(2).getY(), 1e-8);
    // 3
    assertEquals(1, pointList.get(3).getX(), 1e-8);
    assertEquals(0, pointList.get(3).getY(), 1e-8);
    // 4
    assertEquals(0, pointList.get(4).getX(), 1e-8);
    assertEquals(1, pointList.get(4).getY(), 1e-8);

    GeneratorUtil.testGeneratorPoints(gen);
  }
Exemplo n.º 7
0
    private boolean checkContext(SNode contextNode) {
      TemplateGenerator generator = myEnv.getGenerator();

      if (contextNode == null) {
        myEnv
            .getLogger()
            .error(
                myRule.getRuleNode(),
                "weaving rule: cannot find context node",
                GeneratorUtil.describe(myApplicableNode, "input node"));
        return false;
      }
      // Additional check - context should be generated from the same root
      SNode contextRoot = contextNode.getContainingRoot();
      SModel model = contextRoot.getModel();
      if (model == null) {
        return reportErrorIfStrict(
            "bad context for weaving rule: no root for context " + contextNode);
      }

      SNode originalContextRoot = generator.getOriginalRootByGenerated(contextRoot);
      if (originalContextRoot == null) {
        return reportErrorIfStrict(
            String.format(
                "bad context for weaving rule: %s is generated by 'create root' rule",
                contextRoot));
      }

      if (myApplicableNode.getModel() == null) return true;

      SNode inputRoot = myApplicableNode.getContainingRoot();
      if (originalContextRoot != inputRoot) {
        String msg =
            "bad context for weaving rule: %s is generated from %s , while input node is from %s";
        return reportErrorIfStrict(String.format(msg, contextRoot, originalContextRoot, inputRoot));
      }

      return true;
    }
  public static void main(String[] args) throws Exception {

    PropertyManager propManager = PropertyManager.newInstance(args[0]);
    Generator generator = new AttributeManagerGenerator(propManager);
    generator.generate(GeneratorUtil.getConfigBean(args[1]));
  }
Exemplo n.º 9
0
  public void run(WorkingCopy workingCopy) throws Exception {
    try {
      workingCopy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);

      CompilationUnitTree cut = workingCopy.getCompilationUnit();
      ClassTree classTree = (ClassTree) cut.getTypeDecls().get(0);

      TreeMaker make = workingCopy.getTreeMaker();

      // Import org.glassfish.openesb.pojose.api.annotation.POJO
      //       org.glassfish.openesb.pojose.api.annotation.Operation

      CompilationUnitTree copy =
          make.addCompUnitImport(
              cut,
              make.Import(make.Identifier(GeneratorUtil.PROVIDER_QUAL_CLASS_ANNOTATION), false));
      // workingCopy.rewrite(cut, copy);
      // cut = workingCopy.getCompilationUnit();
      // classTree = (ClassTree) cut.getTypeDecls().get(0);

      CompilationUnitTree copy1 =
          make.addCompUnitImport(
              copy,
              make.Import(
                  make.Identifier(GeneratorUtil.POJO_QUAL_OPERATION_ANNOTATION_CLASS), false));

      copy =
          make.addCompUnitImport(
              copy1, make.Import(make.Identifier(GeneratorUtil.CTX_QUAL_CLASS_ANNOTATION), false));

      copy1 =
          make.addCompUnitImport(
              copy, make.Import(make.Identifier(GeneratorUtil.RSRC_QUAL_CLASS_ANNOTATION), false));

      workingCopy.rewrite(cut, copy1);
      cut = workingCopy.getCompilationUnit();
      classTree = (ClassTree) cut.getTypeDecls().get(0);

      // ADD POJO CLASS TYPE ANNOTATION
      /*
      Document dox = workingCopy.getDocument();
      Element[] arrayOfElements = dox.getRootElements();
      for ( Element el : arrayOfElements) {
         displayElements(el,0);
      }*/

      List<ExpressionTree> argumentValueList = new ArrayList<ExpressionTree>();
      if (annotationArguments != null) {
        Set<Map.Entry<String, Object>> annArgValSet = annotationArguments.entrySet();
        for (Map.Entry<String, Object> mapenty : annArgValSet) {
          argumentValueList.add(
              GeneratorUtil.createAnnotationArgument(make, mapenty.getKey(), mapenty.getValue()));
        }
      }
      AnnotationTree pojoAnnTypeTree =
          GeneratorUtil.createAnnotation(
              make, workingCopy, GeneratorUtil.PROVIDER_CLASS_ANNOTATION, argumentValueList);

      ModifiersTree oldTree = classTree.getModifiers();
      ModifiersTree newTree = make.Modifiers(oldTree, Collections.singletonList(pojoAnnTypeTree));
      workingCopy.rewrite(oldTree, newTree);
      cut = workingCopy.getCompilationUnit();
      classTree = (ClassTree) cut.getTypeDecls().get(0);

      ModifiersTree modifiers =
          handleModifiersAndAnnotations(make, workingCopy, GeneratorUtil.RSRC_ANNOTATION, null);

      VariableTree variableTree =
          GeneratorUtil.createField(
              make,
              workingCopy,
              modifiers,
              GeneratorUtil
                  .POJO_CTX_VARIABLE, // TODO: Check if this variable is not used by this class.
              GeneratorUtil.CTX_ANNOTATION, // NOI18N
              null);

      ClassTree newClassTree1 = make.addClassMember(classTree, variableTree);
      // workingCopy.rewrite(classTree, newClassTree1);

      // CompilationUnitTree modClassTree = make.addCompUnitTypeDecl(cut, pojoAnnTypeTree);
      // workingCopy.rewrite(cut, modClassTree);
      cut = workingCopy.getCompilationUnit();
      classTree = newClassTree1; // (ClassTree) cut.getTypeDecls().get(0);
      // ADD POJO OPERATION.
      boolean bOperationReturnsVoid =
          methodReturnType == null || methodReturnType.equals(GeneratorUtil.GENERATE_VOID);
      argumentValueList = new ArrayList<ExpressionTree>();
      if (!bOperationReturnsVoid && this.operationArguments != null) {
        Set<Map.Entry<String, Object>> annArgValSet = operationArguments.entrySet();
        for (Map.Entry<String, Object> mapenty : annArgValSet) {
          argumentValueList.add(
              GeneratorUtil.createAnnotationArgument(make, mapenty.getKey(), mapenty.getValue()));
        }
      }
      AnnotationTree anTree =
          GeneratorUtil.createAnnotation(make, workingCopy, annotationType, argumentValueList);
      Tree returnType = null;
      boolean bReturnVoid = false;
      if (bOperationReturnsVoid) {
        returnType = make.PrimitiveType(TypeKind.VOID); // return type
        bReturnVoid = true;
      } else {
        returnType = GeneratorUtil.createType(make, workingCopy, methodReturnType);
      }

      List<TypeParameterTree> listOfInputTypes = new ArrayList<TypeParameterTree>();
      List<VariableTree> listOfInputVariables = new ArrayList<VariableTree>();
      //   ModifiersTree modTree = make.Modifiers(Collections.singleton(Modifier.PUBLIC));
      ModifiersTree parMods = make.Modifiers(Collections.EMPTY_SET, Collections.EMPTY_LIST);

      int ix = 0;
      String inputVariableName = null;
      String inputVariableType = null;
      VariableTree inputIdentifier = null;
      for (String argumentType : methodArgumentType) {
        if (!argumentType.equals("")) {
          //  listOfInputTypes.add(  make.TypeParameter(argumentType, null));
          inputVariableName = GeneratorUtil.POJO_VARIABLE_NAME_PREFIX + (ix++);
          inputVariableType = argumentType;
          inputIdentifier =
              GeneratorUtil.createField(
                  make,
                  workingCopy,
                  parMods
                  /** modTree* */
                  ,
                  inputVariableName,
                  argumentType,
                  null);
          listOfInputVariables.add(inputIdentifier);
        }
      }

      BlockTree blockTree = null;
      if (bReturnVoid) {
        blockTree = make.Block(Collections.EMPTY_LIST, false);
      } else {
        // List<ExpressionTree> returnExpList =
        // Collections.singletonList((ExpressionTree)make.Identifier("null"));
        if (inputVariableType != null
            && this.methodReturnType != null
            && methodReturnType.equals(inputVariableType)) {
          ReturnTree retTree = make.Return(make.Identifier(inputVariableName));
          blockTree = make.Block(Collections.singletonList(retTree), false);

        } else {
          ReturnTree retTree = make.Return(make.Identifier("null"));
          blockTree = make.Block(Collections.singletonList(retTree), false);
        }
      }

      MethodTree newMethod =
          make.Method(
              make.Modifiers(
                  Collections.singleton(Modifier.PUBLIC), // modifiers
                  Collections.singletonList(anTree)), // modifiers and annotations
              methodName, // name
              returnType, // return type
              Collections.EMPTY_LIST, // listOfInputTypes, // type parameters for parameters
              listOfInputVariables, // parameters
              Collections.EMPTY_LIST,
              blockTree, // empty statement block
              null // default value - not applicable here, used by annotations
              );
      ClassTree oldClassTree = (ClassTree) cut.getTypeDecls().get(0);
      ClassTree newClassTree = make.addClassMember(classTree, newMethod);
      workingCopy.rewrite(oldClassTree, newClassTree);
    } catch (Exception e) {
      myException = e;
      throw e;
    }
  }
Exemplo n.º 10
0
  /** The tags for this TLD. */
  protected void writeTags() throws IOException {
    writer.writeComment("===================== HTML 4.0 basic tags ======================");

    Map<String, ComponentBean> componentsByComponentFamily =
        GeneratorUtil.getComponentFamilyComponentMap(configBean);
    Map<String, ArrayList<RendererBean>> renderersByComponentFamily =
        GeneratorUtil.getComponentFamilyRendererMap(
            configBean, propManager.getProperty(PropertyManager.RENDERKIT_ID));
    String targetPackage = propManager.getProperty(PropertyManager.TARGET_PACKAGE);

    for (Map.Entry entry : renderersByComponentFamily.entrySet()) {

      String componentFamily = (String) entry.getKey();
      List<RendererBean> renderers = (List<RendererBean>) entry.getValue();
      for (Iterator<RendererBean> rendererIter = renderers.iterator(); rendererIter.hasNext(); ) {

        RendererBean renderer = rendererIter.next();

        if (renderer.isIgnoreAll()) {
          continue;
        }
        String rendererType = renderer.getRendererType();
        writer.startElement("tag");

        DescriptionBean description = renderer.getDescription("");
        if (description != null) {
          String descriptionText = description.getDescription().trim();

          if (descriptionText != null) {
            writer.startElement("description");
            StringBuffer sb = new StringBuffer();
            sb.append("<![CDATA[");
            sb.append(descriptionText);
            sb.append("]]>\n");
            writer.writeText(sb.toString());
            writer.closeElement();
          }
        }

        String tagName = renderer.getTagName();

        if (tagName == null) {
          tagName =
              makeTldTagName(
                  GeneratorUtil.stripJavaxFacesPrefix(componentFamily),
                  GeneratorUtil.stripJavaxFacesPrefix(rendererType));
        }

        if (tagName == null) {
          throw new IllegalStateException("Could not determine tag name");
        }

        writer.startElement("name");
        writer.writeText(tagName);
        writer.closeElement();

        if (GeneratorUtil.makeTagClassName(
                GeneratorUtil.stripJavaxFacesPrefix(componentFamily),
                GeneratorUtil.stripJavaxFacesPrefix(rendererType))
            == null) {
          throw new IllegalStateException("Could not determine tag class name");
        }

        writer.startElement("tag-class");
        writer.writeText(
            targetPackage
                + '.'
                + GeneratorUtil.makeTagClassName(
                    GeneratorUtil.stripJavaxFacesPrefix(componentFamily),
                    GeneratorUtil.stripJavaxFacesPrefix(rendererType)));
        writer.closeElement();

        writer.startElement("body-content");
        writer.writeText(getBodyContent(tagName));
        writer.closeElement();

        // Generate tag attributes
        //

        // Component Properties first...
        //
        ComponentBean component = componentsByComponentFamily.get(componentFamily);

        PropertyBean[] properties = component.getProperties();
        PropertyBean property;

        for (int i = 0, len = properties.length; i < len; i++) {
          if (null == (property = properties[i])) {
            continue;
          }
          if (!property.isTagAttribute()) {
            continue;
          }

          writer.startElement("attribute");

          description = property.getDescription("");
          if (description != null) {
            String descriptionText = description.getDescription().trim();

            if (descriptionText != null) {
              writer.startElement("description");
              StringBuffer sb = new StringBuffer();
              sb.append("<![CDATA[");
              sb.append(descriptionText);
              sb.append("]]>\n");
              writer.writeText(sb.toString());
              writer.closeElement();
            }
          }

          String propertyName = property.getPropertyName();

          writer.startElement("name");
          writer.writeText(propertyName);
          writer.closeElement();

          writer.startElement("required");
          writer.writeText(
              property.isRequired() ? Boolean.TRUE.toString() : Boolean.FALSE.toString());
          writer.closeElement();

          if (!"id".equals(propertyName)) {

            if (property.isMethodExpressionEnabled()) {
              writer.startElement("deferred-method");
              writer.startElement("method-signature");
              writer.writeText(property.getMethodSignature());
              writer.closeElement(2);
            } else if (property.isValueExpressionEnabled()) {
              // PENDING FIX ME
              String type = property.getPropertyClass();
              //                            String wrapperType = (String)
              //                                GeneratorUtil.convertToPrimitive(type);
              //                            if (wrapperType != null) {
              //                                type = wrapperType;
              //                            }
              writer.startElement("deferred-value");
              writer.startElement("type");
              writer.writeText(type);
              writer.closeElement(2);
            } else {
              writer.startElement("rtexprvalue");
              writer.writeText(getRtexprvalue(tagName, propertyName));
              writer.closeElement();
            }
          } else {
            writer.startElement("rtexprvalue");
            writer.writeText(getRtexprvalue(tagName, propertyName));
            writer.closeElement();
          }

          writer.closeElement(); // closes attribute element above
        } // END property FOR loop

        // Renderer Attributes Next...
        //
        AttributeBean[] attributes = renderer.getAttributes();
        AttributeBean attribute;
        for (int i = 0, len = attributes.length; i < len; i++) {
          if (null == (attribute = attributes[i])) {
            continue;
          }
          if (!attribute.isTagAttribute()) {
            continue;
          }
          if (attributeShouldBeExcluded(renderer, attribute.getAttributeName())) {
            continue;
          }

          writer.startElement("attribute");

          description = attribute.getDescription("");
          if (description != null) {
            String descriptionText = description.getDescription().trim();

            if (descriptionText != null) {
              writer.startElement("description");
              StringBuffer sb = new StringBuffer();
              sb.append("<![CDATA[");
              sb.append(descriptionText);
              sb.append("]]>\n");
              writer.writeText(sb.toString());
              writer.closeElement();
            }
          }

          String attributeName = attribute.getAttributeName();

          writer.startElement("name");
          writer.writeText(attributeName);
          writer.closeElement();

          writer.startElement("required");
          writer.writeText(
              attribute.isRequired() ? Boolean.TRUE.toString() : Boolean.FALSE.toString());
          writer.closeElement();

          if (!"id".equals(attributeName)) {
            // PENDING FIX ME
            String type = attribute.getAttributeClass();
            // String wrapperType = (String)
            //  GeneratorUtil.convertToPrimitive(type);
            // if (wrapperType != null) {
            //    type = wrapperType;
            // }
            writer.startElement("deferred-value");
            writer.startElement("type");
            writer.writeText(type);
            writer.closeElement(2);

          } else {
            writer.startElement("rtexprvalue");
            writer.writeText(getRtexprvalue(tagName, attributeName));
            writer.closeElement();
          }

          writer.closeElement(); // closes attribute element above
        } // END attribute FOR loop

        // SPECIAL: "Binding" needs to exist on every tag..
        writer.startElement("attribute");

        writer.startElement("description");
        writer.writeText(
            "The ValueExpression linking this component to a property in a backing bean");
        writer.closeElement();

        writer.startElement("name");
        writer.writeText("binding");
        writer.closeElement();

        writer.startElement("required");
        writer.writeText("false");
        writer.closeElement();

        writer.startElement("deferred-value");
        writer.startElement("type");
        writer.writeText("javax.faces.component.UIComponent");
        writer.closeElement(2);

        // close the most recent attribute, and tag
        // elements
        writer.closeElement(2);
      }
    }

    // Include any other tags defined in the optional tag definition file.
    // These might be tags that were not picked up because they have no renderer
    // - for example "column".
    String tagDef = loadOptionalTags();
    if (tagDef != null) {
      writer.write(tagDef);
    }
  } // END writeTags