1 /*
   2  * Copyright (c) 2012, 2014, 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 com.sun.tools.sjavac;
  27 
  28 import java.io.*;
  29 import java.net.URI;
  30 import java.text.MessageFormat;
  31 import java.util.ArrayList;
  32 import java.util.Collections;
  33 import java.util.Iterator;
  34 import java.util.List;
  35 import java.util.Properties;
  36 import java.util.Set;
  37 import java.util.HashSet;
  38 import java.util.Map;
  39 
  40 import com.sun.tools.sjavac.options.Options;
  41 import com.sun.tools.sjavac.server.Sjavac;
  42 
  43 /**
  44  * Compile properties transform a properties file into a Java source file.
  45  * Java has built in support for reading properties from either a text file
  46  * in the source or a compiled java source file.
  47  *
  48  *  <p><b>This is NOT part of any supported API.
  49  *  If you write code that depends on this, you do so at your own risk.
  50  *  This code and its internal interfaces are subject to change or
  51  *  deletion without notice.</b>
  52  */
  53 public class CompileProperties implements Transformer {
  54     // Any extra information passed from the command line, for example if:
  55     // -tr .proppp=com.sun.tools.javac.smart.CompileProperties,sun.util.resources.LocaleNamesBundle
  56     // then extra will be "sun.util.resources.LocaleNamesBundle"
  57     String extra;
  58 
  59     public void setExtra(String e) {
  60         extra = e;
  61     }
  62 
  63     public void setExtra(Options a) {
  64     }
  65 
  66     public boolean transform(Sjavac sjavac,
  67                              Map<String,Set<URI>> pkgSrcs,
  68                              Set<URI>             visibleSrcs,
  69                              Map<URI,Set<String>> visibleClasses,
  70                              Map<String,Set<String>> oldPackageDependents,
  71                              URI destRoot,
  72                              Map<String,Set<URI>>    packageArtifacts,
  73                              Map<String,Set<String>> packageDependencies,
  74                              Map<String,String>      packagePublicApis,
  75                              int debugLevel,
  76                              boolean incremental,
  77                              int numCores,
  78                              PrintStream out,
  79                              PrintStream err) {
  80         boolean rc = true;
  81         for (String pkgName : pkgSrcs.keySet()) {
  82             String pkgNameF = Util.toFileSystemPath(pkgName);
  83             for (URI u : pkgSrcs.get(pkgName)) {
  84                 File src = new File(u);
  85                 boolean r = compile(pkgName, pkgNameF, src, new File(destRoot), debugLevel,
  86                                     packageArtifacts);
  87                 if (r == false) {
  88                     rc = false;
  89                 }
  90             }
  91         }
  92         return rc;
  93     }
  94 
  95     boolean compile(String pkgName, String pkgNameF, File src, File destRoot, int debugLevel,
  96                     Map<String,Set<URI>> packageArtifacts)
  97     {
  98         String superClass = "java.util.ListResourceBundle";
  99 
 100         if (extra != null) {
 101             superClass = extra;
 102         }
 103         // Load the properties file.
 104         Properties p = new Properties();
 105         try {
 106             p.load(new FileInputStream(src));
 107         } catch (IOException e) {
 108             Log.error("Error reading file "+src.getPath());
 109             return false;
 110         }
 111 
 112         // Calculate the name of the Java source file to be generated.
 113         int dp = src.getName().lastIndexOf(".");
 114         String classname = src.getName().substring(0,dp);
 115 
 116         // Sort the properties in increasing key order.
 117         List<String> sortedKeys = new ArrayList<>();
 118         for (Object key : p.keySet()) {
 119             sortedKeys.add((String)key);
 120         }
 121         Collections.sort(sortedKeys);
 122         Iterator<String> keys = sortedKeys.iterator();
 123 
 124         // Collect the properties into a string buffer.
 125         StringBuilder data = new StringBuilder();
 126         while (keys.hasNext()) {
 127             String key = keys.next();
 128             data.append("            { \"" + escape(key) + "\", \"" +
 129                         escape((String)p.get(key)) + "\" },\n");
 130         }
 131 
 132         // Create dest file name. It is derived from the properties file name.
 133         String destFilename = destRoot.getPath()+File.separator+pkgNameF+File.separator+classname+".java";
 134         File dest = new File(destFilename);
 135 
 136         // Make sure the dest directories exist.
 137         if (!dest.getParentFile().isDirectory()) {
 138             if (!dest.getParentFile().mkdirs()) {
 139                 Log.error("Could not create the directory "+dest.getParentFile().getPath());
 140                 return false;
 141             }
 142         }
 143 
 144         Set<URI> as = packageArtifacts.get(pkgName);
 145         if (as == null) {
 146             as = new HashSet<>();
 147             packageArtifacts.put(pkgName, as);
 148         }
 149         as.add(dest.toURI());
 150 
 151         if (dest.exists() && dest.lastModified() > src.lastModified()) {
 152             // A generated file exists, and its timestamp is newer than the source.
 153             // Assume that we do not need to regenerate the dest file!
 154             // Thus we are done.
 155             return true;
 156         }
 157 
 158         String packageString = "package " + pkgNameF.replace(File.separatorChar,'.') + ";\n\n";
 159 
 160         Log.info("Compiling property file "+pkgNameF+File.separator+src.getName());
 161         try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest)))) {
 162             MessageFormat format = new MessageFormat(FORMAT);
 163             writer.write(format.format(new Object[] { packageString, classname, superClass, data }));
 164         } catch ( IOException e ) {
 165             Log.error("Could not write file "+dest.getPath());
 166             return false;
 167         }
 168         return true;
 169     }
 170 
 171     private static final String FORMAT =
 172             "{0}" +
 173             "public final class {1} extends {2} '{'\n" +
 174             "    protected final Object[][] getContents() '{'\n" +
 175             "        return new Object[][] '{'\n" +
 176             "{3}" +
 177             "        };\n" +
 178             "    }\n" +
 179             "}\n";
 180 
 181     public static String escape(String theString) {
 182         int len = theString.length();
 183         StringBuilder outBuffer = new StringBuilder(len*2);
 184 
 185         for(int x=0; x<len; x++) {
 186             char aChar = theString.charAt(x);
 187             switch(aChar) {
 188                 case '\\':outBuffer.append('\\'); outBuffer.append('\\');
 189                 break;
 190                 case '\t':outBuffer.append('\\'); outBuffer.append('t');
 191                 break;
 192                 case '\n':outBuffer.append('\\'); outBuffer.append('n');
 193                 break;
 194                 case '\r':outBuffer.append('\\'); outBuffer.append('r');
 195                 break;
 196                 case '\f':outBuffer.append('\\'); outBuffer.append('f');
 197                 break;
 198                 default:
 199                     if ((aChar < 0x0020) || (aChar > 0x007e)) {
 200                         outBuffer.append('\\');
 201                         outBuffer.append('u');
 202                         outBuffer.append(toHex((aChar >> 12) & 0xF));
 203                         outBuffer.append(toHex((aChar >>  8) & 0xF));
 204                         outBuffer.append(toHex((aChar >>  4) & 0xF));
 205                         outBuffer.append(toHex( aChar        & 0xF));
 206                     } else {
 207                         if (aChar == '"') {
 208                             outBuffer.append('\\');
 209                         }
 210                         outBuffer.append(aChar);
 211                     }
 212             }
 213         }
 214         return outBuffer.toString();
 215     }
 216 
 217     private static char toHex(int nibble) {
 218         return hexDigit[(nibble & 0xF)];
 219     }
 220 
 221     private static final char[] hexDigit = {
 222         '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
 223     };
 224 }