View Javadoc

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