Subversion Repository Public Repository

litesoft

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package com.esotericsoftware.scar;

import java.io.*;
import java.nio.channels.*;
import java.util.*;
import java.util.regex.*;

import static com.esotericsoftware.minlog.Log.*;

public class Utils
{
    /**
     * The Scar installation directory. The value comes from the SCAR_HOME environment variable, if it exists. Alternatively, the
     * "scar.home" System property can be defined.
     */
    static public final String SCAR_HOME;
    static {
        if (System.getProperty("scar.home") != null)
            SCAR_HOME = System.getProperty("scar.home");
        else
            SCAR_HOME = System.getenv("SCAR_HOME");
    }

    /**
     * The Java installation directory.
     */
    static public final String JAVA_HOME = System.getProperty("java.home");

    /**
     * True if running on a Mac OS.
     */
    static public final boolean isMac = System.getProperty("os.name").toLowerCase().contains("mac os x");

    /**
     * True if running on a Windows OS.
     */
    static public final boolean isWindows = System.getProperty("os.name").toLowerCase().contains("windows");

    /**
     * Returns the full path for the specified file name in the current working directory, the {@link #SCAR_HOME}, and the bin
     * directory of {@link #JAVA_HOME}.
     */
    static public String resolvePath (String fileName) {
        if (fileName == null) return null;

        String foundFile = lowLevelResolve( fileName );
        if (TRACE) trace("scar", "Path \"" + fileName + "\" resolved to: " + foundFile);
        return foundFile;
    }

    private static String lowLevelResolve( String fileName ){
        String foundFile;
        if (fileExists(foundFile = canonical(fileName))) return foundFile;
        if (fileExists(foundFile = new File(SCAR_HOME, fileName).getPath())) return foundFile;
        if (fileExists(foundFile = new File(JAVA_HOME, "bin/" + fileName).getPath())) return foundFile;
        return  fileName;
    }

    /**
     * Returns the canonical path for the specified path. Eg, if "." is passed, this will resolve the actual path and return it.
     */
    static public String canonical (String path) {
        if (path == null) throw new IllegalArgumentException("path cannot be null.");

        File file = new File(path);
        try {
            return file.getCanonicalPath();
        } catch (IOException ex) {
            file = file.getAbsoluteFile();
            if (file.getName().equals(".")) file = file.getParentFile();
            return file.getPath();
        }
    }

    /**
     * Deletes a file or directory and all files and subdirecties under it.
     */
    static public boolean delete (String fileName) {
        if (fileName == null) throw new IllegalArgumentException("fileName cannot be null.");

        File file = new File(fileName);
        return !file.exists() || delete( file );
    }

