1
2
3
4
5
6
7
8
9
10
11
12
13 package com.eviware.soapui.support;
14
15 import com.eviware.soapui.support.editor.inspectors.attachments.ContentTypeHandler;
16 import com.eviware.soapui.support.types.StringToStringMap;
17
18 import java.io.*;
19 import java.lang.reflect.Method;
20 import java.net.URL;
21 import java.net.URLDecoder;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.List;
25
26 public class Tools
27 {
28 public static final int COPY_BUFFER_SIZE = 1000;
29
30 public static String[] tokenizeArgs(String args)
31 {
32 if( args == null || args.trim().length() == 0 )
33 return null;
34
35 List<String> l = Arrays.asList( args.split( " " ));
36 List<String> result = new ArrayList<String>();
37
38 for( int c = 0; c < l.size(); c++ )
39 {
40 String s = l.get( c );
41 if( s.startsWith( "\"" ))
42 {
43 c++;
44 s += " " + l.get( c );
45 while( !(s.endsWith( "\"") && !s.endsWith( "//\"" )) && c < l.size() )
46 {
47 c++;
48 }
49
50
51 s = c == l.size() ? s.substring( 1 ) : s.substring( 1, s.length()-1 );
52
53
54 s = s.replace( "//\"", "\"" );
55 }
56
57 result.add( s );
58 }
59
60 return result.toArray( new String[result.size()]);
61 }
62
63 public static String convertToHtml( String str )
64 {
65 StringBuffer result = new StringBuffer( "<html><body>");
66
67 for( int c = 0; c < str.length(); c++ )
68 {
69 char ch = str.charAt( c );
70 if( ch == '\n' )
71 result.append( "<br>" );
72 else
73 result.append( ch );
74 }
75
76 result.append( "</body></html>");
77 return result.toString();
78 }
79
80 public static String getFilename(String filePath)
81 {
82 if (filePath == null || filePath.length() == 0)
83 return filePath;
84
85 int ix = filePath.lastIndexOf( File.separatorChar );
86 if (ix <= 0)
87 return filePath;
88
89 return filePath.substring(ix+1, filePath.length());
90 }
91
92 public static String getDir(String filePath)
93 {
94 if (filePath == null || filePath.length() == 0)
95 return filePath;
96
97 int ix = filePath.lastIndexOf( File.separatorChar );
98 if (ix <= 0)
99 return filePath;
100
101 return ensureDir(filePath.substring(0, ix), "");
102 }
103
104 public static String ensureDir(String dir, String basedir )
105 {
106 if( dir == null || dir.length() == 0 )
107 return "";
108
109 File dirFile = new File( dir );
110 if( !dirFile.isAbsolute() )
111 {
112 if( basedir.length() == 0 )
113 basedir = new File("").getAbsolutePath();
114
115 dirFile = new File( basedir, dir );
116 }
117
118 dirFile.mkdirs();
119 return dirFile.getAbsolutePath();
120 }
121
122 public static String ensureFileDir(String file, String basedir )
123 {
124 if( file == null || file.length() == 0 )
125 return "";
126
127 File dirFile = new File( basedir, file );
128 if( !dirFile.isAbsolute() )
129 {
130 if( basedir.length() == 0 )
131 basedir = new File("").getAbsolutePath();
132
133 dirFile = new File( basedir, file );
134 }
135
136 String absolutePath = dirFile.getAbsolutePath();
137 if( !dirFile.exists() )
138 {
139 int ix = absolutePath.lastIndexOf( File.separatorChar );
140 File fileDir = new File( absolutePath.substring( 0, ix ));
141 fileDir.mkdirs();
142 }
143
144 return absolutePath;
145 }
146
147 public static String ensureDir(String outputDir)
148 {
149 if( outputDir == null )
150 outputDir = "";
151
152 File output = new File(outputDir);
153 output.mkdirs();
154 return outputDir;
155 }
156
157
158 private static final byte[] copyBuffer = new byte[8192];
159 public static final long READ_ALL = 0;
160
161 public static void openURL(String url)
162 {
163 String osName = System.getProperty("os.name");
164
165 try
166 {
167 if (osName.startsWith("Mac OS")) {
168 Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
169 Method openURL = fileMgr.getDeclaredMethod("openURL",
170 new Class[] {String.class});
171 openURL.invoke(null, new Object[] {url});
172 }
173 else if (osName.startsWith("Windows"))
174 {
175 if( url.startsWith( "file:" ))
176 {
177 url = URLDecoder.decode( url.substring( 5 ), "utf-8");
178 while( url.startsWith( "/"))
179 url = url.substring( 1 );
180
181 url = url.replace( '/', '//' );
182
183 if( !new File( url ).exists())
184 {
185 UISupport.showErrorMessage( "File [" + url + "] not found" );
186 return;
187 }
188 }
189
190 Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
191 }
192 else {
193 String[] browsers = {
194 "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
195 String browser = null;
196 for (int count = 0; count < browsers.length && browser == null; count++)
197 if (Runtime.getRuntime().exec(
198 new String[] {"which", browsers[count]}).waitFor() == 0)
199 browser = browsers[count];
200 if (browser == null)
201 throw new Exception("Could not find web browser");
202 else
203 Runtime.getRuntime().exec(new String[] {browser, url});
204 }
205 }
206 catch (Exception e)
207 {
208 UISupport.showErrorMessage(e);
209 }
210 }
211
212 public static ByteArrayOutputStream readAll(InputStream instream, long maxSize) throws IOException
213 {
214 ByteArrayOutputStream outstream = new ByteArrayOutputStream( 4096 );
215
216 readAndWrite(instream, maxSize, outstream);
217
218 outstream.close();
219 return outstream;
220 }
221
222 public static void readAndWrite(InputStream instream, long maxSize, OutputStream outstream)
223 throws IOException
224 {
225 byte[] buffer = new byte[4096];
226 int len;
227 int read = 0;
228 int toRead = 4096;
229
230 if( maxSize > 0 )
231 {
232 if( read + toRead > maxSize )
233 toRead = (int) (maxSize - read);
234 }
235
236 while ((len = instream.read(buffer, 0, toRead )) > 0)
237 {
238 outstream.write(buffer, 0, len);
239 read += toRead;
240
241 if( maxSize > 0 )
242 {
243 if( read + toRead > maxSize )
244 toRead = (int) (maxSize - read);
245 }
246 }
247 }
248
249 public static int copyFile( File source, File target, boolean overwrite ) throws IOException
250 {
251 int bytes = 0;
252
253 if( target.exists() )
254 {
255 if( overwrite )
256 target.delete();
257 else
258 return -1;
259 }
260 else
261 {
262 String path = target.getAbsolutePath();
263 int ix = path.lastIndexOf( File.separatorChar );
264 if( ix != -1 )
265 {
266 path = path.substring( 0, ix );
267 File pathFile = new File( path );
268 if( !pathFile.exists() )
269 pathFile.mkdirs();
270 }
271 }
272
273 BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
274 BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target));
275
276 int read = in.read( copyBuffer );
277 while( read != -1 )
278 {
279 if( read > 0 )
280 {
281 out.write( copyBuffer, 0, read );
282 bytes += read;
283 }
284 read = in.read( copyBuffer );
285 }
286
287 in.close();
288 out.close();
289
290 return bytes;
291 }
292
293 /***
294 * Joins a relative url to a base url.. needs improvements..
295 */
296
297 public static String joinRelativeUrl( String baseUrl, String url )
298 {
299 if( baseUrl.indexOf( '?' ) > 0 )
300 baseUrl = baseUrl.substring(0,baseUrl.indexOf('?'));
301
302 boolean isWindowsUrl = baseUrl.indexOf( '//' ) >= 0;
303 boolean isUsedInUnix = File.separatorChar == '/';
304
305 if( isUsedInUnix && isWindowsUrl )
306 {
307 baseUrl = baseUrl.replace( '//', '/' );
308 url = url.replace( '//', '/' );
309 }
310
311 boolean isFile = baseUrl.startsWith("file:");
312
313 int ix = baseUrl.lastIndexOf( '//' );
314 if( ix == -1 ) ix = baseUrl.lastIndexOf( '/' );
315
316
317 if( url.startsWith("/") && !isFile )
318 {
319 ix = baseUrl.indexOf( "/", baseUrl.indexOf("//")+2);
320 return baseUrl.substring(0, ix ) + url;
321 }
322
323
324 while( url.startsWith( ".//" ) || url.startsWith( "./" ))
325 url = url.substring( 2 );
326
327
328 while( url.startsWith( "../" ) || url.startsWith( "..//" ))
329 {
330 int ix2 = baseUrl.lastIndexOf( '//', ix-1 );
331 if( ix2 == -1 )
332 ix2 = baseUrl.lastIndexOf( '/', ix-1 );
333 if( ix2 == -1 )
334 break;
335
336 baseUrl = baseUrl.substring( 0, ix2+1 );
337 ix = ix2;
338
339 url = url.substring( 3 );
340 }
341
342
343 while( url.indexOf( "/./" ) != -1 || url.indexOf( "//.//") != -1 )
344 {
345 int ix2 = url.indexOf( "/./");
346 if( ix2 == -1 )
347 ix2 = url.indexOf( "//.//" );
348
349 url = url.substring( 0, ix2 ) + url.substring( ix2+2 );
350 }
351
352
353 while( url.indexOf( "/../" ) != -1 || url.indexOf( "//..//") != -1 )
354 {
355 int ix2 = -1;
356
357 int ix3 = url.indexOf( "/../");
358 if( ix3 == -1 )
359 {
360 ix3 = url.indexOf( "//..//" );
361 ix2 = url.lastIndexOf( '//', ix3-1 );
362 }
363 else
364 {
365 ix2 = url.lastIndexOf( '/', ix3-1 );
366 }
367
368 if( ix2 == -1 )
369 break;
370
371 url = url.substring( 0, ix2 ) + url.substring( ix3+3 );
372 }
373
374 String result = baseUrl.substring( 0, ix+1 ) + url;
375 if( isFile )
376 result = result.replace( '/', File.separatorChar );
377
378 return result;
379 }
380
381 public static boolean isEmpty(String str)
382 {
383 return str == null || str.trim().length() == 0;
384 }
385
386 public static long writeAll( OutputStream out, InputStream in ) throws IOException
387 {
388 byte [] buffer = new byte[COPY_BUFFER_SIZE];
389 long total = 0;
390
391 int sz = in.read( buffer );
392 while( sz != -1 )
393 {
394 out.write( buffer, 0, sz );
395 total += sz;
396 sz = in.read( buffer );
397 }
398
399 return total;
400 }
401
402 public static String expandProperties(StringToStringMap values, String content, boolean leaveMissing)
403 {
404 int ix = content.indexOf( "${" );
405 if( ix == -1 )
406 return content;
407
408 StringBuffer buf = new StringBuffer();
409 int lastIx = 0;
410 while( ix != -1 )
411 {
412 buf.append( content.substring( lastIx, ix ));
413
414 int ix2 = content.indexOf( '}', ix+2 );
415 if( ix2 == -1 )
416 break;
417
418 int ix3 = content.lastIndexOf( "${", ix2 );
419 if( ix3 != ix )
420 {
421 buf.append( content.substring( ix, ix3 ));
422 ix = ix3;
423 }
424
425 String propertyName = content.substring( ix+2, ix2 );
426 Object property = values.get( propertyName );
427 if( property != null )
428 {
429 buf.append( property.toString() );
430 }
431 else if( leaveMissing )
432 {
433 buf.append( "${" ).append( propertyName ).append( '}' );
434 }
435
436 lastIx = ix2+1;
437 ix = content.indexOf( "${", lastIx );
438 }
439
440 if( lastIx < content.length() )
441 buf.append( content.substring( lastIx ));
442
443 return buf.toString();
444 }
445
446 /***
447 * Replaces the host part of the specified endpoint with the specified host
448 *
449 * @param endpoint the endpoint to modify
450 * @param host the host to set
451 * @return the modified endpoint
452 */
453
454 public static String replaceHost(String endpoint, String host)
455 {
456 int ix1 = endpoint.indexOf( "://" );
457 if( ix1 < 0 )
458 return endpoint;
459
460 int ix2 = endpoint.indexOf( ":", ix1+3 );
461 if( ix2 == -1 || host.indexOf( ":") > 0 )
462 {
463 ix2 = endpoint.indexOf( "/", ix1+3 );
464 if( ix2 == ix1+3 )
465 ix2 = -1;
466 }
467
468 return endpoint.substring( 0, ix1 )+ "://" + host + (ix2 == -1 ? "" : endpoint.substring(ix2));
469 }
470
471 public static String getEndpointFromUrl(URL baseUrl)
472 {
473 StringBuffer result = new StringBuffer();
474 result.append( baseUrl.getProtocol() ).append( "://" );
475 result.append( baseUrl.getHost());
476 if( baseUrl.getPort() > 0 )
477 result.append( ':').append( baseUrl.getPort());
478
479 return result.toString();
480 }
481
482 public static String getContentTypeFromFilename(String fileName)
483 {
484 return ContentTypeHandler.getContentTypeFromFilename( fileName );
485 }
486
487 public static String getExtensionForContentType( String contentType )
488 {
489 return ContentTypeHandler.getExtensionForContentType( contentType );
490 }
491 }