Java 类com.sun.codemodel.CodeWriter 实例源码

项目:sc-generator    文件:JsonSchemaController.java   
@RequestMapping(value = "/generator/preview", method = RequestMethod.POST)
public String preview(@RequestParam(value = "schema") String schema,
                      @RequestParam(value = "targetpackage") String targetpackage,
                      @RequestParam(value = "sourcetype", required = false) final String sourcetype,
                      @RequestParam(value = "annotationstyle", required = false) final String annotationstyle,
                      @RequestParam(value = "usedoublenumbers", required = false) final boolean usedoublenumbers,
                      @RequestParam(value = "includeaccessors", required = false) final boolean includeaccessors,
                      @RequestParam(value = "includeadditionalproperties", required = false) final boolean includeadditionalproperties,
                      @RequestParam(value = "propertyworddelimiters", required = false) final String propertyworddelimiters,
                      @RequestParam(value = "classname") String classname) throws IOException {

    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    JCodeModel codegenModel = getCodegenModel(schema, targetpackage, sourcetype, annotationstyle, usedoublenumbers, includeaccessors, includeadditionalproperties, propertyworddelimiters, classname);
    codegenModel.build(new CodeWriter() {
        @Override
        public OutputStream openBinary(JPackage pkg, String fileName) throws IOException {
            return byteArrayOutputStream;
        }

        @Override
        public void close() throws IOException {
            byteArrayOutputStream.close();
        }
    });
    return byteArrayOutputStream.toString("utf-8");
}
项目:libraries    文件:BeanGenerator.java   
public void generate(final File targetFolder, final String comment) throws IOException {
  if (!targetFolder.exists()) {
    targetFolder.mkdirs();
  }
  final CodeWriter sourceCodeWriter = new SourceCodeWriter(targetFolder, comment);
  final CodeWriter fileCodeWriter = new FileCodeWriter(targetFolder);
  this.codeModel.build(sourceCodeWriter, fileCodeWriter);
}
项目:aml    文件:JavaWriter.java   
public String writeToString(ITypeLibrary lib) {
    write(lib);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    CodeWriter wr = new SingleStreamCodeWriter(os);
    try {
        getModel().build(wr);
        return new String(os.toByteArray(), "UTF-8");
    } catch (IOException e) {
        throw new IllegalStateException();
    }
}
项目:hyperjaxb3    文件:DynamicCompiler.java   
public void execute() throws IOException, BadCommandLineException {

        final Options options = createOptions();
        final JCodeModel codeModel = createCodeModel();
        final CodeWriter codeWriter = createCodeWriter();
        final ErrorReceiver errorReceiver = createErrorReceiver();
        execute(options, codeModel, codeWriter, errorReceiver);

    }
项目:maven-jaxb2-plugin    文件:XJC21Mojo.java   
protected void writeCode(Outline outline) throws MojoExecutionException {

        if (getWriteCode()) {
            final Model model = outline.getModel();
            final JCodeModel codeModel = model.codeModel;
            final File targetDirectory = model.options.targetDir;
            if (getVerbose()) {
                getLog().info(
                        MessageFormat.format("Writing output to [{0}].",
                                targetDirectory.getAbsolutePath()));
            }
            try {
                if (getCleanPackageDirectories()) {
                    if (getVerbose()) {
                        getLog().info("Cleaning package directories.");
                    }
                    cleanPackageDirectories(targetDirectory, codeModel);
                }
                final CodeWriter codeWriter = new LoggingCodeWriter(
                        model.options.createCodeWriter(), getLog(),
                        getVerbose());
                codeModel.build(codeWriter);
            } catch (IOException e) {
                throw new MojoExecutionException("Unable to write files: "
                        + e.getMessage(), e);
            }
        } else {
            getLog().info(
                    "The [writeCode] setting is set to false, the code will not be written.");
        }
    }
