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