示例#1
0
  protected TreePath getNextPath(TreePath path) {
    TreeModel model = tree.getModel();

    // return the first node
    if (path == null) {
      return new TreePath(model.getRoot());
    }

    Object lastNode = path.getLastPathComponent();

    // if the NODE has children

    if (model.getChildCount(lastNode) > 0) {
      return path.pathByAddingChild(model.getChild(lastNode, 0));
    }

    // if the NODE has NO children

    int index = 0;
    int pathLength = path.getPathCount();
    Object parentNode = path.getPathComponent(pathLength - 2);

    if (pathLength > 1) {
      index = model.getIndexOfChild(parentNode, lastNode);
    }

    // if there is only root node
    if (pathLength == 1) {
      return path;
    }

    // if there are still some siblings (brothers) after this node
    if (index + 1 < model.getChildCount(parentNode)) {
      // replace the lastPathComponent by its next sibling
      return path.getParentPath().pathByAddingChild(model.getChild(parentNode, index + 1));
    } else {
      while (true) {
        // we need to find next sibling for our father
        path = path.getParentPath();

        // if we get to the end of tree then start if
        if (path.getParentPath() == null) {
          // return the root path
          return path;
        }

        pathLength = path.getPathCount();
        parentNode = path.getPathComponent(pathLength - 2);
        index = model.getIndexOfChild(parentNode, path.getLastPathComponent());

        // if there are still some siblings (brothers) after this node
        if (index + 1 < model.getChildCount(parentNode)) {
          // replace the lastPathComponent by its next sibling
          return path.getParentPath().pathByAddingChild(model.getChild(parentNode, index + 1));
        }
      }
    }
  }
 public void collapseSelected() {
   TreePath path = tree.getSelectionPath();
   if (path != null && path.getPathCount() > 1) {
     Object node = path.getPathComponent(1);
     if (node instanceof ResourceTreeFolder) {
       Object root = path.getPathComponent(0);
       processAllNodes(tree, new TreePath(new Object[] {root, node}), false);
     }
   }
 }