项目:maven-jaxb2-plugin    文件:XJC22Mojo.java   
protected void writeCode(Outline outline) throws MojoExecutionException {

        if (getWriteCode()) {
            final Model model = outline.getModel();
            final JCodeModel codeModel = model.codeModel;
            final File targetDirectory = model.options.targetDir;
            if (getVerbose()) {
                getLog().info(
                        MessageFormat.format("Writing output to [{0}].",
                                targetDirectory.getAbsolutePath()));
            }
            try {
                if (getCleanPackageDirectories()) {
                    if (getVerbose()) {
                        getLog().info("Cleaning package directories.");
                    }
                    cleanPackageDirectories(targetDirectory, codeModel);
                }
                final CodeWriter codeWriter = new LoggingCodeWriter(
                        model.options.createCodeWriter(), getLog(),
                        getVerbose());
                codeModel.build(codeWriter);
            } catch (IOException e) {
                throw new MojoExecutionException("Unable to write files: "
                        + e.getMessage(), e);
            }
        } else {
            getLog().info(
                    "The [writeCode] setting is set to false, the code will not be written.");
        }
    }
项目:maven-jaxb2-plugin    文件:XJC20Mojo.java   
protected void writeCode(Outline outline) throws MojoExecutionException {

        if (getWriteCode()) {
            final Model model = outline.getModel();
            final JCodeModel codeModel = model.codeModel;
            final File targetDirectory = model.options.targetDir;
            if (getVerbose()) {
                getLog().info(
                        MessageFormat.format("Writing output to [{0}].",
                                targetDirectory.getAbsolutePath()));
            }
            try {
                if (getCleanPackageDirectories()) {
                    if (getVerbose()) {
                        getLog().info("Cleaning package directories.");
                    }
                    cleanPackageDirectories(targetDirectory, codeModel);
                }
                final CodeWriter codeWriter = new LoggingCodeWriter(
                        model.options.createCodeWriter(), getLog(),
                        getVerbose());
                codeModel.build(codeWriter);
            } catch (IOException e) {
                throw new MojoExecutionException("Unable to write files: "
                        + e.getMessage(), e);
            }
        } else {
            getLog().info(
                    "The [writeCode] setting is set to false, the code will not be written.");
        }
    }
项目:alchemy-rest-client-generator    文件:ServiceStubGenerator.java   
/**
 * Generate a stub interface for a rest web service implemented by the input
 * service class.
 *
 * <p>
 * The code writer is not close to allow for appends to same code writer.
 * The caller should close the code writer.
 * </p>
 *
 * @param serviceClass
 *            the input rest service class.
 * @param destinationInterfaceName
 *            the name of the destination interface
 * @param destinationPackage
 *            the destination package name.
 * @param codeWriter
 *            the writer to output the source to.
 * @throws NotRestInterfaceException
 *             if the service class is not a rest service.
 * @throws Exception
 *             if code generation fails.
 */
