示例#1
1
  /** Fetch the classloader for the given ApplicationID. */
  static URLClassLoader getUrlClassLoader(ApplicationID appId, Map input) {
    NCube cpCube = getCube(appId, CLASSPATH_CUBE);
    if (cpCube
        == null) { // No sys.classpath cube exists, just create regular GroovyClassLoader with no
                   // URLs set into it.
      // Scope the GroovyClassLoader per ApplicationID
      return getLocalClassloader(appId);
    }

    final String envLevel = SystemUtilities.getExternalVariable("ENV_LEVEL");
    if (!input.containsKey("env")
        && StringUtilities.hasContent(
            envLevel)) { // Add in the 'ENV_LEVEL" environment variable when looking up sys.* cubes,
      // if there was not already an entry for it.
      input.put("env", envLevel);
    }
    if (!input.containsKey("username")) { // same as ENV_LEVEL, add it in if not already there.
      input.put("username", System.getProperty("user.name"));
    }
    Object urlCpLoader = cpCube.getCell(input);

    if (urlCpLoader instanceof URLClassLoader) {
      return (URLClassLoader) urlCpLoader;
    }

    throw new IllegalStateException(
        "If the sys.classpath cube exists it must return a URLClassLoader.");
  }
示例#2
0
  /**
   * Formats a URI by adding a forward slash and removing the last forward slash from the URI.
   *
   * <p>e.g. some/random/uri/ -> /some/random/uri e.g. some/random/uri -> /some/random/uri e.g.
   * /some/random/uri/ -> /some/random/uri e.g. / -> / e.g. ////// -> /
   *
   * @param uri
   * @return
   */
  public static String formatUri(String uri) {
    if (StringUtilities.nullSafeStartsWith(uri, "\\")) {
      // windows file system
      return uri;
    }

    if (StringUtilities.isBlank(uri) || StringUtilities.nullSafeEqualsIgnoreCase("/", uri)) {
      return "/";
    }

    final StringBuilder externalName = new StringBuilder(uri);

    if (externalName.charAt(0) != '/') {
      externalName.insert(0, "/");
    }

    int doubleSlash = externalName.indexOf("//");

    while (doubleSlash > -1) {
      // removes leading '/'
      externalName.replace(doubleSlash, doubleSlash + 2, "/");
      doubleSlash = externalName.indexOf("//");
    }

    if (externalName.charAt(externalName.length() - 1) == '/' && externalName.length() != 1) {
      externalName.deleteCharAt(externalName.length() - 1);
    }

    return externalName.toString();
  }
  public void test_StringUtilities_parseArgumentString() {
    Assert.assertArrayEquals(
        new String[] {"one", "two"}, StringUtilities.parseArgumentString("one two"));

    Assert.assertArrayEquals(
        new String[] {"one", "two two"}, StringUtilities.parseArgumentString("one \"two two\""));

    Assert.assertArrayEquals(
        new String[] {"one", "arg='two two'"},
        StringUtilities.parseArgumentString("one arg='two two'"));
  }
示例#4
0
  /**
   * Draw a string. "(" is converted to "\(" and ")" is converted to "\) so as to avoid EPS Syntax
   * errors.
   *
   * @param str The string to draw.
   * @param x The x location of the string.
   * @param y The y location of the string.
   */
  public void drawString(String str, int x, int y) {
    Point start = _convert(x, y);
    _buffer.append("" + start.x + " " + start.y + " moveto\n");

    if ((str.indexOf("(") > -1) && (str.indexOf("\\(") == -1)) {
      str = StringUtilities.substitute(str, "(", "\\(");
    }

    if ((str.indexOf(")") > -1) && (str.indexOf("\\)") == -1)) {
      str = StringUtilities.substitute(str, ")", "\\)");
    }

    _buffer.append("(" + str + ") show\n");
  }
示例#5
0
 public static String getReferrer() {
   String localReferrer = referrer.get();
   if (StringUtilities.hasContent(localReferrer)) {
     return localReferrer;
   }
   return globalReferrer;
 }
示例#6
0
 public static String getUserAgent() {
   String localAgent = userAgent.get();
   if (StringUtilities.hasContent(localAgent)) {
     return localAgent;
   }
   return globalUserAgent;
 }
