@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;
  }
 public String formatSource(JCDiagnostic d, boolean fullname, Locale l) {
   JavaFileObject fo = d.getSource();
   if (fo == null) throw new IllegalArgumentException(); // d should have source set
   if (fullname) return fo.getName();
   else if (fo instanceof BaseFileObject) return ((BaseFileObject) fo).getShortName();
   else return BaseFileObject.getSimpleName(fo);
 }
Exemplo n.º 3
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();
  }
Exemplo n.º 4
0
 private void addResources() throws Abort {
   HashSet<String> written = new HashSet<String>();
   try {
     for (JavaFileObject fo : resourceFileObjects) {
       CeyloncFileManager dfm = (CeyloncFileManager) fileManager;
       String jarFileName =
           JarUtils.toPlatformIndependentPath(
               dfm.getLocation(CeylonLocation.RESOURCE_PATH), fo.getName());
       if (!written.contains(jarFileName)) {
         dfm.setModule(modelLoader.findModuleForFile(new File(jarFileName)));
         FileObject outFile =
             dfm.getFileForOutput(StandardLocation.CLASS_OUTPUT, "", jarFileName, null);
         OutputStream out = outFile.openOutputStream();
         try {
           InputStream in = new FileInputStream(new File(fo.getName()));
           try {
             JarUtils.copy(in, out);
           } finally {
             in.close();
           }
         } finally {
           out.close();
         }
         written.add(jarFileName);
       }
     }
   } catch (IOException ex) {
     throw new Abort(ex);
   }
 }
Exemplo n.º 5
0
  @Override
  public CompilationUnit[] getCompilationUnits() {
    if (this.compilationUnits == null) return EclipseCompilerImpl.NO_UNITS;
    ArrayList<CompilationUnit> units = new ArrayList<CompilationUnit>();
    for (final JavaFileObject javaFileObject : this.compilationUnits) {
      if (javaFileObject.getKind() != JavaFileObject.Kind.SOURCE) {
        throw new IllegalArgumentException();
      }
      String name = javaFileObject.getName();
      name = name.replace('\\', '/');
      CompilationUnit compilationUnit =
          new CompilationUnit(null, name, null) {

            @Override
            public char[] getContents() {
              try {
                return javaFileObject.getCharContent(true).toString().toCharArray();
              } catch (IOException e) {
                e.printStackTrace();
                throw new AbortCompilationUnit(null, e, null);
              }
            }
          };
      units.add(compilationUnit);
      this.javaFileObjectMap.put(compilationUnit, javaFileObject);
    }
    CompilationUnit[] result = new CompilationUnit[units.size()];
    units.toArray(result);
    return result;
  }
 @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;
 }
  private List<Diagnostic<? extends JavaFileObject>> doCompile() {
    List<VolatileJavaFile> sources = packager.getEmitter().getEmitted();
    if (dump) {
      for (JavaFileObject java : sources) {
        try {
          System.out.println("====" + java.getName());
          System.out.println(java.getCharContent(true));
        } catch (IOException e) {
          // ignore.
        }
      }
    }

    for (JavaFileObject java : sources) {
      javaCompiler.addSource(java);
    }
    if (sources.isEmpty()) {
      javaCompiler.addSource(new VolatileJavaFile("A", "public class A {}"));
    }
    List<Diagnostic<? extends JavaFileObject>> diagnostics = javaCompiler.doCompile();
    if (dump) {
      for (Diagnostic<? extends JavaFileObject> d : diagnostics) {
        System.out.println("====");
        System.out.println(d);
      }
    }
    return diagnostics;
  }
  private OutputFileObject getFileForOutput(
      Location location,
      JavaFileObject.Kind kind,
      String fileName,
      @Nullable String className,
      FileObject sibling)
      throws IOException {
    JavaFileObject src = null;
    if (sibling instanceof JavaFileObject) {
      final JavaFileObject javaFileObject = (JavaFileObject) sibling;
      if (javaFileObject.getKind() == JavaFileObject.Kind.SOURCE) {
        src = javaFileObject;
      }
    }

    File dir = getSingleOutputDirectory(location, src);

    if (location == StandardLocation.CLASS_OUTPUT) {
      if (dir == null) {
        throw new IOException("Output directory is not specified");
      }
    } else if (location == StandardLocation.SOURCE_OUTPUT) {
      if (dir == null) {
        dir = getSingleOutputDirectory(StandardLocation.CLASS_OUTPUT, src);
        if (dir == null) {
          throw new IOException("Neither class output directory nor source output are specified");
        }
      }
    }
    final File file =
        (dir == null ? new File(fileName).getAbsoluteFile() : new File(dir, fileName));
    return new OutputFileObject(myContext, file, kind, className, src);
  }
