Create the source file for a given class

@param clazz is the class description
@throws java.io.IOException
182771
public static synchronized void createSource(Java._ClassBody clazz)
			throws IOException {
		if (baseDir == null) {
			throw new IOException("Base directory for output not set, use 'setBaseDirectory'");
		}
		String pkg = clazz.getPackage();
		if (pkg == null) {
			pkg = "";
//			throw new IOException("Class package cannot be null");
		}
		pkg = pkg.replace('.', '/');

		File path = new File(baseDir, pkg);
		path.mkdirs();
		try (PrintWriter fp = new PrintWriter(new FileWriter(new File(path, clazz.getName() + ".java")))) {
			clazz.emit(0, fp);
		}
	}
1227587
protected JavaSource getJavaSourceForClass(String clazzname) {
    String resource = clazzname.replaceAll("\\.", "/") + ".java";
    FileObject fileObject = classPath.findResource(resource);
    if (fileObject == null) {
      return null;
    }
    Project project = FileOwnerQuery.getOwner(fileObject);
    if (project == null) {
      return null;
    }
    SourceGroup[] sourceGroups = ProjectUtils.getSources(project).getSourceGroups("java");
    for (SourceGroup sourceGroup : sourceGroups) {
      return JavaSource.create(ClasspathInfo.create(sourceGroup.getRootFolder()));
    }
    return null;
  }
694716
public static <T> T newInstance(Class<T> clazz) throws ClassInstantiationException {
        if (clazz == null) {
            return null;
        }

        try {
            return clazz.newInstance();
        } catch (Exception e) {
            throw new ClassInstantiationException("Failed to instantiate class: " + clazz.getName(), e);
        }
    }
214996
protected void processClass (File source)
    {
        CtClass clazz;
        InputStream in = null;
        try {
            clazz = _pool.makeClass(in = new BufferedInputStream(new FileInputStream(source)));
        } catch (IOException ioe) {
            System.err.println("Failed to load " + source + ": " + ioe);
            return;
        } finally {
            StreamUtil.close(in);
        }

        try {
            if (clazz.subtypeOf(_streamable)) {
                processStreamable(source, clazz);
            }
        } catch (NotFoundException nfe) {
            System.err.println("Error processing class [class=" + clazz.getName() +
                               ", error=" + nfe + "].");
        }
    }
124758
public static Resource getJar(@NonNull Class<?> clazz) {
      URL fileURL = clazz.getProtectionDomain().getCodeSource().getLocation();
      return new FileResource(fileURL.getFile());
   }
435569
public Class createClass(String className) throws ClassNotFoundException {
        Class clazz;
        try {
            clazz = Class.forName(className);
            return clazz;

        } catch (ExceptionInInitializerError eiie) {
            String info = "Could not load the " + description + " object: " + className
                    + ". Could not initialize static object in server: ";
            info += eiie.getMessage();
            throw new ClassNotFoundException(info, eiie);

        } catch (LinkageError le) {
            String info = "Could not load the " + description + " object: " + className
                    + ". This object is depending on a class that has been changed after compilation ";
            info += "or a class that was not found: ";
            info += le.getMessage();
            throw new ClassNotFoundException(info, le);

        } catch (ClassNotFoundException cnfe) {
            String info = "Could not find the " + description + " object: " + className + ": ";
            info += cnfe.getMessage();
            throw new ClassNotFoundException(info, cnfe);
        }
    }
168747
public static File getClassFile(Class<?> clazz) {
    File dir = new File(clazz.getProtectionDomain().getCodeSource().getLocation().getPath());
    if (!dir.isDirectory()) return null; // class file might be contained in Jar
    File clazzFile = new File(dir, clazz.getName().replace('.', File.separatorChar) + ".class");
    return clazzFile.isFile() ? clazzFile : null;
  }
24360
private function addCreateDiscoveryMethod(Clazz $class)
    {
        $method = new Method('createDiscovery');
        $method->setDescription('Creates the resource discovery.');

        $arg = new Argument(self::REPO_VAR_NAME);
        $arg->setTypeHint('ResourceRepository');
        $arg->setType('ResourceRepository');
        $arg->setDescription('The resource repository to read from.');

        $method->addArgument($arg);

        $method->setReturnValue(new ReturnValue(
            '$'.self::DISCOVERY_VAR_NAME,
            'Discovery',
            'The created discovery.'
        ));

        $method->addBody(
<<<EOF
if (!interface_exists('Puli\Discovery\Api\Discovery')) {
    throw new RuntimeException('Please install puli/discovery to create Discovery instances.');
}

EOF
        );

        $class->addImport(new Import('Puli\Repository\Api\ResourceRepository'));
        $class->addImport(new Import('Puli\Discovery\Api\Discovery'));
        $class->addImport(new Import('RuntimeException'));
        $class->addMethod($method);

        // Add method body
        $config = $this->config;
        $type = $config->get(Config::DISCOVERY_TYPE);
        $options = $this->camelizeKeys($config->get(Config::DISCOVERY));
        $options['root-dir'] = $this->rootDir;

        $generator = $this->generatorRegistry->getServiceGenerator(GeneratorRegistry::DISCOVERY, $type);
        $generator->generateNewInstance(self::DISCOVERY_VAR_NAME, $method, $this->generatorRegistry, $options);
    }