示例#7
0
 private void writeHostAndPortToFile(File portFile) {
   String host = socket.getInetAddress().getHostName();
   int port = socket.getLocalPort();
   // The motivation for the Log.warn would be better satisfied by Bug 38.
   Log.warn("echo " + host + ":" + port + " > " + portFile);
   StringUtilities.writeFile(portFile, host + ":" + port + "\n");
 }
示例#8
0
  /** Associate Advice to all n-cubes that match the passed in regular expression. */
  public static void addAdvice(ApplicationID appId, String wildcard, Advice advice) {
    validateAppId(appId);
    ConcurrentMap<String, Advice> current = advices.get(appId);
    if (current == null) {
      current = new ConcurrentHashMap<>();
      ConcurrentMap<String, Advice> mapRef = advices.putIfAbsent(appId, current);
      if (mapRef != null) {
        current = mapRef;
      }
    }

    current.put(advice.getName() + '/' + wildcard, advice);

    // Apply newly added advice to any fully loaded (hydrated) cubes.
    String regex = StringUtilities.wildcardToRegexString(wildcard);
    Map<String, Object> cubes = getCacheForApp(appId);

    for (Object value : cubes.values()) {
      if (value instanceof NCube) { // apply advice to hydrated cubes
        NCube ncube = (NCube) value;
        Axis axis = ncube.getAxis("method");
        addAdviceToMatchedCube(advice, regex, ncube, axis);
      }
    }
  }
示例#9
0
 /**
  * This method creates an event vector based on a given request object.
  *
  * @param request The HttpRequest object.
  * @return A Vector containing the events
  */
 private Vector createEventVector(HTTPRequest request) {
   Vector eventVector = new Vector();
   if (request.getQueryValue("mauiEvent") != null) {
     eventVector = StringUtilities.split(".", request.getQueryValue("mauiEvent"));
   }
   return eventVector;
 }
示例#10
0
 public static void main(String[] arguments) {
   GuiUtilities.initLookAndFeel();
   for (String argument : arguments) {
     String text = StringUtilities.readFile(argument);
     new HtmlViewer(text).setVisible(true);
   }
 }
 /**
  * Safely convert a string to a Bigdecimal
  *
  * @param bigDecimalValue The String to convert.
  * @return Zero if the String is not a Bigdecimal. Otherwise, the Bigdecimal.
  */
 public static BigDecimal convertStringToBigDecimal(String bigDecimalValue) {
   bigDecimalValue = StringUtilities.trimSafely(bigDecimalValue, "0.0");
   try {
     return new BigDecimal(bigDecimalValue);
   } catch (Exception e) {
     return new BigDecimal(0.0);
   }
 }
  /**
   * This safely converts the first character of a string to a char. It is useful for converting
   * from a single character String field into a flag.
   *
   * @param flag The String to be converted
   * @param defaultChar The char to return if the conversion fails.
   * @return The first character of the String as a char.
   */
  public static char convertStringToChar(String flag, char defaultChar) {
    char newChar = defaultChar;

    if (!StringUtilities.isEmpty(flag)) {
      newChar = flag.charAt(0);
    }

    return newChar;
  }
 /**
  * Safely convert a string to an integer
  *
  * @param numericValue The String to convert.
  * @return Zero if the String is not a number. Otherwise, the integer.
  */
 public static int convertStringToInt(String numericValue) {
   int number = 0;
   numericValue = StringUtilities.trimSafely(numericValue, "0");
   try {
     number = Integer.parseInt(numericValue);
   } catch (Exception e) {
     number = 0;
   }
   return number;
 }
 /**
  * Safely convert a string to a long
  *
  * @param numericValue The String to convert.
  * @return Zero if the String is not a number. Otherwise, the long integer.
  */
 public static long convertStringToLong(String numericValue) {
   long number = 0;
   numericValue = StringUtilities.trimSafely(numericValue, "0");
   try {
     number = Long.parseLong(numericValue);
   } catch (Exception e) {
     number = 0;
   }
   return number;
 }