Exemplo n.º 9
0
 void test(String... args) throws IOException {
   JavaFileObject file = fm.getJavaFileForInput(PLATFORM_CLASS_PATH, "java.lang.Object", CLASS);
   String fileName = file.getName();
   if (!fileName.matches(".*java/lang/Object.class\\)?")) {
     System.err.println(fileName);
     throw new AssertionError(file);
   }
 }
Exemplo n.º 10
0
  public ModuleSymbol findSingleModule() {
    try {
      JavaFileObject src_fo = getModuleInfoFromLocation(StandardLocation.SOURCE_PATH, Kind.SOURCE);
      JavaFileObject class_fo =
          getModuleInfoFromLocation(StandardLocation.CLASS_OUTPUT, Kind.CLASS);
      JavaFileObject fo =
          (src_fo == null)
              ? class_fo
              : (class_fo == null) ? src_fo : classFinder.preferredFileObject(src_fo, class_fo);

      ModuleSymbol msym;
      if (fo == null) {
        msym = syms.unnamedModule;
      } else {
        switch (fo.getKind()) {
          case SOURCE:
            if (!inFindSingleModule) {
              try {
                inFindSingleModule = true;
                // Note: the following will trigger a re-entrant call to Modules.enter
                msym = sourceFileCompleter.complete(fo);
                msym.module_info.classfile = fo;
              } finally {
                inFindSingleModule = false;
              }
            } else {
              // the module-info.java does not contain a module declaration,
              // avoid infinite recursion:
              msym = syms.unnamedModule;
            }
            break;
          case CLASS:
            Name name;
            try {
              name = names.fromString(readModuleName(fo));
            } catch (BadClassFile | IOException ex) {
              // fillIn will report proper errors:
              name = names.error;
            }
            msym = syms.enterModule(name);
            msym.module_info.classfile = fo;
            msym.completer = Completer.NULL_COMPLETER;
            classFinder.fillIn(msym.module_info);
            break;
          default:
            Assert.error();
            msym = syms.unnamedModule;
            break;
        }
      }

      msym.classLocation = StandardLocation.CLASS_OUTPUT;
      return msym;

    } catch (IOException e) {
      throw new Error(e); // FIXME
    }
  }
  private void createBeanInfo(TypeElement classElement) throws Exception {
    if (verbose) {
      processingEnv
          .getMessager()
          .printMessage(
              Diagnostic.Kind.NOTE, "Generating BeanInfo for " + classElement.getSimpleName());
    }

    String className = classElement.getSimpleName().toString();
    String qualifiedName = classElement.getQualifiedName().toString();
    PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();
    String packageName = packageElement.getQualifiedName().toString();

    Map<String, VariableElement> fields = new HashMap<String, VariableElement>();

    Writer writer = null;

    try {
      // Build Bean Info
      TypeElement curClassElement = classElement;
      do {

        for (Element e : curClassElement.getEnclosedElements()) {
          if (e.getKind().equals(ElementKind.FIELD)
              && !e.getModifiers().contains(Modifier.TRANSIENT)
              && !e.getModifiers().contains(Modifier.STATIC)) {

            fields.put(e.getSimpleName().toString(), (VariableElement) e);
          }
        }

        TypeMirror t = curClassElement.getSuperclass();
        if (t instanceof DeclaredType) {
          curClassElement = (TypeElement) ((DeclaredType) t).asElement();
        } else {
          curClassElement = null;
        }

      } while (curClassElement != null);
      VelocityContext vc = new VelocityContext();
      vc.put("className", className);
      vc.put("packageName", packageName);
      vc.put("fields", fields);
      // Create source file
      JavaFileObject jfo = processingEnv.getFiler().createSourceFile(qualifiedName + "BeanInfo");
      if (verbose) {
        processingEnv
            .getMessager()
            .printMessage(Diagnostic.Kind.NOTE, "creating source file: " + jfo.toUri());
      }
      writer = jfo.openWriter();
      template.merge(vc, writer);
    } finally {
      closeQuietly(writer);
    }
  }
 /** Wraps a JavaFileObject in a UsageAsInputReportingJavaFileObject, shares existing instances. */
 private JavaFileObject map(JavaFileObject item) {
   if (item == null) {
     return item;
   }
   InputUsageRecord usage = inputUsageRecords.get(item.toUri());
   if (usage == null) {
     usage = new InputUsageRecord(item);
     inputUsageRecords.put(item.toUri(), usage);
   }
   return new UsageAsInputReportingJavaFileObject(item, usage);
 }
