0001: /*
0002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
0003: *
0004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
0005: *
0006: * The contents of this file are subject to the terms of either the GNU
0007: * General Public License Version 2 only ("GPL") or the Common
0008: * Development and Distribution License("CDDL") (collectively, the
0009: * "License"). You may not use this file except in compliance with the
0010: * License. You can obtain a copy of the License at
0011: * http://www.netbeans.org/cddl-gplv2.html
0012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
0013: * specific language governing permissions and limitations under the
0014: * License. When distributing the software, include this License Header
0015: * Notice in each file and include the License file at
0016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
0017: * particular file as subject to the "Classpath" exception as provided
0018: * by Sun in the GPL Version 2 section of the License file that
0019: * accompanied this code. If applicable, add the following below the
0020: * License Header, with the fields enclosed by brackets [] replaced by
0021: * your own identifying information:
0022: * "Portions Copyrighted [year] [name of copyright owner]"
0023: *
0024: * Contributor(s):
0025: *
0026: * The Original Software is NetBeans. The Initial Developer of the Original
0027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
0028: * Microsystems, Inc. All Rights Reserved.
0029: *
0030: * If you wish your version of this file to be governed by only the CDDL
0031: * or only the GPL Version 2, indicate your decision by adding
0032: * "[Contributor] elects to include this software in this distribution
0033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
0034: * single choice of license, a recipient has the option to distribute
0035: * your version of this file under either the CDDL, the GPL Version 2 or
0036: * to extend the choice of license to its licensees as provided above.
0037: * However, if you add GPL Version 2 code and therefore, elected the GPL
0038: * Version 2 license, then the option applies only if the new code is
0039: * made subject to such option by the copyright holder.
0040: */
0041:
0042: package org.netbeans.modules.uml.common;
0043:
0044: import java.util.*;
0045: import java.math.BigInteger;
0046: import java.math.BigDecimal;
0047: import java.io.*;
0048: import java.lang.reflect.*;
0049: import java.text.*;
0050: import java.net.*;
0051: import org.netbeans.modules.uml.core.coreapplication.ICoreProduct;
0052: import org.netbeans.modules.uml.core.metamodel.core.foundation.INamedElement;
0053: import org.netbeans.modules.uml.core.metamodel.core.foundation.INamespace;
0054: import org.netbeans.modules.uml.core.reverseengineering.reframework.parsingframework.ILanguage;
0055: import org.netbeans.modules.uml.core.reverseengineering.reframework.parsingframework.ILanguageManager;
0056: import org.netbeans.modules.uml.core.support.umlsupport.Log;
0057: import org.netbeans.modules.uml.core.support.umlsupport.ProductRetriever;
0058: import org.netbeans.modules.uml.core.support.umlutils.ETArrayList;
0059: import org.netbeans.modules.uml.core.support.umlutils.ETList;
0060: import org.netbeans.modules.uml.core.support.umlutils.ElementLocator;
0061: import org.netbeans.modules.uml.core.support.umlutils.IElementLocator;
0062: import org.netbeans.modules.uml.ui.support.ProductHelper;
0063: import org.openide.util.NbBundle;
0064:
0065: /**
0066: * Contains commonly used functions.
0067: *
0068: */
0069: public class Util {
0070:
0071: /** Static constant for -1. */
0072: public final static Integer MINUS_ONE = new Integer(-1);
0073:
0074: /** Static constant for 0. */
0075: public final static Integer ZERO = new Integer(0);
0076:
0077: /** Gets the platform dependent line separator. */
0078: public final static String getLineSeparator() {
0079: return cLineSeparator;
0080: }
0081:
0082: private final static String cLineSeparator;
0083:
0084: /* Load the line separator. */
0085: static {
0086: cLineSeparator = (String) java.security.AccessController
0087: .doPrivileged(new sun.security.action.GetPropertyAction(
0088: "line.separator"));
0089: }
0090:
0091: /**
0092: * Replaces occurences of the given pattern in the source string with the replacement value.
0093: * The resulting string is returned.
0094: *
0095: * @param source source string
0096: * @param pattern pattern to search for
0097: * @param replacement replacement string
0098: * @return string with pattern replaced.
0099: */
0100: public final static String replace(String source, String pattern,
0101: String replacement) {
0102: // replaced occurrences of %x with the appropriate parameter
0103: if (source == null)
0104: return null;
0105: int pos = source.indexOf(pattern);
0106: if (pos == -1)
0107: return source;
0108: StringBuffer buffer = new StringBuffer(
0109: (int) (source.length() * 1.5));
0110: int index = 0;
0111: int plength = pattern.length();
0112:
0113: while (pos != -1) {
0114: buffer.append(source.substring(index, pos));
0115: buffer.append(replacement);
0116: index = pos + plength;
0117: pos = source.indexOf(pattern, index);
0118: }
0119:
0120: buffer.append(source.substring(index));
0121: return buffer.toString();
0122: }
0123:
0124: /**
0125: * Converts the given object to a String.
0126: *
0127: * @return "" if null is given
0128: */
0129: public final static String toString(Object value) {
0130: if (value == null)
0131: return "";
0132: return value.toString();
0133: }
0134:
0135: /** Convert a given string to the equivalent HTML string
0136: * @param s The string to be converted.
0137: * @return The converted string */
0138: public final static String convertToHTML(String s) {
0139: StringBuffer str = new StringBuffer();
0140: int len = (s != null) ? s.length() : 0;
0141:
0142: for (int i = 0; i < len; i++) {
0143: char ch = s.charAt(i);
0144:
0145: switch (ch) {
0146: case '<':
0147: str.append("<");
0148: break;
0149:
0150: case '>':
0151: str.append(">");
0152: break;
0153:
0154: case '&':
0155: str.append("&");
0156: break;
0157:
0158: case '"':
0159: str.append(""");
0160: break;
0161:
0162: // Append character
0163: default:
0164: str.append(ch);
0165:
0166: } // END switch
0167: } // END for
0168:
0169: return (str.toString());
0170:
0171: } // END convertToHTML
0172:
0173: /** Converts the given object to an int.
0174: @return 0 if null is given */
0175: public final static int toInt(Object value) {
0176: return toInt(value, 0);
0177: }
0178:
0179: /** Converts the given object to an int.
0180: @return def if null is given */
0181: public final static int toInt(Object value, int def) {
0182: if (value == null)
0183: return def;
0184: if (value instanceof Number)
0185: return ((Number) value).intValue();
0186: String tmp = value.toString().trim();
0187: if (tmp.equals(""))
0188: return 0;
0189: return Integer.parseInt(tmp);
0190: }
0191:
0192: /** Converts the given object to an long.
0193: * @return 0 if null is given */
0194: public final static long toLong(Object value) {
0195: if (value == null)
0196: return 0;
0197: if (value instanceof Number)
0198: return ((Number) value).longValue();
0199: return Long.parseLong(value.toString());
0200: }
0201:
0202: /** Converts the given object to an float.
0203: * @return 0 if null is given */
0204: public final static float toFloat(Object value) {
0205: if (value == null)
0206: return (float) 0.0;
0207: if (value instanceof Number)
0208: return ((Number) value).floatValue();
0209: return Float.parseFloat(value.toString());
0210: }
0211:
0212: /** Converts the given object to an double.
0213: * @return 0 if null is given */
0214: public final static double toDouble(Object value) {
0215: if (value == null)
0216: return 0.0;
0217: if (value instanceof Number)
0218: return ((Number) value).doubleValue();
0219: return Double.parseDouble(value.toString());
0220: }
0221:
0222: /** Converts the given object to a Number.
0223: * return 0 if null is given */
0224: public final static Number toNumber(Object value) {
0225: if (value instanceof Number)
0226: return (Number) value;
0227: if (value == null)
0228: return ZERO;
0229:
0230: // on EBIS true evaluates to -1 and false evaluates to 0
0231: if (value instanceof Boolean) {
0232: if (((Boolean) value).booleanValue())
0233: return MINUS_ONE;
0234: return ZERO;
0235: }
0236:
0237: String tmp = value.toString();
0238: if (tmp.indexOf('.') == -1 || tmp.endsWith(".0"))
0239: return new Long(tmp);
0240: else
0241: return new Double(tmp);
0242: }
0243:
0244: /** Converts the given object to a Number. This will return an Integer if the
0245: * float has no decimal value, Float otherwise. */
0246: public final static Number toNumber(float value) {
0247: // Numbers are output incorrectly where the result is really an integer value
0248: // Java adds a .0 to the end of the number when the value is a Float or Double
0249: // Convert where this is really an integer value...
0250: if (String.valueOf(value).endsWith(".0"))
0251: return new Long((long) value);
0252: return new Float(value);
0253: }
0254:
0255: /** Converts the given object to a Number. This will return a Long if the
0256: * double has no decimal value, Double otherwise. */
0257: public final static Number toNumber(double value) {
0258: // Numbers are output incorrectly where the result is really an integer value
0259: // Java adds a .0 to the end of the number when the value is a Float or Double
0260: // Convert where this is really an integer value...
0261: if (String.valueOf(value).endsWith(".0"))
0262: return new Long((long) value);
0263: return new Double(value);
0264: }
0265:
0266: /** Converts the given object to a boolean.
0267: @return false if null is given */
0268: public final static boolean toBoolean(Object value) {
0269: return toBoolean(value, false);
0270: }
0271:
0272: /** Converts the given object to a boolean.
0273: @return def if null is given */
0274: public final static boolean toBoolean(Object value, boolean def) {
0275: if (value == null)
0276: return def;
0277: else if (value instanceof Boolean)
0278: return ((Boolean) value).booleanValue();
0279: else if (value instanceof Number) {
0280: if (((Number) value).doubleValue() == 0)
0281: return false;
0282: } else if (value.toString().trim().equals(""))
0283: return false;
0284: else if (value.toString().trim().equals("0"))
0285: return false;
0286: else if (value.toString().trim().equals("N"))
0287: return false;
0288: else if (value.toString().trim().equalsIgnoreCase("false"))
0289: return false;
0290:
0291: return true;
0292: }
0293:
0294: /** Converts the given object to a boolean object.
0295: * @return false if null is given */
0296: public final static Boolean toBooleanObj(Object value) {
0297: if (value == null)
0298: return Boolean.FALSE;
0299: else if (value instanceof Boolean)
0300: return (Boolean) value;
0301: else if (value instanceof Number) {
0302: if (((Number) value).doubleValue() == 0)
0303: return Boolean.FALSE;
0304: } else if (value.toString().trim().equals(""))
0305: return Boolean.FALSE;
0306: else if (value.toString().trim().equals("0"))
0307: return Boolean.FALSE;
0308: else if (value.toString().trim().equalsIgnoreCase("false"))
0309: return Boolean.FALSE;
0310:
0311: return Boolean.TRUE;
0312: }
0313:
0314: /**
0315: * Converts the given object to a locale.
0316: *
0317: * @return false if null is given
0318: */
0319: public final static Locale toLocale(Object value) {
0320: if (value == null)
0321: return Locale.US;
0322: else if (value instanceof Locale)
0323: return (Locale) value;
0324: else {
0325: String lang = "", country = "", variant = "";
0326: String loc = value.toString();
0327:
0328: if (loc.length() >= 2)
0329: lang = loc.substring(0, 2);
0330: if (loc.length() >= 5)
0331: country = loc.substring(3, 5);
0332: if (loc.length() >= 6)
0333: variant = loc.substring(6);
0334:
0335: return (new Locale(lang, country, variant));
0336: }
0337: }
0338:
0339: /** Converts the days, hours, minutes and seconds to milli-seconds. */
0340: public final static long toMillis(int days, int hours, int minutes,
0341: int seconds) {
0342: final long HOURS_PER_DAY = 24;
0343: final long MINUTES_PER_HOUR = 60;
0344: final long SECONDS_PER_MINUTE = 60;
0345: final long MILLIS_PER_SECOND = 1000;
0346:
0347: long result = 0;
0348: result = (days) * HOURS_PER_DAY; // units are now hours
0349: result = (result + hours) * MINUTES_PER_HOUR; // units are now minutes
0350: result = (result + minutes) * SECONDS_PER_MINUTE; // units are now seconds
0351: result = (result + seconds) * MILLIS_PER_SECOND; // units are now milliseconds
0352:
0353: return result;
0354: }
0355:
0356: /**
0357: * Given the class, this method returns the static field value corresponding
0358: * to the given field name.
0359: */
0360: public final static int getStaticIntField(Class c, String fieldName) {
0361: try {
0362: Field f = c.getField(fieldName);
0363: return f.getInt(null);
0364: } catch (Throwable exc) {
0365: /* assume it is a numeric value */
0366: return toInt(fieldName);
0367: }
0368: }
0369:
0370: /** Checks to see if the string starts with the
0371: * the given string (ignoring case and whitespace)
0372: * @param source source string
0373: * @param pattern pattern to search for
0374: * @param ws indicator for ignoring leading whitespace */
0375: public final static boolean startsWithIgnoreCase(String source,
0376: String pattern, boolean ws) {
0377: int slen = source.length();
0378: int sind = 0;
0379:
0380: // skip leading white space
0381: if (ws) {
0382: while (sind < slen) {
0383: if (Character.isWhitespace(source.charAt(sind)))
0384: sind++;
0385: else
0386: break;
0387: }
0388: }
0389:
0390: // search for pattern
0391: int pind = 0;
0392: int plen = pattern.length();
0393: if (plen > (slen - sind))
0394: return false; // pattern length is larger than remaining string
0395:
0396: while (pind < plen && sind < slen) {
0397: char sc = Character.toLowerCase(source.charAt(sind));
0398: char pc = Character.toLowerCase(pattern.charAt(pind));
0399: if (sc != pc)
0400: return false;
0401: pind++;
0402: sind++;
0403: }
0404:
0405: return true;
0406: }
0407:
0408: private static int toByte(char c1, int radix) {
0409: int j;
0410: if (c1 >= '0' && c1 <= '9') {
0411: j = c1 - (int) '0';
0412: } else if (c1 >= 'A' && c1 <= 'Z') {
0413: j = (c1 - (int) 'A') + 10;
0414: } else if (c1 >= 'a' && c1 <= 'z') {
0415: j = (c1 - (int) 'a') + 10;
0416: } else {
0417: j = -1;
0418: }
0419: if (j < 0 || j >= radix)
0420: return -1;
0421: else
0422: return j;
0423: }
0424:
0425: /**
0426: * Converts separators '/' and '.' to File.separator.
0427: * Note: for '.' it converts all but the last '.'
0428: */
0429: public static final String convertFilename(String filename) {
0430: /* replace occurences of . with File.separator (except last ccurence)*/
0431: int pos = filename.lastIndexOf(".");
0432:
0433: if (pos == -1)
0434: return null;
0435:
0436: String extension = filename.substring(pos);
0437: String prefix = filename.substring(0, pos);
0438:
0439: /* change "/" to real file separator */
0440: prefix = replace(prefix, "/", File.separator);
0441: /* assume extra '.' refer to file separator */
0442: prefix = replace(prefix, ".", File.separator);
0443:
0444: return prefix + extension;
0445: }
0446:
0447: /**
0448: * Converts separators '\' to '/'.
0449: */
0450: public static final String convertFilenameToUnix(String filename) {
0451: return convertDirnameToUnix(filename);
0452: }
0453:
0454: /**
0455: * Converts separators '\' to '/'.
0456: */
0457: public static final String convertDirnameToUnix(String dirname) {
0458: /* change "/" to unix standard file separator */
0459: dirname = replace(dirname, "\\", "/");
0460: if (!File.separator.equals("/")) {
0461: /* change File.separator to unix standard file separator */
0462: dirname = replace(dirname, File.separator, "/");
0463: }
0464: // remove any trailing slash
0465: if (dirname.endsWith("/") && dirname.length() > 1
0466: && !dirname.equals("~/")) {
0467: dirname = dirname.substring(0, dirname.length() - 1);
0468: }
0469: return dirname;
0470: }
0471:
0472: /**
0473: * Searches the given path for the given filename.
0474: *
0475: * @param filename name of file to search for
0476: * @param path filesystem path to search
0477: * @return the file, null if not found
0478: */
0479: public static final File findFile(String filename, String path) {
0480: filename = convertFilename(filename);
0481:
0482: if (filename == null)
0483: return null;
0484:
0485: // case where separator is set for the Windows platform and we are on unix
0486: if (File.pathSeparator.equals(":")) {
0487: path = replace(path, ";", ":");
0488: }
0489:
0490: File file = new File(filename);
0491: StringTokenizer strtok = new StringTokenizer(path,
0492: File.pathSeparator, false);
0493:
0494: /* check if file already has the full path */
0495: if (file.exists())
0496: return file;
0497:
0498: /* search the given path */
0499: while (strtok.hasMoreTokens()) {
0500: file = new File(strtok.nextToken(), filename);
0501: if (file.exists() && file.isFile())
0502: return file;
0503: }
0504:
0505: return null;
0506: }
0507:
0508: /** Reads the contents of the reader and puts it into a string. */
0509: public final static String toString(Reader reader)
0510: throws IOException {
0511: if (reader == null)
0512: return "";
0513: StringBuffer buffer = new StringBuffer();
0514:
0515: int c = reader.read();
0516: while (c != -1) {
0517: buffer.append((char) c);
0518: c = reader.read();
0519: }
0520:
0521: return buffer.toString();
0522: }
0523:
0524: /** Reads the file with the given name and returns the contents as a String. */
0525: public final static String readFile(String filename)
0526: throws IOException {
0527: return toString(new FileReader(filename));
0528: }
0529:
0530: /*
0531: * Convert a string to the javascript equivalent.
0532: */
0533: public final static String toJavaScriptString(String str) {
0534: if (str == null)
0535: return "";
0536: String newString = str.toString();
0537:
0538: newString = replace(newString, "\\", "\\\\");
0539: newString = replace(newString, "\'", "\\'");
0540: newString = replace(newString, "\"", "\\\"");
0541: newString = replace(newString, "\r\n", "\\n");
0542: newString = replace(newString, "\n", "\\n");
0543: newString = replace(newString, "\r", "\\n");
0544:
0545: return newString;
0546: }
0547:
0548: /**
0549: * Tests if a string is empty or null
0550: */
0551: public final static boolean isEmpty(String str) {
0552: return (str == null || str.length() == 0 || str.trim().equals(
0553: "")) ? true : false;
0554: }
0555:
0556: /**
0557: * Adds two numbers together.
0558: */
0559: public final static Number add(Number x, Number y) {
0560: if (x instanceof Integer && y instanceof Integer) {
0561: return new Integer(x.intValue() + y.intValue());
0562: }
0563:
0564: if (x instanceof Float && y instanceof Float) {
0565: return new Float(x.floatValue() + y.floatValue());
0566: }
0567:
0568: if (x instanceof Double && y instanceof Double) {
0569: return new Double(x.doubleValue() + y.doubleValue());
0570: }
0571:
0572: if (x instanceof BigInteger && y instanceof BigInteger) {
0573: return ((BigInteger) x).add((BigInteger) y);
0574: }
0575:
0576: if (x instanceof BigDecimal && y instanceof BigDecimal) {
0577: return ((BigDecimal) x).add((BigDecimal) y);
0578: }
0579:
0580: return new Long(x.longValue() + y.longValue());
0581: }
0582:
0583: /** Compares the two objects. */
0584: public final static boolean compare(Object x, Object y) {
0585: if (x == null && y == null)
0586: return true;
0587: if (x == null)
0588: return false;
0589: if (y == null)
0590: return false;
0591: return x.equals(y);
0592: }
0593:
0594: /** Compares the two strings after the whitespace is trimmed. */
0595: public final static boolean compareTrimmedStrings(String x, String y) {
0596: if (x == null && y == null)
0597: return true;
0598: if (x == null)
0599: return false;
0600: if (y == null)
0601: return false;
0602:
0603: return x.trim().equals(y.trim());
0604: }
0605:
0606: /** Compares the two numbers and returns true if they are equal. */
0607: public final static boolean compareNumbers(Number x, Number y) {
0608: if (x instanceof BigDecimal && y instanceof BigDecimal) {
0609: return ((BigDecimal) x).compareTo((BigDecimal) y) == 0;
0610: }
0611: if (x instanceof BigInteger && y instanceof BigInteger) {
0612: return ((BigInteger) x).compareTo((BigInteger) y) == 0;
0613: } else if (x instanceof Short && y instanceof Short) {
0614: return ((Number) x).shortValue() == ((Number) y)
0615: .shortValue();
0616: } else if (x instanceof Integer && y instanceof Integer) {
0617: return ((Number) x).intValue() == ((Number) y).intValue();
0618: } else if (x instanceof Long && y instanceof Long) {
0619: return ((Number) x).longValue() == ((Number) y).longValue();
0620: } else if (x instanceof Float && y instanceof Float) {
0621: return ((Number) x).floatValue() == ((Number) y)
0622: .floatValue();
0623: } else {
0624: // comparing of double values seems to cause rounding errors
0625: // float seems to work fine...
0626: return ((Number) x).floatValue() == ((Number) y)
0627: .floatValue();
0628: }
0629: }
0630:
0631: /** Prints the stack trace of the exception to a string. */
0632: public final static String printStackTrace(Throwable exc) {
0633: StringWriter source = new StringWriter();
0634: exc.printStackTrace(new PrintWriter(source));
0635: return source.toString();
0636: }
0637:
0638: /** Convert the date in long to yyyy-MM-dd format String */
0639: public final static String toDate(long dateInMillis) {
0640: return toDate(dateInMillis, cDateFormat);
0641: }
0642:
0643: /** Parse the date from yyyy-MM-dd to long */
0644: public final static Date parseDate(String date) {
0645: if (date == null)
0646: return null;
0647: return parseDate(date, cDateFormat);
0648: }
0649:
0650: /** Converts the date in long to yyyy-MM-dd hh:mm:ss format string */
0651: public final static String toDateTime(long dateInMillis) {
0652: return toDate(dateInMillis, cDateTimeFormat);
0653: }
0654:
0655: /** Parses the date from yyyy-MM-dd hh:mm:ss to long */
0656: public final static Date parseDateTime(String date) {
0657: return parseDate(date, cDateTimeFormat);
0658: }
0659:
0660: /** Parse the date format given by the DateFormat object */
0661: public final static Date parseDate(String date, DateFormat format) {
0662: if (isEmpty(date) || format == null)
0663: return null;
0664: Date d = null;
0665: try {
0666: d = format.parse(date);
0667: } catch (Throwable exc) {
0668: }
0669:
0670: return d;
0671: }
0672:
0673: /** Format the date given by the DateFormat object */
0674: public final static String toDate(long dateInMillis,
0675: DateFormat format) {
0676: if (format == null)
0677: return "";
0678: Date date = new Date(dateInMillis);
0679: try {
0680: return format.format(date);
0681: } catch (Throwable exc) {
0682: return "";
0683: }
0684: }
0685:
0686: /** Pads the given string to the given length. Whitespace is added to the
0687: * end of the string. */
0688: public final static String pad(Object value, int length) {
0689: StringBuffer result = new StringBuffer();
0690: if (value == null)
0691: result.append("null");
0692: else
0693: result.append(value.toString());
0694:
0695: int num = length - result.length();
0696: for (int i = 0; i < num; i++) {
0697: result.append(" ");
0698: }
0699:
0700: return result.toString();
0701: }
0702:
0703: /** Pads the given string to the given length. Whitespace is added to the
0704: * end of the string. */
0705: public final static String pad(Object value, int length,
0706: boolean trim) {
0707: String result = "null";
0708: if (value != null)
0709: result = value.toString();
0710:
0711: int num = length - result.length();
0712: for (int i = 0; i < num; i++) {
0713: result += " ";
0714: }
0715:
0716: if (trim)
0717: return result.substring(0, length - 1);
0718: return result;
0719: }
0720:
0721: /** Pads the given string to the given length. Whitespace is added to the
0722: * front of the string. */
0723: public final static String lpad(Object value, int length) {
0724: String result = "null";
0725: if (value != null)
0726: result = value.toString();
0727:
0728: int num = length - result.length();
0729: for (int i = 0; i < num; i++) {
0730: result = " " + result;
0731: }
0732:
0733: return result;
0734: }
0735:
0736: public static double getTimeDiffInSeconds(long startInMillis,
0737: long endInMillis) {
0738: long timeDiff = endInMillis - startInMillis;
0739: double sec = timeDiff / 1000.0;
0740: return sec;
0741: }
0742:
0743: /** Reads in the contents of the url stream and returns the result
0744: * as a string. */
0745: public static String getURLContentAsString(URL url)
0746: throws IOException {
0747: if (url == null)
0748: return null;
0749: InputStream in = url.openStream();
0750: ByteArrayOutputStream out = new ByteArrayOutputStream();
0751:
0752: final int KILOBYTE = 1024;
0753: byte buf[] = new byte[4 * KILOBYTE];
0754: int bytesRead;
0755: while ((bytesRead = in.read(buf)) != -1) {
0756: out.write(buf, 0, bytesRead);
0757: }
0758:
0759: return out.toString();
0760: }
0761:
0762: private static final String[] cRandomWords = { "a", "b", "c", "d",
0763: "e", "f", "g", "h", "j", "k", "m", "n", "p", "q", "r",
0764: "s",
0765: "t",
0766: "u",
0767: "v",
0768: "w",
0769: "x",
0770: "y",
0771: "z", //ambiguous letters removed
0772: "Alpha", "Omega", "Theta", "Beta", "Delta", "Sun",
0773: "Mercury", "Venus", "Moon", "Earth", "Mars", "Jupiter",
0774: "Saturn", "Neptune", "Color", "Red", "Blue", "Green",
0775: "Black", "White", "Brown", "Yellow", "Orange", "Direction",
0776: "North", "South", "East", "West", "Up", "Down", "Number",
0777: "2", "3", "4", "5", "6", "7", "8",
0778: "9",
0779: //ambiguous numbers removed
0780: "Idea", "Empty", "Time", "Space", "Friend", "Spice",
0781: "Salt", "Pepper", "Sugar", "Knife", "Fork", "Spoon",
0782: "Plate", "Glass", "Bowl" };
0783:
0784: /** Returns a random word from a built in dictionary */
0785: private static String randomWord() {
0786: return cRandomWords[(int) Math.floor(Math.random()
0787: * cRandomWords.length)];
0788: }
0789:
0790: /** Returns a random entry from an array */
0791: public static Object randomEntry(Object array[]) {
0792: return array[(int) Math.floor(Math.random() * array.length)];
0793: }
0794:
0795: /** Returns a random number within the given range */
0796: public static int random(int low, int high) {
0797: int x = (int) Math.floor(Math.random() * (high - low));
0798: return x + low;
0799: }
0800:
0801: /** Creates over 35 million unique passwords.
0802: * Each password is easy to remember consisting of 4 words */
0803: public static String createRandomPassword() {
0804: String password = "";
0805: int length = 4;
0806: for (int count = 0; count < length; count++) {
0807: if (count != 0) {
0808: password = password + "-";
0809: }
0810: password = password + randomWord();
0811: }
0812: return password.toLowerCase();
0813: }
0814:
0815: /** Gets the current working directory. */
0816: public static String getCurrentWorkingDirectory() {
0817: File f = new File(".");
0818: String path = f.getAbsolutePath();
0819: return path.substring(0, path.indexOf('.'));
0820: }
0821:
0822: /** Creates a mapping of the given set of message IDs. */
0823: public static Map createMap(MsgID ids[]) {
0824: if (ids == null)
0825: return null;
0826:
0827: Map map = new HashMap();
0828: for (int i = 0; i < ids.length; i++) {
0829: map.put(ids[i].getID(), ids[i]);
0830: }
0831:
0832: return map;
0833: }
0834:
0835: /** Creates a mapping of the given set of message IDs. */
0836: public static MsgID[] concat(MsgID x[], MsgID y[]) {
0837: if (x == null)
0838: return y;
0839: if (y == null)
0840: return x;
0841:
0842: MsgID z[] = new MsgID[x.length + y.length];
0843:
0844: int ind = 0;
0845: for (int i = 0; i < x.length; i++) {
0846: z[ind++] = x[i];
0847: }
0848: for (int i = 0; i < y.length; i++) {
0849: z[ind++] = y[i];
0850: }
0851:
0852: return z;
0853: }
0854:
0855: /** Creates a Date object with the given information. */
0856: public static Date newDate(int year, int month, int day) {
0857: return (new GregorianCalendar(year, month - 1, day)).getTime();
0858: }
0859:
0860: /** Trims the string to ensure that is has a max number of characters. */
0861: public static String trim(String src, int max) {
0862: if (src == null)
0863: return null;
0864: if (src.length() <= max)
0865: return src;
0866: return src.substring(0, max);
0867: }
0868:
0869: /** Proper case a string*/
0870: public static String properCase(String value) {
0871: String properValue = "";
0872: StringTokenizer st = new StringTokenizer(value, " ");
0873:
0874: String firstCharacterUpperCase = "", restOfWord = "";
0875: while (st.hasMoreTokens()) {
0876: String token = st.nextToken();
0877: firstCharacterUpperCase = (token.substring(0, 1))
0878: .toUpperCase();
0879: restOfWord = token.substring(1);
0880: properValue += firstCharacterUpperCase
0881: + restOfWord.toLowerCase();
0882: }
0883: return properValue;
0884: }
0885:
0886: public static void forceGC() {
0887: runBackgroundGC();
0888: }
0889:
0890: public static void forceGCWait() {
0891: System.gc();
0892: System.runFinalization();
0893: System.gc();
0894: }
0895:
0896: public static void runBackgroundGC() {
0897: Thread gcThread = new Thread(new Runnable() {
0898: public void run() {
0899: forceGCWait();
0900: }
0901: });
0902: gcThread.setPriority(Thread.MIN_PRIORITY);
0903: gcThread.start();
0904: }
0905:
0906: /**
0907: * Strips spaces in a type name, or any string.
0908: */
0909: public static String stripSpacesInString(String s) {
0910: StringBuffer sb = new StringBuffer(s.length());
0911: for (int i = 0; i < s.length(); i++) {
0912: char c = s.charAt(i);
0913: if (c != ' ') {
0914: sb.append(c);
0915: }
0916: }
0917: return sb.toString();
0918: }
0919:
0920: /**
0921: * Checks to see if the namespace already has a child of the same name and type.
0922: * @param space The target namespace being searched.
0923: * @param name The name of the element being searched for.
0924: * @param newType The type of the element being searched for.
0925: * @param self An instance of the NamedElement being search for.
0926: * @return true, if a name collision is detected; false, otherwise.
0927: */
0928: public static boolean hasNameCollision(INamespace space,
0929: String name, String newType, INamedElement self) {
0930: if (space == null)
0931: return false;
0932:
0933: //kris richards - "DefaultElementName" pref expunged. Set to "Unnamed".
0934: String defaultName = NbBundle.getMessage(Util.class, "UNNAMED");
0935:
0936: // skip validation for the newly created unnamed element
0937: if (defaultName != null && defaultName.equals(name))
0938: return false;
0939:
0940: IElementLocator pElementLocator = new ElementLocator();
0941:
0942: ETList<INamedElement> pFoundElements = pElementLocator
0943: .findByName(space, name);
0944:
0945: if (pFoundElements != null) {
0946: String foundType;
0947: int count = pFoundElements.getCount();
0948: for (int i = 0; i < count; i++) {
0949: INamedElement pFoundElement = pFoundElements.get(i);
0950:
0951: if (pFoundElement != null) {
0952: if (self == null
0953: || pFoundElement.getXMIID() != self
0954: .getXMIID()) {
0955: foundType = pFoundElement.getElementType();
0956: if (foundType.equals(newType))
0957: return true;
0958: if (types.contains(newType)
0959: && types.contains(foundType))
0960: return true;
0961: }
0962: }
0963: }
0964: }
0965: return false;
0966: }
0967:
0968: /**
0969: * Checks to see if the namespace already has a <em>similar</em> child.
0970: * @param space The target namespace being searched.
0971: * @param name The name of the element being searched for.
0972: * @param newType The type of the element being searched for.
0973: * @param self An instance of the NamedElement being search for.
0974: * @return true, if a elements are <em>similar</em>; false, otherwise.
0975: */
0976: public static boolean containsSimilarElement(INamespace space,
0977: String name, String newType, INamedElement self) {
0978: IElementLocator pElementLocator = new ElementLocator();
0979: if (space == null)
0980: return false;
0981:
0982: ETList<INamedElement> pFoundElements = pElementLocator
0983: .findByName(space, name);
0984:
0985: if (pFoundElements != null) {
0986: String foundType;
0987: int count = pFoundElements.getCount();
0988:
0989: for (int i = 0; i < count; i++) {
0990: INamedElement pFoundElement = pFoundElements.get(i);
0991:
0992: if (pFoundElement != null) {
0993: if (self == null
0994: || pFoundElement.getXMIID() != self
0995: .getXMIID()) {
0996: foundType = pFoundElement.getElementType();
0997: if (pFoundElement.isSimilar(self))
0998: return true;
0999: }
1000: }
1001: }
1002: }
1003: return false;
1004: }
1005:
1006: public static ETList<INamedElement> getCollidingElements(
1007: INamedElement curElement, String newName) {
1008: ETList<INamedElement> collidingElements = new ETArrayList<INamedElement>();
1009: if (newName != null && newName.length() > 0
1010: && curElement.getNamespace() != null) {
1011: ElementLocator locator = new ElementLocator();
1012: ETList<INamedElement> pFoundElements = locator.findByName(
1013: curElement.getNamespace(), newName);
1014:
1015: if (pFoundElements != null) {
1016: String foundType;
1017: int count = pFoundElements.getCount();
1018: for (int i = 0; i < count; i++) {
1019: INamedElement pFoundElement = pFoundElements.get(i);
1020:
1021: if (pFoundElement != null) {
1022: if (pFoundElement.getXMIID() != curElement
1023: .getXMIID()) {
1024: foundType = pFoundElement.getElementType();
1025: String type = curElement.getElementType();
1026: if ((foundType.equals(type) || (types
1027: .contains(type) && types
1028: .contains(foundType))))
1029: collidingElements.add(pFoundElement);
1030: }
1031: }
1032: }
1033: }
1034: }
1035: return collidingElements;
1036: }
1037:
1038: /**
1039: * Determines if the passed in type is a known Collection data type.
1040: * @param type the data type to be tested
1041: * @return true if java.util.Collection is assignable
1042: * from (is a superclass instance of) the parameter type that is passed
1043: * in; false otherwise, including in the event of an exception.
1044: */
1045: public static boolean isValidCollectionDataType(String type) {
1046: if (type == null || type.length() < 1)
1047: return false;
1048:
1049: // TODO: should we declare the CNFE and force the invoking class
1050: // to handle the exception?
1051: try {
1052: return (Collection.class).isAssignableFrom(Class
1053: .forName(type));
1054: }
1055:
1056: catch (ClassNotFoundException ex) {
1057: // Log exception, but ignore it; we'll just return false
1058: // if class is not found (this happens for primitives as well)
1059: Log.stackTrace(ex);
1060: }
1061:
1062: return false;
1063: }
1064:
1065: /**
1066: *
1067: * @param diagramName diagram name to check for validity
1068: * @return true if valid diagram name; false otherwise
1069: */
1070: public static boolean isDiagramNameValid(String diagramName) {
1071: if (diagramName == null || diagramName.trim().length() == 0)
1072: return false;
1073:
1074: String name = diagramName.trim();
1075: int count = name.length();
1076: for (int i = 0; i < count; i++) {
1077: char c = name.charAt(i);
1078: if (!Character.isLetterOrDigit(c)) {
1079: if (c == '_' || c == '(' || c == ')' || c == '{'
1080: || c == '}' || c == '[' || c == ']' || c == ' ')
1081: continue;
1082: else
1083: return false;
1084: }
1085: }
1086: return true;
1087:
1088: // for (String c : IDS_INVALID_CHARS)
1089: // {
1090: // if ( diagramName.indexOf(c) != -1)
1091: // return false;
1092: // }
1093: // return true;
1094: }
1095:
1096: /**
1097: *
1098: * @param name Name to check for identifier validity
1099: * @return true if invalid identifier; false otherwise
1100: */
1101: public static boolean invalidIdentifier(String name) {
1102: boolean retval = true;
1103:
1104: // Before we look for more complex problems, make sure that this
1105: // name is not a keyword.
1106: retval = isKeyword(name);
1107:
1108: if (!retval) {
1109: // First character must be alpha, underscore, or dollar
1110: // Rest of characters must be alphanum, underscore, or dollar
1111:
1112: // isJavaIdentifierStart and isJavaIdentifierPart will support unicode in JDK1.5
1113: if (name != null && name.length() > 0) {
1114: if (Locale.getDefault().getDisplayLanguage().equals(
1115: "English")) {
1116: retval = true;
1117: char firstchar = name.charAt(0);
1118: if (Character.isJavaIdentifierStart(firstchar)) {
1119: retval = false;
1120: for (int i = 1; i < name.length()
1121: && retval == false; i++) {
1122: char namechar = name.charAt(i);
1123: if (!Character
1124: .isJavaIdentifierPart(namechar))
1125: retval = true;
1126: }
1127: }
1128: } else {
1129: retval = true;
1130: char firstchar = name.charAt(0);
1131: if (Character.isLetter(firstchar)
1132: || firstchar == '_' || firstchar == '$') {
1133: retval = false;
1134: for (int i = 1; i < name.length()
1135: && retval == false; i++) {
1136: char namechar = name.charAt(i);
1137: if (!(Character.isLetterOrDigit(namechar)
1138: || namechar == '_' || namechar == '$')) {
1139: retval = true;
1140: break;
1141: }
1142: }
1143: }
1144: }
1145: }
1146: }
1147:
1148: return retval;
1149: }
1150:
1151: /**
1152: *
1153: * Is the name a keyword in this language
1154: *
1155: * @param name [in] The name
1156: *
1157: * @return true if the name is a language keyword.
1158: *
1159: */
1160: public static boolean isKeyword(String name) {
1161: boolean retval = false;
1162:
1163: try {
1164: ILanguage pLang = getLanguage2();
1165:
1166: if (pLang != null)
1167: retval = pLang.isKeyword(name);
1168: }
1169:
1170: catch (Exception e) {
1171: e.printStackTrace();
1172: }
1173:
1174: return retval;
1175: }
1176:
1177: /**
1178: *
1179: * Retrieves the language this processor supports.
1180: *
1181: * @return pLang[out] The actual ILanguage associated with this processor
1182: */
1183: public static ILanguage getLanguage2() {
1184: ILanguage language = null;
1185:
1186: try {
1187: if (language == null) {
1188: String mylang = "Java"; // NOI18N
1189:
1190: ICoreProduct pProduct = ProductRetriever
1191: .retrieveProduct();
1192:
1193: if (pProduct != null) {
1194: ILanguageManager pManager = pProduct
1195: .getLanguageManager();
1196:
1197: if (pManager != null)
1198: language = pManager.getLanguage(mylang);
1199: }
1200: }
1201: }
1202:
1203: catch (Exception e) {
1204: e.printStackTrace();
1205: }
1206:
1207: return language;
1208: }
1209:
1210: // public static String[] IDS_INVALID_CHARS = {"\\", "/", "*", ":", "?", ".", "&"};
1211:
1212: private static SimpleDateFormat cDateFormat = new SimpleDateFormat(
1213: "yyyy-MM-dd");
1214: private static SimpleDateFormat cDateTimeFormat = new SimpleDateFormat(
1215: "yyyy-MM-dd HH:mm:ss");
1216: private static List types = Arrays.asList("Interface", "Class",
1217: "Enumeration");
1218:
1219: }
|