示例#15
0
 // FIXME: assumes C-family multi-line comments.
 private boolean isUnclosedComment(
     CharSequence entireDocument, int insertionPosition, CharSequence lineToTheLeft) {
   if (Pattern.matches("[ \t]*/\\*{1,2}", lineToTheLeft)) {
     // We're on a line that starts a block comment, but is it unclosed?
     int nextOpenComment = StringUtilities.indexOf(entireDocument, "/*", insertionPosition);
     int nextCloseComment = StringUtilities.indexOf(entireDocument, "*/", insertionPosition);
     if (nextCloseComment == -1) {
       // If there are no close comments after this point, this one we're looking at must be
       // unclosed.
       return true;
     }
     if (nextOpenComment != -1 && nextOpenComment < nextCloseComment) {
       // If there's an open comment after this point, and no intervening close comment, the one
       // we're looking at must be unclosed.
       return true;
     }
   }
   return false;
 }
示例#16
0
  /**
   * Gets a connection from a url. All getConnection calls should go through this code.
   *
   * @param inCookies Supply cookie Map (received from prior setCookies calls from server)
   * @param input boolean indicating whether this connection will be used for input
   * @param output boolean indicating whether this connection will be used for output
   * @param cache boolean allow caching (be careful setting this to true for non-static retrievals).
   * @return URLConnection established URL connection.
   */
  public static URLConnection getConnection(
      URL url, Map inCookies, boolean input, boolean output, boolean cache, boolean allowAllCerts)
      throws IOException {
    URLConnection c = url.openConnection();
    c.setRequestProperty("Accept-Encoding", "gzip, deflate");
    c.setAllowUserInteraction(false);
    c.setDoOutput(output);
    c.setDoInput(input);
    c.setUseCaches(cache);
    c.setReadTimeout(220000);
    c.setConnectTimeout(45000);

    String ref = getReferrer();
    if (StringUtilities.hasContent(ref)) {
      c.setRequestProperty("Referer", ref);
    }
    String agent = getUserAgent();
    if (StringUtilities.hasContent(agent)) {
      c.setRequestProperty("User-Agent", agent);
    }

    if (c
        instanceof
        HttpURLConnection) { // setFollowRedirects is a static (global) method / setting - resetting
      // it in case other code changed it?
      HttpURLConnection.setFollowRedirects(true);
    }

    if (c instanceof HttpsURLConnection && allowAllCerts) {
      try {
        setNaiveSSLSocketFactory((HttpsURLConnection) c);
      } catch (Exception e) {
        LOG.warn("Could not access '" + url.toString() + "'", e);
      }
    }

    // Set cookies in the HTTP header
    if (inCookies != null) { // [optional] place cookies (JSESSIONID) into HTTP headers
      setCookies(c, inCookies);
    }
    return c;
  }
示例#17
0
  /**
   * Given a dot separated classname, return the jar file or directory where the class can be found.
   *
   * @param necessaryClass The dot separated class name, for example "ptolemy.util.ClassUtilities"
   * @return If the class can be found as a resource, return the directory or jar file where the
   *     necessary class can be found. otherwise, return null. If the resource is found in a
   *     directory, then the return value will always have forward slashes, it will never use
   *     backslashes.
   */
  public static String lookupClassAsResource(String necessaryClass) {
    // This method is called from copernicus.kernel.GeneratorAttribute
    // and actor.lib.python.PythonScript.  We moved it here
    // to avoid dependencies.
    String necessaryResource = StringUtilities.substitute(necessaryClass, ".", "/") + ".class";

    URL necessaryURL =
        Thread.currentThread().getContextClassLoader().getResource(necessaryResource);

    if (necessaryURL != null) {
      String resourceResults = necessaryURL.getFile();

      // Strip off the file:/ and the necessaryResource.
      if (resourceResults.startsWith("file:/")) {
        resourceResults = resourceResults.substring(6);
      }

      // Strip off the name of the resource we were looking for
      // so that we are left with the directory or jar file
      // it is in
      resourceResults =
          resourceResults.substring(0, resourceResults.length() - necessaryResource.length());

      // Strip off the trailing !/
      if (resourceResults.endsWith("!/")) {
        resourceResults = resourceResults.substring(0, resourceResults.length() - 2);
      }

      // Unfortunately, under Windows, URL.getFile() may
      // return things like /c:/ptII, so we create a new
      // File and get its path, which will return c:\ptII
      File resourceFile = new File(resourceResults);

      // Convert backslashes
      String sanitizedResourceName = StringUtilities.substitute(resourceFile.getPath(), "\\", "/");
      return sanitizedResourceName;
    }

    return null;
  }
