/**
   * Returns true if the code was executed correctly. False if there was an error trying to share
   * the file. If the file was not supposed to be shared, and was not shared, true would still be
   * returned.
   */
  private boolean shareTorrentFile(File torrentFile) {
    if (torrentManager.isDownloadingTorrent(torrentFile)) {
      return true;
    }

    if (!SharingSettings.SHARE_DOWNLOADED_FILES_IN_NON_SHARED_DIRECTORIES.getValue()) {
      return true;
    }

    BTData btData = null;
    FileInputStream torrentInputStream = null;
    try {
      torrentInputStream = new FileInputStream(torrentFile);
      Map<?, ?> torrentFileMap = (Map<?, ?>) Token.parse(torrentInputStream.getChannel());
      btData = new BTDataImpl(torrentFileMap);
    } catch (IOException e) {
      LOG.error("Error reading torrent file: " + torrentFile, e);
      return false;
    } finally {
      FileUtils.close(torrentInputStream);
    }

    if (btData.isPrivate()) {
      gnutellaFileList.remove(torrentFile);
      return true;
    }

    File saveDir = SharingSettings.getSaveDirectory();
    File torrentParent = torrentFile.getParentFile();
    if (torrentParent.equals(saveDir)) {
      // already in saveDir
      gnutellaFileList.add(torrentFile);
      return true;
    }

    final File tFile = getSharedTorrentMetaDataFile(btData);
    if (tFile.equals(torrentFile)) {
      gnutellaFileList.add(tFile);
      return true;
    }

    gnutellaFileList.remove(tFile);
    File backup = null;
    if (tFile.exists()) {
      backup = new File(tFile.getParent(), tFile.getName().concat(".bak"));
      FileUtils.forceRename(tFile, backup);
    }

    if (FileUtils.copy(torrentFile, tFile)) {
      gnutellaFileList.add(tFile);
    } else {
      if (backup != null) {
        // restore backup
        if (FileUtils.forceRename(backup, tFile)) {
          gnutellaFileList.add(tFile);
        }
      }
    }
    return true;
  }
Beispiel #2
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;
  }
  private static List<File> encryptSubmissionFiles(
      File instanceXml, File submissionXml, EncryptedFormInformation formInfo)
      throws IOException, EncryptionException {
    // NOTE: assume the directory containing the instanceXml contains ONLY
    // files related to this one instance.
    File instanceDir = instanceXml.getParentFile();

    // encrypt files that do not end with ".enc", and do not start with ".";
    // ignore directories
    File[] allFiles = instanceDir.listFiles();
    List<File> filesToProcess = new ArrayList<File>();
    for (File f : allFiles) {
      if (f.equals(instanceXml)) continue; // don't touch restore file
      if (f.equals(submissionXml)) continue; // handled last
      if (f.isDirectory()) continue; // don't handle directories
      if (f.getName().startsWith(".")) continue; // MacOSX garbage
      if (f.getName().endsWith(".enc")) {
        f.delete(); // try to delete this (leftover junk)
      } else {
        filesToProcess.add(f);
      }
    }
    // encrypt here...
    for (File f : filesToProcess) {
      encryptFile(f, formInfo);
    }

    // encrypt the submission.xml as the last file...
    encryptFile(submissionXml, formInfo);

    return filesToProcess;
  }
Beispiel #4
1
 public boolean equals(Object obj) {
   if (obj instanceof Path) {
     return file.equals(((Path) obj).file);
   } else {
     return file.equals(obj);
   }
 }
Beispiel #5
1
 public boolean isProjectFile() {
   if (rootDirectory.equals(testDirectory) || rootDirectory.equals(fixtureDirectory)) return true;
   for (int k = 0; k < moduleDirectories.length; k++) {
     if (rootDirectory.equals(moduleDirectories[k])) return true;
   }
   return false;
 }
Beispiel #6
1
  public void setObject(String location) {

    if (location != null) {
      File dataDirectory = canonicalize(rootDir);
      File file = canonicalize(new File(location));
      if (isSubfile(dataDirectory, file)) {
        File curr = file;
        String path = null;
        // paranoid check to avoid infinite loops
        while (curr != null && !curr.equals(dataDirectory)) {
          if (path == null) {
            path = curr.getName();
          } else {
            path = curr.getName() + "/" + path;
          }
          curr = curr.getParentFile();
        }
        location = "file:" + path;
      } else {
        File dataFile = Files.url(rootDir, location);
        if (dataFile != null && !dataFile.equals(file)) {
          // relative to the data directory, does not need fixing
        } else {
          location = "file://" + file.getAbsolutePath();
        }
      }
    }
    delegate.setObject(location);
  }