Exemplo n.º 13
0
 /** print an error or warning message: */
 private void printRawError(int pos, String msg) {
   if (source == null || pos == Position.NOPOS) {
     printRawLines(errWriter, "error: " + msg);
   } else {
     int line = source.getLineNumber(pos);
     JavaFileObject file = source.getFile();
     if (file != null) printRawLines(errWriter, file.getName() + ":" + line + ": " + msg);
     printErrLine(pos, errWriter);
   }
   errWriter.flush();
 }
  private void serialize(Serializer serializer, Collection<EntityType> models) {
    for (EntityType model : models) {
      try {
        Type type = conf.getTypeMappings().getPathType(model, model, true);
        String packageName = type.getPackageName();
        String className =
            !packageName.isEmpty()
                ? (packageName + "." + type.getSimpleName())
                : type.getSimpleName();

        // skip if type is excluded class or in excluded package
        if (conf.isExcludedPackage(model.getPackageName())
            || conf.isExcludedClass(model.getFullName())) {
          continue;
        }

        Set<TypeElement> elements = context.typeElements.get(model.getFullName());

        if (elements == null) {
          elements = new HashSet<TypeElement>();
        }
        for (Property property : model.getProperties()) {
          if (property.getType().getCategory() == TypeCategory.CUSTOM) {
            Set<TypeElement> customElements =
                context.typeElements.get(property.getType().getFullName());
            if (customElements != null) {
              elements.addAll(customElements);
            }
          }
        }

        processingEnv
            .getMessager()
            .printMessage(Kind.NOTE, "Generating " + className + " for " + elements);
        JavaFileObject fileObject =
            processingEnv
                .getFiler()
                .createSourceFile(className, elements.toArray(new Element[elements.size()]));
        Writer writer = fileObject.openWriter();
        try {
          SerializerConfig serializerConfig = conf.getSerializerConfig(model);
          serializer.serialize(model, serializerConfig, new JavaWriter(writer));
        } finally {
          if (writer != null) {
            writer.close();
          }
        }

      } catch (IOException e) {
        System.err.println(e.getMessage());
        processingEnv.getMessager().printMessage(Kind.ERROR, e.getMessage());
      }
    }
  }
Exemplo n.º 15
0
 public void close() throws IOException {
   if (closed) return;
   closed = true;
   String s = newContent.toString();
   if (!oldContent.equals(s)) {
     int p = file.getName().lastIndexOf(File.separatorChar);
     try (Writer writer = file.openWriter()) {
       writer.write(s);
     }
     stdout.println("Writing " + file.getName().substring(p + 1));
   }
 }
Exemplo n.º 16
0
  private File compileOne(Type type) {
    if (this.flags.contains(Flags.USECACHE)) {
      File dir = cache.get(type.getName());
      if (dir != null) {
        return dir;
      }
    }
    List<JavaFileObject> files = new ArrayList<>();
    SourceProcessor accum = (name, src) -> files.add(new SourceFile(name, src));

    for (Type dep : type.typeDependencies()) {
      dep.generateAsDependency(accum, type.methodDependencies());
    }

    type.generate(accum);

    JavacTask ct =
        (JavacTask) this.systemJavaCompiler.getTask(null, this.fm, null, null, null, files);
    File destDir = null;
    do {
      int value = counter.incrementAndGet();
      destDir = new File(root, Integer.toString(value));
    } while (destDir.exists());

    if (this.flags.contains(Flags.VERBOSE)) {
      System.out.println("Compilation unit for " + type.getName() + " : compiled into " + destDir);
      for (JavaFileObject jfo : files) {
        System.out.println(jfo.toString());
      }
    }

    try {
      destDir.mkdirs();
      this.fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
    } catch (IOException e) {
      throw new RuntimeException(
          "IOException encountered during compilation: " + e.getMessage(), e);
    }
    Boolean result = ct.call();
    if (result == Boolean.FALSE) {
      throw new RuntimeException("Compilation failure in " + type.getName() + " unit");
    }
    if (this.flags.contains(Flags.USECACHE)) {
      File existing = cache.putIfAbsent(type.getName(), destDir);
      if (existing != null) {
        deleteDir(destDir);
        return existing;
      }
    } else {
      this.tempDirs.add(destDir);
    }
    return destDir;
  }
