예제 #1
1
  boolean accept(File parent, File file) {
    try {
      File f1 = parent.getCanonicalFile();
      File f2 = file.getCanonicalFile();
      if (f1.equals(f2)) {
        log.log(
            Level.INFO,
            "Skipping links to itself...: {0} {1}",
            new Object[] {parent.getAbsolutePath(), file.getAbsolutePath()});
        return false;
      }

      // Now, let's verify that it's not a link back up the chain...
      File t1 = f1;
      while ((t1 = t1.getParentFile()) != null) {
        if (f2.equals(t1)) {
          log.log(
              Level.INFO,
              "Skipping links to parent...: {0} {1}",
              new Object[] {parent.getAbsolutePath(), file.getAbsolutePath()});
          return false;
        }
      }

      return accept(file);
    } catch (IOException ex) {
      log.log(
          Level.WARNING,
          "Warning: Failed to resolve name: {0} {1}",
          new Object[] {parent.getAbsolutePath(), file.getAbsolutePath()});
    }
    return false;
  }
 @Override
 public Reader getReader(String resourceName) {
   InputStream is = null;
   File file = fileRoot == null ? new File(resourceName) : new File(fileRoot, resourceName);
   if (file.exists() && file.isFile()) {
     try {
       // Check to make sure that the file is under the file root or current directory.
       // Without this check you might accidentally open a security whole when exposing
       // mustache templates to end users.
       File checkRoot =
           fileRoot == null ? new File("").getCanonicalFile() : fileRoot.getCanonicalFile();
       File parent = file.getCanonicalFile();
       while ((parent = parent.getParentFile()) != null) {
         if (parent.equals(checkRoot)) break;
       }
       if (parent == null) {
         throw new MustacheException("File not under root: " + checkRoot.getAbsolutePath());
       }
       is = new FileInputStream(file);
     } catch (IOException e) {
       throw new MustacheException("Found file, could not open: " + file, e);
     }
   }
   if (is != null) {
     return new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
   } else {
     return null;
   }
 }
  /**
   * Copy sourceURL to destinationFile without doing any byte conversion.
   *
   * @param sourceURL The source URL
   * @param destinationFile The destination File.
   * @return true if the file was copied, false if the file was not copied because the sourceURL and
   *     the destinationFile refer to the same file.
   * @exception IOException If the source file does not exist.
   */
  public static boolean binaryCopyURLToFile(URL sourceURL, File destinationFile)
      throws IOException {
    URL destinationURL = destinationFile.getCanonicalFile().toURI().toURL();

    if (sourceURL.sameFile(destinationURL)) {
      return false;
    }

    // If sourceURL is of the form file:./foo, then we need to try again.
    File sourceFile = new File(sourceURL.getFile());

    // If the sourceURL is not a jar URL, then check to see if we
    // have the same file.
    // FIXME: should we check for !/ and !\ everywhere?
    if ((sourceFile.getPath().indexOf("!/") == -1) && (sourceFile.getPath().indexOf("!\\") == -1)) {
      try {
        if (sourceFile.getCanonicalFile().toURI().toURL().sameFile(destinationURL)) {
          return false;
        }
      } catch (IOException ex) {
        // JNLP Jar urls sometimes throw an exception here.
        // IOException constructor does not take a cause
        IOException ioException =
            new IOException("Cannot find canonical file name of '" + sourceFile + "'");
        ioException.initCause(ex);
        throw ioException;
      }
    }

    _binaryCopyStream(sourceURL.openStream(), destinationFile);

    return true;
  }
예제 #4
0
 public static boolean contentEqualsIgnoreEOL(File file1, File file2, String charsetName)
     throws IOException {
   boolean file1Exists = file1.exists();
   if (file1Exists != file2.exists()) {
     return false;
   }
   if (!file1Exists) {
     return true;
   }
   if ((file1.isDirectory()) || (file2.isDirectory())) {
     throw new IOException("Can't compare directories, only files");
   }
   if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
     return true;
   }
   Reader input1 = null;
   Reader input2 = null;
   try {
     if (charsetName == null) {
       input1 = new InputStreamReader(new FileInputStream(file1));
       input2 = new InputStreamReader(new FileInputStream(file2));
     } else {
       input1 = new InputStreamReader(new FileInputStream(file1), charsetName);
       input2 = new InputStreamReader(new FileInputStream(file2), charsetName);
     }
     return IOUtils.contentEqualsIgnoreEOL(input1, input2);
   } finally {
     IOUtils.closeQuietly(input1);
     IOUtils.closeQuietly(input2);
   }
 }