示例#3
0
文件: TreeState.java 项目: jexp/idea2
  private static List<PathElement> createPath(final TreePath treePath) {
    final ArrayList<PathElement> result = new ArrayList<PathElement>();
    for (int i = 0; i < treePath.getPathCount(); i++) {
      final Object pathComponent = treePath.getPathComponent(i);
      if (pathComponent instanceof DefaultMutableTreeNode) {
        final DefaultMutableTreeNode node = (DefaultMutableTreeNode) pathComponent;
        final TreeNode parent = node.getParent();

        final Object userObject = node.getUserObject();
        if (userObject instanceof NodeDescriptor) {
          final NodeDescriptor nodeDescriptor = (NodeDescriptor) userObject;
          // nodeDescriptor.update();
          final int childIndex = parent != null ? parent.getIndex(node) : 0;
          result.add(
              new PathElement(
                  getDescriptorKey(nodeDescriptor),
                  getDescriptorType(nodeDescriptor),
                  childIndex,
                  nodeDescriptor));
        } else {
          result.add(new PathElement("", "", 0, userObject));
        }
      } else {
        return null;
      }
    }
    return result;
  }
 @Override
 public void calcData(DataKey key, DataSink sink) {
   if (key == VcsDataKeys.CHANGES) {
     sink.put(VcsDataKeys.CHANGES, getSelectedChanges());
   } else if (key == VcsDataKeys.CHANGE_LEAD_SELECTION) {
     sink.put(VcsDataKeys.CHANGE_LEAD_SELECTION, getLeadSelection());
   } else if (key == VcsDataKeys.CHANGE_LISTS) {
     sink.put(VcsDataKeys.CHANGE_LISTS, getSelectedChangeLists());
   } else if (key == PlatformDataKeys.VIRTUAL_FILE_ARRAY) {
     sink.put(PlatformDataKeys.VIRTUAL_FILE_ARRAY, getSelectedFiles());
   } else if (key == PlatformDataKeys.NAVIGATABLE) {
     final VirtualFile[] files = getSelectedFiles();
     if (files.length == 1 && !files[0].isDirectory()) {
       sink.put(PlatformDataKeys.NAVIGATABLE, new OpenFileDescriptor(myProject, files[0], 0));
     }
   } else if (key == PlatformDataKeys.NAVIGATABLE_ARRAY) {
     sink.put(
         PlatformDataKeys.NAVIGATABLE_ARRAY,
         ChangesUtil.getNavigatableArray(myProject, getSelectedFiles()));
   } else if (key == PlatformDataKeys.DELETE_ELEMENT_PROVIDER) {
     final TreePath[] paths = getSelectionPaths();
     if (paths != null) {
       for (TreePath path : paths) {
         ChangesBrowserNode node = (ChangesBrowserNode) path.getLastPathComponent();
         if (!(node.getUserObject() instanceof ChangeList)) {
           sink.put(PlatformDataKeys.DELETE_ELEMENT_PROVIDER, new VirtualFileDeleteProvider());
           break;
         }
       }
     }
   } else if (key == PlatformDataKeys.COPY_PROVIDER) {
     sink.put(PlatformDataKeys.COPY_PROVIDER, myCopyProvider);
   } else if (key == UNVERSIONED_FILES_DATA_KEY) {
     sink.put(UNVERSIONED_FILES_DATA_KEY, getSelectedUnversionedFiles());
   } else if (key == VcsDataKeys.MODIFIED_WITHOUT_EDITING_DATA_KEY) {
     sink.put(VcsDataKeys.MODIFIED_WITHOUT_EDITING_DATA_KEY, getSelectedModifiedWithoutEditing());
   } else if (key == LOCALLY_DELETED_CHANGES) {
     sink.put(LOCALLY_DELETED_CHANGES, getSelectedLocallyDeletedChanges());
   } else if (key == MISSING_FILES_DATA_KEY) {
     sink.put(MISSING_FILES_DATA_KEY, getSelectedMissingFiles());
   } else if (VcsDataKeys.HAVE_LOCALLY_DELETED == key) {
     sink.put(VcsDataKeys.HAVE_LOCALLY_DELETED, haveLocallyDeleted());
   } else if (VcsDataKeys.HAVE_MODIFIED_WITHOUT_EDITING == key) {
     sink.put(VcsDataKeys.HAVE_MODIFIED_WITHOUT_EDITING, haveLocallyModified());
   } else if (VcsDataKeys.HAVE_SELECTED_CHANGES == key) {
     sink.put(VcsDataKeys.HAVE_SELECTED_CHANGES, haveSelectedChanges());
   } else if (key == HELP_ID_DATA_KEY) {
     sink.put(HELP_ID_DATA_KEY, ourHelpId);
   } else if (key == VcsDataKeys.CHANGES_IN_LIST_KEY) {
     final TreePath selectionPath = getSelectionPath();
     if (selectionPath != null && selectionPath.getPathCount() > 1) {
       ChangesBrowserNode<?> firstNode = (ChangesBrowserNode) selectionPath.getPathComponent(1);
       if (firstNode instanceof ChangesBrowserChangeListNode) {
         final List<Change> list = firstNode.getAllChangesUnder();
         sink.put(VcsDataKeys.CHANGES_IN_LIST_KEY, list);
       }
     }
   }
 }
示例#5
0
文件: TreeUtil.java 项目: jexp/idea2
 private static boolean areComponentsEqual(final TreePath[] paths, final int componentIndex) {
   if (paths[0].getPathCount() <= componentIndex) return false;
   final Object pathComponent = paths[0].getPathComponent(componentIndex);
   for (final TreePath treePath : paths) {
     if (treePath.getPathCount() <= componentIndex) return false;
     if (!pathComponent.equals(treePath.getPathComponent(componentIndex))) return false;
   }
   return true;
 }