Exemplo n.º 17
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();
  }
Exemplo n.º 18
0
 private boolean isResource(JavaFileObject fo) {
   JavacFileManager dfm = (JavacFileManager) fileManager;
   for (File dir : dfm.getLocation(CeylonLocation.RESOURCE_PATH)) {
     String prefix = dir.getPath();
     if (fo.getName().startsWith(prefix)) {
       return true;
     }
     String absPrefix = dir.getAbsolutePath();
     if (fo.getName().startsWith(absPrefix)) {
       return true;
     }
   }
   return false;
 }
Exemplo n.º 19
0
 // This is a bit of a hack, but if we got passed a list of resources
 // without any accompaning source files we'll not be able to determine
 // the module to which the resource files belong. So to try to fix that
 // we see if a module file exists in the source folders and add it to
 // the list of source files
 private List<JavaFileObject> addModuleDescriptors(
     List<JavaFileObject> sourceFiles, List<JavaFileObject> resourceFiles) {
   List<JavaFileObject> result = sourceFiles;
   JavacFileManager dfm = (JavacFileManager) fileManager;
   for (JavaFileObject fo : resourceFiles) {
     String resName =
         JarUtils.toPlatformIndependentPath(
             dfm.getLocation(CeylonLocation.RESOURCE_PATH), fo.getName());
     JavaFileObject moduleFile = findModuleDescriptorForFile(new File(resName));
     if (moduleFile != null && !result.contains(moduleFile)) {
       result = result.append(moduleFile);
     }
   }
   return result;
 }
Exemplo n.º 20
0
 private void forceNewRound(JavacFiler filer) {
   if (!filer.newFiles()) {
     try {
       JavaFileObject dummy =
           filer.createSourceFile("lombok.dummy.ForceNewRound" + (dummyCount++));
       Writer w = dummy.openWriter();
       w.close();
     } catch (Exception e) {
       e.printStackTrace();
       processingEnv
           .getMessager()
           .printMessage(Kind.WARNING, "Can't force a new processing round. Lombok won't work.");
     }
   }
 }
Exemplo n.º 21
0
 public void withFields(Collection<AnnotatedField> annotatedFields) throws IOException {
   Writer writer = javaFileObject.openWriter();
   String lBrew = brewJava(annotatedFields);
   writer.write(lBrew);
   writer.flush();
   writer.close();
 }
Exemplo n.º 22
0
  private String getPackage(JavaFileObject file) throws IOException {
    Iterable<? extends File> prefixes =
        ((JavacFileManager) fileManager).getLocation(StandardLocation.SOURCE_PATH);

    // Figure out the package name by stripping the "-src" prefix and
    // extracting
    // the package part of the fullname.

    String filePath = file.toUri().getPath();
    // go absolute
    filePath = new File(filePath).getCanonicalPath();

    int srcDirLength = 0;
    for (File prefixFile : prefixes) {
      String prefix = prefixFile.getCanonicalPath();
      if (filePath.startsWith(prefix) && prefix.length() > srcDirLength) {
        srcDirLength = prefix.length();
      }
    }

    if (srcDirLength > 0) {
      String fullname = filePath.substring(srcDirLength);
      assert fullname.endsWith(".ceylon");
      fullname = fullname.substring(0, fullname.length() - ".ceylon".length());
      fullname = fullname.replace(File.separator, ".");
      if (fullname.startsWith(".")) fullname = fullname.substring(1);
      String packageName = Convert.packagePart(fullname);
      if (!packageName.equals("")) return packageName;
    }
    return null;
  }
