Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/make/src/classes/build/tools/compileproperties/CompileProperties.java
32287 views
/*1* Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package build.tools.compileproperties;2627import java.io.BufferedWriter;28import java.io.File;29import java.io.FileInputStream;30import java.io.FileNotFoundException;31import java.io.FileOutputStream;32import java.io.IOException;33import java.io.OutputStreamWriter;34import java.io.Writer;35import java.text.MessageFormat;36import java.util.ArrayList;37import java.util.Collections;38import java.util.List;39import java.util.Properties;4041/** Translates a .properties file into a .java file containing the42* definition of a java.util.Properties subclass which can then be43* compiled with javac. <P>44*45* Usage: java -jar compileproperties.jar [path to .properties file] [path to .java file to be output] [super class]46*47* Infers the package by looking at the common suffix of the two48* inputs, eliminating "classes" from it.49*50* @author Scott Violet51* @author Kenneth Russell52*/5354public class CompileProperties {55private static final String FORMAT =56"{0}" +57"import java.util.ListResourceBundle;\n\n" +58"public final class {1} extends {2} '{'\n" +59" protected final Object[][] getContents() '{'\n" +60" return new Object[][] '{'\n" +61"{3}" +62" };\n" +63" }\n" +64"}\n";656667// This comes from Properties68private static final char[] hexDigit = {69'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'70};7172// Note: different from that in Properties73private static final String specialSaveChars = "\"";7475// This comes from Properties76private static char toHex(int nibble) {77return hexDigit[(nibble & 0xF)];78}7980private static void error(String msg, Exception e) {81System.err.println("ERROR: compileproperties: " + msg);82if ( e != null ) {83System.err.println("EXCEPTION: " + e.toString());84e.printStackTrace();85}86}8788private static String propfiles[];89private static String outfiles[] ;90private static String supers[] ;91private static int compileCount = 0;92private static boolean quiet = false;9394private static boolean parseOptions(String args[]) {95boolean ok = true;96if ( compileCount > 0 ) {97String new_propfiles[] = new String[compileCount + args.length];98String new_outfiles[] = new String[compileCount + args.length];99String new_supers[] = new String[compileCount + args.length];100System.arraycopy(propfiles, 0, new_propfiles, 0, compileCount);101System.arraycopy(outfiles, 0, new_outfiles, 0, compileCount);102System.arraycopy(supers, 0, new_supers, 0, compileCount);103propfiles = new_propfiles;104outfiles = new_outfiles;105supers = new_supers;106} else {107propfiles = new String[args.length];108outfiles = new String[args.length];109supers = new String[args.length];110}111for ( int i = 0; i < args.length ; i++ ) {112if ( "-compile".equals(args[i]) && i+3 < args.length ) {113propfiles[compileCount] = args[++i];114outfiles[compileCount] = args[++i];115supers[compileCount] = args[++i];116compileCount++;117} else if ( args[i].charAt(0) == '@') {118String filename = args[i].substring(1);119FileInputStream finput = null;120byte contents[] = null;121try {122finput = new FileInputStream(filename);123int byteCount = finput.available();124if ( byteCount <= 0 ) {125error("The @file is empty", null);126ok = false;127} else {128contents = new byte[byteCount];129int bytesRead = finput.read(contents);130if ( byteCount != bytesRead ) {131error("Cannot read all of @file", null);132ok = false;133}134}135} catch ( IOException e ) {136error("cannot open " + filename, e);137ok = false;138}139if ( finput != null ) {140try {141finput.close();142} catch ( IOException e ) {143ok = false;144error("cannot close " + filename, e);145}146}147if ( ok && contents != null ) {148String tokens[] = (new String(contents)).split("\\s+");149if ( tokens.length > 0 ) {150ok = parseOptions(tokens);151}152}153if ( !ok ) {154break;155}156} else {157error("argument error", null);158ok = false;159}160}161return ok;162}163164public static void main(String[] args) {165boolean ok = true;166if (args.length >= 1 && args[0].equals("-quiet"))167{168quiet = true;169String[] newargs = new String[args.length-1];170System.arraycopy(args, 1, newargs, 0, newargs.length);171args = newargs;172}173/* Original usage */174if (args.length == 2 && args[0].charAt(0) != '-' ) {175ok = createFile(args[0], args[1], "ListResourceBundle");176} else if (args.length == 3) {177ok = createFile(args[0], args[1], args[2]);178} else if (args.length == 0) {179usage();180ok = false;181} else {182/* New batch usage */183ok = parseOptions(args);184if ( ok && compileCount == 0 ) {185error("options parsed but no files to compile", null);186ok = false;187}188/* Need at least one file. */189if ( !ok ) {190usage();191} else {192/* Process files */193for ( int i = 0; i < compileCount && ok ; i++ ) {194ok = createFile(propfiles[i], outfiles[i], supers[i]);195}196}197}198if ( !ok ) {199System.exit(1);200}201}202203private static void usage() {204System.err.println("usage:");205System.err.println(" java -jar compileproperties.jar path_to_properties_file path_to_java_output_file [super_class]");206System.err.println(" -OR-");207System.err.println(" java -jar compileproperties.jar {-compile path_to_properties_file path_to_java_output_file super_class} -or- @filename");208System.err.println("");209System.err.println("Example:");210System.err.println(" java -jar compileproperties.jar -compile test.properties test.java ListResourceBundle");211System.err.println(" java -jar compileproperties.jar @option_file");212System.err.println("option_file contains: -compile test.properties test.java ListResourceBundle");213}214215private static boolean createFile(String propertiesPath, String outputPath,216String superClass) {217boolean ok = true;218if (!quiet) {219System.out.println("parsing: " + propertiesPath);220}221Properties p = new Properties();222try {223p.load(new FileInputStream(propertiesPath));224} catch ( FileNotFoundException e ) {225ok = false;226error("Cannot find file " + propertiesPath, e);227} catch ( IOException e ) {228ok = false;229error("IO error on file " + propertiesPath, e);230}231if ( ok ) {232String packageName = inferPackageName(propertiesPath, outputPath);233if (!quiet) {234System.out.println("inferred package name: " + packageName);235}236List<String> sortedKeys = new ArrayList<>();237for ( Object key : p.keySet() ) {238sortedKeys.add((String)key);239}240Collections.sort(sortedKeys);241242StringBuffer data = new StringBuffer();243244for (String key : sortedKeys) {245data.append(" { \"" + escape(key) + "\", \"" +246escape((String)p.get(key)) + "\" },\n");247}248249// Get class name from java filename, not the properties filename.250// (zh_TW properties might be used to create zh_HK files)251File file = new File(outputPath);252String name = file.getName();253int dotIndex = name.lastIndexOf('.');254String className;255if (dotIndex == -1) {256className = name;257} else {258className = name.substring(0, dotIndex);259}260261String packageString = "";262if (packageName != null && !packageName.equals("")) {263packageString = "package " + packageName + ";\n\n";264}265266Writer writer = null;267try {268writer = new BufferedWriter(269new OutputStreamWriter(new FileOutputStream(outputPath), "8859_1"));270MessageFormat format = new MessageFormat(FORMAT);271writer.write(format.format(new Object[] { packageString, className, superClass, data }));272} catch ( IOException e ) {273ok = false;274error("IO error writing to file " + outputPath, e);275}276if ( writer != null ) {277try {278writer.flush();279} catch ( IOException e ) {280ok = false;281error("IO error flush " + outputPath, e);282}283try {284writer.close();285} catch ( IOException e ) {286ok = false;287error("IO error close " + outputPath, e);288}289}290if (!quiet) {291System.out.println("wrote: " + outputPath);292}293}294return ok;295}296297private static String escape(String theString) {298// This is taken from Properties.saveConvert with changes for Java strings299int len = theString.length();300StringBuffer outBuffer = new StringBuffer(len*2);301302for(int x=0; x<len; x++) {303char aChar = theString.charAt(x);304switch(aChar) {305case '\\':outBuffer.append('\\'); outBuffer.append('\\');306break;307case '\t':outBuffer.append('\\'); outBuffer.append('t');308break;309case '\n':outBuffer.append('\\'); outBuffer.append('n');310break;311case '\r':outBuffer.append('\\'); outBuffer.append('r');312break;313case '\f':outBuffer.append('\\'); outBuffer.append('f');314break;315default:316if ((aChar < 0x0020) || (aChar > 0x007e)) {317outBuffer.append('\\');318outBuffer.append('u');319outBuffer.append(toHex((aChar >> 12) & 0xF));320outBuffer.append(toHex((aChar >> 8) & 0xF));321outBuffer.append(toHex((aChar >> 4) & 0xF));322outBuffer.append(toHex( aChar & 0xF));323} else {324if (specialSaveChars.indexOf(aChar) != -1) {325outBuffer.append('\\');326}327outBuffer.append(aChar);328}329}330}331return outBuffer.toString();332}333334private static String inferPackageName(String inputPath, String outputPath) {335// Normalize file names336inputPath = new File(inputPath).getPath();337outputPath = new File(outputPath).getPath();338// Split into components339String sep;340if (File.separatorChar == '\\') {341sep = "\\\\";342} else {343sep = File.separator;344}345String[] inputs = inputPath.split(sep);346String[] outputs = outputPath.split(sep);347// Match common names, eliminating first "classes" entry from348// each if present349int inStart = 0;350int inEnd = inputs.length - 2;351int outEnd = outputs.length - 2;352int i = inEnd;353int j = outEnd;354while (i >= 0 && j >= 0) {355if (!inputs[i].equals(outputs[j]) ||356(inputs[i].equals("gensrc") && inputs[j].equals("gensrc"))) {357++i;358++j;359break;360}361--i;362--j;363}364String result;365if (i < 0 || j < 0 || i >= inEnd || j >= outEnd) {366result = "";367} else {368if (inputs[i].equals("classes") && outputs[j].equals("classes")) {369++i;370}371inStart = i;372StringBuffer buf = new StringBuffer();373for (i = inStart; i <= inEnd; i++) {374buf.append(inputs[i]);375if (i < inEnd) {376buf.append('.');377}378}379result = buf.toString();380}381return result;382}383}384385386