466776
public static String getJavadoc(@Nullable final Class<?> clazz) {
    try {
      if (null == clazz) return null;
      @Nullable final File source = com.simiacryptus.util.lang.CodeUtil.findFile(clazz);
      if (null == source) return clazz.getName() + " not found";
      final List<String> lines = IOUtils.readLines(new FileInputStream(source), Charset.forName("UTF-8"));
      final int classDeclarationLine = IntStream.range(0, lines.size())
        .filter(i -> lines.get(i).contains("class " + clazz.getSimpleName())).findFirst().getAsInt();
      final int firstLine = IntStream.rangeClosed(1, classDeclarationLine).map(i -> classDeclarationLine - i)
        .filter(i -> !lines.get(i).matches("\\s*[/\\*@].*")).findFirst().orElse(-1) + 1;
      final String javadoc = lines.subList(firstLine, classDeclarationLine).stream()
        .filter(s -> s.matches("\\s*[/\\*].*"))
        .map(s -> s.replaceFirst("^[ \t]*[/\\*]+", "").trim())
        .filter(x -> !x.isEmpty()).reduce((a, b) -> a + "\n" + b).orElse("");
      return javadoc.replaceAll("<p>", "\n");
    } catch (@javax.annotation.Nonnull final Throwable e) {
      e.printStackTrace();
      return "";
    }
  }
475916
@Override
    @Trivial
    public void open() throws ClassSource_Exception {
        String methodName = "open";
        if ( tc.isEntryEnabled() ) {
            String msg = MessageFormat.format(
                "[ {0} ] State [ {1} ]",
                new Object[] { getHashText(), Integer.valueOf(opens) });
            Tr.entry(tc, methodName, msg);
        }

        if ( (opens < 0) ||
             ((opens == 0) && (jarFile != null)) ||
             ((opens > 0) && (jarFile == null)) ) {

            Tr.warning(tc, "ANNO_CLASSSOURCE_JAR_STATE_BAD", getHashText(), getJarPath(), Integer.valueOf(opens));

            String eMsg = "[ " + getHashText() + " ]" +
                " Failed to open [ " + getJarPath() + " ]" +
                " Count of opens [ " + opens + " ]" +
                " Jar state [ " + jarFile + " ]";
            throw getFactory().newClassSourceException(eMsg);
        }

        opens++;

        if ( jarFile == null ) {
            try {
                jarFile = UtilImpl_FileUtils.createJarFile(jarPath); // throws IOException
            } catch ( IOException e ) {
                Tr.warning(tc, "ANNO_CLASSSOURCE_OPEN4_EXCEPTION", getHashText(), jarPath);
                String eMsg = "[ " + getHashText() + " ] Failed to open [ " + jarPath + " ]";
                throw getFactory().wrapIntoClassSourceException(CLASS_NAME, methodName, eMsg, e);
            }

            if ( tc.isEntryEnabled() ) {
                Tr.exit(tc, methodName, MessageFormat.format("[ {0} ] RETURN (new open)", getHashText()));
            }

        } else {
            if ( tc.isEntryEnabled() ) {
                Tr.exit(tc, methodName, MessageFormat.format("[ {0} ] RETURN (already open)", getHashText()));
            }
        }
    }
354034
protected SourceReader createSourceReader(CompilationUnit unit)
    throws IOException {

        Reader r = new BufferedReader(unit.getReader());
        return new SourceReader(r, "<%", "%>");
    }
442680
public void setClazz(Class<? extends ElementBase> clazz) {
        this.clazz = clazz;

        try {
            // Force execution of static initializers
            Class.forName(clazz.getName());
        } catch (ClassNotFoundException e) {
            MiscUtil.toUnchecked(e);
        }
    }
1224016
@Override
  public Source create() throws InitializationFailedException {
    Source source = null;
    try {
      source = sourceClass.newInstance();
    } catch (InstantiationException e) {
      LOG.fatal("Creating source failed, " + SOURCE_CLASS_CONFIG_KEY + ": " + sourceClass, e);
      System.exit(0);
    } catch (IllegalAccessException e) {
      LOG.fatal("Creating source failed, " + SOURCE_CLASS_CONFIG_KEY + ": " + sourceClass, e);
      System.exit(0);
    }
    LOG.info("Initializing source...");
    source.init(config);
    LOG.info("Initializing source... DONE.");
    return source;
  }