Beispiel #7
0
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      LayoutInflater inflater = LayoutInflater.from(context);
      View view = inflater.inflate(R.layout.file_item, null);
      File f = filelist.get(position);

      ImageView iv = (ImageView) view.findViewById(R.id.file_img);
      TextView tv = (TextView) view.findViewById(R.id.file_name);
      if (f.equals(currentFile)) {
        iv.setImageResource(R.drawable.directory_icon);
        tv.setText("..");

      } else {
        if (f.isDirectory()) {
          iv.setImageResource(R.drawable.directory_icon);
        }
        if (f.isFile()) {
          iv.setImageResource(R.drawable.file_icon);
        }
        tv.setText(f.getName());
      }
      if (f.equals(selectFile)) {
        view.setBackgroundResource(R.drawable.selected_file);
      } else {
        view.setBackgroundColor(Color.BLACK);
      }
      return view;
    }
    public Result parseModel(FetchedModels fetchedModels) {
      ProjectModelsOfExtensions extensionsForDefault =
          new ProjectModelsOfExtensions(this, fetchedModels.getDefaultProjectModels());

      File defaultProjectDir = extensionsForDefault.getProjectDir();

      Collection<FetchedProjectModels> otherProjectModels = fetchedModels.getOtherProjectModels();

      Map<File, ProjectModelsOfExtensions> extensionModels =
          CollectionUtils.newHashMap(otherProjectModels.size());
      for (FetchedProjectModels models : otherProjectModels) {
        File projectDir = getProjectDirFromModels(models);
        if (defaultProjectDir.equals(projectDir)) {
          continue;
        }

        extensionModels.put(projectDir, new ProjectModelsOfExtensions(this, models));
      }

      extensionModels.put(defaultProjectDir, extensionsForDefault);

      NbGradleModel mainModel =
          parseModel(fetchedModels.getDefaultProjectModels(), extensionModels);

      List<NbGradleModel> otherModels = new ArrayList<>();
      for (FetchedProjectModels models : otherProjectModels) {
        File projectDir = getProjectDirFromModels(models);
        if (defaultProjectDir.equals(projectDir)) {
          continue;
        }
        otherModels.add(parseModel(models, extensionModels));
      }

      return new Result(mainModel, otherModels, issues);
    }
Beispiel #9
0
 /**
  * Determines whether one file is the parent of another.
  *
  * @param ancestor possible parent of <code>descendant</code>
  * @param descendant possible child 0f <code>ancestor</code>
  * @return return true if ancestor is a parent of descendant
  */
 static boolean isParentOf(final File ancestor, File descendant) {
   if (ancestor != null) {
     if (ancestor.equals(descendant)) {
       return false;
     }
     while (descendant != null && !ancestor.equals(descendant)) {
       descendant = descendant.getParentFile();
     }
   }
   return ancestor != null && descendant != null;
 }
Beispiel #10
0
  /**
   * Add a file to the sketch.
   *
   * <p>.gcode files will be added to the sketch folder. <br>
   * All other files will be added to the "data" folder.
   *
   * <p>If they don't exist already, the "code" or "data" folder will be created.
   *
   * <p>
   *
   * @return true if successful.
   */
  public boolean addFile(File sourceFile) {
    String filename = sourceFile.getName();
    File destFile = null;
    boolean addingCode = false;

    destFile = new File(this.folder, filename);
    addingCode = true;

    // make sure they aren't the same file
    if (!addingCode && sourceFile.equals(destFile)) {
      Base.showWarning(
          "You can't fool me",
          "This file has already been copied to the\n"
              + "location where you're trying to add it.\n"
              + "I ain't not doin nuthin'.",
          null);
      return false;
    }

    // in case the user is "adding" the code in an attempt
    // to update the sketch's tabs
    if (!sourceFile.equals(destFile)) {
      try {
        Base.copyFile(sourceFile, destFile);

      } catch (IOException e) {
        Base.showWarning("Error adding file", "Could not add '" + filename + "' to the sketch.", e);
        return false;
      }
    }

    // make the tabs update after this guy is added
    if (addingCode) {
      String newName = destFile.getName();
      int newFlavor = -1;
      if (newName.toLowerCase().endsWith(".gcode")) {
        newName = newName.substring(0, newName.length() - 6);
        newFlavor = GCODE;
      }

      // see also "nameCode" for identical situation
      SketchCode newCode = new SketchCode(newName, destFile, newFlavor);
      insertCode(newCode);
      sortCode();
      setCurrent(newName);
      editor.header.repaint();
    }
    return true;
  }