示例#18
0
/**
 * Common character classes used for input validation, output encoding, verifying password strength
 * CSRF token generation, generating salts, etc
 *
 * @author Neil Matatall (neil.matatall .at. gmail.com)
 */
public class EncoderConstants {

  public static final char[] CHAR_LOWERS = {
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
    't', 'u', 'v', 'w', 'x', 'y', 'z'
  };

  public static final char[] CHAR_UPPERS = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
    'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
  };

  public static final char[] CHAR_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

  public static final char[] CHAR_SPECIALS = {
    '!', '$', '*', '+', '-', '.', '=', '?', '@', '^', '_', '|', '~'
  };

  public static final char[] CHAR_LETTERS = StringUtilities.union(CHAR_LOWERS, CHAR_UPPERS);

  public static final char[] CHAR_ALPHANUMERICS = StringUtilities.union(CHAR_LETTERS, CHAR_DIGITS);
}
  /**
   * Given a file name or URL, construct a java.io.File object that refers to the file name or URL.
   * This method first attempts to directly use the file name to construct the File. If the
   * resulting File is a relative pathname, then it is resolved relative to the specified base URI,
   * if there is one. If there is no such base URI, then it simply returns the relative File object.
   * See the java.io.File documentation for a details about relative and absolute pathnames.
   *
   * <p>If the name begins with "xxxxxxCLASSPATHxxxxxx" or "$CLASSPATH" then search for the file
   * relative to the classpath.
   *
   * <p>Note that "xxxxxxCLASSPATHxxxxxx" is the value of the globally defined constant $CLASSPATH
   * available in the Ptolemy II expression language.
   *
   * <p>If the name begins with $CLASSPATH or "xxxxxxCLASSPATHxxxxxx" but that name cannot be found
   * in the classpath, the value of the ptolemy.ptII.dir property is substituted in.
   *
   * <p>The file need not exist for this method to succeed. Thus, this method can be used to
   * determine whether a file with a given name exists, prior to calling openForWriting(), for
   * example.
   *
   * <p>This method is similar to {@link #nameToURL(String, URI, ClassLoader)} except that in this
   * method, the file or URL must be readable. Usually, this method is use for write a file and
   * {@link #nameToURL(String, URI, ClassLoader)} is used for reading.
   *
   * @param name The file name or URL.
   * @param base The base for relative URLs.
   * @return A File, or null if the filename argument is null or an empty string.
   * @see #nameToURL(String, URI, ClassLoader)
   */
  public static File nameToFile(String name, URI base) {
    if ((name == null) || name.trim().equals("")) {
      return null;
    }

    if (name.startsWith(_CLASSPATH_VALUE) || name.startsWith("$CLASSPATH")) {
      URL result = null;
      try {
        result = _searchClassPath(name, null);
      } catch (IOException ex) {
        // Ignore.  In nameToFile(), it is ok if we don't find the variable
      }
      if (result != null) {
        return new File(result.getPath());
      } else {
        String ptII = StringUtilities.getProperty("ptolemy.ptII.dir");
        if (ptII != null && ptII.length() > 0) {
          return new File(ptII, _trimClassPath(name));
        }
      }
    }

    File file = new File(name);

    if (!file.isAbsolute()) {
      // Try to resolve the base directory.
      if (base != null) {
        // Need to replace \ with /, otherwise resolve would fail even
        // if invoked in a windows OS. -- tfeng (02/27/2009)
        URI newURI = base.resolve(StringUtilities.substitute(name, " ", "%20").replace('\\', '/'));

        // file = new File(newURI);
        String urlString = newURI.getPath();
        file = new File(StringUtilities.substitute(urlString, "%20", " "));
      }
    }
    return file;
  }