示例#6
0
  /**
   * Called whenever the value of the selection changes, we watch this to cache whenever
   * HermesTreeNode is in the selection path and to change the components tooltip text.
   */
  public void valueChanged(TreeSelectionEvent e) {
    final TreePath treePath = e.getNewLeadSelectionPath();

    try {
      if (treePath != null) {
        for (int i = 0; i < treePath.getPathCount(); i++) {
          if (treePath.getPathComponent(i) instanceof HermesTreeNode) {
            final HermesTreeNode node = (HermesTreeNode) treePath.getPathComponent(i);
            lastSelectedHermesTreeNode = node;

            setToolTipText(node.getHermes().getMetaData().getToolTipText());
          } else if (treePath.getPathComponent(i) instanceof DestinationConfigTreeNode) {
            final DestinationConfigTreeNode node =
                (DestinationConfigTreeNode) treePath.getPathComponent(i);
            setToolTipText(node.getDestinationName());

            maybeRefocusDocument(node);

          } else if (treePath.getPathComponent(i) instanceof RepositoryTreeNode) {
            final RepositoryTreeNode node = (RepositoryTreeNode) treePath.getPathComponent(i);
            setToolTipText(node.getRepository().getId());
          } else if (treePath.getPathComponent(i) instanceof MessageStoreTreeNode) {
            final MessageStoreTreeNode node = (MessageStoreTreeNode) treePath.getPathComponent(i);
            setToolTipText(node.getMessageStore().getTooltipText());
            maybeRefocusDocument(node);

          } else if (treePath.getPathComponent(i) instanceof MessageStoreURLTreeNode) {
            final MessageStoreURLTreeNode node =
                (MessageStoreURLTreeNode) treePath.getPathComponent(i);

            setToolTipText(node.getURL());
          }
        }
      }
    } catch (JMSException ex) {
      Hermes.ui.getDefaultMessageSink().add(ex.getMessage());
    }
  }
 protected boolean haveSelectedFileType(final Object tag) {
   final TreePath[] paths = getSelectionPaths();
   if (paths != null) {
     for (TreePath path : paths) {
       if (path.getPathCount() > 1) {
         ChangesBrowserNode firstNode = (ChangesBrowserNode) path.getPathComponent(1);
         if ((tag == null || firstNode.getUserObject() == tag) && path.getPathCount() > 2) {
           return true;
         }
       }
     }
   }
   return false;
 }
示例#8
0
 /** opens pop-up menu or displays context node content */
 public void mouseReleased(MouseEvent e) {
   // on Solaris, the right mouse button somehow seems not be a popup trigger, so we
   // accept mouse 3 explicitly
   if (e.isPopupTrigger() || e.getModifiers() == java.awt.event.InputEvent.BUTTON3_MASK) {
     popup.pack();
     popup.show(tree, e.getX(), e.getY());
   } else {
     TreePath path = tree.getPathForLocation(e.getX(), e.getY());
     if (path != null) {
       DefaultMutableTreeNode node =
           (DefaultMutableTreeNode) path.getPathComponent(path.getPathCount() - 1);
       ((ContextNode) node.getUserObject()).display();
     }
   }
 }
 private List<FilePath> getSelectedFilePaths(final Object tag) {
   Set<FilePath> files = new HashSet<FilePath>();
   final TreePath[] paths = getSelectionPaths();
   if (paths != null) {
     for (TreePath path : paths) {
       if (path.getPathCount() > 1) {
         ChangesBrowserNode firstNode = (ChangesBrowserNode) path.getPathComponent(1);
         if (tag == null || firstNode.getUserObject() == tag) {
           ChangesBrowserNode<?> node = (ChangesBrowserNode) path.getLastPathComponent();
           files.addAll(node.getAllFilePathsUnder());
         }
       }
     }
   }
   return new ArrayList<FilePath>(files);
 }
 // ======================================================
 // ======================================================
 private void treeMousePressed(java.awt.event.MouseEvent evt) {
   int mask = evt.getModifiers();
   if ((mask & MouseEvent.BUTTON1_MASK) != 0) {
     TreePath selectedPath = getPathForLocation(evt.getX(), evt.getY());
     if (selectedPath == null) return;
     DefaultMutableTreeNode node =
         (DefaultMutableTreeNode) selectedPath.getPathComponent(selectedPath.getPathCount() - 1);
     Object o = node.getUserObject();
     if (o instanceof String) {
       TransferHandler transfer = this.getTransferHandler();
       transfer.exportAsDrag(this, evt, TransferHandler.COPY);
       dragged_node = node;
       parent.setCursor(renderer.getNodeCursor(node));
     }
   }
 }
 private List<LocallyDeletedChange> getSelectedLocallyDeletedChanges() {
   Set<LocallyDeletedChange> files = new HashSet<LocallyDeletedChange>();
   final TreePath[] paths = getSelectionPaths();
   if (paths != null) {
     for (TreePath path : paths) {
       if (path.getPathCount() > 1) {
         ChangesBrowserNode firstNode = (ChangesBrowserNode) path.getPathComponent(1);
         if (firstNode.getUserObject() == TreeModelBuilder.LOCALLY_DELETED_NODE) {
           ChangesBrowserNode<?> node = (ChangesBrowserNode) path.getLastPathComponent();
           final List<LocallyDeletedChange> objectsUnder =
               node.getAllObjectsUnder(LocallyDeletedChange.class);
           files.addAll(objectsUnder);
         }
       }
     }
   }
   return new ArrayList<LocallyDeletedChange>(files);
 }
 // ======================================================
 // ======================================================
 private void treeMouseReleased(java.awt.event.MouseEvent evt) {
   int mask = evt.getModifiers();
   if ((mask & MouseEvent.BUTTON1_MASK) != 0) {
     if (dragged_node == null) return;
     TreePath selectedPath = getPathForLocation(evt.getX(), evt.getY());
     if (selectedPath == null)
       if ((selectedPath = getUpperPath(evt.getX(), evt.getY())) == null) return;
     DefaultMutableTreeNode node =
         (DefaultMutableTreeNode) selectedPath.getPathComponent(selectedPath.getPathCount() - 1);
     Object o = node.getUserObject();
     int pos = 0;
     if (o instanceof String) {
       DefaultMutableTreeNode p_node = (DefaultMutableTreeNode) node.getParent();
       pos = p_node.getIndex(node);
       node = p_node;
     }
     moveLeaf(node, dragged_node, pos);
     dragged_node = null;
     Cursor cursor = new Cursor(Cursor.DEFAULT_CURSOR);
     parent.setCursor(cursor);
   }
 }