예제 #5
0
 public static boolean contentEquals(File file1, File file2) throws IOException {
   boolean file1Exists = file1.exists();
   if (file1Exists != file2.exists()) {
     return false;
   }
   if (!file1Exists) {
     return true;
   }
   if ((file1.isDirectory()) || (file2.isDirectory())) {
     throw new IOException("Can't compare directories, only files");
   }
   if (file1.length() != file2.length()) {
     return false;
   }
   if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
     return true;
   }
   InputStream input1 = null;
   InputStream input2 = null;
   try {
     input1 = new FileInputStream(file1);
     input2 = new FileInputStream(file2);
     return IOUtils.contentEquals(input1, input2);
   } finally {
     IOUtils.closeQuietly(input1);
     IOUtils.closeQuietly(input2);
   }
 }
예제 #6
0
 /**
  * 检查两个文件是否是同一个文件
  *
  * @param file1 文件1
  * @param file2 文件2
  * @return 是否相同
  */
 public static boolean equals(File file1, File file2) {
   try {
     file1 = file1.getCanonicalFile();
     file2 = file2.getCanonicalFile();
   } catch (IOException ignore) {
     return false;
   }
   return file1.equals(file2);
 }
예제 #7
0
  private void initializeLoader() {
    File modsDir = new File(minecraftDir, "mods");
    File configDir = new File(minecraftDir, "config");
    String canonicalModsPath;
    String canonicalConfigPath;

    try {
      canonicalModsPath = modsDir.getCanonicalPath();
      canonicalConfigPath = configDir.getCanonicalPath();
      canonicalConfigDir = configDir.getCanonicalFile();
      canonicalModsDir = modsDir.getCanonicalFile();
    } catch (IOException ioe) {
      FMLLog.log(
          Level.ERROR,
          ioe,
          "Failed to resolve loader directories: mods : %s ; config %s",
          canonicalModsDir.getAbsolutePath(),
          configDir.getAbsolutePath());
      throw new LoaderException(ioe);
    }

    if (!canonicalModsDir.exists()) {
      FMLLog.info("No mod directory found, creating one: %s", canonicalModsPath);
      boolean dirMade = canonicalModsDir.mkdir();
      if (!dirMade) {
        FMLLog.severe("Unable to create the mod directory %s", canonicalModsPath);
        throw new LoaderException(
            String.format("Unable to create the mod directory %s", canonicalModsPath));
      }
      FMLLog.info("Mod directory created successfully");
    }

    if (!canonicalConfigDir.exists()) {
      FMLLog.fine("No config directory found, creating one: %s", canonicalConfigPath);
      boolean dirMade = canonicalConfigDir.mkdir();
      if (!dirMade) {
        FMLLog.severe("Unable to create the config directory %s", canonicalConfigPath);
        throw new LoaderException();
      }
      FMLLog.info("Config directory created successfully");
    }

    if (!canonicalModsDir.isDirectory()) {
      FMLLog.severe("Attempting to load mods from %s, which is not a directory", canonicalModsPath);
      throw new LoaderException();
    }

    if (!configDir.isDirectory()) {
      FMLLog.severe(
          "Attempting to load configuration from %s, which is not a directory",
          canonicalConfigPath);
      throw new LoaderException();
    }

    readInjectedDependencies();
  }
예제 #8
0
  /**
   * Return the relative path. Path elements are separated with / char.
   *
   * @param baseDir a parent directory of {@code file}
   * @param file the file to get the relative path
   * @return the relative path
   */
  public static String relativize(File baseDir, File file) {
    try {
      baseDir = baseDir.getCanonicalFile();
      file = file.getCanonicalFile();

      return baseDir.toURI().relativize(file.toURI()).getPath();
    } catch (IOException e) {
      throw new DockerClientException(e.getMessage(), e);
    }
  }