示例#20
0
  /**
   * Apply existing advices loaded into the NCubeManager, to the passed in n-cube. This allows
   * advices to be added first, and then let them be applied 'on demand' as an n-cube is loaded
   * later.
   *
   * @param appId ApplicationID
   * @param ncube NCube to which all matching advices will be applied.
   */
  private static void applyAdvices(ApplicationID appId, NCube ncube) {
    final Map<String, Advice> appAdvices = advices.get(appId);

    if (MapUtilities.isEmpty(appAdvices)) {
      return;
    }
    for (Map.Entry<String, Advice> entry : appAdvices.entrySet()) {
      final Advice advice = entry.getValue();
      final String wildcard = entry.getKey().replace(advice.getName() + '/', "");
      final String regex = StringUtilities.wildcardToRegexString(wildcard);
      final Axis axis = ncube.getAxis("method");
      addAdviceToMatchedCube(advice, regex, ncube, axis);
    }
  }
 /**
  * Extract the contents of a jar file.
  *
  * @param args An array of arguments. The first argument names the jar file to be extracted. The
  *     first argument is required. The second argument names the directory in which to extract the
  *     files from the jar file. The second argument is optional.
  */
 public static void main(String[] args) {
   if (args.length < 1 || args.length > 2) {
     System.err.println(
         "Usage: java -classpath $PTII "
             + "ptolemy.util.FileUtilities jarFile [directory]\n"
             + "where jarFile is the name of the jar file\n"
             + "and directory is the optional directory in which to "
             + "extract.");
     StringUtilities.exit(2);
   }
   String jarFileName = args[0];
   String directoryName = null;
   if (args.length >= 2) {
     directoryName = args[1];
   }
   try {
     extractJarFile(jarFileName, directoryName);
   } catch (Throwable throwable) {
     System.err.println("Failed to extract \"" + jarFileName + "\"");
     throwable.printStackTrace();
     StringUtilities.exit(3);
   }
 }
示例#22
0
  public static String concatUris(String... uris) {
    StringBuilder builder = new StringBuilder();

    for (String uri : uris) {
      if (StringUtilities.isNotBlank(uri)) {
        if (!uri.startsWith("/") && !uri.isEmpty()) {
          builder.append("/");
        }

        builder.append(uri);
      }
    }

    return builder.toString();
  }
示例#23
0
  public static String appendPath(String baseUrl, String... paths) {
    String path = concatUris(paths);
    if (StringUtilities.isBlank(path)) {
      return baseUrl;
    }

    StringBuilder url;
    if (baseUrl.endsWith("/")) {
      url = new StringBuilder(baseUrl.substring(0, baseUrl.length() - 1));
    } else {
      url = new StringBuilder(baseUrl);
    }

    return url.append(path).toString();
  }
示例#24
0
  public static String resolveRelativeUrl(ApplicationID appId, String relativeUrl) {
    validateAppId(appId);
    if (StringUtilities.isEmpty(relativeUrl)) {
      throw new IllegalArgumentException(
          "Cannot resolve relative url - relative url cannot be null or empty string.");
    }
    final String loUrl = relativeUrl.toLowerCase();
    if (loUrl.startsWith("http:") || loUrl.startsWith("https:") || loUrl.startsWith("file:")) {
      return relativeUrl;
    }

    URLClassLoader classLoader = getUrlClassLoader(appId, new HashMap());
    URL absUrl = classLoader.getResource(relativeUrl);
    return absUrl != null ? absUrl.toString() : null;
  }
  @Override
  public void processMessage(Chat chat, Message message) {
    System.out.println("Processing a message.");

    String body = message.toXML();
    String formatedBody = StringUtilities.toJava(body);

    System.out.println("Formatted XML: ");
    System.out.println(formatedBody);

    //        String updateType = (String)message.getProperty("updateType");
    //
    //        if(updateType == "inFrontOf"){
    //          String submitter = (String)message.getProperty("name");
    //          frontPlanet = (String)message.getProperty("front");
    //          backPlanet = (String)message.getProperty("back");
    //
    //          System.out.println(submitter +" says " +frontPlanet +" is in Front of "
    //              +backPlanet);
    //        }else{
    //          String body =message.toXML();
    //          System.out.println("I'm not responsible for this type of packet: "
    //          +body);
    //
    //          Collection<Message.Body> bodies = message.getBodies();
    //          System.out.println("Bodies size: "+bodies.size());
    //          for(Message.Body s: bodies)
    //           System.out.println("body message " +s.getMessage());
    //
    //          Message.Type typeM= message.getType();
    //          System.out.println("Type " +typeM);
    //
    ////          Collection<String> props = message.getPropertyNames();
    ////          for(String s: props)
    ////            System.out.println("Prop " +s);
    //        }

  }