    private static boolean delete(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for ( File aFile : files )
            {
                delete( aFile );
            }
        }
        if (TRACE) trace("scar", "Deleting file: " + file);
        return file.delete();
    }

    /**
     * Creates the directories in the specified path.
     */
    static public String mkdir (String path) {
        if (path == null) throw new IllegalArgumentException("path cannot be null.");

        if (new File(path).mkdirs() && TRACE) trace("scar", "Created directory: " + path);
        return path;
    }

    /**
     * Returns true if the file exists.
     */
    static public boolean fileExists (String path) {
        if (path == null) throw new IllegalArgumentException("path cannot be null.");

        return new File(path).exists();
    }

    /**
     * Reads to the end of the input stream and writes the bytes to the output stream.
     */
    static public void copyStream (InputStream input, OutputStream output) throws IOException {
        if (input == null) throw new IllegalArgumentException("input cannot be null.");
        if (output == null) throw new IllegalArgumentException("output cannot be null.");

        try {
            byte[] buffer = new byte[4096];
            while (true) {
                int length = input.read(buffer);
                if (length == -1) break;
                output.write(buffer, 0, length);
            }
        } finally {
            try {
                output.close();
            } catch (Exception ignored) {
            }
            try {
                input.close();
            } catch (Exception ignored) {
            }
        }
    }

    /**
     * Copies a file, overwriting any existing file at the destination.
     */
    static public String copyFile (String in, String out) throws IOException {
        if (in == null) throw new IllegalArgumentException("in cannot be null.");
        if (out == null) throw new IllegalArgumentException("out cannot be null.");

        if (TRACE) trace("scar", "Copying file: " + in + " -> " + out);

        FileChannel sourceChannel = null;
        FileChannel destinationChannel = null;
        try {
            sourceChannel = new FileInputStream(in).getChannel();
            destinationChannel = new FileOutputStream(out).getChannel();
            sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
        } finally {
            try {
                if (sourceChannel != null) sourceChannel.close();
            } catch (Exception ignored) {
            }
            try {
                if (destinationChannel != null) destinationChannel.close();
            } catch (Exception ignored) {
            }
        }
        return out;
    }

    /**
     * Moves a file, overwriting any existing file at the destination.
     */
    static public String moveFile (String in, String out) throws IOException {
        if (in == null) throw new IllegalArgumentException("in cannot be null.");
        if (out == null) throw new IllegalArgumentException("out cannot be null.");

        copyFile(in, out);
        delete(in);
        return out;
    }

    /**
     * Returns the textual contents of the specified file.
     */
    static public String fileContents (String path) throws IOException {
        StringBuilder stringBuffer = new StringBuilder(4096);
        FileReader reader = new FileReader(path);
        try {
            char[] buffer = new char[2048];
            while (true) {
                int length = reader.read(buffer);
                if (length == -1) break;
                stringBuffer.append(buffer, 0, length);
            }
        } finally {
            try {
                reader.close();
            } catch (Exception ignored) {
            }
        }
        return stringBuffer.toString();
    }

    /**
     * Returns only the filename portion of the specified path.
     */
    static public String fileName (String path) {
        return new File(canonical(path)).getName();
    }

    /**
     * Returns the parent directory of the specified path.
     */
    static public String parent (String path) {
        return new File(canonical(path)).getParent();
    }

    /**
     * Returns only the extension portion of the specified path, or an empty string if there is no extension.
     */
    static public String fileExtension (String file) {
        if (file == null) throw new IllegalArgumentException("fileName cannot be null.");

        int commaIndex = file.indexOf( '.' );
        if (commaIndex == -1) return "";
        return file.substring(commaIndex + 1);
    }

    /**
     * Returns only the filename portion of the specified path, without the extension, if any.
     */
    static public String fileWithoutExtension (String file) {
        if (file == null) throw new IllegalArgumentException("fileName cannot be null.");

        int commaIndex = file.indexOf('.');
        if (commaIndex == -1) commaIndex = file.length();
        int slashIndex = file.replace('\\', '/').lastIndexOf('/');
        if (slashIndex == -1)
            slashIndex = 0;
        else
            slashIndex++;
        return file.substring(slashIndex, commaIndex);
    }

    /**
     * Returns a substring of the specified text.
     * @param end The end index of the substring. If negative, the index used will be "text.length() + end".
     */
    static public String substring (String text, int start, int end) {
        if (text == null) throw new IllegalArgumentException("text cannot be null.");

        if (end >= 0) return text.substring(start, end);
        return text.substring(start, text.length() + end);
    }

    /**
     * Splits the specified command at spaces that are not surrounded by quotes and passes the result to {@link #shell(String...)}.
     */
    static public void shell (String command) throws IOException {
        List<String> matchList = new ArrayList<String>();
        Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
        Matcher regexMatcher = regex.matcher(command);
        while (regexMatcher.find()) {
            if (regexMatcher.group(1) != null)
                matchList.add(regexMatcher.group(1));
            else if (regexMatcher.group(2) != null)
                matchList.add(regexMatcher.group(2));
            else
                matchList.add(regexMatcher.group());
        }
        shell(matchList.toArray(new String[matchList.size()]));
    }

    /**
     * Executes the specified shell command. {@link #resolvePath(String)} is used to locate the file to execute. If not found, on
     * Windows the same filename with an "exe" extension is also tried.
     */
    static public void shell (String... command) throws IOException {
        if (command == null) throw new IllegalArgumentException("command cannot be null.");
        if (command.length == 0) throw new IllegalArgumentException("command cannot be empty.");

        String originalCommand = command[0];
        command[0] = resolvePath(command[0]);
        if (!fileExists(command[0]) && isWindows) {
            command[0] = resolvePath(command[0] + ".exe");
            if (!fileExists(command[0])) command[0] = originalCommand;
        }

        if (TRACE) {
            StringBuilder buffer = new StringBuilder(256);
            for (String text : command) {
                buffer.append(text);
                buffer.append(' ');
            }
            trace("scar", "Executing command: " + buffer);
        }

        Process process = new ProcessBuilder(command).start();
        // try {
        // process.waitFor();
        // } catch (InterruptedException ignored) {
        // }
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        while (true) {
            String line = reader.readLine();
            if (line == null) break;
            System.out.println(line);
        }
        reader.close();
        reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        while (true) {
            String line = reader.readLine();
            if (line == null) break;
            System.out.println(line);
        }
        if (process.exitValue() != 0) {
            StringBuilder buffer = new StringBuilder(256);
            for (String text : command) {
                buffer.append(text);
                buffer.append(' ');
            }
            throw new RuntimeException("Error executing command: " + buffer);
        }
    }

    /**
     * Creates a new keystore for signing JARs. If the keystore file already exists, no action will be taken.
     * @return The path to the keystore file.
     */
    static public String keystore (String keystoreFile, String alias, String password, String company, String title)
        throws IOException {
        if (keystoreFile == null) throw new IllegalArgumentException("keystoreFile cannot be null.");
        if (fileExists(keystoreFile)) return keystoreFile;
        if (alias == null) throw new IllegalArgumentException("alias cannot be null.");
        if (password == null) throw new IllegalArgumentException("password cannot be null.");
        if (password.length() < 6) throw new IllegalArgumentException("password must be 6 or more characters.");
        if (company == null) throw new IllegalArgumentException("company cannot be null.");
        if (title == null) throw new IllegalArgumentException("title cannot be null.");

        if (DEBUG)
            debug("scar", "Creating keystore (" + alias + ":" + password + ", " + company + ", " + title + "): " + keystoreFile);

        File file = new File(keystoreFile);
        file.delete();
        Process process = Runtime.getRuntime().exec(
            new String[] {resolvePath("keytool"), "-genkey", "-keystore", keystoreFile, "-alias", alias});
        OutputStreamWriter writer = new OutputStreamWriter(process.getOutputStream());
        writer.write(password + "\n"); // Enter keystore password:
        writer.write(password + "\n"); // Re-enter new password:
        writer.write(company + "\n"); // What is your first and last name?
        writer.write(title + "\n"); // What is the name of your organizational unit?
        writer.write(title + "\n"); // What is the name of your organization?
        writer.write("\n"); // What is the name of your City or Locality? [Unknown]
        writer.write("\n"); // What is the name of your State or Province? [Unknown]
        writer.write("\n"); // What is the two-letter country code for this unit? [Unknown]
        writer.write("yes\n"); // Correct?
        writer.write("\n"); // Return if same alias key password as keystore.
        writer.flush();
        process.getOutputStream().close();
        process.getInputStream().close();
        process.getErrorStream().close();
        try {
            process.waitFor();
        } catch (InterruptedException ignored) {
        }
        if (!file.exists()) throw new RuntimeException("Error creating keystore.");
        return keystoreFile;
    }

}

Commits for litesoft/trunk/Java/ScarPlus/src/com/esotericsoftware/scar/Utils.java

Diff revisions: vs.
Revision Author Commited Message
182 GeorgeS picture GeorgeS Sat 23 Apr, 2011 00:19:10 +0000