Пример #1
0
  public void testUnicodeChars() throws Exception {
    File file = new File("unicodeáéíóú");
    if (file.exists()) {
      if (!file.delete()) {
        fail("Unable to delete file: " + file);
      }
    }
    try {
      if (!file.mkdirs()) {
        fail("Unable to create directory: " + file);
      }
      Ruby runtime;
      RubyInstanceConfig.nativeEnabled = false;
      runtime = Ruby.newInstance();

      JRubyFile rubyFile = RubyFile.file(RubyString.newString(runtime, file.getAbsolutePath()));
      assertTrue(rubyFile.exists());
      assertTrue(file.exists());
      assertTrue(file.isDirectory());
      try {
        assertTrue(runtime.getPosix().stat(rubyFile.getAbsolutePath()).isDirectory());
      } catch (Exception e) {
        throw new RuntimeException("Expecting posix layer to work properly", e);
      }
    } finally {
      if (file.exists()) {
        file.delete();
      }
    }
  }
Пример #2
0
  protected LoadServiceResource tryResourceAsIs(String namePlusSuffix) throws RaiseException {
    LoadServiceResource foundResource = null;

    try {
      if (!Ruby.isSecurityRestricted()) {
        String reportedPath = namePlusSuffix;
        File actualPath;
        // we check length == 0 for 'load', which does not use load path
        if (new File(reportedPath).isAbsolute()) {
          // it's an absolute path, use it as-is
          actualPath =
              new File(RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
        } else {
          // prepend ./ if . is not already there, since we're loading based on CWD
          if (reportedPath.charAt(0) == '.' && reportedPath.charAt(1) == '/') {
            reportedPath = reportedPath.replaceFirst("\\./", runtime.getCurrentDirectory());
          }

          actualPath =
              JRubyFile.create(
                  runtime.getCurrentDirectory(),
                  RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
        }
        debugLogTry("resourceAsIs", actualPath.toString());
        if (actualPath.isFile() && actualPath.canRead()) {
          foundResource = new LoadServiceResource(actualPath, reportedPath);
          debugLogFound(foundResource);
        }
      }
    } catch (SecurityException secEx) {
    }

    return foundResource;
  }
Пример #3
0
  protected LoadServiceResource tryResourceFromCWD(
      SearchState state, String baseName, SuffixType suffixType) throws RaiseException {
    LoadServiceResource foundResource = null;

    for (String suffix : suffixType.getSuffixes()) {
      String namePlusSuffix = baseName + suffix;
      // check current directory; if file exists, retrieve URL and return resource
      try {
        JRubyFile file =
            JRubyFile.create(
                runtime.getCurrentDirectory(),
                RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
        debugLogTry("resourceFromCWD", file.toString());
        if (file.isFile() && file.isAbsolute() && file.canRead()) {
          boolean absolute = true;
          String s = namePlusSuffix;
          if (!namePlusSuffix.startsWith("./")) {
            s = "./" + s;
          }
          foundResource = new LoadServiceResource(file, s, absolute);
          debugLogFound(foundResource);
          state.loadName = resolveLoadName(foundResource, namePlusSuffix);
          break;
        }
      } catch (IllegalArgumentException illArgEx) {
      } catch (SecurityException secEx) {
      }
    }

    return foundResource;
  }
Пример #4
0
  @JRubyMethod(required = 1, optional = 1, visibility = PRIVATE)
  @Override
  public IRubyObject initialize(IRubyObject[] args, Block block) {
    Ruby runtime = getRuntime();
    IRubyObject basename = args[0];
    IRubyObject dir = defaultTmpDir(runtime, args);

    File tmp = null;
    synchronized (tmpFileLock) {
      while (true) {
        try {
          if (counter == -1) {
            counter = RND.nextInt() & 0xffff;
          }
          counter++;

          // We do this b/c make_tmpname might be overridden
          IRubyObject tmpname =
              callMethod(
                  runtime.getCurrentContext(),
                  "make_tmpname",
                  new IRubyObject[] {basename, runtime.newFixnum(counter)});
          tmp =
              JRubyFile.create(
                  getRuntime().getCurrentDirectory(),
                  new File(dir.convertToString().toString(), tmpname.convertToString().toString())
                      .getPath());
          if (tmp.createNewFile()) {
            tmpFile = tmp;
            path = tmp.getPath();
            try {
              tmpFile.deleteOnExit();
            } catch (NullPointerException npe) {
              // See JRUBY-4624.
              // Due to JDK bug, NPE could be thrown
              // when shutdown is in progress.
              // Do nothing.
            } catch (IllegalStateException ise) {
              // do nothing, shutdown in progress
            }
            initializeOpen();
            referenceSet.put(reaper = new Reaper(this, runtime, tmpFile, openFile), Boolean.TRUE);
            return this;
          }
        } catch (IOException e) {
          throw runtime.newIOErrorFromException(e);
        }
      }
    }
  }
Пример #5
0
  protected LoadServiceResource tryResourceFromLoadPath(String namePlusSuffix, String loadPathEntry)
      throws RaiseException {
    LoadServiceResource foundResource = null;

    try {
      if (!Ruby.isSecurityRestricted()) {
        String reportedPath = loadPathEntry + "/" + namePlusSuffix;
        JRubyFile actualPath;
        boolean absolute = false;
        // we check length == 0 for 'load', which does not use load path
        if (new File(reportedPath).isAbsolute()) {
          absolute = true;
          // it's an absolute path, use it as-is
          actualPath =
              JRubyFile.create(
                  loadPathEntry,
                  RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
        } else {
          absolute = false;
          // prepend ./ if . is not already there, since we're loading based on CWD
          if (reportedPath.charAt(0) != '.') {
            reportedPath = "./" + reportedPath;
          }
          actualPath =
              JRubyFile.create(
                  JRubyFile.create(runtime.getCurrentDirectory(), loadPathEntry).getAbsolutePath(),
                  RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
        }
        debugLogTry(
            "resourceFromLoadPath",
            "'" + actualPath.toString() + "' " + actualPath.isFile() + " " + actualPath.canRead());
        if (actualPath.isFile() && actualPath.canRead()) {
          foundResource = new LoadServiceResource(actualPath, reportedPath, absolute);
          debugLogFound(foundResource);
        }
      }
    } catch (SecurityException secEx) {
    }

    return foundResource;
  }
Пример #6
0
  /**
   * Open a new descriptor using the given working directory, file path, mode flags, and file
   * permission. This is equivalent to the open(2) POSIX function.
   *
   * @param cwd the "current working directory" to use when opening the file
   * @param path the file path to open
   * @param flags the mode flags to use for opening the file
   * @param perm the file permissions to use when creating a new file (currently unobserved)
   * @param posix a POSIX api implementation, used for setting permissions; if null, permissions are
   *     ignored
   * @param classLoader a ClassLoader to use for classpath: resources
   * @return a new ChannelDescriptor based on the specified parameters
   */
  public static ChannelDescriptor open(
      String cwd, String path, ModeFlags flags, int perm, POSIX posix, ClassLoader classLoader)
      throws FileNotFoundException, DirectoryAsFileException, FileExistsException, IOException {
    if (path.equals("/dev/null") || path.equalsIgnoreCase("nul:") || path.equalsIgnoreCase("nul")) {
      Channel nullChannel = new NullChannel();
      // FIXME: don't use RubyIO for this
      return new ChannelDescriptor(nullChannel, flags);
    }

    if (path.startsWith("classpath:/") && classLoader != null) {
      path = path.substring("classpath:/".length());
      InputStream is = classLoader.getResourceAsStream(path);
      // FIXME: don't use RubyIO for this
      return new ChannelDescriptor(Channels.newChannel(is), flags);
    }

    return JRubyFile.createResource(posix, cwd, path).openDescriptor(flags, perm);
  }
Пример #7
0
  public synchronized void freopen(Ruby runtime, String path, ModeFlags modes)
      throws DirectoryAsFileException, IOException, InvalidValueException, PipeException,
          BadDescriptorException {
    // flush first
    flushWrite();

    // reset buffer
    buffer.clear();
    if (reading) {
      buffer.flip();
    }

    this.modes = modes;

    if (descriptor.isOpen()) {
      descriptor.close();
    }

    if (path.equals("/dev/null") || path.equalsIgnoreCase("nul:") || path.equalsIgnoreCase("nul")) {
      descriptor = descriptor.reopen(new NullChannel(), modes);
    } else {
      String cwd = runtime.getCurrentDirectory();
      JRubyFile theFile = JRubyFile.create(cwd, path);

      if (theFile.isDirectory() && modes.isWritable()) throw new DirectoryAsFileException();

      if (modes.isCreate()) {
        if (theFile.exists() && modes.isExclusive()) {
          throw runtime.newErrnoEEXISTError("File exists - " + path);
        }
        theFile.createNewFile();
      } else {
        if (!theFile.exists()) {
          throw runtime.newErrnoENOENTError("file not found - " + path);
        }
      }

      // We always open this rw since we can only open it r or rw.
      RandomAccessFile file = new RandomAccessFile(theFile, modes.toJavaModeString());

      if (modes.isTruncate()) file.setLength(0L);

      descriptor = descriptor.reopen(file, modes);

      try {
        if (modes.isAppendable()) lseek(0, SEEK_END);
      } catch (PipeException pe) {
        // ignore, it's a pipe or fifo
      }
    }
  }
Пример #8
0
  protected LoadServiceResource tryResourceFromHome(
      SearchState state, String baseName, SuffixType suffixType) throws RaiseException {
    LoadServiceResource foundResource = null;

    RubyHash env = (RubyHash) runtime.getObject().fastGetConstant("ENV");
    RubyString env_home = runtime.newString("HOME");
    if (env.has_key_p(env_home).isFalse()) {
      return null;
    }
    String home = env.op_aref(runtime.getCurrentContext(), env_home).toString();
    String path = baseName.substring(2);

    for (String suffix : suffixType.getSuffixes()) {
      String namePlusSuffix = path + suffix;
      // check home directory; if file exists, retrieve URL and return resource
      try {
        JRubyFile file =
            JRubyFile.create(
                home, RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
        debugLogTry("resourceFromHome", file.toString());
        if (file.isFile() && file.isAbsolute() && file.canRead()) {
          boolean absolute = true;
          String s = "~/" + namePlusSuffix;

          foundResource = new LoadServiceResource(file, s, absolute);
          debugLogFound(foundResource);
          state.loadName = resolveLoadName(foundResource, s);
          break;
        }
      } catch (IllegalArgumentException illArgEx) {
      } catch (SecurityException secEx) {
      }
    }

    return foundResource;
  }