예제 #9
0
 public static boolean directoryIsAncestorOfOrEqualTo(File dir, File file) throws IOException {
   dir = dir.getCanonicalFile();
   for (File currentFile = file.getCanonicalFile();
       null != currentFile;
       currentFile = currentFile.getParentFile()) {
     if (currentFile.equals(dir)) {
       return true;
     }
   }
   return false;
 }
  public static void removeDuplicatingClasses(
      final Module module,
      @NotNull final String packageName,
      @NotNull String className,
      @Nullable File classFile,
      String sourceRootPath) {
    if (sourceRootPath == null) {
      return;
    }
    VirtualFile sourceRoot = LocalFileSystem.getInstance().findFileByPath(sourceRootPath);
    if (sourceRoot == null) {
      return;
    }
    final Project project = module.getProject();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
    final String interfaceQualifiedName = packageName + '.' + className;
    PsiClass[] classes =
        facade.findClasses(interfaceQualifiedName, GlobalSearchScope.moduleScope(module));
    final ProjectFileIndex projectFileIndex =
        ProjectRootManager.getInstance(project).getFileIndex();
    for (PsiClass c : classes) {
      PsiFile psiFile = c.getContainingFile();
      if (className.equals(FileUtil.getNameWithoutExtension(psiFile.getName()))) {
        VirtualFile virtualFile = psiFile.getVirtualFile();
        if (virtualFile != null
            && projectFileIndex.getSourceRootForFile(virtualFile) == sourceRoot) {
          final String path = virtualFile.getPath();
          File f = new File(path);

          try {
            f = f.getCanonicalFile();
            classFile = classFile != null ? classFile.getCanonicalFile() : null;
            if (f != null && !f.equals(classFile) && f.exists()) {
              if (f.delete()) {
                virtualFile.refresh(true, false);
              } else {
                ApplicationManager.getApplication()
                    .invokeLater(
                        new Runnable() {
                          public void run() {
                            Messages.showErrorDialog(
                                project, "Can't delete file " + path, CommonBundle.getErrorTitle());
                          }
                        },
                        project.getDisposed());
              }
            }
          } catch (IOException e) {
            LOG.info(e);
          }
        }
      }
    }
  }