public void generateStubInterface(final Class<?> serviceClass,
        final String destinationInterfaceName, final String destinationPackage,
        final CodeWriter codeWriter) throws NotRestInterfaceException, Exception {
    final RestInterfaceMetadata metaData = interfaceAnalyzer.analyze(serviceClass);

    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jPackage = jCodeModel._package(destinationPackage);
    final JDefinedClass jInterface = jPackage._interface(destinationInterfaceName);
    final String path = metaData.getPath();
    addSingleValueAnnotation(jInterface, Path.class, ANNOTATION_VALUE_PARAM_NAME, path);

    // add consumes annotation
    addListAnnotation(jInterface, Consumes.class, ANNOTATION_VALUE_PARAM_NAME,
            metaData.getConsumed());

    // add produces annotation
    addListAnnotation(jInterface, Produces.class, ANNOTATION_VALUE_PARAM_NAME,
            metaData.getProduced());
    final JDocComment jDocComment = jInterface.javadoc();
    jDocComment.add(String.format("Client side stub interface for {@link %s}.",
            serviceClass.getCanonicalName()));

    final List<Entry<Method, RestMethodMetadata>> methodEntries =
            new ArrayList<>(metaData.getMethodMetaData().entrySet());

    // sort methods alphabetically to give consistent order.
    Collections.sort(methodEntries, new Comparator<Entry<Method, RestMethodMetadata>>() {

        @Override
        public int compare(final Entry<Method, RestMethodMetadata> o1,
                final Entry<Method, RestMethodMetadata> o2) {
            return o1.getKey().toGenericString().compareTo(o2.getKey().toGenericString());
        }
    });

    // generate methods.
    for (final Entry<Method, RestMethodMetadata> methodEntry : methodEntries) {
        final Method method = methodEntry.getKey();
        final RestMethodMetadata methodMetaData = methodEntry.getValue();
        addMethod(jCodeModel, jInterface, method, methodMetaData);

    }

    jCodeModel.build(codeWriter);
}
项目:hyperjaxb3    文件:DynamicCompiler.java   
public CodeWriter createCodeWriter() throws IOException {
    return new FileCodeWriter(targetDirectory, false);
}
项目:hyperjaxb3    文件:DynamicCompiler.java   
protected void execute(final Options options, final JCodeModel codeModel,
        final CodeWriter codeWriter, final ErrorReceiver errorReceiver)
        throws IOException {
    logger.debug("Loading the model.");
    final Model model = ModelLoader.load(options, codeModel, errorReceiver);
    logger.debug("Generating the code.");
    final Outline outline = model.generateCode(options, errorReceiver);
    logger.debug("Writing the code.");
    model.codeModel.build(codeWriter);
    this.outline = outline;
    final StringBuffer contextPathStringBuffer = new StringBuffer();
    String delimiter = "";
    for (final PackageOutline packageOutline : this.outline
            .getAllPackageContexts()) {
        contextPathStringBuffer.append(delimiter);
        contextPathStringBuffer.append(packageOutline._package().name());
        delimiter = ":";
    }
    this.contextPath = contextPathStringBuffer.toString();
    logger.debug("Compiling the code.");
    final JavaCompiler systemJavaCompiler = ToolProvider
            .getSystemJavaCompiler();
    final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    final StandardJavaFileManager standardFileManager = systemJavaCompiler
            .getStandardFileManager(diagnostics, null, null);

    final Collection<File> javaFiles = FileUtils.listFiles(targetDirectory,
            FileFilterUtils.suffixFileFilter(".java"),
            TrueFileFilter.INSTANCE);

    final Iterable<? extends JavaFileObject> fileObjects = standardFileManager
            .getJavaFileObjectsFromFiles(javaFiles);

    ClassLoader contextClassLoader = Thread.currentThread()
            .getContextClassLoader();

    final List<String> compilerOptions = new LinkedList<String>();

    if (contextClassLoader instanceof URLClassLoader) {
        final URLClassLoader urlClassLoader = (URLClassLoader) contextClassLoader;
        final URL[] urls = urlClassLoader.getURLs();
        if (urls.length > 0) {
            compilerOptions.add("-classpath");

            final StringBuffer classpathStringBuffer = new StringBuffer();
            String separator = "";
            for (final URL url : urls) {
                logger.debug("URL:" + url);
                classpathStringBuffer.append(separator);
                try {
                    classpathStringBuffer.
                    // append("\"").
                            append(new File(url.toURI()).getAbsolutePath())
                    // .append("\"")
                    ;
                    separator = SystemUtils.PATH_SEPARATOR;
                } catch (URISyntaxException ignored) {
                }
            }
            compilerOptions.add(classpathStringBuffer.toString());
        }
    }
    compilerOptions.add("-verbose");
    compilerOptions.add("-d");
    compilerOptions.add(targetDirectory.getAbsolutePath());

    logger.debug("Compiler options:"
            + StringUtils.join(compilerOptions.iterator(), " "));
    // // conte
    //
    // final String[] compilerOptions = new String[] { "-d",
    // targetDirectory.getAbsolutePath(), "-verbose" };

    systemJavaCompiler.getTask(null, standardFileManager, null,
            compilerOptions, null, fileObjects).call();
    standardFileManager.close();
}
项目:maven-jaxb2-plugin    文件:LoggingCodeWriter.java   
public LoggingCodeWriter(CodeWriter output, Log log, boolean verbose) {
    super(output);
    this.log = log;
    this.verbose = verbose;
}
项目:maven-jaxb2-plugin    文件:LoggingCodeWriter.java   
public LoggingCodeWriter(CodeWriter output, Log log, boolean verbose) {
    super(output);
    this.log = log;
    this.verbose = verbose;
}
项目:maven-jaxb2-plugin    文件:LoggingCodeWriter.java   
public LoggingCodeWriter(CodeWriter output, Log log, boolean verbose) {
    super(output);
    this.log = log;
    this.verbose = verbose;
}
项目:jsignalml    文件:JavaClassGen.java   
public void write(CodeWriter writer)
    throws java.io.IOException
{
    this.model.build(writer);
}
项目:jsignalml    文件:JavaClassGen.java   
public void write(CodeWriter writer)
    throws java.io.IOException
{
    this.model.build(writer);
}
项目:groovy-cps    文件:Translator.java   
/**
 * Generate transalted result into source files.
 */
