/*
  * Filter elements to avoid having files of directory traces listed as
  * separate traces.
  */
 private void filterElements(TracePackageElement parentElement) {
   for (TracePackageElement childElement : parentElement.getChildren()) {
     filterElements(childElement);
     if (childElement instanceof TracePackageTraceElement) {
       // no need to do length check here
       RemoteImportTraceFilesElement filesElement =
           (RemoteImportTraceFilesElement) childElement.getChildren()[0];
       IFileStore parentFile = filesElement.getRemoteFile().getParent();
       if (fDirectoryTraces.contains(
           TmfTraceCoreUtils.newSafePath(parentFile.toURI().getPath()))) {
         removeChild(childElement, parentElement);
         continue;
       }
       IFileStore grandParentFile = parentFile.getParent();
       if (grandParentFile != null
           && fDirectoryTraces.contains(
               TmfTraceCoreUtils.newSafePath(grandParentFile.toURI().getPath()))) {
         // ignore file if grandparent is a directory trace
         // for example: file is a index file of a LTTng kernel trace
         parentElement.removeChild(childElement);
         if (parentElement.getChildren().length == 0) {
           TracePackageElement grandParentElement = parentElement.getParent();
           removeChild(parentElement, grandParentElement);
         }
         continue;
       }
     } else if (childElement instanceof RemoteImportFolderElement) {
       if (childElement.getChildren().length == 0) {
         parentElement.removeChild(childElement);
       }
     }
   }
 }
  private IHyperlink openModule(Node current, ITextViewer textViewer, int offset) {
    while (current != null && !(current instanceof Element)) {
      current = current.getParentNode();
    }
    if (current == null) {
      return null;
    }
    String pathUp = XmlUtils.pathUp(current, 2);
    if (!"modules/module".equals(pathUp)) { // $NON-NLS-1$
      // just in case we are in some random plugin configuration snippet..
      return null;
    }

    ITextFileBuffer buf =
        FileBuffers.getTextFileBufferManager().getTextFileBuffer(textViewer.getDocument());
    if (buf == null) {
      // for repository based poms..
      return null;
    }
    IFileStore folder = buf.getFileStore().getParent();

    String path = XmlUtils.getTextValue(current);
    final String fPath = path;
    // construct IPath for the child pom file, handle relative paths..
    while (folder != null && path.startsWith("../")) { // $NON-NLS-1$
      folder = folder.getParent();
      path = path.substring("../".length()); // $NON-NLS-1$
    }
    if (folder == null) {
      return null;
    }
    IFileStore modulePom = folder.getChild(path);
    if (!modulePom.getName().endsWith("xml")) { // $NON-NLS-1$
      modulePom = modulePom.getChild("pom.xml"); // $NON-NLS-1$
    }
    final IFileStore fileStore = modulePom;
    if (!fileStore.fetchInfo().exists()) {
      return null;
    }
    assert current instanceof IndexedRegion;
    final IndexedRegion region = (IndexedRegion) current;

    return new IHyperlink() {
      public IRegion getHyperlinkRegion() {
        return new Region(region.getStartOffset(), region.getEndOffset() - region.getStartOffset());
      }

      public String getHyperlinkText() {
        return NLS.bind(Messages.PomHyperlinkDetector_open_module, fPath);
      }

      public String getTypeLabel() {
        return "pom-module"; //$NON-NLS-1$
      }

      public void open() {
        openXmlEditor(fileStore);
      }
    };
  }
 private static IFileStore getFolderStore(IAdaptable destination) {
   IFileStore store = Utils.getFileStore(destination);
   IFileInfo info = Utils.getFileInfo(destination);
   if (store != null && info != null && !info.isDirectory()) {
     store = store.getParent();
   }
   return store;
 }
  /** Allow user to specify a TAU bin directory. */
  protected void handleBinBrowseButtonSelected(Text field, String group) {
    final DirectoryDialog dialog = new DirectoryDialog(getShell());
    IFileStore path = null;
    final String correctPath = getFieldContent(field.getText());
    if (correctPath != null) {
      path = EFS.getLocalFileSystem().getStore(new Path(correctPath)); // new File(correctPath);
      if (path.fetchInfo().exists()) {
        dialog.setFilterPath(
            !path.fetchInfo().isDirectory() ? correctPath : path.getParent().toURI().getPath());
      }
    }
    // The specified directory previously had to contain at least one
    // recognizable TAU makefile in its lib sub-directory to be accepted.
    // String tlpath = correctPath+File.separator+"lib";
    //
    // class makefilter implements FilenameFilter{
    // public boolean accept(File dir, String name) {
    // if(name.indexOf("Makefile.tau")!=0 || name.indexOf("-pdt")<=0)
    // return false;
    // return true;
    // }
    // }
    // File[] mfiles=null;
    // makefilter mfilter = new makefilter();
    // File test = new File(tlpath);

    dialog.setText(
        Messages.ToolLocationPreferencePage_Select
            + group
            + Messages.ToolLocationPreferencePage_BinDirectory);
    // dialog.setMessage("You must select a valid TAU bin directory.  Such a directory should be
    // created when you configure and install TAU.  It should contain least one valid stub makefile
    // configured with the Program Database Toolkit (pdt)");

    final String selectedPath = dialog.open(); // null;
    if (selectedPath != null) {
      field.setText(selectedPath);
      // while(true)
      // {
      // selectedPath = dialog.open();
      // if(selectedPath==null)
      // break;
      //
      // tlpath=selectedPath+File.separator+"lib";
      // test = new File(tlpath);
      // if(test.exists()){
      // mfiles = test.listFiles(mfilter);
      // }
      // if (mfiles!=null&&mfiles.length>0)
      // {
      // if (selectedPath != null)
      // tauBin.setText(selectedPath);
      // break;
      // }
      // }
    }
  }
 @Override
 public Object getParent(Object object) {
   if (object instanceof IFileStore) {
     IFileStore fileStore = (IFileStore) object;
     return fileStore.getParent();
   } else {
     return null;
   }
 }
  private static String validateDestination(IAdaptable destination, IFileStore[] sourceStores) {
    IFileStore destinationStore = getFolderStore(destination);
    IFileStore sourceParentStore;
    for (IFileStore sourceStore : sourceStores) {
      sourceParentStore = sourceStore.getParent();
      if (destinationStore.equals(sourceStore)
          || (sourceParentStore != null && destinationStore.equals(sourceParentStore))) {
        return "The source is already contained in the destination";
      }

      if (sourceStore.isParentOf(destinationStore)) {
        return "Destination cannot be a descendent of the source";
      }
    }
    return null;
  }
  @Override
  public Object getParent(Object element) {
    if (element instanceof IResource) {
      return ((IResource) element).getParent();
    } else if (element instanceof IFileStore) {
      IFileStore fileStore = (IFileStore) element;

      if (getSdkParent(fileStore) != null) {
        return getSdkParent(fileStore);
      }

      return fileStore.getParent();
    } else if (element instanceof SdkLibraryNode) {
      return SdkDirectoryNode.INSTANCE;
    } else {
      return null;
    }
  }
 /**
  * Unzips the transferred file. Returns <code>true</code> if the unzip was successful, and <code>
  * false</code> otherwise. In case of failure, this method handles setting an appropriate
  * response.
  */
 private boolean completeUnzip(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException {
   IPath destPath = new Path(getPath());
   try {
     ZipFile source = new ZipFile(new File(getStorageDirectory(), FILE_DATA));
     IFileStore destinationRoot = NewFileServlet.getFileStore(destPath);
     Enumeration<? extends ZipEntry> entries = source.entries();
     while (entries.hasMoreElements()) {
       ZipEntry entry = entries.nextElement();
       IFileStore destination = destinationRoot.getChild(entry.getName());
       if (entry.isDirectory()) destination.mkdir(EFS.NONE, null);
       else {
         destination.getParent().mkdir(EFS.NONE, null);
         IOUtilities.pipe(
             source.getInputStream(entry),
             destination.openOutputStream(EFS.NONE, null),
             false,
             true);
       }
     }
     source.close();
   } catch (ZipException e) {
     // zip exception implies client sent us invalid input
     String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString());
     statusHandler.handleRequest(
         req, resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, e));
     return false;
   } catch (Exception e) {
     // other failures should be considered server errors
     String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString());
     statusHandler.handleRequest(
         req,
         resp,
         new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
     return false;
   }
   return true;
 }
 @Override
 protected IBaseModel createModel(IEditorInput input) throws CoreException {
   BundleModel model = null;
   boolean isReconciling = input instanceof IFileEditorInput;
   IDocument document = getDocumentProvider().getDocument(input);
   model = new BundleModel(document, isReconciling);
   if (input instanceof IFileEditorInput) {
     IFile file = ((IFileEditorInput) input).getFile();
     model.setUnderlyingResource(file);
     model.setCharset(file.getCharset());
   } else if (input instanceof IURIEditorInput) {
     IFileStore store = EFS.getStore(((IURIEditorInput) input).getURI());
     model.setInstallLocation(store.getParent().getParent().toString());
     model.setCharset(getDefaultCharset());
   } else if (input instanceof JarEntryEditorInput) {
     File file = (File) ((JarEntryEditorInput) input).getAdapter(File.class);
     model.setInstallLocation(file.toString());
     model.setCharset(getDefaultCharset());
   } else {
     model.setCharset(getDefaultCharset());
   }
   model.load();
   return model;
 }
  /**
   * Scan traceFolder for files that match the patterns specified in the template file. When there
   * is a match, the trace package element is used to determine the trace name and trace type.
   *
   * @param traceGroup The parent trace group element
   * @param parentElement The immediate parent trace group or folder element
   * @param traceFolder The folder to scan
   * @param recursionLevel The recursion level (needed to find directory traces under the
   *     traceFolder
   * @param monitor The progress monitor
   * @throws CoreException Thrown by the file system implementation
   * @throws InterruptedException Thrown if operation was cancelled
   */
  private void generateElementsFromArchive(
      final RemoteImportTraceGroupElement traceGroup,
      final TracePackageElement parentElement,
      final IFileStore traceFolder,
      final int recursionLevel,
      IProgressMonitor monitor)
      throws CoreException, InterruptedException {

    int localRecursionLevel = recursionLevel + 1;
    IFileStore[] sources = traceFolder.childStores(EFS.NONE, monitor);

    for (int i = 0; i < sources.length; i++) {
      ModalContext.checkCanceled(monitor);
      SubMonitor subMonitor = SubMonitor.convert(monitor, sources.length);

      IFileStore fileStore = sources[i];
      IPath fullArchivePath = TmfTraceCoreUtils.newSafePath(fileStore.toURI().getPath());

      IFileInfo sourceInfo = fileStore.fetchInfo();
      if (!sourceInfo.isDirectory()) {

        String rootPathString = traceGroup.getRootImportPath();
        IPath rootPath = TmfTraceCoreUtils.newSafePath(rootPathString);
        IPath relativeTracePath = Path.EMPTY;
        if (rootPath.isPrefixOf(fullArchivePath)) {
          relativeTracePath = fullArchivePath.makeRelativeTo(rootPath);
        }
        Entry<Pattern, TracePackageTraceElement> matchingTemplateEntry =
            getMatchingTemplateElement(relativeTracePath);
        if (matchingTemplateEntry != null) {
          TracePackageTraceElement matchingTemplateElement = matchingTemplateEntry.getValue();
          String traceType = matchingTemplateElement.getTraceType();

          // If a single file is part of a directory trace, use the parent directory instead
          TracePackageElement parent = parentElement;
          if (matchesDirectoryTrace(relativeTracePath, matchingTemplateEntry)) {
            fullArchivePath = fullArchivePath.removeLastSegments(1);
            fDirectoryTraces.add(fullArchivePath);
            fileStore = fileStore.getParent();
            parent = parentElement.getParent();
            // Let the auto-detection choose the best trace type
            traceType = null;
          } else if ((localRecursionLevel > 1) && (!traceGroup.isRecursive())) {
            // Don't consider file traces on level 2 if it's not recursive
            continue;
          }
          String traceName = fullArchivePath.lastSegment();
          String fileName = fileStore.getName();
          // create new elements to decouple from input elements
          TracePackageTraceElement traceElement =
              new TracePackageTraceElement(parent, traceName, traceType);
          RemoteImportTraceFilesElement tracePackageFilesElement =
              new RemoteImportTraceFilesElement(traceElement, fileName, fileStore);
          tracePackageFilesElement.setVisible(false);
        }
      } else {
        if (traceGroup.isRecursive() || localRecursionLevel < 2) {
          RemoteImportFolderElement folder =
              new RemoteImportFolderElement(parentElement, fileStore.getName());
          generateElementsFromArchive(
              traceGroup, folder, fileStore, localRecursionLevel, subMonitor);
        }
      }
    }
  }
  /** Opens a file or directory browser depending on the link type. */
  private void handleLinkTargetBrowseButtonPressed() {
    IFileStore store = null;
    String selection = null;
    FileSystemConfiguration config = getSelectedConfiguration();
    @SuppressWarnings("unused")
    boolean isDefault =
        (config == null)
            || (FileSystemSupportRegistry.getInstance().getDefaultConfiguration()).equals(config);

    if (linkTarget.length() > 0) {
      store = IDEResourceInfoUtils.getFileStore(linkTarget);
      if (!store.fetchInfo().exists()) {
        store = null;
      }
    }
    if (type == IResource.FILE) {
      // if (isDefault) {
      // FileDialog dialog = new FileDialog(linkTargetField.getShell());
      // dialog.setText(IDEWorkbenchMessages.CreateLinkedResourceGroup_targetSelectionTitle);
      // if (store != null) {
      // if (store.fetchInfo().isDirectory()) {
      // dialog.setFilterPath(linkTarget);
      // } else {
      // dialog.setFileName(linkTarget);
      // }
      // }
      // selection = dialog.open();
      // } else {
      @SuppressWarnings("null")
      URI uri = config.getContributor().browseFileSystem(linkTarget, linkTargetField.getShell());
      if (uri != null) {
        selection = uri.toString();
        // }
      }
    } else {
      String filterPath = null;
      if (store != null) {
        IFileStore path = store;
        if (!store.fetchInfo().isDirectory()) {
          path = store.getParent();
        }
        if (path != null) {
          filterPath = store.toString();
        }
      }

      // if (isDefault) {
      // DirectoryDialog dialog = new DirectoryDialog(linkTargetField
      // .getShell());
      // dialog
      // .setMessage(IDEWorkbenchMessages.CreateLinkedResourceGroup_targetSelectionLabel);
      // if (filterPath != null)
      // dialog.setFilterPath(filterPath);
      // selection = dialog.open();
      // } else {
      String initialPath = IDEResourceInfoUtils.EMPTY_STRING;
      if (filterPath != null) {
        initialPath = filterPath;
      }
      if (config != null) {
        URI uri = config.getContributor().browseFileSystem(initialPath, linkTargetField.getShell());
        if (uri != null) {
          selection = uri.toString();
        }
      }
      // }
    }
    if (selection != null) {
      linkTargetField.setText(selection);
    }
  }