Exemplo n.º 23
0
 /** Returns the name of JavaFileObject, similar to {@link java.io.File#getName} */
 public static String getName(final JavaFileObject fo, final boolean noExt) {
   assert fo != null;
   if (fo instanceof Base) {
     Base baseFileObject = (Base) fo;
     if (noExt) {
       return baseFileObject.getName();
     } else {
       StringBuilder sb = new StringBuilder();
       sb.append(baseFileObject.getName());
       sb.append('.'); // NOI18N
       sb.append(baseFileObject.getExt());
       return sb.toString();
     }
   }
   try {
     final URL url = fo.toUri().toURL();
     String path = url.getPath();
     int index1 = path.lastIndexOf('/'); // NOI18N
     int len;
     if (noExt) {
       final int index2 = path.lastIndexOf('.'); // NOI18N
       if (index2 > index1) {
         len = index2;
       } else {
         len = path.length();
       }
     } else {
       len = path.length();
     }
     path = path.substring(index1 + 1, len);
     return path;
   } catch (MalformedURLException e) {
     return null;
   }
 }
  void emitApplication(ProcessingContext env, ApplicationMetaModel application)
      throws ProcessingException {
    PackageElement elt = env.get(application.getHandle());
    FQN fqn = new FQN(application.getName(), "Application");

    //
    Writer writer = null;
    try {
      JavaFileObject applicationFile = env.createSourceFile(fqn, elt);
      writer = applicationFile.openWriter();

      writer.append("package ").append(fqn.getPackageName()).append(";\n");

      // Imports
      writer.append("import ").append(Tools.getImport(ApplicationDescriptor.class)).append(";\n");

      // Open class
      writer.append("public class ").append(fqn.getSimpleName()).append(" {\n");

      // Field
      writer.append("private final ").append(APPLICATION_DESCRIPTOR).append(" descriptor;\n");

      // Constructor
      writer.append("public ").append(fqn.getSimpleName()).append("() throws Exception {\n");
      writer
          .append("this.descriptor = ")
          .append(APPLICATION_DESCRIPTOR)
          .append(".create(getClass());\n");
      writer.append("}\n");

      // Getter
      writer.append("public ").append(APPLICATION_DESCRIPTOR).append(" getDescriptor() {\n");
      writer.append("return descriptor;\n");
      writer.append("}\n");

      // Close class
      writer.append("}\n");

      //
      env.log("Generated application " + fqn.getName() + " as " + applicationFile.toUri());
    } catch (IOException e) {
      throw TemplateMetaModel.CANNOT_WRITE_APPLICATION.failure(e, elt, application.getName());
    } finally {
      Tools.safeClose(writer);
    }
  }
  private JCCompilationUnit ceylonParse(JavaFileObject filename, CharSequence readSource) {
    if (ceylonEnter.hasRun())
      throw new RuntimeException(
          "Trying to load new source file after CeylonEnter has been called: " + filename);
    try {
      String source = readSource.toString();
      ANTLRStringStream input = new ANTLRStringStream(source);
      CeylonLexer lexer = new CeylonLexer(input);

      CommonTokenStream tokens = new CommonTokenStream(lexer);

      CeylonParser parser = new CeylonParser(tokens);
      CompilationUnit cu = parser.compilationUnit();

      char[] chars = source.toCharArray();
      LineMap map = Position.makeLineMap(chars, chars.length, false);

      java.util.List<LexError> lexerErrors = lexer.getErrors();
      for (LexError le : lexerErrors) {
        printError(le, le.getMessage(), "ceylon.lexer", map);
      }

      java.util.List<ParseError> parserErrors = parser.getErrors();
      for (ParseError pe : parserErrors) {
        printError(pe, pe.getMessage(), "ceylon.parser", map);
      }

      if (lexer.getNumberOfSyntaxErrors() != 0) {
        log.error("ceylon.lexer.failed");
      } else if (parser.getNumberOfSyntaxErrors() != 0) {
        log.error("ceylon.parser.failed");
      } else {
        ModuleManager moduleManager = phasedUnits.getModuleManager();
        File sourceFile = new File(filename.toString());
        // FIXME: temporary solution
        VirtualFile file = vfs.getFromFile(sourceFile);
        VirtualFile srcDir = vfs.getFromFile(getSrcDir(sourceFile));
        // FIXME: this is bad in many ways
        String pkgName = getPackage(filename);
        // make a Package with no module yet, we will resolve them later
        com.redhat.ceylon.compiler.typechecker.model.Package p =
            modelLoader.findOrCreatePackage(null, pkgName == null ? "" : pkgName);
        PhasedUnit phasedUnit =
            new CeylonPhasedUnit(file, srcDir, cu, p, moduleManager, ceylonContext, filename, map);
        phasedUnits.addPhasedUnit(file, phasedUnit);
        gen.setMap(map);

        return gen.makeJCCompilationUnitPlaceholder(cu, filename, pkgName, phasedUnit);
      }
    } catch (Exception e) {
      log.error("ceylon", e.getMessage());
    }

    JCCompilationUnit result =
        make.TopLevel(List.<JCAnnotation>nil(), null, List.<JCTree>of(make.Erroneous()));
    result.sourcefile = filename;
    return result;
  }
