private void writeSignaller(SignallerPojo pojo) {
    try {
      Writer entityFactoryWriter =
          filerUtils
              .createSourceFile(pojo.packageName + QUALIFIER + pojo.name + FACTORY_SUFFIX)
              .openWriter();
      MustacheEngine.INSTANCE.getFactoryMustache().execute(entityFactoryWriter, pojo).flush();
      entityFactoryWriter.close();

      Writer entitySignalsWriter =
          filerUtils
              .createSourceFile(pojo.packageName + QUALIFIER + pojo.name + IMPLEMENTATION_SUFFIX)
              .openWriter();
      MustacheEngine.INSTANCE
          .getImplementationMustache()
          .execute(entitySignalsWriter, pojo)
          .flush();
      entitySignalsWriter.close();

      Writer wrapperWriter =
          filerUtils
              .createSourceFile(pojo.packageName + QUALIFIER + pojo.name + WRAPPER_SUFFIX)
              .openWriter();
      MustacheEngine.INSTANCE.getWrapperMustache().execute(wrapperWriter, pojo).flush();
      wrapperWriter.close();
    } catch (IOException e) {
      messagerUtils.printMessage(Kind.ERROR, e.getMessage());
    }
  }
  /**
   * ソース生成.
   *
   * @throws IOException
   * @author vvakame
   */
  public void write() throws IOException {

    Filer filer = processingEnv.getFiler();
    String generateClassName = classElement.asType().toString() + postfix;
    JavaFileObject fileObject = filer.createSourceFile(generateClassName, classElement);
    Template.write(fileObject, g);
  }
Пример #3
0
  /**
   * Velocity の実行(Javaソース用)。出力先はパッケージ名とクラス名から自動生成。
   *
   * @param context VelocityContext
   * @param pkgName パッケージ名
   * @param clsName クラス名
   * @param templ Velocityテンプレート名。
   * @throws Exception
   */
  protected void applyTemplate(
      VelocityContext context, String pkgName, String clsName, String templ) throws Exception {
    context.put("packageName", pkgName);
    context.put("className", clsName);
    context.put("environment", environment);

    Template template = getVelocityTemplate(templ);
    Filer filer = environment.getFiler();
    JavaFileObject file = filer.createSourceFile(pkgName + '.' + clsName);
    PrintWriter writer = new PrintWriter(file.openWriter());
    template.merge(context, writer);
    writer.close();
  }
  @Override
  public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
    Map<TypeElement, BindingClass> targetClassMap = findAndParseTargets(env);

    for (Map.Entry<TypeElement, BindingClass> entry : targetClassMap.entrySet()) {
      TypeElement typeElement = entry.getKey();
      BindingClass bindingClass = entry.getValue();

      try {
        JavaFileObject jfo = filer.createSourceFile(bindingClass.getFqcn(), typeElement);
        Writer writer = jfo.openWriter();
        writer.write(bindingClass.brewJava());
        writer.flush();
        writer.close();
      } catch (IOException e) {
        error(
            typeElement,
            "Unable to write view binder for type %s: %s",
            typeElement,
            e.getMessage());
      }
    }

    return true;
  }
