Generate java code by the specified xml.

@param file
@param srcPath
@param packageName
@param className
@param isPublicField
769965
public static void xml2Java(File file, String srcPath, String packageName, String className, boolean isPublicField) {
        InputStream is = null;

        try {
            is = new FileInputStream(file);

            xml2Java(is, srcPath, packageName, className, isPublicField);
        } catch (FileNotFoundException e) {
            throw new UncheckedIOException(e);
        } finally {
            IOUtil.close(is);
        }
    }
763425
private void scanUserPaths(PackageSymbol p, boolean includeSourcePath) throws IOException {
        Set<JavaFileObject.Kind> kinds = getPackageFileKinds();

        Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
        classKinds.remove(JavaFileObject.Kind.SOURCE);
        boolean wantClassFiles = !classKinds.isEmpty();

        Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
        sourceKinds.remove(JavaFileObject.Kind.CLASS);
        boolean wantSourceFiles = !sourceKinds.isEmpty();

        boolean haveSourcePath = includeSourcePath && fileManager.hasLocation(SOURCE_PATH);

        if (verbose && verbosePath) {
            if (fileManager instanceof StandardJavaFileManager) {
                StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
                if (haveSourcePath && wantSourceFiles) {
                    List<Path> path = List.nil();
                    for (Path sourcePath : fm.getLocationAsPaths(SOURCE_PATH)) {
                        path = path.prepend(sourcePath);
                    }
                    log.printVerbose("sourcepath", path.reverse().toString());
                } else if (wantSourceFiles) {
                    List<Path> path = List.nil();
                    for (Path classPath : fm.getLocationAsPaths(CLASS_PATH)) {
                        path = path.prepend(classPath);
                    }
                    log.printVerbose("sourcepath", path.reverse().toString());
                }
                if (wantClassFiles) {
                    List<Path> path = List.nil();
                    for (Path platformPath : fm.getLocationAsPaths(PLATFORM_CLASS_PATH)) {
                        path = path.prepend(platformPath);
                    }
                    for (Path classPath : fm.getLocationAsPaths(CLASS_PATH)) {
                        path = path.prepend(classPath);
                    }
                    log.printVerbose("classpath",  path.reverse().toString());
                }
            }
        }

        String packageName = p.fullname.toString();
        if (wantSourceFiles && !haveSourcePath) {
            fillIn(p, CLASS_PATH,
                   list(CLASS_PATH,
                        p,
                        packageName,
                        kinds));
        } else {
            if (wantClassFiles)
                fillIn(p, CLASS_PATH,
                       list(CLASS_PATH,
                            p,
                            packageName,
                            classKinds));
            if (wantSourceFiles)
                fillIn(p, SOURCE_PATH,
                       list(SOURCE_PATH,
                            p,
                            packageName,
                            sourceKinds));
        }
    }
314322
private static CodeDependent createCodeByType(EnumType type, boolean topLevelClass, String packageName,
            Map<String, String> mappedUniName, boolean isUniName) {

        CodeDependent cd = new CodeDependent();

        String defaultClsName = type.getName();
        String simpleName = getProxyClassName(defaultClsName, mappedUniName, isUniName);

        // To generate class
        StringBuilder code = new StringBuilder();
        if (topLevelClass) {
            // define package
            if (!StringUtils.isEmpty(packageName)) {
                code.append("package ").append(packageName).append(CODE_END);
                code.append("\n");
            }
            // add import;
            code.append("import com.baidu.bjf.remoting.protobuf.EnumReadable;\n");
        }

        // define class
        if (topLevelClass) {
            code.append("public enum ");
        } else {
            code.append("public static enum ");
        }
        code.append(simpleName).append(" implements EnumReadable {\n");

        Iterator<Value> iter = type.getValues().iterator();
        while (iter.hasNext()) {
            Value value = iter.next();
            String name = value.getName();
            int tag = value.getTag();

            code.append(name).append("(").append(tag).append(")");
            if (iter.hasNext()) {
                code.append(",").append("\n");
            } else {
                code.append(";\n");
            }
        }

        code.append("private final int value;\n");
        code.append(simpleName).append("(int value) { this.value = value;  }\n");
        code.append("public int value() { return value; }\n");
        code.append("}\n");

        cd.name = simpleName;
        cd.pkg = packageName;
        cd.code = code.toString();

        return cd;
    }
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);
    }
