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

Save This Page
Home » openjdk-7 » build.tools » compileproperties » [javadoc | source]