Пример #5
0
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   // check if process was done on previous round
   if (OcelotProcessor.isDone()
       || roundEnv.processingOver()) { // Returns true if types generated by this round will not be
     // subject to a subsequent round of annotation processing; returns
     // false otherwise.
     return true; // if is it : stop
   }
   // Create provider of ocelot-services.js
   String js = createJSServicesProvider();
   // Create file ocelot-services.js
   try {
     FileObject resource = filer.createResource(StandardLocation.CLASS_OUTPUT, "", js);
     try (Writer writer = resource.openWriter()) {
       ElementVisitor visitor = new DataServiceVisitor(processingEnv);
       for (Element element : roundEnv.getElementsAnnotatedWith(DataService.class)) {
         messager.printMessage(
             Diagnostic.Kind.MANDATORY_WARNING, " javascript generation class : " + element);
         element.accept(visitor, writer);
       }
     }
   } catch (IOException e) {
     messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage());
   }
   OcelotProcessor.setDone(true);
   return true;
 }
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   try {
     Set<? extends Element> set = roundEnv.getElementsAnnotatedWith(Parcelable.class);
     for (Element element : set) {
       try {
         TypeElement enclosingElement = (TypeElement) element;
         ProxyInfo pi = new ProxyInfo(enclosingElement.getQualifiedName().toString());
         writeLog(pi.getFullName());
         JavaFileObject jfo = filer.createSourceFile(pi.getFullName(), enclosingElement);
         Writer writer = jfo.openWriter();
         writeLog(pi.createCode());
         writer.write(pi.createCode());
         writer.flush();
         writer.close();
         writeLog("ok");
       } catch (Exception e) {
         e.printStackTrace();
         writeLog(e.getMessage());
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
     writeLog(e.getMessage());
   }
   return true;
 }
Пример #7
0
  private void generateOptionProcessor(final Filer filer, final HashMap<String, String> values)
      throws Exception {

    final String generatedClassName = className + "Processor";

    final JavaFileObject source = filer.createSourceFile(generatedClassName);
    final Writer writer = source.openWriter();

    writer.write("/* Generated on " + new Date() + " */\n");
    writer.write("public class " + generatedClassName + " {\n");
    writer.write("\tpublic static " + className + " process(String[] args) {\n");
    writer.write("\t\t" + className + " options = new " + className + "();\n");
    writer.write("\t\tint idx = 0;\n");
    writer.write("\t\twhile (idx < args.length) {\n");

    for (final String key : values.keySet()) {
      writer.write("\t\t\tif (args[idx].equals(\"" + key + "\")) {\n");
      writer.write("\t\t\t\toptions." + values.get(key) + " = args[++idx];\n");
      writer.write("\t\t\t\tidx++;\n");
      writer.write("\t\t\t\tcontinue;\n");
      writer.write("\t\t\t}\n");
    }

    writer.write("\t\t\tSystem.err.println(\"Unknown option: \" + args[idx++]);\n");
    writer.write("\t\t}\n");
    writer.write("\t\treturn (options);\n");
    writer.write("\t}\n");
    writer.write("}");
    writer.flush();
    writer.close();
  }
Пример #8
0
  /**
   * Velocity の実行(リソース用)。出力先はパッケージ名とリソース名から自動生成。
   *
   * @param context VelocityContext
   * @param pkgName パッケージ名
   * @param resName リソース名
   * @param templ Velocityテンプレート名。
   * @throws Exception
   */
  public void applyTemplateText(
      VelocityContext context, String pkgName, String resName, String templ) throws Exception {
    context.put("packageName", pkgName);
    context.put("resourceName", resName);
    context.put("environment", environment);

    Template template = getVelocityTemplate(templ);

    String resFullPath = pkgName.replace('.', '/') + "/" + resName;
    Filer filer = environment.getFiler();
    FileObject file =
        filer.createResource(StandardLocation.SOURCE_OUTPUT, "", resFullPath, (Element[]) null);
    PrintWriter writer = new PrintWriter(file.openWriter());
    template.merge(context, writer);
    writer.close();
  }
Пример #9
0
  private void generateXLogProcessor(
      String classSuffix, List<MethodToLog> methodToLogs, List<String> classNames) {
    StringBuilder methodsSb = new StringBuilder();
    methodsSb.append("[");
    if (methodToLogs != null) {
      for (int i = 0; i < methodToLogs.size(); i++) {
        methodsSb.append(methodToLogs.get(i).toString());
        if (i < methodToLogs.size() - 1) {
          methodsSb.append(",");
        }
      }
    }
    methodsSb.append("]");

    String methodToLogStr = methodsSb.toString();

    StringBuilder classSb = new StringBuilder();
    classSb.append("[");
    if (methodToLogs != null) {
      for (int i = 0; i < classNames.size(); i++) {
        classSb.append(classNames.get(i).toString());
        if (i < classNames.size() - 1) {
          classSb.append(",");
        }
      }
    }
    classSb.append("]");

    String classNamesStr = classSb.toString();

    System.out.println(methodToLogStr);

    try {
      JavaFileObject jfo =
          filer.createSourceFile(XLogUtils.PKG_NAME + "." + XLogUtils.CLASS_NAME + classSuffix);
      Writer writer = jfo.openWriter();
      writer.write(brewJava(methodToLogStr, classNamesStr, classSuffix));
      writer.flush();
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Пример #10
0
 /**
  * Create provider of ocelot-services.js and return a part of unic name for ocelot-service.js
  *
  * @return
  */
 private String createJSServicesProvider() {
   // Creation du provider de ocelot-services.js
   String prefix = "srv_" + RANDOM.nextInt(100_000_000);
   try {
     FileObject servicesProvider = filer.createSourceFile(prefix + ".ServiceProvider");
     try (Writer writer = servicesProvider.openWriter()) {
       writer.append("package " + prefix + ";\n");
       writer.append("import org.ocelotds.AbstractServiceProvider;\n");
       writer.append("public class ServiceProvider extends AbstractServiceProvider {\n");
       writer.append("	@Override\n");
       writer.append("	protected String getJsFilename() {\n");
       writer.append("		return \"" + prefix + ".js\";\n");
       writer.append("	}\n");
       writer.append("}");
     }
   } catch (IOException e) {
     messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage());
   }
   return prefix + ".js";
 }
Пример #11
0
  @Override
  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {

    Set<? extends Element> elements = env.getElementsAnnotatedWith(Struct.class);

    for (Element element : elements) {

      String pakage = eltUtils.getPackageOf(element).toString();

      try {
        Struct struct = element.getAnnotation(Struct.class);
        String headerRelPath = struct.header();
        // yes, this is a hack but there are simple to many bugs in this api.
        // e.g.: 6647998
        FileObject header = filer.getResource(StandardLocation.SOURCE_PATH, pakage, headerRelPath);

        String root = basedir;
        File headerFile = null;
        if (header.toUri().isAbsolute()) {
          headerFile = new File(header.toUri());

          root = headerFile.getAbsolutePath();
          root = root.substring(0, root.length() - headerFile.getName().length() - 1);
          root = root.substring(0, root.length() - pakage.length()) + "../";
        } else {
          root = System.getProperty("user.dir");
          headerFile = new File(root + separator + header.toUri());
        }

        System.out.println("processing header: " + header.toUri());

        generateStructBinding(element, struct, root, pakage, headerFile);
      } catch (IOException ex) {
        throw new RuntimeException("IOException encountered, run if you can!", ex);
      }
    }
    return true;
  }
Пример #12
0
  @Override
  @SuppressWarnings("unchecked")
  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
      return false;
    }

    Set<String> beans = new TreeSet<String>();

    // JavaBean is a type only annotation, so cast to TypeElement is safe
    for (TypeElement type : (Set<TypeElement>) roundEnv.getElementsAnnotatedWith(JavaBean.class)) {
      beans.add(type.getQualifiedName().toString());
    }

    // remove any existing values; we append to the file
    Filer filer = processingEnv.getFiler();

    FileObject manifest = null;

    try {
      processingEnv.getMessager().printMessage(Kind.NOTE, "Attempting to open manifest...");

      manifest = filer.getResource(StandardLocation.SOURCE_PATH, "", "META-INF/MANIFEST.MF");

      if (manifest != null) {
        processingEnv.getMessager().printMessage(Kind.NOTE, "Succeeded: " + manifest.getName());

        BufferedReader r = null;

        try {
          processingEnv
              .getMessager()
              .printMessage(Kind.NOTE, "Attempting to find previously defined Java beans");

          r = new BufferedReader(new InputStreamReader(manifest.openInputStream(), "UTF-8"));

          String possibleBean = null;

          for (String line = r.readLine(); line != null; line = r.readLine()) {
            if (possibleBean == null) {
              if (line.startsWith("Name: ") && line.endsWith(".class")) {
                possibleBean =
                    line.substring("Name: ".length(), line.length() - ".class".length())
                        .replace('/', '.');

                try {
                  Class.forName(possibleBean);
                } catch (ClassNotFoundException notABean) {
                  possibleBean = null;
                }
              }
            } else {
              if (line.equals("Java-Bean: True")) {
                processingEnv
                    .getMessager()
                    .printMessage(Kind.NOTE, possibleBean + " already defined");
                beans.remove(possibleBean);
              }

              possibleBean = null;
            }
          }

          r.close();

        } catch (FileNotFoundException ignore) {
          processingEnv.getMessager().printMessage(Kind.NOTE, "Manifest not found");
        } catch (IOException e) {
          throw new RuntimeException("Failed to read current Java-Bean information", e);
        } finally {
          if (r != null) {
            try {
              r.close();
            } catch (IOException ignore) {
            }
          }
        }
      }
    } catch (FileNotFoundException ignore) {
      // no file to process
      processingEnv.getMessager().printMessage(Kind.NOTE, "Manifest does not exist...");
    } catch (IOException e) {
      processingEnv
          .getMessager()
          .printMessage(
              Kind.ERROR, "Failed to load existing manifest for Java-Bean processing:\n" + e);

      return false;
    }

    try {
      processingEnv
          .getMessager()
          .printMessage(Kind.NOTE, "Attempting to create output manifest...");

      manifest = filer.createResource(StandardLocation.SOURCE_OUTPUT, "", "META-INF/MANIFEST.MF");

      processingEnv.getMessager().printMessage(Kind.NOTE, "Succeeded: " + manifest.getName());
    } catch (IOException e) {
      processingEnv
          .getMessager()
          .printMessage(Kind.ERROR, "Cannot create manifest for Java-Bean processing:\n" + e);

      return false;
    }

    processingEnv.getMessager().printMessage(Kind.NOTE, "Appending Java-Beans to MANIFEST.MF");
    processingEnv.getMessager().printMessage(Kind.NOTE, beans.toString());

    PrintWriter pw = null;

    try {
      pw = new PrintWriter(new OutputStreamWriter(manifest.openOutputStream(), "UTF-8"));

      pw.println();

      for (String value : beans) {
        pw.println("Name: " + value + ".class");
        pw.println("Java-Bean: True");
        pw.println();
      }
    } catch (IOException e) {
      throw new RuntimeException("Failed to write Java-Bean information", e);
    } finally {
      if (pw != null) {
        pw.close();
      }
    }

    return false;
  }
