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.File;
  29 import java.io.PrintWriter;
  30 import java.io.StringWriter;
  31 import java.nio.file.Path;
  32 import java.util.Arrays;
  33 import java.util.HashSet;
  34 import java.util.Set;
  35 import java.util.StringTokenizer;
  36 
  37 /**
  38  * Utilities.
  39  *
  40  *  <p><b>This is NOT part of any supported API.
  41  *  If you write code that depends on this, you do so at your own risk.
  42  *  This code and its internal interfaces are subject to change or
  43  *  deletion without notice.</b>
  44  */
  45 public class Util {
  46 
  47     public static String toFileSystemPath(String pkgId) {
  48         if (pkgId == null || pkgId.length()==0) return null;
  49         String pn;
  50         if (pkgId.charAt(0) == ':') {
  51             // When the module is the default empty module.
  52             // Do not prepend the module directory, because there is none.
  53             // Thus :java.foo.bar translates to java/foo/bar (or \)
  54             pn = pkgId.substring(1).replace('.',File.separatorChar);
  55         } else {
  56             // There is a module. Thus jdk.base:java.foo.bar translates
  57             // into jdk.base/java/foo/bar
  58             int cp = pkgId.indexOf(':');
  59             String mn = pkgId.substring(0,cp);
  60             pn = mn+File.separatorChar+pkgId.substring(cp+1).replace('.',File.separatorChar);
  61         }
  62         return pn;
  63     }
  64 
  65     public static String justPackageName(String pkgName) {
  66         int c = pkgName.indexOf(":");
  67         if (c == -1)
  68             throw new IllegalArgumentException("Expected ':' in package name (" + pkgName + ")");
  69         return pkgName.substring(c+1);
  70     }
  71 
  72     public static String extractStringOption(String opName, String s) {
  73         return extractStringOption(opName, s, null);
  74     }
  75 
  76     public static String extractStringOption(String opName, String s, String deflt) {
  77         int p = s.indexOf(opName+"=");
  78         if (p == -1) return deflt;
  79         p+=opName.length()+1;
  80         int pe = s.indexOf(',', p);
  81         if (pe == -1) pe = s.length();
  82         return s.substring(p, pe);
  83     }
  84 
  85     public static boolean extractBooleanOption(String opName, String s, boolean deflt) {
  86        String str = extractStringOption(opName, s);
  87         return "true".equals(str) ? true
  88              : "false".equals(str) ? false
  89              : deflt;
  90     }
  91 
  92     public static int extractIntOption(String opName, String s) {
  93         return extractIntOption(opName, s, 0);
  94     }
  95 
  96     public static int extractIntOption(String opName, String s, int deflt) {
  97         int p = s.indexOf(opName+"=");
  98         if (p == -1) return deflt;
  99         p+=opName.length()+1;
 100         int pe = s.indexOf(',', p);
 101         if (pe == -1) pe = s.length();
 102         int v = 0;
 103         try {
 104             v = Integer.parseInt(s.substring(p, pe));
 105         } catch (Exception e) {}
 106         return v;
 107     }
 108 
 109     /**
 110      * Clean out unwanted sub options supplied inside a primary option.
 111      * For example to only had portfile remaining from:
 112      *    settings="--server:id=foo,portfile=bar"
 113      * do settings = cleanOptions("--server:",Util.set("-portfile"),settings);
 114      *    now settings equals "--server:portfile=bar"
 115      *
 116      * @param allowsSubOptions A set of the allowed sub options, id portfile etc.
 117      * @param s The option settings string.
 118      */
 119     public static String cleanSubOptions(Set<String> allowedSubOptions, String s) {
 120         StringBuilder sb = new StringBuilder();
 121         StringTokenizer st = new StringTokenizer(s, ",");
 122         while (st.hasMoreTokens()) {
 123             String o = st.nextToken();
 124             int p = o.indexOf('=');
 125             if (p>0) {
 126                 String key = o.substring(0,p);
 127                 String val = o.substring(p+1);
 128                 if (allowedSubOptions.contains(key)) {
 129                     if (sb.length() > 0) sb.append(',');
 130                     sb.append(key+"="+val);
 131                 }
 132             }
 133         }
 134         return sb.toString();
 135     }
 136 
 137     /**
 138      * Convenience method to create a set with strings.
 139      */
 140     public static Set<String> set(String... ss) {
 141         Set<String> set = new HashSet<>();
 142         set.addAll(Arrays.asList(ss));
 143         return set;
 144     }
 145 
 146     /**
 147      * Normalize windows drive letter paths to upper case to enable string
 148      * comparison.
 149      *
 150      * @param file File name to normalize
 151      * @return The normalized string if file has a drive letter at the beginning,
 152      *         otherwise the original string.
 153      */
 154     public static String normalizeDriveLetter(String file) {
 155         if (file.length() > 2 && file.charAt(1) == ':') {
 156             return Character.toUpperCase(file.charAt(0)) + file.substring(1);
 157         } else if (file.length() > 3 && file.charAt(0) == '*'
 158                    && file.charAt(2) == ':') {
 159             // Handle a wildcard * at the beginning of the string.
 160             return file.substring(0, 1) + Character.toUpperCase(file.charAt(1))
 161                    + file.substring(2);
 162         }
 163         return file;
 164     }
 165 
 166     /**
 167      * Locate the setting for the server properties.
 168      */
 169     public static String findServerSettings(String[] args) {
 170         for (String s : args) {
 171             if (s.startsWith("--server:")) {
 172                 return s;
 173             }
 174         }
 175         return null;
 176     }
 177 
 178     public static <E> Set<E> union(Set<? extends E> s1,
 179                                    Set<? extends E> s2) {
 180         Set<E> union = new HashSet<>();
 181         union.addAll(s1);
 182         union.addAll(s2);
 183         return union;
 184     }
 185 
 186     public static String getStackTrace(Throwable t) {
 187         StringWriter sw = new StringWriter();
 188         t.printStackTrace(new PrintWriter(sw));
 189         return sw.toString();
 190     }
 191 
 192     // TODO: Remove when refactoring from java.io.File to java.nio.file.Path.
 193     public static File pathToFile(Path path) {
 194         return path == null ? null : path.toFile();
 195     }
 196 }