396884
public static void generate(ConfigurationImpl configuration,
                                ClassUseMapper mapper, PackageDoc pkgdoc) {
        PackageUseWriter pkgusegen;
        DocPath filename = DocPaths.PACKAGE_USE;
        try {
            pkgusegen = new PackageUseWriter(configuration,
                                             mapper, filename, pkgdoc);
            pkgusegen.generatePackageUseFile();
            pkgusegen.close();
        } catch (IOException exc) {
            configuration.standardmessage.error(
                "doclet.exception_encountered",
                exc.toString(), filename);
            throw new DocletAbortException(exc);
        }
    }
865597
public void generateCode(final MetadataParserPath path, final boolean verbose) throws TransformerException {
        /** initialize the map which will overwrite global parameters as defined in metadata.xsl/ddJava.xsl */
        final Map<String, String> xsltParameters = new HashMap<String, String>();
        xsltParameters.put("gOutputFolder", getURIPath(path.getPathToImpl()));
        xsltParameters.put("gOutputFolderApi", getURIPath(path.getPathToApi()));
        xsltParameters.put("gOutputFolderTest", getURIPath(path.getPathToTest()));
        xsltParameters.put("gOutputFolderService", getURIPath(path.getPathToServices()));
        xsltParameters.put("gVerbose", Boolean.toString(verbose));

        final InputStream is = MetadataParser.class.getResourceAsStream("/META-INF/ddJavaAll.xsl");
        if (log.isLoggable(Level.FINE)) {
            log.fine("Stream resource: " + is);
        }

        XsltTransformer.simpleTransform(pathToMetadata, is, new File("./tempddJava.xml"), xsltParameters);
    }
439561
private void createClasspathJar(File outputFile, String classpath) throws IOException {
        FileOutputStream out = new FileOutputStream(outputFile);
        try {
            Manifest manifest = new Manifest();
            Attributes attrs = manifest.getMainAttributes();
            attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
            attrs.put(Attributes.Name.CLASS_PATH, classpath);
            new JarOutputStream(out, manifest).close();
        } finally {
            out.close();
        }
    }
852258
public static Map<String, IDLProxyObject> create(InputStream is, boolean debug, File path, boolean isUniName)
            throws IOException {
        ProtoFile protoFile = ProtoSchemaParser.parseUtf8(DEFAULT_FILE_NAME, is);
        List<CodeDependent> cds = new ArrayList<CodeDependent>();
        return doCreate(protoFile, true, debug, path, false, null, cds, new HashMap<String, String>(), isUniName);
    }
845996
void generatePackageInfo(Definition def, String outputDir, String subDir)
   {
      try
      {
         FileWriter fw;
         PackageInfoGen phGen;
         if (outputDir.equals("test"))
         {
            fw = Utils.createTestFile("package-info.java", def.getRaPackage(), def.getOutputDir());
            phGen = new PackageInfoGen();

         }
         else
         {

            if (subDir == null)
            {
               fw = Utils.createSrcFile("package-info.java", def.getRaPackage(), def.getOutputDir());
               phGen = new PackageInfoGen();
            }
            else
            {
               fw = Utils.createSrcFile("package-info.java", def.getRaPackage() + "." + subDir, def.getOutputDir());
               phGen = new PackageInfoGen(subDir);
            }
         }
         phGen.generate(def, fw);
         fw.close();
      }
      catch (IOException ioe)
      {
         ioe.printStackTrace();
      }
   }