示例#26
0
  public static Map<String, Object> getSystemParams() {
    final ConcurrentMap<String, Object> params = systemParams;

    if (params != null) {
      return params;
    }

    synchronized (NCubeManager.class) {
      if (systemParams == null) {
        String jsonParams = SystemUtilities.getExternalVariable(NCUBE_PARAMS);
        systemParams = new ConcurrentHashMap<>();

        if (StringUtilities.hasContent(jsonParams)) {
          try {
            systemParams = new ConcurrentHashMap<>(JsonReader.jsonToMaps(jsonParams));
          } catch (Exception e) {
            LOG.warn("Parsing of NCUBE_PARAMS failed.  " + jsonParams);
          }
        }
      }
    }
    return systemParams;
  }
 @Test
 public void testFindLineBreaks() throws Exception {
   Assert.assertTrue(
       Arrays.equals(
           new int[] {6}, StringUtilities.findBreakPoints("Hallo Du!", 2))); // $NON-NLS-1$
   Assert.assertTrue(
       Arrays.equals(
           new int[] {6, 9}, StringUtilities.findBreakPoints("Hallo Du da!", 3))); // $NON-NLS-1$
   Assert.assertTrue(
       Arrays.equals(
           new int[] {6}, StringUtilities.findBreakPoints("Hallo-Du!", 2))); // $NON-NLS-1$
   Assert.assertTrue(
       Arrays.equals(
           new int[] {6, 9}, StringUtilities.findBreakPoints("Hallo-Du da!", 3))); // $NON-NLS-1$
   Assert.assertTrue(
       Arrays.equals(
           new int[] {6, 13},
           StringUtilities.findBreakPoints("Oh Du Lebest draussen!", 3))); // $NON-NLS-1$
   int[] breakPoints = StringUtilities.findBreakPoints("Hallo Du da drueben!", 3);
   Assert.assertTrue(Arrays.equals(new int[] {6, 12}, breakPoints)); // $NON-NLS-1$
   Assert.assertTrue(
       Arrays.equals(
           new int[] {0, 3}, StringUtilities.findBreakPoints("Zu kurz.", 3))); // $NON-NLS-1$
 }
 @Test
 public void testCutOffLastCharacters() throws Exception {
   Assert.assertEquals(
       "S", StringUtilities.cutOffLastCharacters("Su", 1)); // $NON-NLS-1$ //$NON-NLS-2$
 }
