001: /*
002: * soapUI, copyright (C) 2004-2007 eviware.com
003: *
004: * soapUI is free software; you can redistribute it and/or modify it under the
005: * terms of version 2.1 of the GNU Lesser General Public License as published by
006: * the Free Software Foundation.
007: *
008: * soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
009: * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
010: * See the GNU Lesser General Public License for more details at gnu.org.
011: */
012:
013: package com.eviware.soapui.support;
014:
015: import java.io.BufferedInputStream;
016: import java.io.BufferedOutputStream;
017: import java.io.ByteArrayOutputStream;
018: import java.io.File;
019: import java.io.FileInputStream;
020: import java.io.FileOutputStream;
021: import java.io.IOException;
022: import java.io.InputStream;
023: import java.io.OutputStream;
024: import java.lang.reflect.Method;
025: import java.util.ArrayList;
026: import java.util.Arrays;
027: import java.util.List;
028:
029: import com.eviware.soapui.support.types.StringToStringMap;
030:
031: public class Tools {
032: public static final int COPY_BUFFER_SIZE = 1000;
033:
034: public static String[] tokenizeArgs(String args) {
035: if (args == null || args.trim().length() == 0)
036: return null;
037:
038: List<String> l = Arrays.asList(args.split(" "));
039: List<String> result = new ArrayList<String>();
040:
041: for (int c = 0; c < l.size(); c++) {
042: String s = l.get(c);
043: if (s.startsWith("\"")) {
044: c++;
045: s += " " + l.get(c);
046: while (!(s.endsWith("\"") && !s.endsWith("\\\""))
047: && c < l.size()) {
048: c++;
049: }
050:
051: // remove trailing/leading quotes
052: s = c == l.size() ? s.substring(1) : s.substring(1, s
053: .length() - 1);
054:
055: // replace backslashed quotes
056: s = s.replace("\\\"", "\"");
057: }
058:
059: result.add(s);
060: }
061:
062: return result.toArray(new String[result.size()]);
063: }
064:
065: public static String convertToHtml(String str) {
066: StringBuffer result = new StringBuffer("<html><body>");
067:
068: for (int c = 0; c < str.length(); c++) {
069: char ch = str.charAt(c);
070: if (ch == '\n')
071: result.append("<br>");
072: else
073: result.append(ch);
074: }
075:
076: result.append("</body></html>");
077: return result.toString();
078: }
079:
080: public static String getFilename(String filePath) {
081: if (filePath == null || filePath.length() == 0)
082: return filePath;
083:
084: int ix = filePath.lastIndexOf(File.separatorChar);
085: if (ix <= 0)
086: return filePath;
087:
088: return filePath.substring(ix + 1, filePath.length());
089: }
090:
091: public static String getDir(String filePath) {
092: if (filePath == null || filePath.length() == 0)
093: return filePath;
094:
095: int ix = filePath.lastIndexOf(File.separatorChar);
096: if (ix <= 0)
097: return filePath;
098:
099: return ensureDir(filePath.substring(0, ix), "");
100: }
101:
102: public static String ensureDir(String dir, String basedir) {
103: if (dir == null || dir.length() == 0)
104: return "";
105:
106: File dirFile = new File(dir);
107: if (!dirFile.isAbsolute()) {
108: if (basedir.length() == 0)
109: basedir = new File("").getAbsolutePath();
110:
111: dirFile = new File(basedir, dir);
112: }
113:
114: dirFile.mkdirs();
115: return dirFile.getAbsolutePath();
116: }
117:
118: public static String ensureFileDir(String file, String basedir) {
119: if (file == null || file.length() == 0)
120: return "";
121:
122: File dirFile = new File(basedir, file);
123: if (!dirFile.isAbsolute()) {
124: if (basedir.length() == 0)
125: basedir = new File("").getAbsolutePath();
126:
127: dirFile = new File(basedir, file);
128: }
129:
130: String absolutePath = dirFile.getAbsolutePath();
131: if (!dirFile.exists()) {
132: int ix = absolutePath.lastIndexOf(File.separatorChar);
133: File fileDir = new File(absolutePath.substring(0, ix));
134: fileDir.mkdirs();
135: }
136:
137: return absolutePath;
138: }
139:
140: public static String ensureDir(String outputDir) {
141: if (outputDir == null)
142: outputDir = "";
143:
144: File output = new File(outputDir);
145: output.mkdirs();
146: return outputDir;
147: }
148:
149: // preallocate so it does not consume memory after out-of-memory errors
150: private static final byte[] copyBuffer = new byte[8192];
151: public static final long READ_ALL = 0;
152:
153: public static void openURL(String url) {
154: String osName = System.getProperty("os.name");
155:
156: try {
157: if (osName.startsWith("Mac OS")) {
158: Class fileMgr = Class
159: .forName("com.apple.eio.FileManager");
160: Method openURL = fileMgr.getDeclaredMethod("openURL",
161: new Class[] { String.class });
162: openURL.invoke(null, new Object[] { url });
163: } else if (osName.startsWith("Windows")) {
164: Runtime.getRuntime().exec(
165: "rundll32 url.dll,FileProtocolHandler " + url);
166: } else { //assume Unix or Linux
167: String[] browsers = { "firefox", "opera", "konqueror",
168: "epiphany", "mozilla", "netscape" };
169: String browser = null;
170: for (int count = 0; count < browsers.length
171: && browser == null; count++)
172: if (Runtime.getRuntime().exec(
173: new String[] { "which", browsers[count] })
174: .waitFor() == 0)
175: browser = browsers[count];
176: if (browser == null)
177: throw new Exception("Could not find web browser");
178: else
179: Runtime.getRuntime().exec(
180: new String[] { browser, url });
181: }
182: } catch (Exception e) {
183: UISupport.showErrorMessage(e);
184: }
185: }
186:
187: public static ByteArrayOutputStream readAll(InputStream instream,
188: long maxSize) throws IOException {
189: ByteArrayOutputStream outstream = new ByteArrayOutputStream(
190: 4096);
191:
192: byte[] buffer = new byte[4096];
193: int len;
194: int read = 0;
195: int toRead = 4096;
196:
197: if (maxSize > 0) {
198: if (read + toRead > maxSize)
199: toRead = (int) (maxSize - read);
200: }
201:
202: while ((len = instream.read(buffer, 0, toRead)) > 0) {
203: outstream.write(buffer, 0, len);
204: read += toRead;
205:
206: if (maxSize > 0) {
207: if (read + toRead > maxSize)
208: toRead = (int) (maxSize - read);
209: }
210: }
211:
212: outstream.close();
213: return outstream;
214: }
215:
216: public static int copyFile(File source, File target,
217: boolean overwrite) throws IOException {
218: int bytes = 0;
219:
220: if (overwrite && target.exists()) {
221: target.delete();
222: } else if (!target.exists()) {
223: String path = target.getAbsolutePath();
224: int ix = path.lastIndexOf(File.separatorChar);
225: if (ix != -1) {
226: path = path.substring(0, ix);
227: File pathFile = new File(path);
228: if (!pathFile.exists())
229: pathFile.mkdirs();
230: }
231: }
232:
233: BufferedInputStream in = new BufferedInputStream(
234: new FileInputStream(source));
235: BufferedOutputStream out = new BufferedOutputStream(
236: new FileOutputStream(target));
237:
238: int read = in.read(copyBuffer);
239: while (read != -1) {
240: if (read > 0) {
241: out.write(copyBuffer, 0, read);
242: bytes += read;
243: }
244: read = in.read(copyBuffer);
245: }
246:
247: in.close();
248: out.close();
249:
250: return bytes;
251: }
252:
253: /**
254: * Joins a relative url to a base url.. needs improvements..
255: */
256:
257: public static String joinRelativeUrl(String baseUrl, String url) {
258: boolean isWindowsUrl = baseUrl.indexOf('\\') >= 0;
259: boolean isUsedInUnix = File.separatorChar == '/';
260:
261: if (isUsedInUnix && isWindowsUrl) {
262: baseUrl = baseUrl.replace('\\', '/');
263: url = url.replace('\\', '/');
264: }
265:
266: boolean isFile = baseUrl.startsWith("file:");
267:
268: int ix = baseUrl.lastIndexOf('\\');
269: if (ix == -1)
270: ix = baseUrl.lastIndexOf('/');
271:
272: // remove leader "./"
273: while (url.startsWith(".\\") || url.startsWith("./"))
274: url = url.substring(2);
275:
276: // remove leading "../"
277: while (url.startsWith("../") || url.startsWith("..\\")) {
278: int ix2 = baseUrl.lastIndexOf('\\', ix - 1);
279: if (ix2 == -1)
280: ix2 = baseUrl.lastIndexOf('/', ix - 1);
281: if (ix2 == -1)
282: break;
283:
284: baseUrl = baseUrl.substring(0, ix2 + 1);
285: ix = ix2;
286:
287: url = url.substring(3);
288: }
289:
290: // remove "/./"
291: while (url.indexOf("/./") != -1 || url.indexOf("\\.\\") != -1) {
292: int ix2 = url.indexOf("/./");
293: if (ix2 == -1)
294: ix2 = url.indexOf("\\.\\");
295:
296: url = url.substring(0, ix2) + url.substring(ix2 + 2);
297: }
298:
299: // remove "/../"
300: while (url.indexOf("/../") != -1 || url.indexOf("\\..\\") != -1) {
301: int ix2 = -1;
302:
303: int ix3 = url.indexOf("/../");
304: if (ix3 == -1) {
305: ix3 = url.indexOf("\\..\\");
306: ix2 = url.lastIndexOf('\\', ix3 - 1);
307: } else {
308: ix2 = url.lastIndexOf('/', ix3 - 1);
309: }
310:
311: if (ix2 == -1)
312: break;
313:
314: url = url.substring(0, ix2) + url.substring(ix3 + 3);
315: }
316:
317: String result = baseUrl.substring(0, ix + 1) + url;
318: if (isFile)
319: result = result.replace('/', File.separatorChar);
320:
321: return result;
322: }
323:
324: public static boolean isEmpty(String str) {
325: return str == null || str.trim().length() == 0;
326: }
327:
328: public static long writeAll(OutputStream out, InputStream in)
329: throws IOException {
330: byte[] buffer = new byte[COPY_BUFFER_SIZE];
331: long total = 0;
332:
333: int sz = in.read(buffer);
334: while (sz != -1) {
335: out.write(buffer, 0, sz);
336: total += sz;
337: sz = in.read(buffer);
338: }
339:
340: return total;
341: }
342:
343: public static String expandProperties(StringToStringMap values,
344: String content, boolean leaveMissing) {
345: int ix = content.indexOf("${");
346: if (ix == -1)
347: return content;
348:
349: StringBuffer buf = new StringBuffer();
350: int lastIx = 0;
351: while (ix != -1) {
352: buf.append(content.substring(lastIx, ix));
353:
354: int ix2 = content.indexOf('}', ix + 2);
355: if (ix2 == -1)
356: break;
357:
358: int ix3 = content.lastIndexOf("${", ix2);
359: if (ix3 != ix) {
360: buf.append(content.substring(ix, ix3));
361: ix = ix3;
362: }
363:
364: String propertyName = content.substring(ix + 2, ix2);
365: Object property = values.get(propertyName);
366: if (property != null) {
367: buf.append(property.toString());
368: } else if (leaveMissing) {
369: buf.append("${").append(propertyName).append('}');
370: }
371:
372: lastIx = ix2 + 1;
373: ix = content.indexOf("${", lastIx);
374: }
375:
376: if (lastIx < content.length())
377: buf.append(content.substring(lastIx));
378:
379: return buf.toString();
380: }
381:
382: /**
383: * Replaces the host part of the specified endpoint with the specified host
384: *
385: * @param endpoint the endpoint to modify
386: * @param host the host to set
387: * @return the modified endpoint
388: */
389:
390: public static String replaceHost(String endpoint, String host) {
391: int ix1 = endpoint.indexOf("://");
392: if (ix1 < 0)
393: return endpoint;
394:
395: int ix2 = endpoint.indexOf(":", ix1 + 3);
396: if (ix2 == -1 || host.indexOf(":") > 0) {
397: ix2 = endpoint.indexOf("/", ix1 + 3);
398: if (ix2 == ix1 + 3)
399: ix2 = -1;
400: }
401:
402: return endpoint.substring(0, ix1) + "://" + host
403: + (ix2 == -1 ? "" : endpoint.substring(ix2));
404: }
405: }
|