示例#13
0
    public void valueChanged(TreeSelectionEvent evt) {
      TreePath path = evt.getPath();
      String fqn = SEP;
      String component_name;
      HashMap data = null;

      for (int i = 0; i < path.getPathCount(); i++) {
        component_name = ((MyNode) path.getPathComponent(i)).name;
        if (component_name.equals(SEP)) continue;
        if (fqn.equals(SEP)) fqn += component_name;
        else fqn = fqn + SEP + component_name;
      }
      data = getData(tree, fqn);
      if (data != null) {
        getContentPane().add(tablePanel, BorderLayout.SOUTH);
        populateTable(data);
        validate();
      } else {
        clearTable();
        getContentPane().remove(tablePanel);
        validate();
      }
    }
示例#14
0
文件: TreeUtil.java 项目: jexp/idea2
 private static boolean isAncestor(final TreePath ancestor, final TreePath path) {
   if (path.getPathCount() < ancestor.getPathCount()) return false;
   for (int i = 0; i < ancestor.getPathCount(); i++)
     if (!path.getPathComponent(i).equals(ancestor.getPathComponent(i))) return false;
   return true;
 }
示例#15
0
  @Override
  public void drop(DropTargetDropEvent dtde) {
    Point pt = dtde.getLocation();
    DropTargetContext dtc = dtde.getDropTargetContext();
    JTree tree = (JTree) dtc.getComponent();
    TreePath parentpath = tree.getClosestPathForLocation(pt.x, pt.y);
    Object node = parentpath.getLastPathComponent();

    if (dtde.isDataFlavorSupported(TransferableUDO.UDO_CAT_FLAVOR)) {
      if (!(node instanceof UDOCategory)) {
        dtde.rejectDrop();
        return;
      }

      if (dtde.getDropAction() == DnDConstants.ACTION_MOVE) {
        dtde.acceptDrop(dtde.getDropAction());

        Transferable tr = dtde.getTransferable();
        try {
          Object transferNode = tr.getTransferData(TransferableUDO.UDO_CAT_FLAVOR);

          UDOCategory udoCategory = (UDOCategory) transferNode;
          UDOCategory parentNode = (UDOCategory) node;

          UDOLibrary udoLibrary = (UDOLibrary) tree.getModel();

          udoLibrary.addCategory(parentNode, udoCategory);

          dtde.dropComplete(true);
        } catch (UnsupportedFlavorException | IOException e) {
          dtde.dropComplete(false);
        }
      } else {
        dtde.rejectDrop();
      }

    } else if (dtde.isDataFlavorSupported(TransferableUDO.UDO_FLAVOR)) {
      dtde.acceptDrop(dtde.getDropAction());

      try {
        Transferable tr = dtde.getTransferable();

        Object transferNode = tr.getTransferData(TransferableUDO.UDO_FLAVOR);

        UserDefinedOpcode udo = (UserDefinedOpcode) transferNode;
        UDOLibrary udoLibrary = (UDOLibrary) tree.getModel();

        // iLibrary.removeInstrument(instrument);
        if (node instanceof UDOCategory) {
          UDOCategory parentNode = (UDOCategory) node;

          udoLibrary.addUDO(parentNode, udo);
        } else if (node instanceof UserDefinedOpcode) {
          UDOCategory parentNode =
              (UDOCategory) parentpath.getPathComponent(parentpath.getPathCount() - 2);

          int index = ListUtil.indexOfByRef(parentNode.getUserDefinedOpcodes(), node);

          int closestRow = tree.getClosestRowForLocation(pt.x, pt.y);

          Rectangle bounds = tree.getRowBounds(closestRow);

          if (pt.y > bounds.y + bounds.height) {
            udoLibrary.addUDO(parentNode, udo);
          } else {
            udoLibrary.addUDO(parentNode, index, udo);
          }
        }

        dtde.dropComplete(true);
      } catch (UnsupportedFlavorException | IOException e) {
        dtde.dropComplete(false);
      }
    } else {
      dtde.rejectDrop();
    }
  }