Пример #13
0
  @Override
  public boolean process(
      final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnvironment) {
    // Get all classes that has the annotation
    Set<? extends Element> classElements =
        roundEnvironment.getElementsAnnotatedWith(BoundBox.class);
    // For each class that has the annotation
    for (final Element classElement : classElements) {

      // Get the annotation information
      TypeElement boundClass = null;
      String maxSuperClass = null;
      String[] prefixes = null;
      String boundBoxPackageName = null;

      List<? extends AnnotationValue> extraBoundFields = null;
      List<? extends AnnotationMirror> listAnnotationMirrors = classElement.getAnnotationMirrors();
      if (listAnnotationMirrors == null) {
        messager.printMessage(Kind.WARNING, "listAnnotationMirrors is null", classElement);
        return true;
      }

      StringBuilder message = new StringBuilder();
      for (AnnotationMirror annotationMirror : listAnnotationMirrors) {
        log.info("mirror " + annotationMirror.getAnnotationType());
        Map<? extends ExecutableElement, ? extends AnnotationValue> map =
            annotationMirror.getElementValues();
        for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
            map.entrySet()) {
          message.append(entry.getKey().getSimpleName().toString());
          message.append("\n");
          message.append(entry.getValue().toString());
          if (BOUNDBOX_ANNOTATION_PARAMETER_BOUND_CLASS.equals(
              entry.getKey().getSimpleName().toString())) {
            boundClass = getAnnotationValueAsTypeElement(entry.getValue());
          }
          if (BOUNDBOX_ANNOTATION_PARAMETER_MAX_SUPER_CLASS.equals(
              entry.getKey().getSimpleName().toString())) {
            maxSuperClass = getAnnotationValueAsTypeElement(entry.getValue()).asType().toString();
          }
          if (BOUNDBOX_ANNOTATION_PARAMETER_EXTRA_BOUND_FIELDS.equals(
              entry.getKey().getSimpleName().toString())) {
            extraBoundFields = getAnnotationValueAsAnnotationValueList(entry.getValue());
          }
          if (BOUNDBOX_ANNOTATION_PARAMETER_PREFIXES.equals(
              entry.getKey().getSimpleName().toString())) {
            List<? extends AnnotationValue> listPrefixes =
                getAnnotationValueAsAnnotationValueList(entry.getValue());
            prefixes = new String[listPrefixes.size()];
            for (int indexAnnotation = 0;
                indexAnnotation < listPrefixes.size();
                indexAnnotation++) {
              prefixes[indexAnnotation] =
                  getAnnotationValueAsString(listPrefixes.get(indexAnnotation));
            }
          }
          if (BOUNDBOX_ANNOTATION_PARAMETER_PACKAGE.equals(
              entry.getKey().getSimpleName().toString())) {
            boundBoxPackageName = getAnnotationValueAsString(entry.getValue());
          }
        }
      }

      if (boundClass == null) {
        messager.printMessage(Kind.WARNING, "BoundClass is null : " + message, classElement);
        return true;
      }

      if (maxSuperClass != null) {
        boundClassVisitor.setMaxSuperClassName(maxSuperClass);
      }

      if (prefixes != null && prefixes.length != 2 && prefixes.length != 1) {
        error(
            classElement,
            "You must provide 1 or 2 prefixes. The first one for class names, the second one for methods.");
        return true;
      }
      if (prefixes != null && prefixes.length == 1) {
        String[] newPrefixes = new String[] {prefixes[0], prefixes[0].toLowerCase(Locale.US)};
        prefixes = newPrefixes;
      }
      boundboxWriter.setPrefixes(prefixes);

      if (boundBoxPackageName == null) {
        String boundClassFQN = boundClass.getQualifiedName().toString();
        if (boundClassFQN.contains(PACKAGE_SEPARATOR)) {
          boundBoxPackageName = StringUtils.substringBeforeLast(boundClassFQN, PACKAGE_SEPARATOR);
        } else {
          boundBoxPackageName = StringUtils.EMPTY;
        }
      }
      boundClassVisitor.setBoundBoxPackageName(boundBoxPackageName);
      boundboxWriter.setBoundBoxPackageName(boundBoxPackageName);

      ClassInfo classInfo = boundClassVisitor.scan(boundClass);

      injectExtraBoundFields(extraBoundFields, classInfo);

      listClassInfo.add(classInfo);

      // perform some computations on meta model
      inheritanceComputer.computeInheritanceAndHidingFields(classInfo.getListFieldInfos());
      inheritanceComputer.computeInheritanceAndOverridingMethods(
          classInfo.getListMethodInfos(), boundClass, elements);
      inheritanceComputer.computeInheritanceAndHidingInnerClasses(
          classInfo.getListInnerClassInfo());
      inheritanceComputer.computeInheritanceInInnerClasses(classInfo, elements);

      // write meta model to java class file
      Writer sourceWriter = null;
      try {
        String boundBoxClassName =
            boundboxWriter.getNamingGenerator().createBoundBoxName(classInfo);
        String boundBoxClassFQN =
            boundBoxPackageName.isEmpty()
                ? boundBoxClassName
                : boundBoxPackageName + PACKAGE_SEPARATOR + boundBoxClassName;
        JavaFileObject sourceFile = filer.createSourceFile(boundBoxClassFQN, (Element[]) null);
        sourceWriter = sourceFile.openWriter();

        boundboxWriter.writeBoundBox(classInfo, sourceWriter);
      } catch (IOException e) {
        e.printStackTrace();
        error(classElement, e.getMessage());
      } finally {
        if (sourceWriter != null) {
          IOUtils.closeQuietly(sourceWriter);
        }
      }
    }

    return true;
  }