示例#29
0
 private void writeNewSecret() {
   long secretValue = secureRandom.nextLong();
   secret = new Long(secretValue).toString();
   StringUtilities.writeFile(secretFile, secret);
 }
  /**
   * Given a file or URL name, return as a URL. If the file name is relative, then it is interpreted
   * as being relative to the specified base directory. If the name begins with
   * "xxxxxxCLASSPATHxxxxxx" or "$CLASSPATH" then search for the file relative to the classpath.
   *
   * <p>Note that "xxxxxxCLASSPATHxxxxxx" is the value of the globally defined constant $CLASSPATH
   * available in the Ptolemy II expression language. II expression language.
   *
   * <p>If no file is found, then throw an exception.
   *
   * <p>This method is similar to {@link #nameToFile(String, URI)} except that in this method, the
   * file or URL must be readable. Usually, this method is use for reading a file and is used for
   * writing {@link #nameToFile(String, URI)}.
   *
   * @param name The name of a file or URL.
   * @param baseDirectory The base directory for relative file names, or null to specify none.
   * @param classLoader The class loader to use to locate system resources, or null to use the
   *     system class loader that was used to load this class.
   * @return A URL, or null if the name is null or the empty string.
   * @exception IOException If the file cannot be read, or if the file cannot be represented as a
   *     URL (e.g. System.in), or the name specification cannot be parsed.
   * @see #nameToFile(String, URI)
   */
  public static URL nameToURL(String name, URI baseDirectory, ClassLoader classLoader)
      throws IOException {
    if ((name == null) || name.trim().equals("")) {
      return null;
    }

    if (name.startsWith(_CLASSPATH_VALUE) || name.startsWith("$CLASSPATH")) {
      URL result = _searchClassPath(name, classLoader);
      if (result == null) {
        throw new IOException("Cannot find file '" + _trimClassPath(name) + "' in classpath");
      }

      return result;
    }

    File file = new File(name);

    if (file.isAbsolute()) {
      if (!file.canRead()) {
        // FIXME: This is a hack.
        // Expanding the configuration with Ptolemy II installed
        // in a directory with spaces in the name fails on
        // JAIImageReader because PtolemyII.jpg is passed in
        // to this method as C:\Program%20Files\Ptolemy\...
        file = new File(StringUtilities.substitute(name, "%20", " "));

        URL possibleJarURL = null;

        if (!file.canRead()) {
          // ModelReference and FilePortParameters sometimes
          // have paths that have !/ in them.
          possibleJarURL = ClassUtilities.jarURLEntryResource(name);

          if (possibleJarURL != null) {
            file = new File(possibleJarURL.getFile());
          }
        }

        if (!file.canRead()) {
          throw new IOException(
              "Cannot read file '"
                  + name
                  + "' or '"
                  + StringUtilities.substitute(name, "%20", " ")
                  + "'"
                  + ((possibleJarURL == null) ? "" : (" or '" + possibleJarURL.getFile() + "")));
        }
      }

      return file.toURI().toURL();
    } else {
      // Try relative to the base directory.
      if (baseDirectory != null) {
        // Try to resolve the URI.
        URI newURI;

        try {
          newURI = baseDirectory.resolve(name);
        } catch (Exception ex) {
          // FIXME: Another hack
          // This time, if we try to open some of the JAI
          // demos that have actors that have defaults FileParameters
          // like "$PTII/doc/img/PtolemyII.jpg", then resolve()
          // bombs.
          String name2 = StringUtilities.substitute(name, "%20", " ");
          try {
            newURI = baseDirectory.resolve(name2);
            name = name2;
          } catch (Exception ex2) {
            IOException io =
                new IOException(
                    "Problem with URI format in '"
                        + name
                        + "'. "
                        + "and '"
                        + name2
                        + "' "
                        + "This can happen if the file name "
                        + "is not absolute "
                        + "and is not present relative to the "
                        + "directory in which the specified model "
                        + "was read (which was '"
                        + baseDirectory
                        + "')");
            io.initCause(ex2);
            throw io;
          }
        }

        String urlString = newURI.toString();

        try {
          // Adding another '/' for remote execution.
          if ((newURI.getScheme() != null) && (newURI.getAuthority() == null)) {
            // Change from Efrat:
            // "I made these change to allow remote
            // execution of a workflow from within a web
            // service."

            // "The first modification was due to a URI
            // authentication exception when trying to
            // create a file object from a URI on the
            // remote side. The second modification was
            // due to the file protocol requirements to
            // use 3 slashes, 'file:///' on the remote
            // side, although it would be probably be a
            // good idea to also make sure first that the
            // url string actually represents the file
            // protocol."
            urlString = urlString.substring(0, 6) + "//" + urlString.substring(6);

            // } else {
            // urlString = urlString.substring(0, 6) + "/"
            // + urlString.substring(6);
          }
          // Unfortunately, between Java 1.5 and 1.6,
          // The URL constructor changed.
          // In 1.5, new URL("file:////foo").toString()
          // returns "file://foo"
          // In 1.6, new URL("file:////foo").toString()
          // return "file:////foo".
          // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6561321
          return new URL(urlString);
        } catch (Exception ex3) {
          try {
            // Under Webstart, opening
            // hoc/demo/ModelReference/ModelReference.xml
            // requires this because the URL is relative.
            return new URL(baseDirectory.toURL(), urlString);
          } catch (Exception ex4) {

            try {
              // Under Webstart, ptalon, EightChannelFFT
              // requires this.
              return new URL(baseDirectory.toURL(), newURI.toString());
            } catch (Exception ex5) {
              // Ignore
            }

            IOException io =
                new IOException(
                    "Problem with URI format in '"
                        + urlString
                        + "'. "
                        + "This can happen if the '"
                        + urlString
                        + "' is not absolute"
                        + " and is not present relative to the directory"
                        + " in which the specified model was read"
                        + " (which was '"
                        + baseDirectory
                        + "')");
            io.initCause(ex3);
            throw io;
          }
        }
      }

      // As a last resort, try an absolute URL.

      URL url = new URL(name);

      // If we call new URL("http", null, /foo);
      // then we get "http:/foo", which should be "http://foo"
      // This change suggested by Dan Higgins and Kevin Kruland
      // See kepler/src/util/URLToLocalFile.java
      try {
        String fixedURLAsString = url.toString().replaceFirst("(https?:)//?", "$1//");
        url = new URL(fixedURLAsString);
      } catch (Exception e) {
        // Ignore
      }
      return url;
    }
  }