示例#16
0
  /**
   * Synchronize the file system structure before the subtree that is supposed to be synchronized.
   * This structure to the subtree node is created if and only if the addProjectItems is true.
   * Otherwise no items on the file system are created and the whole synchronization finishes
   * successfully, even though that there is still differences between file system and project
   * navigation.
   *
   * @param file is the project root directory
   * @param treePath is the path to the project tree subtree which is supposed to be synchronized
   * @param addProjectItems indicates whether new items are supposed to be created on the file
   *     system if they are missing
   * @return the file system path related to the subtree chosen to synchronize, null if any error
   *     occurs or an instance of file class with empty path in it, if there are still differences
   *     but the method is not allowed to create items on the file system
   * @throws InterruptedException user has canceled the synchronization
   */
  private File syncPathToTreeRootToFS(
      final File file, final TreePath treePath, final boolean addProjectItems)
      throws InterruptedException {
    File path = file;

    for (int i = 1; i < treePath.getPathCount(); i++) {
      checkInterruption();

      final DefaultMutableTreeNode defaultMutableTreeNode =
          (DefaultMutableTreeNode) treePath.getPathComponent(i);
      final Object userObject = defaultMutableTreeNode.getUserObject();

      // update sync dialog
      if (userObject instanceof ProjectItem) {
        syncDialog.updatePosition(((ProjectItem) userObject).getDisplayName());

      } else {
        // should never happened
        LOG.error(
            "All project items have to be instances of classes implementing ProjectItem interface.");
        return null;
      }

      if (userObject instanceof ProjectRoot) {
        if (i > 1) { // should never happened
          return null;
        }

      } else if (userObject instanceof ProjectDiagram) {
        if (i < 2) { // should never happened
          return null;
        }

        if (defaultMutableTreeNode == treePath.getLastPathComponent()) {
          return path;
        } else {
          return null; // diagram cannot have any children in the tree path
        }

      } else if (userObject instanceof ProjectSubFolder) {
        if (i < 2) { // should never happened
          return null;
        }

        final ProjectItem projectItem = (ProjectItem) userObject;
        final File subfolder = new File(path.getAbsolutePath(), projectItem.getDisplayName());

        if (!subfolder.exists()) {

          if (addProjectItems) {
            if (subfolder.mkdir()) {
              LOG.debug(
                  "Sync PN -> FS: new subfolder has been created, "
                      + subfolder.getAbsolutePath()
                      + ".");
            } else {
              LOG.error(
                  "Sync PN -> FS: Creating of a new subfolder has failed failed, "
                      + subfolder.getAbsolutePath()
                      + ".");
              return null;
            }
          } else { // there are differences between PN and FS, but synchronize method is not invoked
                   // with addProjectItems flag
            return new File("");
          }
        }

        path = new File(subfolder.getAbsolutePath());

      } else {
        // should never happened
        LOG.error(
            "Project node has to be an instance of ProjectRoot, ProjectSubFolder or Project Diagram class.");
      }
    }

    return path;
  }