Beispiel #11
0
  // open a file only one time
  public static boolean openOneTimeOnglet(final File file) {

    boolean returnStatement = true;
    final int tabCount = EditorOngletCreator.getTabbedpane().getTabCount();
    if (tabCount != 0) {

      int iterator;
      EditorOnglet courant;
      File courantFile = null;
      for (iterator = 0; iterator <= tabCount - 1; iterator++) {

        courant = (EditorOnglet) EditorOngletCreator.getTabbedpane().getComponentAt(iterator);

        courantFile = new File(courant.getProjectModeleSelector().getClassPath());

        if (courantFile.equals(file)) {

          EditorOngletCreator.getTabbedpane().setSelectedComponent(courant);

          returnStatement = false;
        }
      }
    }

    return returnStatement;
  }
  @Override
  public void loadProject(String fileName) throws Exception {
    Application application = Application.getInstance();
    ProjectDescriptor projectDescriptor = null;

    // First, check if the user is logged in to teamwork server.
    /*String loggedUserName = TeamworkUtils.getLoggedUserName();
    if(loggedUserName != null){
    	// Ok, the user is logged in. So try to load the project remotely.
    	// load teamwork project
    	projectDescriptor =
    			TeamworkUtils.getRemoteProjectDescriptorByQualifiedName(fileName);
    }*/

    if (projectDescriptor == null) {
      File projectFile = new File(fileName);
      if (!projectFile.exists())
        throw new FileNotFoundException(IGUILabels.TITLE + ": Can't find project file " + fileName);
      String activeProjectFileName = getActiveProjectFileName();
      File activeProjectFile = null;
      if (activeProjectFileName != null) {
        activeProjectFile = new File(activeProjectFileName);
      }
      if (activeProjectFile == null || !(activeProjectFile.equals(projectFile))) {
        projectDescriptor = ProjectDescriptorsFactory.createProjectDescriptor(projectFile.toURI());
      }
    }

    if (projectDescriptor != null) {
      application.getProjectsManager().loadProject(projectDescriptor, true);
    }
  }
 /**
  * @param folder a <code>File</code> object repesenting a directory
  * @param file a <code>File</code> object
  * @return <code>true</code> if <code>folder</code> is a directory and contains <code>file</code>.
  */
 public boolean isParent(File folder, File file) {
   if (folder == null || file == null) {
     return false;
   } else {
     return folder.equals(file.getParentFile());
   }
 }
 public void setSoftKey0Icon(File image) {
   if (image == null || !image.equals(softKey0Icon)) {
     softKey0Icon = image;
     createImage();
     repaint();
   }
 }
Beispiel #15
0
 public static boolean renameTo(File orig, File dest) {
   // Try an atomic rename
   // Shall we prevent symlink-race-conditions here ?
   if (orig.equals(dest))
     throw new IllegalArgumentException("Huh? the two file descriptors are the same!");
   if (!orig.exists()) {
     throw new IllegalArgumentException("Original doesn't exist!");
   }
   if (!orig.renameTo(dest)) {
     // Not supported on some systems (Windows)
     if (!dest.delete()) {
       if (dest.exists()) {
         Logger.error("FileUtil", "Could not delete " + dest + " - check permissions");
         System.err.println("Could not delete " + dest + " - check permissions");
       }
     }
     if (!orig.renameTo(dest)) {
       String err =
           "Could not rename "
               + orig
               + " to "
               + dest
               + (dest.exists() ? " (target exists)" : "")
               + (orig.exists() ? " (source exists)" : "")
               + " - check permissions";
       Logger.error(FileUtil.class, err);
       System.err.println(err);
       return false;
     }
   }
   return true;
 }
Beispiel #16
0
  /*
   * Checks to make sure that all types in a package are defined by files in the same directory.
   */
  private void checkPackageDirectories(Package _package) {
    Collection<Type> types = _package.getTypes();

    Type firstType = null;
    File path1 = null;

    /* Gets the directory of the first type and compares all others to it. */
    if (types.size() > 1) {
      for (Type type : types) {
        if (firstType == null) {
          firstType = type;
          path1 = typeTable.get(type).getFile().getParentFile();
        } else {
          File path2 = typeTable.get(type).getFile().getParentFile();
          if (!path1.equals(path2))
            addWarning(
                Error.MISMATCHED_PACKAGE,
                "Type "
                    + firstType
                    + " and "
                    + type
                    + " both belong to package "
                    + _package
                    + " but are defined in different directories");
        }
      }
    }

    // Recursively check child packages.
    for (Package child : _package.getChildren().values()) checkPackageDirectories(child);
  }
