Debian Codegraph @

ssl-proxies/src/main/java/org/globus/util/Util.java

raw
1 /*
2 * Copyright 1999-2010 University of Chicago
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5 * compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is
10 * distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11 * express or implied.
12 *
13 * See the License for the specific language governing permissions and limitations under the License.
14 */
15 package org.globus.util;
16
17 import java.io.IOException;
18 import java.io.BufferedReader;
19 import java.io.InputStreamReader;
20 import java.io.RandomAccessFile;
21 import java.io.File;
22 import java.io.UnsupportedEncodingException;
23 import java.net.InetAddress;
24 import java.net.UnknownHostException;
25
26 import org.globus.common.CoGProperties;
27
28
29 public class Util {
30
31 private static final String CHMOD = "chmod";
32
33 private static final String DMSG =
34 "Destroyed by Java Globus Proxy Destroy\r\n";
35
36 /**
37 * Attempts to create a new file in an atomic way.
38 * If the file already exists, it if first deleted.
39 *
40 * @param filename the name of file to create.
41 * @return the created file.
42 * @throws SecurityException if the existing file cannot be deleted.
43 * @throws IOException if an I/O error occurred.
44 */
45 public static File createFile(String filename)
46 throws SecurityException, IOException {
47
48 File f = new File(filename);
49 if (!f.createNewFile()) {
50 if (!destroy(f)) {
51 throw new SecurityException(
52 "Could not destroy existing file");
53 }
54 if (!f.createNewFile()) {
55 throw new SecurityException(
56 "Failed to atomically create new file");
57 }
58 }
59 return f;
60 }
61
62 /**
63 * Sets permissions on a given file to be only accessible by the current
64 * user.
65 *
66 * @see #setFilePermissions(String, int)
67 */
68 public static boolean setOwnerAccessOnly(String file) {
69 return setFilePermissions(file, 600);
70 }
71
72 /**
73 * Sets permissions on a given file. The permissions
74 * are set using the <i>chmod</i> command and will only
75 * work on Linux/Unix machines. <i>Chmod</i> command must be in the path.
76 * <BR><BR><B>Note: </B><I>
77 * This function executes an external program; thus, its behavior is
78 * influenced by environment variables such as the caller's PATH and the
79 * environment variables that control dynamic loading. Care should be
80 * used if calling this function from a program that will be run as a
81 * Unix setuid program, or in any other manner in which the owner of the
82 * Unix process does not completely control its runtime environment.
83 * </I>
84 *
85 * @param file the file to set the permissions of.
86 * @param mode the Unix style permissions.
87 * @return true, if change was successful, otherwise false.
88 * It can return false, in many instances, e.g. when file
89 * does not exits, when chmod is not found, or other error
90 * occurs.
91 */
92 public static boolean setFilePermissions(String file, int mode) {
93 // since this will not work on Windows
94 if (ConfigUtil.getOS() == ConfigUtil.WINDOWS_OS) {
95 return false;
96 }
97
98 Runtime runtime = Runtime.getRuntime();
99 String [] cmd = new String[] { CHMOD,
100 String.valueOf(mode),
101 file };
102 Process process = null;
103 try {
104 process = runtime.exec(cmd, null);
105 return (process.waitFor() == 0) ? true : false;
106 } catch(Exception e) {
107 return false;
108 } finally {
109 if (process != null) {
110 try {
111 process.getErrorStream().close();
112 } catch (IOException e) {}
113 try {
114 process.getInputStream().close();
115 } catch (IOException e) {}
116 try {
117 process.getOutputStream().close();
118 } catch (IOException e) {}
119 }
120 }
121 }
122
123 /**
124 * Overwrites the contents of the file with a random
125 * string and then deletes the file.
126 *
127 * @param file file to remove
128 */
129 public static boolean destroy(String file) {
130 return destroy(new File(file));
131 }
132
133 /**
134 * Overwrites the contents of the file with a random
135 * string and then deletes the file.
136 *
137 * @param file file to remove
138 */
139 public static boolean destroy(File file) {
140 if (!file.exists()) return false;
141
142 RandomAccessFile f = null;
143 long size = file.length();
144 try {
145 f = new RandomAccessFile(file, "rw");
146 long rec = size/DMSG.length();
147 int left = (int)(size - rec*DMSG.length());
148 while(rec != 0) {
149 f.write(DMSG.getBytes(), 0, DMSG.length());
150 rec--;
151 }
152 if (left > 0) {
153 f.write(DMSG.getBytes(), 0, left);
154 }
155 } catch(Exception e) {
156 return false;
157 } finally {
158 try {
159 if (f != null) f.close();
160 } catch(Exception e) {}
161 }
162
163 return file.delete();
164 }
165
166 /**
167 * Displays a prompt and then reads in the input from System.in.
168 *
169 * @param prompt the prompt to be displayed
170 * @return <code>String</code> the input read in (entered after the prompt)
171 */
172 public static String getInput(String prompt) {
173 System.out.print(prompt);
174
175 try {
176 BufferedReader in =
177 new BufferedReader(new InputStreamReader(System.in));
178 return in.readLine();
179 } catch(IOException e) {
180 return null;
181 }
182 }
183
184 /**
185 * Displays a prompt and then reads in private input from System.in.
186 * Characters typed by the user are replaced with a space on the screen.
187 *
188 * @param prompt the prompt to be displayed
189 * @return <code>String</code> the input read in (entered after the prompt)
190 */
191 public static String getPrivateInput(String prompt) {
192 System.out.print(prompt);
193
194 PrivateInputThread privateInput = new PrivateInputThread();
195 BufferedReader in =
196 new BufferedReader(new InputStreamReader(System.in));
197
198 privateInput.start();
199 try {
200 return in.readLine();
201 } catch(Exception e) {
202 return null;
203 } finally {
204 privateInput.kill();
205 }
206 }
207
208 /**
209 * A helper thread to mask private user input.
210 */
211 private static class PrivateInputThread extends Thread {
212 private volatile boolean stopThread = false;
213
214 public void kill() {
215 this.stopThread = true;
216 }
217
218 public void run() {
219 while(!this.stopThread) {
220 System.out.print("\b ");
221
222 try {
223 sleep(1);
224 } catch(InterruptedException e) { }
225 }
226 }
227 }
228
229 /**
230 * Quotifies a specified string.
231 * The entire string is encompassed by double quotes and each
232 * " is replaced with \", \ is replaced with \\.
233 *
234 * @param str the string to quotify
235 * @return quotified and escaped string
236 */
237 public static String quote(String str) {
238 int len = str.length();
239 StringBuffer buf = new StringBuffer(len+2);
240 buf.append("\"");
241 char c;
242 for (int i=0;i<len;i++) {
243 c = str.charAt(i);
244 if (c == '"' || c == '\\') {
245 buf.append("\\");
246 }
247 buf.append(c);
248 }
249 buf.append("\"");
250 return buf.toString();
251 }
252
253 /**
254 * Dequotifies a specified string.
255 * The quotes are removed and each \" is replaced with " and
256 * each \\ is replaced with \.
257 *
258 * @param str the string to dequotify.
259 * @return unquotified string.
260 */
261 public static String unquote(String str)
262 throws Exception {
263 int len = str.length();
264 StringBuffer buf = new StringBuffer(len);
265 boolean inQuotes = false;
266 char c;
267 int i = 0;
268
269 if (str.charAt(i) == '"') {
270 inQuotes = true;
271 i++;
272 }
273 while(i < len) {
274 c = str.charAt(i);
275 if (inQuotes) {
276 if (c == '"') {
277 inQuotes = false;
278 } else if (c == '\\') {
279 buf.append(str.charAt(++i));
280 } else {
281 buf.append(c);
282 }
283 } else {
284 if (c == '\r') {
285 if (str.charAt(i++) != '\n') {
286 throw new Exception("Malformed string.");
287 }
288 } else if (c == '"') {
289 inQuotes = true;
290 i++;
291 } else {
292 buf.append(c);
293 }
294 }
295 i++;
296 }
297 return buf.toString();
298 }
299
300 /**
301 * The function decodes URL-encoded strings into a regular string.
302 * This function is mostly copied from the Java source code.
303 * To convert to a <code>String</code>, each character is examined in turn:
304 * <ul>
305 * <li>The remaining characters are represented by 3-character
306 * strings which begin with the percent sign,
307 * "<code>%<i>xy</i></code>", where <i>xy</i> is the two-digit
308 * hexadecimal representation of the lower 8-bits of the character.
309 * </ul>
310 */
311 public static String decode(String s) {
312 StringBuffer sb = new StringBuffer();
313 for(int i=0; i<s.length(); i++) {
314 char c = s.charAt(i);
315 switch (c) {
316 case '%':
317 try {
318 sb.append((char)Integer.parseInt(
319 s.substring(i+1,i+3),16));
320 } catch (NumberFormatException e) {
321 throw new IllegalArgumentException();
322 }
323 i += 2;
324 break;
325 default:
326 sb.append(c);
327 break;
328 }
329 }
330 // Undo conversion to external encoding
331 String result = sb.toString();
332 try {
333 byte[] inputBytes = result.getBytes("8859_1");
334 result = new String(inputBytes);
335 } catch (UnsupportedEncodingException e) {
336 // The system should always have 8859_1
337 }
338 return result;
339 }
340
341
342 /**
343 * Generates string representation of given time specified
344 * as long. The format is: [days][,][h][,][min][,][sec]
345 *
346 */
347 public static String formatTimeSec(long time) {
348
349 StringBuffer str = new StringBuffer();
350
351 if (time < 60) {
352 str.append(time + " sec");
353 return str.toString();
354 }
355
356 int days = (int) time / 86400;
357
358 if (days != 0) {
359 str.append(days + " days");
360 time -= days * 86400;
361 }
362
363 int hours = (int) time / 3600;
364
365 if (hours != 0) {
366 if (str.length() != 0) str.append(", ");
367 str.append(hours + " h");
368 time -= hours * 3600;
369 }
370
371 int mins = (int) time / 60;
372
373 if (mins != 0) {
374 if (str.length() != 0) str.append(", ");
375 str.append(mins + " min");
376 time -= mins * 60;
377 }
378
379 int sec = (int) time;
380
381 if (sec != 0) {
382 if (str.length() != 0) str.append(", ");
383 str.append(sec + " sec");
384 }
385
386 return str.toString();
387 }
388
389 /**
390 * Returns the ip address of the local machine.
391 * If the 'ip' system property is defined it is returned,
392 * otherwise, the local ip address is lookup using the
393 * <code>InetAddress</code> class. In case the lookup
394 * fails, the address 127.0.0.1 is returned.
395 *
396 * @return local ip address
397 */
398 public static String getLocalHostAddress() {
399 String ipAddr = CoGProperties.getDefault().getIPAddress();
400 if (ipAddr == null) {
401 try {
402 return InetAddress.getLocalHost().getHostAddress();
403 } catch (UnknownHostException e) {
404 return "127.0.0.1";
405 }
406 } else {
407 return ipAddr;
408 }
409 }
410
411 }