1190586
@SuppressWarnings("unchecked")
    public static <T extends Annotation> T createAnnotation(final Class<T> clazz) {
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz, Annotation.class}, new SimpleAnnoInvocationHandler(clazz));
    }
72606
public static void generateSource(File file, File sourceOutputPath, List<CodeDependent> cds,
            Set<String> compiledClass) throws IOException {

        doCreatePro(file, true, false, null, true, sourceOutputPath, cds, compiledClass, new HashMap<String, String>(),
                false);
    }
296960
public static String readResource(Class<?> clazz, String path)
    {
        File targetFile = resolve(clazz, path);
        if (targetFile == null)
        {
            return null;
        }

        String result;

        try
        {
            result = FileUtils.readFileToString(targetFile, "UTF-8");
        }
        catch (IOException ex)
        {
            return null;
        }

        return result;
    }
1194698
@Override
    public void processClass (File source, Class<?> oclass)
        throws Exception
    {
        // make sure we extend distributed object
        if (!_doclass.isAssignableFrom(oclass) || _doclass.equals(oclass)) {
            // System.err.println("Skipping " + oclass.getName() + "...");
            return;
        }

        // determine which fields we need to deal with
        ArrayList<Field> flist = Lists.newArrayList();
        Field[] fields = oclass.getDeclaredFields();
        for (Field f : fields) {
            int mods = f.getModifiers();
            if (!Modifier.isPublic(mods) ||
                Modifier.isStatic(mods) ||
                Modifier.isTransient(mods)) {
                continue;
            }
            flist.add(f);
        }

        // slurp our source file into newline separated strings
        SourceFile sfile = new SourceFile();
        sfile.readFrom(source);

        // generate our fields section and our methods section
        StringBuilder fsection = new StringBuilder();
        StringBuilder msection = new StringBuilder();
        for (int ii = 0; ii < flist.size(); ii++) {
            Field f = flist.get(ii);
            Class<?> ftype = f.getType();
            String fname = f.getName();

            // create a map to hold our template data
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("field", fname);
            data.put("generated", GenUtil.getGeneratedAnnotation(getClass(), 4, false));
            data.put("type", GenUtil.simpleName(f));
            data.put("wrapfield", GenUtil.boxArgument(ftype, "value"));
            data.put("wrapofield", GenUtil.boxArgument(ftype, "ovalue"));
            data.put("clonefield", GenUtil.cloneArgument(_dsclass, f, "value"));
            data.put("capfield", StringUtil.unStudlyName(fname).toUpperCase());
            data.put("upfield", StringUtil.capitalize(fname));

            // determine the type of transport
            TransportHint hint = f.getAnnotation(TransportHint.class);
            if (hint == null) {
                // inherit hint from class annotation
                hint = f.getDeclaringClass().getAnnotation(TransportHint.class);
            }
            String transport;
            if (hint == null) {
                transport = "";
            } else {
                transport = ",\n" +
                    "            com.threerings.presents.net.Transport.getInstance(\n" +
                    "                com.threerings.presents.net.Transport.Type." +
                        hint.type().name() + ", " + hint.channel() + ")";
            }
            data.put("transport", transport);

            // if this field is an array, we need its component types
            boolean array = ftype.isArray();
            data.put("have_elem", array);
            if (array) {
                Class<?> etype = ftype.getComponentType();
                data.put("elemtype", GenUtil.simpleName(etype));
                data.put("wrapelem", GenUtil.boxArgument(etype, "value"));
                data.put("wrapoelem", GenUtil.boxArgument(etype, "ovalue"));
            }

            // if this field is a generic DSet, we need its bound type
            if (_dsclass.isAssignableFrom(ftype)) {
                Type t = f.getGenericType();
                // we need to walk up the heirarchy until we get to the parameterized DSet
                while (t instanceof Class<?>) {
                    t = ((Class<?>)t).getGenericSuperclass();
                }
                if (t instanceof ParameterizedType) {
                    ParameterizedType pt = (ParameterizedType)t;
                    if (pt.getActualTypeArguments().length > 0) {
                        data.put("etype", GenUtil.simpleName(pt.getActualTypeArguments()[0]));
                    }
                } else {
                    data.put("etype", "DSet.Entry");
                }
            }

            // now figure out which template to use
            String tname = "field.tmpl";
            if (_dsclass.isAssignableFrom(ftype)) {
                tname = "set.tmpl";
            } else if (_olclass.isAssignableFrom(ftype)) {
                tname = "oidlist.tmpl";
            }

            // append the merged templates as appropriate to the string buffers
            if (ii > 0) {
                fsection.append(EOL);
                msection.append(EOL);
            }
            fsection.append(mergeTemplate(NAME_TMPL, data));
            msection.append(mergeTemplate(BASE_TMPL + tname, data));
        }

        // now bolt everything back together into a class declaration
        writeFile(source.getAbsolutePath(), sfile.generate(fsection.toString(), msection.toString()));
    }