示例#17
0
  /**
   * Prepares the synchronization process and starts the synchronization.
   *
   * @return true if there were no errors during synchronization process, false otherwise
   * @throws Exception when something happened, synchronize(...) (see above) method deals with
   *     possible problems
   */
  protected Boolean doInBackground() throws Exception {
    showDialog();

    // First goes the JTree main projects root (root node, invisible for users) and then a project
    // root node.
    if (!ProjectServiceUtils.isValidTreePath(treePath) || treePath.getPathCount() < 2) {
      LOG.error("Invalid tree path.");
      syncDialog.appendErrorInfo(INVALID_TREE_PATH_LABEL, true);
      return false;
    }

    final DefaultMutableTreeNode projectRootNode;
    final ProjectRoot projectRoot;
    try {
      projectRootNode = (DefaultMutableTreeNode) treePath.getPathComponent(1);
      projectRoot = (ProjectRoot) projectRootNode.getUserObject();
    } catch (ClassCastException exception) {
      // should never happened, because isValidTreePath() method ensures this; testing & debuging
      // purposes
      LOG.error("Project root not found.");
      syncDialog.appendErrorInfo(PROJECT_ROOT_NOT_FOUND_LABEL, true);
      return false;
    }

    final File projectRootFile =
        new File(
            projectRoot.getProjectLocation(),
            projectRoot.getDisplayName() + ProjectService.PROJECT_FILE_EXTENSION);

    if (projectRootFile.exists()
        && overwriteProjectItems
        &&
        /* overwrite project file only when the project root is set as tree path (constructor argument) */
        treePath.equals(
            ModelerSession.getProjectService().getProjectPath(projectRoot.getDisplayName()))) {

      final SaveProjectResult result =
          ModelerSession.getProjectControlService()
              .saveProject(treePath); // overwrite the project file
      if (!SaveProjectResult.SUCCESS.equals(result)) {
        LOG.error("Not possible to save project file");
        syncDialog.appendErrorInfo(IMPOSSIBLE_TO_SAVE_PROJECT_FILE_LABEL, true);
        return false;
      }

    } else if (!projectRootFile.exists() && addProjectItems) {
      final SaveProjectResult result =
          ModelerSession.getProjectControlService()
              .saveProject(treePath); // create the project file
      if (!SaveProjectResult.SUCCESS.equals(result)) {
        LOG.error("Not possible to save project file");
        syncDialog.appendErrorInfo(IMPOSSIBLE_TO_SAVE_PROJECT_FILE_LABEL, true);
        return false;
      }

    } else if (!projectRootFile.exists()) {
      LOG.error(
          "Project file not found and synchronization is not allowed to add items to the file system.");
      syncDialog.appendErrorInfo(MISSING_PROJECT_FILE_LABEL, true);
      return false;
    }

    final File path =
        syncPathToTreeRootToFS(new File(projectRootFile.getParent()), treePath, addProjectItems);

    if (path == null) {
      syncDialog.appendErrorInfo(SYNC_SUBTREE_BUILD_ERROR_LABEL, true);
      return false;
    }

    /* This is kind of hack to show, that there is no need to continue,
    there are still differences between FS and PN, but the method is not allowed to create FS items. */
    return path.getAbsolutePath().equals("")
        || syncSubtreeToFS(
            path, treePath, addProjectItems, overwriteProjectItems, deleteProjectItems);
  }
示例#18
0
  protected TreePath getPrevPath(TreePath path) {
    int childCount;
    Object lastNode;
    TreeModel model = tree.getModel();

    // return last component
    if (path == null) {
      path = new TreePath(model.getRoot());

      lastNode = path.getLastPathComponent();

      while ((childCount = model.getChildCount(lastNode)) > 0) {
        // add the last child of the lastPathNode
        path = path.pathByAddingChild(model.getChild(lastNode, childCount - 1));
        lastNode = path.getLastPathComponent();
      }

      return path;
    }

    int index = 0;
    int pathLength = path.getPathCount();
    Object parentNode = null;

    lastNode = path.getLastPathComponent();

    if (pathLength > 1) {
      parentNode = path.getPathComponent(pathLength - 2);
      index = model.getIndexOfChild(parentNode, lastNode);
    }

    // if there are still some siblings (brothers) before this node
    if (index > 0) {
      TreePath siblingPath =
          path.getParentPath().pathByAddingChild(model.getChild(parentNode, index - 1));

      lastNode = siblingPath.getLastPathComponent();

      while ((childCount = model.getChildCount(lastNode)) > 0) {
        siblingPath = siblingPath.pathByAddingChild(model.getChild(lastNode, childCount - 1));
        lastNode = siblingPath.getLastPathComponent();
      }

      // return the siblingPath
      return siblingPath;
    } else {
      TreePath parentPath = path.getParentPath();

      // if there is still some parent
      if (parentPath != null) {
        // return his path
        return parentPath;
      }

      lastNode = path.getLastPathComponent();

      while ((childCount = model.getChildCount(lastNode)) > 0) {
        // add the last child of the lastPathNode
        path = path.pathByAddingChild(model.getChild(lastNode, childCount - 1));
        lastNode = path.getLastPathComponent();
      }

      return path;
    }
  }