예제 #11
0
  // Derived from http://stackoverflow.com/a/3054692/250076
  public static File getRelativeFile(File targetFile, File baseFile) {
    try {
      targetFile = targetFile.getCanonicalFile();
      baseFile = baseFile.getCanonicalFile();
    } catch (IOException ignored) {
    }
    String pathSeparator = File.separator;
    String basePath = baseFile.getAbsolutePath();
    String normalizedTargetPath = normalize(targetFile.getAbsolutePath(), pathSeparator);
    String normalizedBasePath = normalize(basePath, pathSeparator);

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    StringBuilder common = new StringBuilder();

    int commonIndex = 0;
    while (commonIndex < target.length
        && commonIndex < base.length
        && target[commonIndex].equals(base[commonIndex])) {
      common.append(target[commonIndex]).append(pathSeparator);
      commonIndex++;
    }

    if (commonIndex == 0) {
      throw new Error(
          "No common path element found for '"
              + normalizedTargetPath
              + "' and '"
              + normalizedBasePath
              + '\'');
    }

    boolean baseIsFile = true;

    if (baseFile.exists()) {
      baseIsFile = baseFile.isFile();
    } else if (basePath.endsWith(pathSeparator)) {
      baseIsFile = false;
    }

    StringBuilder relative = new StringBuilder();

    if (base.length != commonIndex) {
      int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

      for (int i = 0; i < numDirsUp; i++) {
        relative.append("..").append(pathSeparator);
      }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return new File(relative.toString());
  }
  @Nullable
  static ClassLoader createPluginClassLoader(
      @NotNull File[] classPath,
      @NotNull ClassLoader[] parentLoaders,
      @NotNull IdeaPluginDescriptor pluginDescriptor) {

    if (pluginDescriptor.getUseIdeaClassLoader()) {
      try {
        final ClassLoader loader = PluginManagerCore.class.getClassLoader();
        final Method addUrlMethod = getAddUrlMethod(loader);

        for (File aClassPath : classPath) {
          final File file = aClassPath.getCanonicalFile();
          addUrlMethod.invoke(loader, file.toURI().toURL());
        }

        return loader;
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }

    PluginId pluginId = pluginDescriptor.getPluginId();
    File pluginRoot = pluginDescriptor.getPath();

    // if (classPath.length == 0) return null;
    if (isUnitTestMode()) return null;
    try {
      final List<URL> urls = new ArrayList<URL>(classPath.length);
      for (File aClassPath : classPath) {
        final File file =
            aClassPath
                .getCanonicalFile(); // it is critical not to have "." and ".." in classpath
                                     // elements
        urls.add(file.toURI().toURL());
      }
      return new PluginClassLoader(
          urls, parentLoaders, pluginId, pluginDescriptor.getVersion(), pluginRoot);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
예제 #13
0
 public static File relativizeFile(File ancestorDirectory, File file) throws IOException {
   File currentParent = file.getCanonicalFile();
   ancestorDirectory = ancestorDirectory.getCanonicalFile();
   LinkedList fileParents = new LinkedList();
   while (!currentParent.equals(ancestorDirectory)) {
     fileParents.addFirst(currentParent.getName());
     currentParent = currentParent.getParentFile();
   }
   File relativeFile = new File((String) fileParents.removeFirst());
   for (Iterator iterator = fileParents.iterator(); iterator.hasNext(); ) {
     relativeFile = new File(relativeFile, (String) iterator.next());
   }
   return relativeFile;
 }
 @Test
 public void testReadDefinition() throws IOException {
   DefinitionLoadingOptions options = new DefinitionLoadingOptions();
   new JCommander(options, "--directory", "src/test/resources");
   DefinitionLoadingModule module = new DefinitionLoadingModule();
   File defDir = module.directory(options, new File("."), null, System.getenv());
   assertEquals(new File("src/test/resources").getCanonicalFile(), defDir.getCanonicalFile());
   File kompiledDir = module.definition(defDir, null);
   assertEquals(
       new File("src/test/resources/test-kompiled").getCanonicalFile(),
       kompiledDir.getCanonicalFile());
   assertTrue(kompiledDir.exists());
   assertTrue(kompiledDir.isDirectory());
 }
  @Test
  public void testRelativePath() throws IOException {
    DefaultTargetPlatform tp = new DefaultTargetPlatform();

    File relative = new File("relative.xml");
    File canonical = new File("canonical.xml");

    tp.addArtifactFile(new DefaultArtifactKey("foo", "relative", "1"), relative, null);
    tp.addArtifactFile(
        new DefaultArtifactKey("foo", "canonical", "1"), canonical.getCanonicalFile(), null);

    Assert.assertNotNull(tp.getArtifact(relative.getCanonicalFile()));
    Assert.assertNotNull(tp.getArtifact(canonical));
  }
  public void testGetJiraBackupFilesWithFileNameAndNoAOFile() throws IOException {
    String f = getDataFilePath("jira-export-test.xml");
    replayMocks();

    final DefaultDataImportService defaultDataImportService = createImportService();
    final DataImportParams params = new DataImportParams.Builder("jira-export-test.xml").build();
    final File backupFile = defaultDataImportService.getJiraBackupFile(params);
    final File aoBackupFile = defaultDataImportService.getAOBackupFile(params);

    final File expectedFile = new File(f).getCanonicalFile();
    assertEquals(expectedFile, backupFile.getCanonicalFile());
    assertEquals(expectedFile, aoBackupFile.getCanonicalFile());
    verifyMocks();
  }
예제 #17
0
  /**
   * Determines whether a file or directory is beneath a given base directory. This involves finding
   * the actual files in the file system to get their 'canonical' representations as File objects,
   * in which the pathnames are absolute and contain no '.' or '..' elements.
   *
   * @param f file or directory to be checked
   * @param base directory against which to check
   * @return true if f is below base in the filesystem
   * @throws IOException if there is an error in getting the canonical files
   */
  private static boolean checkIsBelow(File base, File f) throws IOException {
    // convert to "canonical" files to normalize the pathnames
    base = base.getCanonicalFile();
    File current = f.getCanonicalFile();

    // make sure that some parent file of the given one
    // is the base directory
    while (current != null) {
      if (current.equals(base)) {
        return true;
      }
      current = current.getParentFile();
    }
    return false;
  }
  /**
   * Extracts the inline plugin dirs from the given config, relative to the given baseDir.
   *
   * <p>TODO: consider trowing an error here if an plugin does not exists at the location.
   */
  @SuppressWarnings({"rawtypes", "hiding"})
  protected Collection<File> getInlinePluginsFromConfiguration(Map config, File baseDir) {
    Collection<File> inlinePlugins = new ConcurrentLinkedQueue<File>();
    if (config != null) {
      Map pluginLocations = lookupPluginLocationConfig(config);
      if (pluginLocations != null) {
        for (Object value : pluginLocations.values()) {
          if (value != null) {
            File resource;
            try {
              // GRAILS-7045: Check whether the plugin location is absolute
              // before resolving against the project's base dir.
              resource = new File(value.toString());
              if (!resource.isAbsolute()) {
                resource = new File(baseDir, resource.getPath());
              }

              resource = resource.getCanonicalFile();
              inlinePlugins.add(resource);
            } catch (IOException e) {
              System.err.println(
                  "Cannot add location ["
                      + value
                      + "] as an inline plugin dependencies due to I/O error: "
                      + e.getMessage());
            }
          }
        }
      }
    }
    return inlinePlugins;
  }
예제 #19
0
 /**
  * Sets the root directory of the project. For a regular project, this is where is located the
  * csproj file.
  *
  * @param directory The directory to set.
  */
 void setDirectory(File directory) {
   try {
     this.directory = directory.getCanonicalFile();
   } catch (IOException e) {
     LOG.warn("Invalid project directory : " + directory);
   }
 }
예제 #20
0
 public static File canonicalise(File src) {
   try {
     return src.getCanonicalFile();
   } catch (IOException e) {
     throw new UncheckedIOException(e);
   }
 }
        public String adapt(File file) {
          String libraryName = null;
          try {
            // String canoFile = value.getCanonicalPath();
            // libraryFile = libraryByFile.get(canoFile);
            file = file.getCanonicalFile();
            libraryName = libraryByFile.get(file);

            if (libraryName == null) {
              libraryName = libraryByDirectory.get(file.getParentFile());
            }
            // if (value.toString().startsWith("\""))
            //	new Exception("Double quotes in file !").printStackTrace();
            //				if (!canoFile.contains("Program Files")) {
            //					System.out.println("libraryByFile = " + libraryByFile);
            //					System.out.println("libraryByFile(" + canoFile + ") = " + libraryFile);
            //					System.out.println("    value = " + value);
            //					System.out.println("can value = " + value.getCanonicalFile());
            //					System.out.println("abs value = " + value.getAbsoluteFile());
            //				}

          } catch (IOException e) {
            e.printStackTrace();
          }
          return libraryName == null ? defaultLibrary : libraryName;
        }
  public void addSourceFile(File file, String library, boolean applyFilters, boolean retainAsTarget)
      throws IOException {
    if (file.isFile()) {
      if (fileFilter == null || !applyFilters || fileFilter.accept(file)) {
        file = file.getCanonicalFile();
        if (library == null && fileToLibrary != null) library = fileToLibrary.adapt(file);
        sourceFiles.add(file);
        if (retainAsTarget) {
          libraryByFile.put(file, library);

          File directory = file.getParentFile().getAbsoluteFile();
          String oldLib = libraryByDirectory.put(directory, library);
          if (oldLib != null && !oldLib.equals(library)) {
            JNAerator.logger.log(
                Level.WARNING,
                "Directory "
                    + directory
                    + " contains files from different libraries, so there won't be any default library for its files (symbols defined in files from that library that were included but not explicitly listed will not be JNAerated).");
            libraryByDirectory.put(directory, "");
          }
        }
      }
    } else {
      File[] fs = file.listFiles();
      if (fs != null) {
        for (File f : fs) {
          addSourceFile(f, library, true, retainAsTarget);
        }
      }
    }
  }
예제 #23
0
  public static boolean isSubtitlesExists(File file, DLNAMediaInfo media, boolean usecache) {
    boolean found = false;
    if (file.exists()) {
      found = browseFolderForSubtitles(file.getParentFile(), file, media, usecache);
    }
    String alternate = PMS.getConfiguration().getAlternateSubtitlesFolder();

    if (isNotBlank(alternate)) { // https://code.google.com/p/ps3mediaserver/issues/detail?id=737#c5
      File subFolder = new File(alternate);

      if (!subFolder.isAbsolute()) {
        subFolder = new File(file.getParent() + "/" + alternate);
        try {
          subFolder = subFolder.getCanonicalFile();
        } catch (IOException e) {
          LOGGER.debug("Caught exception", e);
        }
      }

      if (subFolder.exists()) {
        found = found || browseFolderForSubtitles(subFolder, file, media, usecache);
      }
    }

    return found;
  }
  /**
   * Initializes the sql query environment from the SqlResources file. Will look for
   * conf/sqlResources.xml.
   *
   * @param conn The connection for accessing the database
   * @param sqlFileUrl The url which we use to get the sql file
   * @throws Exception If any error occurs
   */
  private void initSqlQueries(Connection conn, String sqlFileUrl) throws Exception {
    try {

      File sqlFile;

      try {
        sqlFile = fileSystem.getFile(sqlFileUrl);
        sqlFileUrl = null;
      } catch (Exception e) {
        serviceLog.error(e.getMessage(), e);
        throw e;
      }

      sqlQueries.init(sqlFile.getCanonicalFile(), "GreyList", conn, sqlParameters);

      selectQuery = sqlQueries.getSqlString("selectQuery", true);
      insertQuery = sqlQueries.getSqlString("insertQuery", true);
      deleteQuery = sqlQueries.getSqlString("deleteQuery", true);
      deleteAutoWhiteListQuery = sqlQueries.getSqlString("deleteAutoWhitelistQuery", true);
      updateQuery = sqlQueries.getSqlString("updateQuery", true);

    } finally {
      theJDBCUtil.closeJDBCConnection(conn);
    }
  }
예제 #25
0
 private File canonicalise(File file) {
   try {
     return file.getCanonicalFile();
   } catch (IOException e) {
     return file.getAbsoluteFile();
   }
 }
예제 #26
0
 public static File getCanonicalFile(File file) {
   try {
     return file.getCanonicalFile();
   } catch (IOException ex) {
     return file;
   }
 }
예제 #27
0
 @Action()
 public void openProject() {
   final JFileChooser chooser = new JFileChooser();
   chooser.setFileFilter(new ProjectFileFilter());
   final int option = chooser.showOpenDialog(this);
   if (JFileChooser.APPROVE_OPTION != option) {
     return;
   }
   File file = chooser.getSelectedFile();
   ResourceMap resourceMap = context.getResourceMap();
   try {
     file = file.getCanonicalFile();
     logger.info(resourceMap.getString("openProject.info.loading"), file.getName());
     projectService.openProject(file);
     logger.info(resourceMap.getString("openProject.info.loaded"), file.getName());
   } catch (IOException e) {
     logger.error(e, resourceMap.getString("openProject.error.loading"), file.getName());
   }
   try {
     // XXX we should really save connection state in the project file
     //     and restore it after re-opening
     RvConnection.resumeQueue();
   } catch (TibrvException e) {
     logger.error(e, resourceMap.getString("openProject.error.starting"), e.error);
   }
 }
예제 #28
0
 @Override
 public String getSourceLocation() {
   IResource sourceResource;
   String sourceLocation = null;
   if (fFileSystemObject.isDirectory()) {
     sourceResource =
         ResourcesPlugin.getWorkspace()
             .getRoot()
             .getContainerForLocation(Path.fromOSString(fFileSystemObject.getAbsolutePath()));
   } else {
     sourceResource =
         ResourcesPlugin.getWorkspace()
             .getRoot()
             .getFileForLocation(Path.fromOSString(fFileSystemObject.getAbsolutePath()));
   }
   if (sourceResource != null && sourceResource.exists()) {
     try {
       sourceLocation = sourceResource.getPersistentProperty(TmfCommonConstants.SOURCE_LOCATION);
     } catch (CoreException e) {
       // Something went wrong with the already existing resource.
       // This is not a problem, we'll assign a new location below.
     }
   }
   if (sourceLocation == null) {
     try {
       sourceLocation = URIUtil.toUnencodedString(fFileSystemObject.getCanonicalFile().toURI());
     } catch (IOException e) {
       // Something went wrong canonicalizing the file. We can still
       // use the URI but there might be extra ../ in it.
       sourceLocation = URIUtil.toUnencodedString(fFileSystemObject.toURI());
     }
   }
   return sourceLocation;
 }
예제 #29
0
파일: TileSet.java 프로젝트: niuzb/ATCS
  /**
   * Creates a tileset from a tileset image file.
   *
   * @param imgFilename
   * @param cutter
   * @throws IOException
   * @see TileSet#importTileBitmap(BufferedImage, TileCutter)
   */
  public void importTileBitmap(String imgFilename, TileCutter cutter) throws IOException {
    setTilesetImageFilename(imgFilename);

    File f = new File(imgFilename);

    Image image = ImageIO.read(f.getCanonicalFile());
    if (image == null) {
      throw new IOException("Failed to load " + tilebmpFile);
    }

    Toolkit tk = Toolkit.getDefaultToolkit();

    if (transparentColor != null) {
      int rgb = transparentColor.getRGB();
      image =
          tk.createImage(
              new FilteredImageSource(image.getSource(), new TransparentImageFilter(rgb)));
    }

    BufferedImage buffered =
        new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    buffered.getGraphics().drawImage(image, 0, 0, null);

    importTileBitmap(buffered, cutter);
  }
예제 #30
0
 private static File resolve(final File logs_dir) {
   try {
     return logs_dir.getCanonicalFile();
   } catch (IOException e) {
     return logs_dir.getAbsoluteFile();
   }
 }