770816
private void processFilePath(File file) {
        try {
            if (file.getCanonicalPath().toLowerCase().endsWith(".jar")
                    || file.getCanonicalPath().toLowerCase().endsWith(".zip")) {

                ZipFile zip = new ZipFile(file);
                Enumeration<? extends ZipEntry> entries = zip.entries();

                while (entries.hasMoreElements()) {
                    ZipEntry entry = entries.nextElement();

                    if (entry.getName().endsWith("class")) {
                        InputStream zin = zip.getInputStream(entry);
                        tryClass(entry.getName().replace(File.separatorChar, '.').substring(0, entry.getName().length() - 6));
                        zin.close();
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
1094601
private boolean isSipServletArchive(File file) {
		if (file.getName().toLowerCase().endsWith(SAR_EXTENSION)) {
			return true;
		} else if (file.getName().toLowerCase().endsWith(WAR_EXTENSION)) {
			try{
                JarFile jar = new JarFile(file);                                  
                JarEntry entry = jar.getJarEntry(SipContext.APPLICATION_SIP_XML);
                if(entry != null) {
                        return true;
                }                
	        } catch (IOException e) {
	        	if(logger.isInfoEnabled()) {
	        		logger.info("couldn't find WEB-INF/sip.xml in " + file + " checking for package-info.class");
	        	}
	        }
			return SipApplicationAnnotationUtils.findPackageInfoInArchive(file);
		} 		
		return false;
	}
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);
		}
	}
75739
@Override
	protected StringBuffer doPostProcessBundle(BundleProcessingStatus status, StringBuffer bundleData)
			throws IOException {

		JoinableResourceBundle bundle = status.getCurrentBundle();
		Charset charset = status.getJawrConfig().getResourceCharset();
		if (bundle.getLicensesPathList().isEmpty())
			return bundleData;

		ByteArrayOutputStream baOs = new ByteArrayOutputStream();
		WritableByteChannel wrChannel = Channels.newChannel(baOs);
		Writer writer = Channels.newWriter(wrChannel, charset.name());
		try (BufferedWriter bwriter = new BufferedWriter(writer)) {
			for (Iterator<String> it = bundle.getLicensesPathList().iterator(); it.hasNext();) {
				String path = it.next();
				if (LOGGER.isDebugEnabled())
					LOGGER.debug("Adding license file: " + path);

				Reader rd = null;
				try {
					rd = status.getRsReader().getResource(bundle, path);
				} catch (ResourceNotFoundException e) {
					throw new BundlingProcessException(
							"Unexpected ResourceNotFoundException when reading a sorting file [" + path + "]");
				}

				try (BufferedReader bRd = new BufferedReader(rd)) {
					// Make a buffered reader, to read line by line.
					String line = bRd.readLine();

					// Write each line and the corresponding new line.
					while (line != null) {
						bwriter.write(line);
						if (((line = bRd.readLine()) != null) || it.hasNext())
							bwriter.newLine();
					}
				}
			}
		}
		return new StringBuffer(baOs.toString(charset.name())).append(bundleData);
	}
670361
protected void code(String template, String packageName, String className, Supplier<Map<String, Object>> context) {
        StringBuffer code = generate(template, context);
        writeCode(packageName, className, code);
    }
552612
private static CodeDependent createCodeByType(EnumElement type, boolean topLevelClass, String packageName,
            Map<String, String> mappedUniName, boolean isUniName) {

        CodeDependent cd = new CodeDependent();

        String defaultClsName = type.name();
        String simpleName = getProxyClassName(defaultClsName, mappedUniName, isUniName);

        // To generate class
        StringBuilder code = new StringBuilder();
        if (topLevelClass) {
            // define package
            code.append("package ").append(packageName).append(CODE_END);
            code.append("\n");
            // add import;
            code.append("import com.baidu.bjf.remoting.protobuf.EnumReadable;\n");
        }

        // define class
        // define class
        if (topLevelClass) {
            code.append("public enum ");
        } else {
            code.append("public static enum ");
        }
        code.append(simpleName).append(" implements EnumReadable {\n");

        Iterator<EnumConstantElement> iter = type.constants().iterator();
        while (iter.hasNext()) {
            EnumConstantElement value = iter.next();
            String name = value.name();
            int tag = value.tag();

            code.append(name).append("(").append(tag).append(")");
            if (iter.hasNext()) {
                code.append(",");
            } else {
                code.append(";\n");
            }
        }

        code.append("private final int value;\n");
        code.append(simpleName).append("(int value) { this.value = value;  }\n");
        code.append("public int value() { return value; }\n");
        code.append("}\n");

        cd.name = simpleName;
        cd.pkg = packageName;
        cd.code = code.toString();

        return cd;
    }
252994
@Override
  protected void visitSoyFileNode(SoyFileNode node) {
    StringBuilder file = new StringBuilder();

    file.append("// This file was automatically generated from ")
        .append(node.getFileName())
        .append(".\n");
    file.append("// Please don't edit this file by hand.\n");

    // Output a section containing optionally-parsed compiler directives in comments. Since these
    // are comments, they are not controlled by an option, and will be removed by minifiers that do
    // not understand them.
    file.append("\n");
    String fileOverviewDescription = "Templates in namespace " + node.getNamespace() + ".";
    JsDoc.Builder jsDocBuilder = JsDoc.builder();
    jsDocBuilder.addAnnotation("fileoverview", fileOverviewDescription);
    if (node.getDelPackageName() != null) {
      jsDocBuilder.addParameterizedAnnotation("modName", node.getDelPackageName());
    }
    addJsDocToProvideDelTemplates(jsDocBuilder, node);
    addJsDocToRequireDelTemplates(jsDocBuilder, node);
    addCodeToRequireCss(jsDocBuilder, node);
    jsDocBuilder.addAnnotation("public");
    file.append(jsDocBuilder.build());
    file.append("\n\n");

    // Add code to define JS namespaces or add provide/require calls for Closure Library.
    templateAliases = AliasUtils.IDENTITY_ALIASES;
    jsCodeBuilder = createCodeBuilder();

    if (jsSrcOptions.shouldGenerateGoogModules()) {
      templateAliases = AliasUtils.createTemplateAliases(node);

      addCodeToDeclareGoogModule(file, node);
      addCodeToRequireGoogModules(node);
    } else if (jsSrcOptions.shouldProvideRequireSoyNamespaces()) {
      addCodeToProvideSoyNamespace(file, node);
      file.append('\n');
      addCodeToRequireSoyNamespaces(node);
    } else {
      throw new AssertionError("impossible");
    }

    // add declarations for the ijdata params
    // This takes advantage of the way '@record' types in closure are 'open'.
    // Unfortunately clutz doesn't understand this:
    // https://github.com/angular/clutz/issues/832
    // So TS users will not be able to see the property definitions.
    // The most practical solution to that is for soy to generate its own .d.ts files.
    Map<String, SoyType> ijData = getAllIjDataParams(node);
    if (!ijData.isEmpty()) {
      GoogRequire require = GoogRequire.create("soy");
      jsCodeBuilder.appendLine();
      for (Map.Entry<String, SoyType> entry : ijData.entrySet()) {
        jsCodeBuilder.appendLine();
        //
        jsCodeBuilder.appendLine(
            JsDoc.builder()
                // Because every declaration can declare a type, we can get errors if they don't
                // declare identical types.  There isn't a good way to force identical declarations
                // so we just suppress the duplicate error warning.
                .addParameterizedAnnotation("suppress", "duplicate")
                // declare every field as optional.  This is because if a template is unused and
                // declares an ij param we don't want to force people to supply a value.
                .addParameterizedAnnotation(
                    "type",
                    getJsTypeForParamForDeclaration(entry.getValue()).typeExpr() + "|undefined")
                .build()
                .toString());
        jsCodeBuilder.append(
            require
                .reference()
                .dotAccess("IjData")
                .dotAccess("prototype")
                .dotAccess(entry.getKey())
                .asStatement());
      }
    }

    // Add code for each template.
    for (TemplateNode template : node.getChildren()) {
      jsCodeBuilder.appendLine().appendLine();
      staticVarDeclarations = new ArrayList<>();
      visit(template);
      if (!staticVarDeclarations.isEmpty()) {
        jsCodeBuilder.append(Statement.of(staticVarDeclarations));
      }
    }
    jsCodeBuilder.appendGoogRequiresTo(file);
    jsCodeBuilder.appendCodeTo(file);
    jsFilesContents.add(file.toString());
    jsCodeBuilder = null;
  }
613534
private static void generateJavaFiles(final StatusUpdateTemplate template,
			final String workingPath) throws FileNotFoundException {
		final String javaPath = WORKING_DIR + template.getName() + ".java";
		final File javaFile = new File(javaPath);
		final String[] optionsAndSources = { "-classpath", workingPath,
				"-proc:none", "-source", "1.7", "-target", "1.7", javaPath };

		// write java file
		final PrintWriter writer = new PrintWriter(javaFile);
		writer.write(template.getJavaCode());
		writer.flush();
		writer.close();

		// delete previous class file
		final File classFile = new File(WORKING_DIR + template.getName()
				+ ".class");
		classFile.delete();

		// compile java file to class file
		final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		compiler.run(System.in, System.out, System.err, optionsAndSources);

		// delete java file
		javaFile.delete();
	}