Beispiel #17
0
 /**
  * Given the parameters for copying doc-files, check for errors.
  *
  * @param configuration The configuration of the current doclet.
  * @param path The relative path to the directory to be copied.
  * @param dirName The original directory name to copy from.
  */
 private static boolean checkCopyDocFilesErrors(
     Configuration configuration, String path, String dirName) {
   if ((configuration.sourcepath == null || configuration.sourcepath.length() == 0)
       && (configuration.destDirName == null || configuration.destDirName.length() == 0)) {
     // The destination path and source path are definitely equal.
     return true;
   }
   File sourcePath, destPath = new File(configuration.destDirName);
   StringTokenizer pathTokens =
       new StringTokenizer(
           configuration.sourcepath == null ? "" : configuration.sourcepath, File.pathSeparator);
   // Check if the destination path is equal to the source path.  If yes,
   // do not copy doc-file directories.
   while (pathTokens.hasMoreTokens()) {
     sourcePath = new File(pathTokens.nextToken());
     if (destPath.equals(sourcePath)) {
       return true;
     }
   }
   // Make sure the doc-file being copied exists.
   File srcdir = new File(path + dirName);
   if (!srcdir.exists()) {
     return true;
   }
   return false;
 }
 @Override
 public boolean equals(Object obj) {
   if (obj instanceof AsbruXMLEditorInput) {
     return asbruXmlFile.equals(((AsbruXMLEditorInput) obj).asbruXmlFile);
   }
   return false;
 }
  private void copyAllFilesToLogDir(File node, File parent) throws IOException {
    if (!node.getAbsoluteFile().equals(parent.getAbsoluteFile())
        && node.isFile()
        && !node.getParentFile().equals(parent)) {
      String fileNamePrefix = node.getName().substring(0, node.getName().lastIndexOf('.'));
      String fileNameSuffix = node.getName().substring(node.getName().lastIndexOf('.'));
      String newFilePath =
          node.getParentFile().getAbsolutePath()
              + File.separator
              + fileNamePrefix.replace(".", "_")
              + fileNameSuffix;

      File newNode = new File(newFilePath);
      if (node.renameTo(newNode)) {
        FileUtils.copyFileToDirectory(newNode, parent);
      }
    }
    if (node.isDirectory()) {
      String[] subNote = node.list();
      for (String filename : subNote) {
        copyAllFilesToLogDir(new File(node, filename), parent);
      }
      if (!node.equals(parent)) {
        FileUtils.deleteDirectory(node);
      }
    }
  }
Beispiel #20
0
 @Override
 public boolean equals(Object o) {
   if (!(o instanceof Directory)) {
     return false;
   }
   return directory.equals(((Directory) o).directory);
 }
 /**
  * Adds a root to the tree if it's not already in there.
  *
  * @return false if dir is already in the tree
  */
 public boolean addRoot(File dir) {
   // remove from deselected in any case
   boolean changed = deselected.remove(dir);
   // check if already included
   for (File root : roots) {
     if (FileUtils.isAncestor(root, dir)) {
       if (root.equals(dir)) {
         if (changed) {
           directoryTreeModel.valueForPathChanged(getTreePath(dir), null);
         }
         return changed;
       }
       // make sure it is included
       removeFromPath(dir);
       TreePath path = getTreePath(dir);
       directoryTree.scrollPathToVisible(path);
       return changed;
     } else if (FileUtils.isAncestor(dir, root)) {
       removeRoot(root);
       addDirToTree(dir);
       // expand to root and its parent, since expand has no effect if root
       // doesn't have subfolders
       setExpanded(root);
       // guaranteed to not be null since at least dir is its real ancestor
       setExpanded(root.getParentFile());
       return true;
     }
   }
   addDirToTree(dir);
   setRootExpanded();
   return true;
 }
  @Override
  public boolean equals(final Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    RobolectricConfig that = (RobolectricConfig) o;

    if (androidManifestFile != null
        ? !androidManifestFile.equals(that.androidManifestFile)
        : that.androidManifestFile != null) {
      return false;
    }
    if (getAssetsDirectory() != null
        ? !getAssetsDirectory().equals(that.getAssetsDirectory())
        : that.getAssetsDirectory() != null) {
      return false;
    }
    if (getResourceDirectory() != null
        ? !getResourceDirectory().equals(that.getResourceDirectory())
        : that.getResourceDirectory() != null) {
      return false;
    }

    return true;
  }
 /**
  * In case an error print out the trail file context. Because of the XML reader buffering, we can
  * only get the block (8K). It has to be visually inspected
  */
 protected void printErrorContext(PrintStream errOut) throws IOException {
   final File file = _inputStream.getCurrentFile();
   final long position = _inputStream.getCurrentPosition();
   File lastFile = new File(file.getParentFile(), getLastFileName());
   errOut.println(
       "error between "
           + lastFile
           + " @ "
           + getLastPosition()
           + " and "
           + _inputStream.getCurrentFile()
           + " @ "
           + _inputStream.getCurrentPosition());
   RandomAccessFile f = new RandomAccessFile(file, "r");
   try {
     long startPos = lastFile.equals(file) ? getLastPosition() : 0;
     long endPos = position + ERROR_CONTEXT_LEN;
     int contextSize = (int) (endPos - startPos);
     byte[] context = new byte[contextSize];
     f.seek(startPos);
     if (f.read(context, 0, contextSize) > 0) {
       errOut.println("context: " + new String(context, "ISO-8859-1"));
     } else {
       errOut.println("unable to read XML error context");
     }
   } finally {
     f.close();
   }
 }
