示例#1
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");
  }
示例#2
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;
  }
  /**
   * 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;
  }
  /**
   * 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;
    }
  }