public void generateTo(CodeWriter cw) throws IOException {
    codeModel.build(cw);
}
项目:LRPaGe    文件:ProgressCodeWriter.java   
public ProgressCodeWriter( CodeWriter output, PrintStream progress ) {
    super(output);
    this.progress = progress;
    if(progress==null)
        throw new IllegalArgumentException();
}
项目:LRPaGe    文件:FilterCodeWriter.java   
public FilterCodeWriter(CodeWriter core) {
    this.core = core;
}
项目:renjin-statet    文件:WrapperGenerator2.java   
private void generateSources()
    throws IOException {

  int implementedCount = 0;

  JCodeModel codeModel = new JCodeModel();

  List<Entry> entries = Primitives.getEntries();
  for(Entry entry : entries) {
    if(singleFunction == null || singleFunction.equals(entry.name)) {
      List<JvmMethod> overloads = JvmMethod.findOverloads(entry.functionClass, entry.name, entry.methodName);
      if(!overloads.isEmpty()) {
        generate(codeModel, new PrimitiveModel(entry, overloads));
        implementedCount ++;
      }
    }
  }

  codeModel.build(new CodeWriter() {
    @Override
    public Writer openSource(JPackage pkg, String fileName) throws IOException {
      File pkgDir = new File(sourcesDir, pkg.name().replace('.', '/'));
      pkgDir.mkdirs();

      File sourceFile = new File(pkgDir, fileName);
      compilationUnits.add(new WrapperSource(sourceFile));
      return new FileWriter(sourceFile);
    }

    @Override
    public OutputStream openBinary(JPackage jPackage, String s) throws IOException {
      throw new UnsupportedOperationException();
    }

    @Override
    public void close() throws IOException {
    }
  });

  System.out.println("Total primitives: " + entries.size());
  System.out.println("   % Implemented: " + ((double)implementedCount / entries.size() * 100d) + "%");
}
项目:javacash    文件:CashGenerator.java   
public void generate(final InputStream in, final CodeWriter writer) throws Exception {
    loadDocument(in);
    processRNGFile();
    generate(writer);
}
项目:javacash    文件:CashGenerator.java   
public void generate(final CodeWriter writer) throws IOException {
    writeTo(writer);
}
项目:javacash    文件:CashGenerator.java   
public void writeTo(final com.sun.codemodel.CodeWriter writer) throws IOException {
    closeClasses();
    model.build(writer);
}
项目:LRPaGe    文件:PrologCodeWriter.java   
/**
 * @param core
 *      This CodeWriter will be used to actually create a storage for files.
 *      PrologCodeWriter simply decorates this underlying CodeWriter by
 *      adding prolog comments.
 * @param prolog
 *      Strings that will be added as comments.
 *      This string may contain newlines to produce multi-line comments.
 *      '//' will be inserted at the beginning of each line to make it
 *      a valid Java comment, so the caller can just pass strings like
 *      "abc\ndef" 
 */
public PrologCodeWriter( CodeWriter core, String prolog ) {
    super(core);
    this.prolog = prolog;
}