Beispiel #24
0
 public boolean equals(Object o) {
   if (o instanceof MatrixFile) {
     MatrixFile m = (MatrixFile) o;
     return matrixFile.equals(m.matrixFile) && format.equals(m.format);
   }
   return false;
 }
  /**
   * Load the board.txt file provided.
   *
   * @param BoardsFile the full name to the boards.txt file
   * @return true when the action was successful. else false.
   * @author jan
   */
  public boolean LoadBoardsFile(String boardsFile) {

    if ((mLastLoadedBoardsFile != null) && (mLastLoadedBoardsFile.equals(boardsFile)))
      return true; // do nothing when value didn't change
    mLastLoadedBoardsFile = new File(boardsFile);
    return LoadBoardsFile();
  }
Beispiel #26
0
  public static void moveOldData(String src, String dst) {
    File srcFile = new File(src);
    File dstFile = new File(dst);

    if (srcFile.equals(dstFile)) return;

    if (srcFile.isDirectory() && srcFile.listFiles().length > 1) {
      for (File f : srcFile.listFiles()) {
        if (f.equals(dstFile)) {
          moveOldData(f.getAbsolutePath(), dst + "/" + f.getName());
          continue;
        }
        f.renameTo(new File(dst + "/" + f.getName()));
      }
    }
  }
Beispiel #27
0
  /**
   * @param file - the file to delete
   * @param deleteEmptyParents - removing empty parent folders flag
   * @param rootPath - if deleteEmptyParents is true, this parameters shows the parent folder where
   *     removing parents must stop
   * @return True, if the file has been successfully removed, otherwise returns false
   */
  public static boolean delete(File file, boolean deleteEmptyParents, String rootPath) {
    log.info("M-DELETE file: " + file);
    if (!file.exists()) {
      File rootFile = rootPath == null ? null : toFile(rootPath);
      boolean isParentReliable = isReliable(file.getParentFile(), rootFile);

      log.warn(
          format(
              isParentReliable
                  ? "File [%s] has already been deleted."
                  : "Cannot list file [%s]; is its parent-directory tree mounted and executable?",
              file));

      return isParentReliable;
    }
    if (!file.delete()) {
      log.warn("Failed to delete file: " + file);
      return false;
    }
    if (deleteEmptyParents) {
      File parentToKeep = null;
      if (rootPath != null) parentToKeep = toFile(rootPath);

      File parent = file.getParentFile();
      while (!parent.equals(parentToKeep) && parent.delete()) {
        log.info("M-DELETE directory: " + parent);
        parent = parent.getParentFile();
      }
    }
    return true;
  }
 public void setControlImage(File image) {
   if (image == null || !image.equals(controlImage)) {
     controlImage = image;
     createImage();
     repaint();
   }
 }
  @Override
  public void executeNode() {
    final File sourceDir = getSourceDir();
    final File workingDir = getWorkingDir();

    if (!sourceDir.equals(workingDir)) {
      Project project = getProject();

      project.copy(
          new Action<CopySpec>() {

            @Override
            public void execute(CopySpec copySpec) {
              copySpec.from(sourceDir);

              copySpec.include(getSoySrcIncludes());
              copySpec.include(getSrcIncludes());

              copySpec.into(workingDir);
            }
          });
    }

    super.executeNode();
  }
Beispiel #30
0
 private static boolean isParentInner(File possParent, File filename) {
   while (true) {
     if (filename.equals(possParent)) return true;
     filename = filename.getParentFile();
     if (filename == null) return false;
   }
 }