示例#19
0
  /**
   * Description of the Method
   *
   * @exception IllegalActionException Description of the Exception
   */
  private void buildResultTree(EntityLibrary newRoot) throws IllegalActionException {
    if (isDebugging) log.debug("buildResultTree()");

    // iterate over each treepath in results
    for (int i = 0; i < results.size(); i++) {

      try {

        TreePath currentPath = results.getTreePath(i);
        if (isDebugging) log.debug(currentPath);

        EntityLibrary treeCurrent = newRoot;
        for (int j = 1; j < currentPath.getPathCount(); j++) {

          NamedObj pathCurrent = (NamedObj) currentPath.getPathComponent(j);

          if (pathCurrent instanceof EntityLibrary) {

            List<EntityLibrary> children = treeCurrent.entityList(EntityLibrary.class);

            boolean alreadyThere = false;
            for (EntityLibrary child : children) {
              if (isDebugging) log.debug(child.getName());
              if (child.getName().equals(pathCurrent.getName())) {
                // this EntityLibrary is already there
                treeCurrent = child;
                alreadyThere = true;
                break;
              }
            }
            if (!alreadyThere) {
              // create it
              EntityLibrary newEntity = copyEntityLibrary((EntityLibrary) pathCurrent);
              setContainer(treeCurrent, newEntity);
              treeCurrent = newEntity;
            }

          } else {
            List<NamedObj> children = treeCurrent.entityList(NamedObj.class);

            boolean alreadyThere = false;
            for (NamedObj child : children) {
              if (child.getName().equals(pathCurrent.getName())) {
                // this NamedObj is already there
                alreadyThere = true;
                break;
              }
            }
            if (!alreadyThere) {
              // create it
              NamedObj newEntity = cloneEntity((NamedObj) pathCurrent);
              setContainer(treeCurrent, newEntity);
              // Leaf node, all done
              break;
            }
          }
        }

      } catch (IllegalActionException iae) {
        throw new IllegalActionException("cannot build search result tree: " + iae);
      } catch (NameDuplicationException nde) {
        log.error("EXCEPTION CAUGHT: " + nde.getMessage());
      } catch (Exception e) {
        log.error("EXCEPTION CAUGHT: " + e.getMessage());
      }
    } // end for loop
  }
