CompileProperties.java revision 553
0N/A/*
1472N/A * Copyright (c) 2002, 2005, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
0N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
0N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
1472N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1472N/A *
1472N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
0N/A * or visit www.oracle.com if you need additional information or have any
0N/A * questions.
0N/A */
1879N/A
1879N/Aimport java.io.BufferedWriter;
1879N/Aimport java.io.File;
1879N/Aimport java.io.FileInputStream;
1879N/Aimport java.io.FileNotFoundException;
1879N/Aimport java.io.FileOutputStream;
1879N/Aimport java.io.IOException;
1879N/Aimport java.io.OutputStreamWriter;
0N/Aimport java.io.Writer;
0N/Aimport java.text.MessageFormat;
342N/Aimport java.util.ArrayList;
0N/Aimport java.util.Collections;
0N/Aimport java.util.Iterator;
0N/Aimport java.util.List;
0N/Aimport java.util.Properties;
0N/A
342N/A/** Translates a .properties file into a .java file containing the
0N/A * definition of a java.util.Properties subclass which can then be
0N/A * compiled with javac. <P>
0N/A *
0N/A * Usage: java CompileProperties [path to .properties file] [path to .java file to be output] [super class]
0N/A *
0N/A * Infers the package by looking at the common suffix of the two
0N/A * inputs, eliminating "classes" from it.
0N/A *
1378N/A * @author Scott Violet
1378N/A * @author Kenneth Russell
0N/A */
0N/A
0N/Apublic class CompileProperties {
0N/A
0N/A public static void main(String[] args) {
0N/A CompileProperties cp = new CompileProperties();
0N/A boolean ok = cp.run(args);
0N/A if ( !ok ) {
0N/A System.exit(1);
0N/A }
0N/A }
0N/A
0N/A static interface Log {
0N/A void info(String msg);
0N/A void verbose(String msg);
0N/A void error(String msg, Exception e);
0N/A }
0N/A
0N/A private String propfiles[];
0N/A private String outfiles[] ;
0N/A private String supers[] ;
0N/A private int compileCount = 0;
0N/A private boolean quiet = false;
0N/A private Log log;
0N/A
0N/A public void setLog(Log log) {
0N/A this.log = log;
0N/A }
0N/A
0N/A public boolean run(String[] args) {
0N/A if (log == null) {
0N/A log = new Log() {
0N/A public void error(String msg, Exception e) {
0N/A System.err.println("ERROR: CompileProperties: " + msg);
0N/A if ( e != null ) {
0N/A System.err.println("EXCEPTION: " + e.toString());
0N/A e.printStackTrace();
0N/A }
304N/A }
304N/A public void info(String msg) {
304N/A System.out.println(msg);
0N/A }
0N/A public void verbose(String msg) {
1484N/A if (!quiet)
0N/A System.out.println(msg);
0N/A }
0N/A };
0N/A }
0N/A
0N/A boolean ok = true;
0N/A /* Original usage */
0N/A if (args.length == 2 && args[0].charAt(0) != '-' ) {
0N/A ok = createFile(args[0], args[1], "java.util.ListResourceBundle");
0N/A } else if (args.length == 3) {
0N/A ok = createFile(args[0], args[1], args[2]);
0N/A } else if (args.length == 0) {
0N/A usage(log);
0N/A ok = false;
0N/A } else {
0N/A /* New batch usage */
0N/A ok = parseOptions(args);
0N/A if ( ok && compileCount == 0 ) {
0N/A log.error("options parsed but no files to compile", null);
0N/A ok = false;
0N/A }
0N/A /* Need at least one file. */
0N/A if ( !ok ) {
0N/A usage(log);
0N/A } else {
0N/A /* Process files */
0N/A for ( int i = 0; i < compileCount && ok ; i++ ) {
0N/A ok = createFile(propfiles[i], outfiles[i], supers[i]);
0N/A }
0N/A }
0N/A }
0N/A return ok;
0N/A }
0N/A
0N/A private boolean parseOptions(String args[]) {
0N/A boolean ok = true;
0N/A if ( compileCount > 0 ) {
0N/A String new_propfiles[] = new String[compileCount + args.length];
0N/A String new_outfiles[] = new String[compileCount + args.length];
0N/A String new_supers[] = new String[compileCount + args.length];
0N/A System.arraycopy(propfiles, 0, new_propfiles, 0, compileCount);
0N/A System.arraycopy(outfiles, 0, new_outfiles, 0, compileCount);
0N/A System.arraycopy(supers, 0, new_supers, 0, compileCount);
0N/A propfiles = new_propfiles;
0N/A outfiles = new_outfiles;
0N/A supers = new_supers;
0N/A } else {
0N/A propfiles = new String[args.length];
0N/A outfiles = new String[args.length];
0N/A supers = new String[args.length];
1204N/A }
1378N/A
0N/A for ( int i = 0; i < args.length ; i++ ) {
1204N/A if ( "-compile".equals(args[i]) && i+3 < args.length ) {
0N/A propfiles[compileCount] = args[++i];
0N/A outfiles[compileCount] = args[++i];
0N/A supers[compileCount] = args[++i];
0N/A compileCount++;
0N/A } else if ( "-optionsfile".equals(args[i]) && i+1 < args.length ) {
0N/A String filename = args[++i];
0N/A FileInputStream finput = null;
0N/A byte contents[] = null;
0N/A try {
0N/A finput = new FileInputStream(filename);
0N/A int byteCount = finput.available();
0N/A if ( byteCount <= 0 ) {
0N/A log.error("The -optionsfile file is empty", null);
0N/A ok = false;
0N/A } else {
0N/A contents = new byte[byteCount];
0N/A int bytesRead = finput.read(contents);
0N/A if ( byteCount != bytesRead ) {
0N/A log.error("Cannot read all of -optionsfile file", null);
0N/A ok = false;
0N/A }
0N/A }
0N/A } catch ( IOException e ) {
0N/A log.error("cannot open " + filename, e);
0N/A ok = false;
0N/A }
0N/A if ( finput != null ) {
0N/A try {
0N/A finput.close();
0N/A } catch ( IOException e ) {
0N/A ok = false;
0N/A log.error("cannot close " + filename, e);
0N/A }
0N/A }
0N/A if ( ok = true && contents != null ) {
0N/A String tokens[] = (new String(contents)).split("\\s+");
0N/A if ( tokens.length > 0 ) {
0N/A ok = parseOptions(tokens);
0N/A }
0N/A }
0N/A if ( !ok ) {
0N/A break;
0N/A }
0N/A } else if ( "-quiet".equals(args[i]) ) {
0N/A quiet = true;
0N/A } else {
0N/A log.error("argument error", null);
0N/A ok = false;
1711N/A }
0N/A }
0N/A return ok;
0N/A }
0N/A
0N/A private boolean createFile(String propertiesPath, String outputPath,
0N/A String superClass) {
0N/A boolean ok = true;
0N/A log.verbose("parsing: " + propertiesPath);
0N/A Properties p = new Properties();
0N/A try {
0N/A p.load(new FileInputStream(propertiesPath));
0N/A } catch ( FileNotFoundException e ) {
0N/A ok = false;
0N/A log.error("Cannot find file " + propertiesPath, e);
0N/A } catch ( IOException e ) {
0N/A ok = false;
0N/A log.error("IO error on file " + propertiesPath, e);
0N/A }
0N/A if ( ok ) {
0N/A String packageName = inferPackageName(propertiesPath, outputPath);
0N/A log.verbose("inferred package name: " + packageName);
1295N/A List<String> sortedKeys = new ArrayList<String>();
1295N/A for ( Object key : p.keySet() ) {
1295N/A sortedKeys.add((String)key);
1295N/A }
0N/A Collections.sort(sortedKeys);
0N/A Iterator keys = sortedKeys.iterator();
0N/A
0N/A StringBuffer data = new StringBuffer();
1378N/A
1378N/A while (keys.hasNext()) {
0N/A Object key = keys.next();
0N/A data.append(" { \"" + escape((String)key) + "\", \"" +
0N/A escape((String)p.get(key)) + "\" },\n");
0N/A }
0N/A
0N/A // Get class name from java filename, not the properties filename.
0N/A // (zh_TW properties might be used to create zh_HK files)
0N/A File file = new File(outputPath);
0N/A String name = file.getName();
0N/A int dotIndex = name.lastIndexOf('.');
0N/A String className;
0N/A if (dotIndex == -1) {
0N/A className = name;
0N/A } else {
0N/A className = name.substring(0, dotIndex);
0N/A }
0N/A
1879N/A String packageString = "";
1879N/A if (packageName != null && !packageName.equals("")) {
1879N/A packageString = "package " + packageName + ";\n\n";
1879N/A }
1879N/A
1879N/A Writer writer = null;
1879N/A try {
0N/A writer = new BufferedWriter(
1879N/A new OutputStreamWriter(new FileOutputStream(outputPath), "8859_1"));
1879N/A MessageFormat format = new MessageFormat(FORMAT);
writer.write(format.format(new Object[] { packageString, className, superClass, data }));
} catch ( IOException e ) {
ok = false;
log.error("IO error writing to file " + outputPath, e);
}
if ( writer != null ) {
try {
writer.flush();
} catch ( IOException e ) {
ok = false;
log.error("IO error flush " + outputPath, e);
}
try {
writer.close();
} catch ( IOException e ) {
ok = false;
log.error("IO error close " + outputPath, e);
}
}
log.verbose("wrote: " + outputPath);
}
return ok;
}
private static void usage(Log log) {
log.info("usage:");
log.info(" java CompileProperties path_to_properties_file path_to_java_output_file [super_class]");
log.info(" -OR-");
log.info(" java CompileProperties {-compile path_to_properties_file path_to_java_output_file super_class} -or- -optionsfile filename");
log.info("");
log.info("Example:");
log.info(" java CompileProperties -compile test.properties test.java java.util.ListResourceBundle");
log.info(" java CompileProperties -optionsfile option_file");
log.info("option_file contains: -compile test.properties test.java java.util.ListResourceBundle");
}
private static String escape(String theString) {
// This is taken from Properties.saveConvert with changes for Java strings
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len*2);
for(int x=0; x<len; x++) {
char aChar = theString.charAt(x);
switch(aChar) {
case '\\':outBuffer.append('\\'); outBuffer.append('\\');
break;
case '\t':outBuffer.append('\\'); outBuffer.append('t');
break;
case '\n':outBuffer.append('\\'); outBuffer.append('n');
break;
case '\r':outBuffer.append('\\'); outBuffer.append('r');
break;
case '\f':outBuffer.append('\\'); outBuffer.append('f');
break;
default:
if ((aChar < 0x0020) || (aChar > 0x007e)) {
outBuffer.append('\\');
outBuffer.append('u');
outBuffer.append(toHex((aChar >> 12) & 0xF));
outBuffer.append(toHex((aChar >> 8) & 0xF));
outBuffer.append(toHex((aChar >> 4) & 0xF));
outBuffer.append(toHex( aChar & 0xF));
} else {
if (specialSaveChars.indexOf(aChar) != -1) {
outBuffer.append('\\');
}
outBuffer.append(aChar);
}
}
}
return outBuffer.toString();
}
private static String inferPackageName(String inputPath, String outputPath) {
// Normalize file names
inputPath = new File(inputPath).getPath();
outputPath = new File(outputPath).getPath();
// Split into components
String sep;
if (File.separatorChar == '\\') {
sep = "\\\\";
} else {
sep = File.separator;
}
String[] inputs = inputPath.split(sep);
String[] outputs = outputPath.split(sep);
// Match common names, eliminating first "classes" entry from
// each if present
int inStart = 0;
int inEnd = inputs.length - 2;
int outEnd = outputs.length - 2;
int i = inEnd;
int j = outEnd;
while (i >= 0 && j >= 0) {
if (!inputs[i].equals(outputs[j]) ||
(inputs[i].equals("gensrc") && inputs[j].equals("gensrc"))) {
++i;
++j;
break;
}
--i;
--j;
}
String result;
if (i < 0 || j < 0 || i >= inEnd || j >= outEnd) {
result = "";
} else {
if (inputs[i].equals("classes") && outputs[j].equals("classes")) {
++i;
}
inStart = i;
StringBuffer buf = new StringBuffer();
for (i = inStart; i <= inEnd; i++) {
buf.append(inputs[i]);
if (i < inEnd) {
buf.append('.');
}
}
result = buf.toString();
}
return result;
}
private static final String FORMAT =
"{0}" +
"public final class {1} extends {2} '{'\n" +
" protected final Object[][] getContents() '{'\n" +
" return new Object[][] '{'\n" +
"{3}" +
" };\n" +
" }\n" +
"}\n";
// This comes from Properties
private static char toHex(int nibble) {
return hexDigit[(nibble & 0xF)];
}
// This comes from Properties
private static final char[] hexDigit = {
'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
};
// Note: different from that in Properties
private static final String specialSaveChars = "\"";
}