Exemplo n.º 26
0
  public JavaFileObject getJavaFileForOutput(
      Location location, String className, Kind kind, FileObject sibling) throws IOException {
    JavaFileObject object =
        standardJavaFileManager.getJavaFileForOutput(location, className, kind, sibling);

    if (kind == Kind.CLASS) {
      className = className.replace("/", ".");
      String enclosingClassName = className.split("\\$")[0];
      String sourceFileName =
          enclosingClassName.substring(enclosingClassName.lastIndexOf(".") + 1) + ".java";
      Optional<PluginSource> source = result.findSource(sourceFileName);
      Path binaryFile = Paths.get(object.toUri());
      URL binaryURL = binaryFile.toUri().toURL();
      PluginBinary binary = new PluginBinary(binaryURL, source, Optional.of(className));
      result.getBinaries().add(binary);
    }
    return object;
  }
 @Override
 public void onSourceFile(JavaFileObject sourceFile) {
   try {
     writer.writeAttribute("filename", getRelativeFileName(sourceFile.getName()));
   } catch (XMLStreamException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Exemplo n.º 28
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();
    }
  }
 public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
   final CompilerMessage.Kind kind;
   switch (diagnostic.getKind()) {
     case ERROR:
       kind = BuildMessage.Kind.ERROR;
       myErrorCount++;
       break;
     case MANDATORY_WARNING:
     case WARNING:
     case NOTE:
       kind = BuildMessage.Kind.WARNING;
       myWarningCount++;
       break;
     default:
       kind = BuildMessage.Kind.INFO;
   }
   File sourceFile = null;
   try {
     // for eclipse compiler just an attempt to call getSource() may lead to an NPE,
     // so calling this method under try/catch to avoid induced compiler errors
     final JavaFileObject source = diagnostic.getSource();
     sourceFile = source != null ? Utils.convertToFile(source.toUri()) : null;
   } catch (Exception e) {
     LOG.info(e);
   }
   final String srcPath =
       sourceFile != null ? FileUtil.toSystemIndependentName(sourceFile.getPath()) : null;
   String message = diagnostic.getMessage(Locale.US);
   if (Utils.IS_TEST_MODE) {
     LOG.info(message);
   }
   myContext.processMessage(
       new CompilerMessage(
           BUILDER_NAME,
           kind,
           message,
           srcPath,
           diagnostic.getStartPosition(),
           diagnostic.getEndPosition(),
           diagnostic.getPosition(),
           diagnostic.getLineNumber(),
           diagnostic.getColumnNumber()));
 }
 @Override
 public void postProcessAnnotations(ApplicationMetaModel metaModel) {
   ElementHandle.Package pkg = metaModel.getHandle();
   AnnotationState annotation = servlets.remove(pkg);
   if (annotation != null) {
     PackageElement pkgElt = metaModel.processingContext.get(pkg);
     String urlPattern = (String) annotation.get("value");
     String simpleName = (String) annotation.get("name");
     if (simpleName == null) {
       simpleName = metaModel.getBaseName() + "Servlet";
     }
     Name clazz = pkg.getPackage().append(simpleName);
     Writer writer = null;
     try {
       JavaFileObject file = metaModel.processingContext.createSourceFile(clazz, pkgElt);
       writer = file.openWriter();
       writer.append("package ").append(pkg.getPackage()).append(";\n");
       writer.append("import javax.servlet.annotation.WebServlet;\n");
       writer.append("import javax.servlet.annotation.WebInitParam;\n");
       writer
           .append("@WebServlet(name=\"")
           .append(simpleName)
           .append("\",urlPatterns=\"")
           .append(urlPattern)
           .append("\")\n");
       writer
           .append("public class ")
           .append(simpleName)
           .append(" extends juzu.bridge.servlet.JuzuServlet {\n");
       writer.append("@Override\n");
       writer.append(
           "protected String getApplicationName(javax.servlet.ServletConfig config) {\n");
       writer.append("return \"").append(pkg.getPackage()).append("\";\n");
       writer.append("}\n");
       writer.append("}\n");
     } catch (IOException e) {
       throw CANNOT_WRITE_SERVLET_CLASS.failure(e, pkgElt, pkg.getPackage());
     } finally {
       Tools.safeClose(writer);
     }
   }
 }