示例#20
0
  /**
   * Downloads the given node from the device onto your local machine, performing filename
   * evaluation and tag rewriting if you have any tagwriters installed. Normally this would be in
   * SynchronizeUI with all the other downloading code, but if you ever wanted to initiate a
   * download without a UI, you could call this method.
   *
   * @param _path a treepath that points to the desired node (this can be a path of one entry that
   *     is the node's parent if you have EmplodeConstants.DOWNLOAD_FULL_PATH_PROPERTY disabled)
   * @param _node the node to download
   * @param _index the index of the node in its parent (some evaluated tags care about this)
   * @param _protocolClient the ProtocolClient to download with
   * @param _baseDir the base folder to download into
   * @param _changeSet the change set that will contain the results of the download
   * @param _packetSize the packet size to download with
   * @param _useHijack lame, but it has to come from somewhere -- this says whether or not the
   *     hijack API's should be used
   * @param _progressListener the progress listener to report download status to
   * @throws IOException if the download files
   */
  public static void downloadFile(
      TreePath _path,
      IFIDNode _node,
      int _index,
      IProtocolClient _protocolClient,
      File _baseDir,
      FIDChangeSet _changeSet,
      int _packetSize,
      boolean _useHijack,
      IProgressListener _progressListener)
      throws IOException {
    if (!_progressListener.isStopRequested()) {
      PropertiesManager propertiesManager = PropertiesManager.getInstance();
      try {
        _progressListener.operationStarted(ResourceBundleUtils.getUIString("download.operation"));

        File targetDir;
        boolean downloadFullPath =
            propertiesManager.getBooleanProperty(JEmplodeProperties.DOWNLOAD_FULL_PATH_PROPERTY);
        if (downloadFullPath) {
          StringBuffer fullPath = new StringBuffer();
          int size = _path.getPathCount();
          for (int i = size - 1; i >= 0; i--) {
            IFIDNode node = (IFIDNode) _path.getPathComponent(i);
            fullPath.insert(0, File.separator);
            fullPath.insert(0, FileUtils.cleanseFilename(node.getTitle(), true));
          }
          targetDir = new File(_baseDir, fullPath.toString());
        } else {
          targetDir = _baseDir;
        }

        File targetFile = null;
        if (_node instanceof FIDPlaylist) {
          FIDPlaylist playlist = (FIDPlaylist) _node;

          String filenameFormatBase =
              (playlist.isTransient())
                  ? JEmplodeProperties.FILENAME_FORMAT_SOUP_BASE
                  : JEmplodeProperties.FILENAME_FORMAT_BASE;
          String filenameFormat =
              propertiesManager.getProperty(
                  filenameFormatBase + playlist.getTags().getValue(DatabaseTags.TYPE_TAG));
          String parsedName =
              FileUtils.cleanseFilename(
                  new NodeTagStringEvaluator(playlist).evaluate(filenameFormat), false);
          if (filenameFormat == null || filenameFormat.indexOf('{') == -1) {
            filenameFormat =
                PropertiesManager.getDefaults()
                    .getProperty(JEmplodeProperties.FILENAME_FORMAT_PLAYLIST_KEY);
          }
          targetFile = new File(targetDir, parsedName);
          targetFile.mkdirs();

          int size = playlist.getSize();
          _progressListener.operationUpdated(0, size);
          for (int i = 0; i < size; i++) {
            IFIDNode node = playlist.getNodeAt(i);
            File newDir = (downloadFullPath) ? _baseDir : targetFile;
            downloadFile(
                _path.pathByAddingChild(playlist),
                node,
                i,
                _protocolClient,
                newDir,
                _changeSet,
                _packetSize,
                _useHijack,
                _progressListener);
            _progressListener.operationStarted(
                ResourceBundleUtils.getUIString(
                    "download.downloadFile.operation", new Object[] {parsedName}));
            _progressListener.operationUpdated(i + 1, size);
          }
        } else {
          try {
            FIDPlaylist parentPlaylist = (FIDPlaylist) _path.getLastPathComponent();
            IFIDNode child = parentPlaylist.getNodeAt(_index);
            String filenameFormatBase =
                (parentPlaylist.isTransient())
                    ? JEmplodeProperties.FILENAME_FORMAT_SOUP_BASE
                    : JEmplodeProperties.FILENAME_FORMAT_BASE;
            String filenameFormat =
                propertiesManager.getProperty(
                    filenameFormatBase + child.getTags().getValue(DatabaseTags.TYPE_TAG));
            if (filenameFormat == null || filenameFormat.indexOf('{') == -1) {
              filenameFormat =
                  PropertiesManager.getDefaults()
                      .getProperty(JEmplodeProperties.FILENAME_FORMAT_TAXI_KEY);
            }
            String parsedName =
                FileUtils.cleanseFilename(
                    new NodeTagStringEvaluator(parentPlaylist, _index).evaluate(filenameFormat),
                    false);

            targetFile = new File(targetDir, parsedName);
            String targetFileStr = targetFile.getParent();
            if (targetFileStr != null) {
              // make sure all directories are created
              new File(targetFileStr).mkdirs();
            }

            if (!targetFile.exists()) {
              OutputStream os = new BufferedOutputStream(new FileOutputStream(targetFile));
              _progressListener.taskStarted(
                  ResourceBundleUtils.getUIString(
                      "download.downloadFile.operation", new Object[] {parsedName}));
              RemoteImportFile remoteFile = RemoteImportFile.createInstance(_node, _protocolClient);
              InputStream is = remoteFile.getInputStream(_useHijack);
              try {
                StreamUtils.copy(is, os, _packetSize, _node.getLength(), _progressListener);
              } finally {
                is.close();
              }
              os.close();
              _changeSet.nodeAdded(_node);

              try {
                ITagWriter tagWriter = TagWriterFactory.createTagWriter(_node);
                tagWriter.writeTags(_node, parentPlaylist, targetFile);
              } catch (Throwable t) {
                // That's OK ...
                Debug.println(Debug.WARNING, t);
              }
            } else {
              IImportFile importFile = ImportFileFactory.createImportFile(targetFile);
              _changeSet.fileSkipped(
                  importFile, ResourceBundleUtils.getUIString("download.downloadFile.skipped"));
            }
          } catch (IOException e) {
            Debug.println(e);
            IImportFile importFile = ImportFileFactory.createImportFile(targetFile);
            _changeSet.fileFailed(importFile, e);
            try {
              targetFile.delete();
            } catch (Throwable t) {
              Debug.println(e);
            }
            // myEmplode.handleError("Failed to download " + targetFile.getName(), e);
          }
        }
      } finally {
        _progressListener.operationUpdated(1, 1);
      }
    }
  }