protected void testFilesExists(
      HashMap<String, IFileStore> destMap,
      IFileStore sourceRoot,
      IFileStore sourceFile,
      int timeTolerance)
      throws CoreException {
    String relPath = EFSUtils.getRelativePath(sourceRoot, sourceFile, null);
    IFileStore destFile = destMap.get(relPath);
    // System.out.println("Comparing " + relPath);

    assertNotNull(MessageFormat.format("File {0} not found on destination", relPath), destFile);
    IFileInfo f1 = sourceFile.fetchInfo(IExtendedFileStore.DETAILED, null);
    IFileInfo f2 = destFile.fetchInfo(IExtendedFileStore.DETAILED, null);
    if (!f1.isDirectory()) {
      long sourceFileTime = f1.getLastModified();
      long destFileTime = f2.getLastModified();
      long timeDiff = destFileTime - sourceFileTime;

      assertTrue(
          MessageFormat.format(
              "File {0} is {1} seconds newer on destination", relPath, (int) timeDiff / 1000),
          -timeTolerance <= timeDiff && timeDiff <= timeTolerance);
      assertEquals(
          MessageFormat.format("File {0} different sizes", relPath),
          f1.getLength(),
          f2.getLength());
    }
  }
  /** @see junit.framework.TestCase#tearDown() */
  protected void tearDown() throws Exception {
    try {
      if (clientDirectory.fetchInfo().exists()) {
        // clientDirectory.delete(EFS.NONE, null);
        // assertFalse(clientDirectory.fetchInfo().exists());
      }
    } finally {
      if (clientManager.isConnected()) {
        clientManager.disconnect(null);
      }
    }

    try {
      if (serverDirectory.fetchInfo().exists()) {
        // serverDirectory.delete(EFS.NONE, null);
        // assertFalse(serverDirectory.fetchInfo().exists());
      }
    } finally {
      if (serverManager.isConnected()) {
        serverManager.disconnect(null);
      }
    }

    super.tearDown();
  }
Beispiel #3
0
 private void openFile(File file, DotGraphView view) {
   if (view.currentFile == null) { // no workspace file for cur. graph
     IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path("")); // $NON-NLS-1$
     fileStore = fileStore.getChild(file.getAbsolutePath());
     if (!fileStore.fetchInfo().isDirectory() && fileStore.fetchInfo().exists()) {
       IWorkbenchPage page = view.getSite().getPage();
       try {
         IDE.openEditorOnFileStore(page, fileStore);
       } catch (PartInitException e) {
         e.printStackTrace();
       }
     }
   } else {
     IWorkspace workspace = ResourcesPlugin.getWorkspace();
     IPath location = Path.fromOSString(file.getAbsolutePath());
     IFile copy = workspace.getRoot().getFileForLocation(location);
     IEditorRegistry registry = PlatformUI.getWorkbench().getEditorRegistry();
     if (registry.isSystemExternalEditorAvailable(copy.getName())) {
       try {
         view.getViewSite()
             .getPage()
             .openEditor(new FileEditorInput(copy), IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
       } catch (PartInitException e) {
         e.printStackTrace();
       }
     }
   }
 }
 private boolean handlePost(
     HttpServletRequest request, HttpServletResponse response, IFileStore dir)
     throws JSONException, CoreException, ServletException, IOException {
   // setup and precondition checks
   JSONObject requestObject = OrionServlet.readJSONRequest(request);
   String name = computeName(request, requestObject);
   if (name.length() == 0)
     return statusHandler.handleRequest(
         request,
         response,
         new ServerStatus(
             IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "File name not specified.", null));
   int options = getCreateOptions(request);
   IFileStore toCreate = dir.getChild(name);
   boolean destinationExists = toCreate.fetchInfo().exists();
   if (!validateOptions(request, response, toCreate, destinationExists, options)) return true;
   // perform the operation
   if (performPost(request, response, requestObject, toCreate, options)) {
     // write the response
     URI location = URIUtil.append(getURI(request), name);
     JSONObject result = ServletFileStoreHandler.toJSON(toCreate, toCreate.fetchInfo(), location);
     OrionServlet.writeJSONResponse(request, response, result);
     response.setHeader(ProtocolConstants.HEADER_LOCATION, location.toString());
     // response code should indicate if a new resource was actually created or not
     response.setStatus(
         destinationExists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_CREATED);
   }
   return true;
 }
  /** 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;
      // }
      // }
    }
  }
Beispiel #6
0
  @Test
  public void testLocalFileProxy() {
    IRemoteFileProxy fileProxy = null;
    try {
      fileProxy = proxyManager.getFileProxy(localProject.getProject());
      assertTrue("Should have returned a remote launcher", fileProxy instanceof LocalFileProxy);
    } catch (CoreException e) {
      fail("Should have returned a launcher: " + e.getCause());
    }

    /*
     * Test getDirectorySeparator()
     */
    String ds = fileProxy.getDirectorySeparator();
    assertNotNull(ds);
    /*
     *  Test getResource()
     */
    IFileStore actualFileStore =
        fileProxy.getResource(localProject.getProject().getLocation().toOSString());
    assertNotNull(actualFileStore);

    IFileStore expectedFileStore = null;
    try {
      expectedFileStore = EFS.getStore(localProject.getLocationURI());
    } catch (CoreException e) {
      fail("Unabled to get FileStore to local project: " + e.getMessage());
    }
    assertEquals("FileStore to local project folder diverge", expectedFileStore, actualFileStore);
    assertTrue(actualFileStore.fetchInfo().isDirectory());

    actualFileStore = fileProxy.getResource("/filenotexits");
    assertNotNull(actualFileStore);
    IFileInfo fileInfo = actualFileStore.fetchInfo();
    assertNotNull(fileInfo);
    assertFalse(fileInfo.exists());

    /*
     * Test getWorkingDir()
     */
    URI workingDir = fileProxy.getWorkingDir();
    assertNotNull(workingDir);
    assertEquals(localProject.getLocationURI(), workingDir);

    /*
     * Test toPath()
     */
    assertEquals(
        localProject.getProject().getLocation().toOSString(),
        fileProxy.toPath(localProject.getLocationURI()));
  }
  public static boolean isExecutable(IPath path) {
    if (path == null) {
      return false;
    }
    File file = path.toFile();
    if (file == null || !file.exists() || file.isDirectory()) {
      return false;
    }

    // OK, file exists
    try {
      Method m = File.class.getMethod("canExecute"); // $NON-NLS-1$
      if (m != null) {
        return (Boolean) m.invoke(file);
      }
    } catch (Exception e) {
    }

    // File.canExecute() doesn't exist; do our best to determine if file is executable...
    if (Platform.OS_WIN32.equals(Platform.getOS())) {
      return true;
    }
    IFileStore fileStore = EFS.getLocalFileSystem().getStore(path);
    return fileStore.fetchInfo().getAttribute(EFS.ATTRIBUTE_EXECUTABLE);
  }
Beispiel #8
0
 private static IEditorInput getEditorInput(final IErlElement element0) {
   IErlElement element = element0;
   final IResource resource = element.getResource();
   if (resource instanceof IFile) {
     IFile file = (IFile) resource;
     file = resolveFile(file);
     return new FileEditorInput(file);
   }
   String filePath = element.getFilePath();
   while (filePath == null) {
     final IParent parent = element.getParent();
     if (parent instanceof IErlElement) {
       element = (IErlElement) parent;
       filePath = element.getFilePath();
     } else {
       break;
     }
   }
   if (filePath != null) {
     final IPath path = new Path(filePath);
     IFileStore fileStore = EFS.getLocalFileSystem().getStore(path.removeLastSegments(1));
     fileStore = fileStore.getChild(path.lastSegment());
     final IFileInfo fetchInfo = fileStore.fetchInfo();
     if (!fetchInfo.isDirectory() && fetchInfo.exists()) {
       if (element instanceof IErlModule && element.getParent() instanceof IErlExternal) {
         return new ErlangExternalEditorInput(fileStore, (IErlModule) element);
       }
       return new FileStoreEditorInput(fileStore);
     }
   }
   return null;
 }
  /**
   * @param sourceStore the file to be copied
   * @param destinationStore the destination location
   * @param monitor the progress monitor
   * @return true if the file is successfully copied, false if the operation did not go through for
   *     any reason
   */
  protected boolean copyFile(
      IFileStore sourceStore, IFileStore destinationStore, IProgressMonitor monitor) {
    if (sourceStore == null) {
      return false;
    }

    boolean success = true;
    monitor.subTask(
        MessageFormat.format(
            "Copying {0} to {1}", sourceStore.getName(), destinationStore.getName()));
    try {
      if (fAlwaysOverwrite) {
        sourceStore.copy(destinationStore, EFS.OVERWRITE, monitor);
      } else if (destinationStore.fetchInfo(0, monitor).exists()) {
        String overwrite = fOverwriteQuery.queryOverwrite(destinationStore.toString());
        if (overwrite.equals(IOverwriteQuery.ALL) || overwrite.equals(IOverwriteQuery.YES)) {
          sourceStore.copy(destinationStore, EFS.OVERWRITE, monitor);
        } else {
          success = false;
        }
      } else {
        sourceStore.copy(destinationStore, EFS.NONE, monitor);
      }
    } catch (CoreException e) {
      // TODO: report the error
      success = false;
    }
    return success;
  }
  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);
      }
    };
  }
  /**
   * Performs a git clone to a temporary location and then copies the files over top the already
   * generated project. This is because git cannot clone into an existing directory.
   *
   * @param monitor
   * @throws Exception
   */
  protected void cloneAfter(IProgressMonitor monitor) throws Exception {
    SubMonitor sub =
        SubMonitor.convert(monitor, Messages.AbstractNewProjectWizard_CloningFromGitMsg, 100);
    // clone to tmp dir then copy files over top the project!
    File tmpFile = File.createTempFile("delete_me", "tmp"); // $NON-NLS-1$ //$NON-NLS-2$
    File dest = new File(tmpFile.getParent(), "git_clone_tmp"); // $NON-NLS-1$
    GitExecutable.instance()
        .clone(
            selectedTemplate.getLocation(),
            Path.fromOSString(dest.getAbsolutePath()),
            true,
            sub.newChild(85));

    IFileStore tmpClone = EFS.getStore(dest.toURI());
    // Wipe the .git folder before copying? Wipe the .project file before copying?
    IFileStore dotGit = tmpClone.getChild(".git"); // $NON-NLS-1$
    dotGit.delete(EFS.NONE, sub.newChild(2));

    IFileStore dotProject = tmpClone.getChild(IProjectDescription.DESCRIPTION_FILE_NAME);
    if (dotProject.fetchInfo().exists()) {
      dotProject.delete(EFS.NONE, sub.newChild(1));
    }
    // OK, copy the cloned template's contents over
    IFileStore projectStore = EFS.getStore(newProject.getLocationURI());
    tmpClone.copy(projectStore, EFS.OVERWRITE, sub.newChild(9));
    // Now get rid of the temp clone!
    tmpClone.delete(EFS.NONE, sub.newChild(3));
    sub.done();
  }
    @Override
    public ImageDescriptor getImageDescriptor(Object object) {
      if (object instanceof IFileStore) {
        IFileStore fileStore = (IFileStore) object;

        try {
          if (fileStore.fetchInfo().isDirectory()) {
            return PlatformUI.getWorkbench()
                .getSharedImages()
                .getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER);
          }

          IEditorDescriptor descriptor = IDE.getEditorDescriptor(fileStore.getName());

          if (descriptor != null) {
            return descriptor.getImageDescriptor();
          } else {
            return PlatformUI.getWorkbench()
                .getSharedImages()
                .getImageDescriptor(ISharedImages.IMG_OBJ_FILE);
          }
        } catch (PartInitException e) {

        }
      }

      return null;
    }
 public void testSetFileLastModified() {
   IFileStore file = baseStore.getChild("file");
   ensureExists(file, false);
   IFileInfo info = file.fetchInfo();
   long oldLastModified = info.getLastModified();
   long newLastModified = oldLastModified + 100;
   info = EFS.createFileInfo();
   info.setLastModified(newLastModified);
   try {
     file.putInfo(info, EFS.SET_LAST_MODIFIED, getMonitor());
   } catch (CoreException e) {
     fail("1.99", e);
   }
   info = file.fetchInfo();
   assertEquals("1.0", newLastModified, info.getLastModified());
   assertEquals("1.1", file.getName(), info.getName());
 }
  /**
   * Uploads ppkFile to the specified workspace of the asccount associated with the given username
   * and password
   *
   * @param usr Username
   * @param pwd Password
   * @param workspace Selected workspace
   * @param ppkFile Packed profile file
   * @return
   * @throws Exception
   */
  private static String uploadPPK(
      String url, String usr, String pwd, String workspace, IFileStore ppkFile) throws Exception {

    String pwd2 = SHA1(pwd);

    String portalURL = url + "/trial/batch_upload"; // $NON-NLS-1$
    String ppkName = ppkFile.getName();
    ppkName = ppkName.substring(0, ppkName.lastIndexOf('.'));

    // RandomAccessFile rfile = new RandomAccessFile(ppkFile.openOutputStream(EFS.NONE, null), "r");
    // //$NON-NLS-1$
    InputStream rfile = (new BufferedInputStream(ppkFile.openInputStream(EFS.NONE, null)));
    ppkFile.fetchInfo().getLength();
    byte barr[] = new byte[(int) ppkFile.fetchInfo().getLength()]; // TODO: This needs testing.
    rfile.read(barr);
    String ppkString = new String(barr, "ISO-8859-1"); // $NON-NLS-1$
    ppkString = URLEncoder.encode(ppkString, "ISO-8859-1"); // $NON-NLS-1$

    String data =
        URLEncoder.encode("username", "UTF-8")
            + "="
            + URLEncoder.encode(
                usr, "UTF-8"); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
    data +=
        "&"
            + URLEncoder.encode("password", "UTF-8")
            + "="
            + URLEncoder.encode(
                pwd2,
                "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
    data +=
        "&"
            + URLEncoder.encode(ppkName, "UTF-8")
            + "="
            + ppkString; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    data +=
        "&"
            + URLEncoder.encode("workspace", "UTF-8")
            + "="
            + URLEncoder.encode(
                workspace,
                "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$

    return portalAccess(portalURL, data);
  }
 /**
  * Compiles a single source code unit.
  *
  * @param newRepo
  * @param source
  * @param baseDestination
  * @param mode
  * @param deferred
  * @param problemTracker
  * @throws CoreException
  */
 private boolean compileUnit(
     IRepository newRepo,
     final IFileStore source,
     int mode,
     IReferenceTracker refTracker,
     final IProblemTracker problemTracker,
     IProgressMonitor monitor)
     throws CoreException {
   if (monitor.isCanceled()) throw new OperationCanceledException();
   if (!source.fetchInfo().exists()) return false;
   Assert.isLegal(!source.fetchInfo().isDirectory());
   ICompiler compiler =
       findCompiler(source, newRepo.getProperties().getProperty(IRepository.DEFAULT_LANGUAGE));
   if (compiler == null) return false;
   // TODO need to provide a way for receiving the encoding to be used
   // (IResource has that)
   monitor.beginTask("Compiling " + source.toURI().getPath(), 1);
   Reader contents = null;
   try {
     contents =
         new InputStreamReader(
             new BufferedInputStream(source.openInputStream(EFS.NONE, null), 8192));
     compiler.compile(
         contents,
         new CompilationContext(
             refTracker,
             new LocalProblemTracker(problemTracker, source),
             newRepo,
             (mode & DEBUG) != 0));
   } catch (AbortedScopeCompilationException e) {
     // continue with next source unit
   } finally {
     if (contents != null)
       try {
         contents.close();
       } catch (IOException e) {
         // we don't care about these
       }
     monitor.done();
   }
   // we compiled this unit
   return true;
 }
  public static boolean openEditor(final UiAutomatorResult r) {
    final IFileStore fileStore =
        EFS.getLocalFileSystem().getStore(new Path(r.uiHierarchy.getAbsolutePath()));
    if (!fileStore.fetchInfo().exists()) {
      return false;
    }

    final AtomicBoolean status = new AtomicBoolean(false);

    final IWorkbench workbench = PlatformUI.getWorkbench();
    workbench
        .getDisplay()
        .syncExec(
            new Runnable() {
              @Override
              public void run() {
                IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
                if (window == null) {
                  return;
                }

                IWorkbenchPage page = window.getActivePage();
                if (page == null) {
                  return;
                }

                // try to switch perspectives if possible
                if (page.isEditorAreaVisible() == false && InstallDetails.isAdtInstalled()) {
                  try {
                    workbench.showPerspective(
                        "org.eclipse.jdt.ui.JavaPerspective", window); // $NON-NLS-1$
                  } catch (WorkbenchException e) {
                  }
                }

                IEditorPart editor = null;
                try {
                  editor = IDE.openEditorOnFileStore(page, fileStore);
                } catch (PartInitException e) {
                  return;
                }

                if (!(editor instanceof UiAutomatorViewer)) {
                  return;
                }

                ((UiAutomatorViewer) editor).setModel(r.model, r.uiHierarchy, r.screenshot);
                status.set(true);
              }
            });

    return status.get();
  }
  /** Checks whether the specified inclusion exists. */
  public boolean getInclusionExists(final String path) {
    if (UNCPathConverter.isUNC(path)) {
      try {
        IFileStore store = EFS.getStore(UNCPathConverter.getInstance().toURI(path));
        return store.fetchInfo().exists();
      } catch (CoreException e) {
        return false;
      }
    }

    return new File(path).exists();
  }
 protected void testFilesEqual(
     IFileStore root1, IFileStore root2, IFileStore file1, IFileStore file2) throws CoreException {
   String file1RelPath = EFSUtils.getRelativePath(root1, file1, null);
   String file2RelPath = EFSUtils.getRelativePath(root2, file2, null);
   assertEquals(
       MessageFormat.format("File {0} and {1} not equal", file1RelPath, file2RelPath),
       file1RelPath,
       file2RelPath);
   IFileInfo f1 = file1.fetchInfo(IExtendedFileStore.DETAILED, null);
   IFileInfo f2 = file2.fetchInfo(IExtendedFileStore.DETAILED, null);
   if (!f1.isDirectory()) {
     assertEquals(
         MessageFormat.format(
             "File {0} and {1} modification times differ", file1RelPath, file2RelPath),
         f1.getLastModified(),
         f2.getLastModified());
     assertEquals(
         MessageFormat.format("File {0} and {1} different sizes", file1RelPath, file2RelPath),
         f1.getLength(),
         f2.getLength());
   }
 }
  private void addChildrenHierarchy(
      ISemanticFileStore childStore,
      String rootURI,
      String[] parts,
      int index,
      IProgressMonitor monitor)
      throws CoreException {

    IFileStore child = childStore.getChild(parts[index]);

    if (parts.length > index + 1) {
      if (!child.fetchInfo().exists()) {
        this.addResource(childStore, parts[index], ResourceType.FOLDER_TYPE, monitor);
      }

      child = childStore.getChild(parts[index]);

      addChildrenHierarchy(
          (ISemanticFileStore) child,
          rootURI + "/" + parts[index],
          parts,
          index + 1,
          monitor); //$NON-NLS-1$
    } else {
      // create a file
      if (!child.fetchInfo().exists()) {
        super.addFileFromRemoteByURI(
            childStore,
            parts[index],
            URI.create(rootURI + "/" + parts[index]),
            monitor); //$NON-NLS-1$

        this.addDependentFiles(
            (ISemanticFileStore) childStore.getChild(parts[index]),
            rootURI + "/" + parts[index],
            monitor); //$NON-NLS-1$
      }
    }
  }
 public void testSetReadOnly() {
   IFileStore file = baseStore.getChild("file");
   ensureExists(file, false);
   IFileInfo info = EFS.createFileInfo();
   info.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true);
   try {
     file.putInfo(info, EFS.SET_ATTRIBUTES, getMonitor());
   } catch (CoreException e) {
     fail("1.99", e);
   }
   info = file.fetchInfo();
   assertEquals("1.0", true, info.getAttribute(EFS.ATTRIBUTE_READ_ONLY));
   assertEquals("1.1", file.getName(), info.getName());
 }
  // returns true if the request has been served, false if not (only if failEarlyOn404 is true)
  private boolean serveOrionFile(
      HttpServletRequest req,
      HttpServletResponse resp,
      IHostedSite site,
      IPath path,
      boolean failEarlyOn404)
      throws ServletException {
    String userName = site.getUserName();
    String workspaceId = site.getWorkspaceId();
    String workspaceUri = WORKSPACE_SERVLET_ALIAS + "/" + workspaceId; // $NON-NLS-1$
    boolean allow = false;
    // Check that user who launched the hosted site really has access to the workspace
    try {
      if (AuthorizationService.checkRights(userName, workspaceUri, "GET")) { // $NON-NLS-1$
        allow = true;
      }
    } catch (JSONException e) {
      throw new ServletException(e);
    }

    if (allow) {
      // FIXME: this code is copied from NewFileServlet, fix it
      // start copied
      String pathInfo = path.toString();
      IPath filePath = pathInfo == null ? Path.ROOT : new Path(pathInfo);
      IFileStore file = tempGetFileStore(filePath);
      if (file == null || !file.fetchInfo().exists()) {
        if (failEarlyOn404) {
          return false;
        }
        handleException(
            resp,
            new ServerStatus(IStatus.ERROR, 404, NLS.bind("File not found: {0}", filePath), null));
      }
      if (fileSerializer.handleRequest(req, resp, file)) {
        // return;
      }
      // end copied

      if (file != null) {
        addEditHeaders(resp, site, path);
        addContentTypeHeader(resp, path);
      }
    } else {
      String msg = NLS.bind("No rights to access {0}", workspaceUri);
      handleException(
          resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, msg, null));
    }
    return true;
  }
Beispiel #22
0
 /* (non-Javadoc)
  * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
  */
 @Override
 protected IStatus run(IProgressMonitor monitor) {
   if (monitor.isCanceled()) {
     return Status.CANCEL_STATUS;
   }
   IFileInfo fileInfo;
   try {
     fileInfo = fileStore.fetchInfo(options, monitor);
   } catch (CoreException e) {
     IOUIPlugin.logImportant(Messages.FetchFileInfoJob_FailedToFetch, e);
     return e.getStatus();
   }
   return new FetchFileInfoStatus(fileInfo);
 }
 /**
  * The limit is the maximum number of directories managed by this store. This number must be power
  * of 2 and do not exceed 256. The location should be an existing valid directory.
  */
 public BlobStore(IFileStore store, int limit) {
   Assert.isNotNull(store);
   localStore = store;
   Assert.isTrue(localStore.fetchInfo().isDirectory());
   Assert.isTrue(
       limit == 256
           || limit == 128
           || limit == 64
           || limit == 32
           || limit == 16
           || limit == 8
           || limit == 4
           || limit == 2
           || limit == 1);
   mask = (byte) (limit - 1);
 }
 private boolean handleGet(
     HttpServletRequest request, HttpServletResponse response, IFileStore dir)
     throws IOException, CoreException {
   URI location = getURI(request);
   JSONObject result = ServletFileStoreHandler.toJSON(dir, dir.fetchInfo(), location);
   String depthString = request.getParameter(ProtocolConstants.PARM_DEPTH);
   int depth = 0;
   if (depthString != null) {
     try {
       depth = Integer.parseInt(depthString);
     } catch (NumberFormatException e) {
       // ignore
     }
   }
   encodeChildren(dir, location, result, depth);
   OrionServlet.writeJSONResponse(request, response, result);
   return true;
 }
Beispiel #25
0
 /**
  * Grabs the list of {@link IBuildPathEntry}s for a project and make sure the indices for them are
  * up-to-date.
  *
  * @param monitor
  */
 private void indexProjectBuildPaths(IProgressMonitor monitor) {
   IProject project = getProjectHandle();
   Set<IBuildPathEntry> entries = getBuildPathManager().getBuildPaths(project);
   SubMonitor sub = SubMonitor.convert(monitor, entries.size());
   for (IBuildPathEntry entry : entries) {
     try {
       IFileStore fileStore = EFS.getStore(entry.getPath());
       if (fileStore != null) {
         if (fileStore.fetchInfo().isDirectory()) {
           new IndexContainerJob(entry.getDisplayName(), entry.getPath()).run(sub.newChild(1));
         } else {
           new IndexFileJob(entry.getDisplayName(), entry.getPath()).run(sub.newChild(1));
         }
       }
     } catch (Throwable e) {
       IdeLog.logError(BuildPathCorePlugin.getDefault(), e);
     }
   }
 }
 private int compileTree(
     IRepository newRepo,
     IFileStore store,
     IFileStore baseDestination,
     int mode,
     IProgressMonitor monitor,
     IReferenceTracker refTracker,
     IProblemTracker problems)
     throws CoreException {
   try {
     if (!store.fetchInfo().exists()) return 0;
     if (!store.fetchInfo().isDirectory()) {
       boolean compiled =
           compileUnit(
               newRepo,
               store,
               mode,
               refTracker,
               problems,
               new SubProgressMonitor(monitor, IProgressMonitor.UNKNOWN));
       return compiled ? 1 : 0;
     }
     IFileStore[] children = store.childStores(EFS.NONE, null);
     int compiledUnits = 0;
     for (int i = 0; i < children.length; i++)
       compiledUnits +=
           compileTree(
               newRepo,
               children[i],
               baseDestination,
               mode,
               new SubProgressMonitor(monitor, IProgressMonitor.UNKNOWN),
               refTracker,
               problems);
     return compiledUnits;
   } finally {
     monitor.done();
   }
 }
 private void encodeChildren(IFileStore dir, URI location, JSONObject result, int depth)
     throws CoreException {
   if (depth <= 0) return;
   JSONArray children = new JSONArray();
   IFileStore[] childStores = dir.childStores(EFS.NONE, null);
   for (IFileStore childStore : childStores) {
     IFileInfo childInfo = childStore.fetchInfo();
     String name = childInfo.getName();
     if (childInfo.isDirectory()) name += "/"; // $NON-NLS-1$
     URI childLocation = URIUtil.append(location, name);
     JSONObject childResult = ServletFileStoreHandler.toJSON(childStore, childInfo, childLocation);
     if (childInfo.isDirectory())
       encodeChildren(childStore, childLocation, childResult, depth - 1);
     children.put(childResult);
   }
   try {
     result.put(ProtocolConstants.KEY_CHILDREN, children);
   } catch (JSONException e) {
     // cannot happen
     throw new RuntimeException(e);
   }
 }
  /**
   * 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);
        }
      }
    }
  }
Beispiel #29
0
  /**
   * @see
   *     org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent)
   */
  public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);

    Spec spec = Activator.getSpecManager().getSpecLoaded();

    FileDialog openFileDialog = UIHelper.getFileDialog(window.getShell());
    openFileDialog.setText("Add TLA+ module to the spec");
    openFileDialog.setFilterPath(ResourceHelper.getParentDirName(spec.getRootFile()));

    openFileDialog.setFilterExtensions(ACCEPTED_EXTENSIONS);
    String moduleFileName = openFileDialog.open();
    if (moduleFileName != null) {
      IFile module = ResourceHelper.getLinkedFile(spec.getProject(), moduleFileName, false);

      // add .tla extension is the file does not have any extension
      if (module != null && module.getFileExtension() == null) {
        moduleFileName = ResourceHelper.getModuleFileName(moduleFileName);
        module = ResourceHelper.getLinkedFile(spec.getProject(), moduleFileName, false);
      }

      // check if it a TLA file
      if (!ResourceHelper.isModule(module)) {
        // selected non-TLA file
        // module exists and is already registered in the spec
        MessageDialog.openInformation(
            window.getShell(),
            "The selected file is not a TLA+ file",
            "The provided file "
                + module.getName()
                + " is not a TLA+ file.\n Please select a file with .tla extension.");
        return null;

      } else {
        if (module.isLinked()) {
          // module exists and is already registered in the spec
          MessageDialog.openInformation(
              window.getShell(),
              "TLA+ Module is part of the spec",
              "The provided module "
                  + module.getName()
                  + " has already been added to the specification previously.");
        } else {
          IPath modulePath = new Path(moduleFileName);
          // check the folder we are in
          if (!ResourceHelper.isProjectParent(
              modulePath.removeLastSegments(1), spec.getProject())) {
            // the selected resource is not in the same directory as
            // the root file
            MessageDialog.openInformation(
                window.getShell(),
                "TLA+ Module is not part of the current spec.",
                "The provided module "
                    + module.getName()
                    + " is not part of the spec which is currently open. It will therefore be opened in read-only mode.\n"
                    + "If you want to make changes to this file, you will have to open the corresponding spec first.");

            // Open TLA's read-only editor on a .tla file that does
            // *not* belong to the current spec. It is opened
            // read-only, because we want to allow any changes,
            // because we couldn't parse the spec anyway. The reason
            // why this functionality is offered, is to allow users
            // to look at .tla files of closed spec.
            // http://wiki.eclipse.org/FAQ_How_do_I_open_an_editor_on_a_file_outside_the_workspace%3F
            final IFileStore fileStore =
                EFS.getLocalFileSystem().getStore(new Path(moduleFileName));
            if (!fileStore.fetchInfo().isDirectory() && fileStore.fetchInfo().exists()) {
              UIHelper.openEditor(
                  "org.lamport.tla.toolbox.editor.basic.TLAEditorReadOnly",
                  new FileStoreEditorInput(fileStore));
            } else {
              throw new ExecutionException(
                  moduleFileName
                      + " cannot be opened in read-only mode because its file content could not be obtained.");
            }
            return null;
          }

          // !module.exists()
          if (!modulePath.toFile().exists()) {
            // the provided file does not exist
            boolean createNew =
                MessageDialog.openQuestion(
                    window.getShell(),
                    "TLA+ Module is not found",
                    "The provided module "
                        + module.getName()
                        + " does not exist. Should the new file be created?");
            if (createNew) {
              // the module point to a virtual path /WS_ROOT/SPEC_NAME/module_name.tla
              // assuming the fact that the root file is located in directory
              // /ROOT_DIR/SPEC_NAME.tla
              // and the Spec's project name is /ROOT_DIR/SPEC_NAME.project
              // the file should be created in /ROOT_DIR/module_name.tla and linked to the virtual
              // path.

              try {
                ResourcesPlugin.getWorkspace()
                    .run(ResourceHelper.createTLAModuleCreationOperation(modulePath), null);
              } catch (CoreException e) {
                e.printStackTrace();
                // exception, no chance to recover
                return null;
              }
            } else {
              return null;
            }
          }
          // adding the file to the spec
          module = createModuleFile(spec, moduleFileName, modulePath);
        }

        // create parameters for the handler
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put(
            OpenModuleHandler.PARAM_MODULE,
            ResourceHelper.getModuleNameChecked(module.getName(), false));

        // runs the command and opens the module in the editor
        UIHelper.runCommand(OpenModuleHandler.COMMAND_ID, parameters);
      }
    }

    return null;
  }
  @Override
  public boolean visit(final IResource resource) {
    if (resource == null || !resource.isAccessible()) {
      return false;
    }

    final URI resourceLocation = resource.getLocationURI();
    resourcename = resource.getName();
    if (resourcename == null || resourcename.startsWith(DOT)) {
      return false;
    }

    try {
      URI resolved = resource.getWorkspace().getPathVariableManager().resolveURI(resourceLocation);
      IFileStore store = EFS.getStore(resolved);
      IFileInfo fileInfo = store.fetchInfo();
      if (!fileInfo.exists()) {
        ErrorReporter.logError(
            "The resource `" + resource.getFullPath() + "' points to a non-existing location.");
        return false;
      }
    } catch (CoreException e) {
      ErrorReporter.logExceptionStackTrace(e);
      return false;
    }

    switch (resource.getType()) {
      case IResource.FILE:
        if (!ResourceExclusionHelper.isDirectlyExcluded((IFile) resource)
            && !helper.isExcludedByRegexp(resourcename)) {
          boolean inExcluded = false;
          IPath resourceFullPath = resource.getFullPath();
          for (int i = 0; i < excludedFolders.size(); i++) {
            IPath excludedFolder = excludedFolders.get(i);
            if (excludedFolder.isPrefixOf(resourceFullPath)) {
              inExcluded = true;
              break;
            }
          }

          IFile file = (IFile) resource;
          if (inExcluded) {
            excludedFiles.put(resource.getName(), file);
            return false;
          }

          boolean inCentralStorage = false;
          for (int i = 0; i < centralStorages.size(); i++) {
            URI centralFolder = centralStorages.get(i);
            if (centralFolder.getHost() == resourceLocation.getHost()
                && resourceLocation.getPath().startsWith(centralFolder.getPath())) {
              inCentralStorage = true;
              break;
            }
          }
          file = (IFile) resource;
          if (inCentralStorage) {
            if (file.getLocation() == null) {
              centralStorageFiles.put(file.getName(), file);
            } else {
              centralStorageFiles.put(file.getLocation().toOSString(), file);
            }
          } else {
            files.put(resourcename, file);
          }
        }
        return false;
      case IResource.FOLDER:
        for (IContainer workingDirectory : workingDirectories) {
          if (workingDirectory.equals(resource)) {
            return false;
          }
        }

        try {
          if (ResourceExclusionHelper.isDirectlyExcluded((IFolder) resource)
              || helper.isExcludedByRegexp(resourcename)) {
            excludedFolders.add(resource.getFullPath());
          }

          if (TRUE.equals(
              resource.getPersistentProperty(
                  new QualifiedName(
                      FolderBuildPropertyData.QUALIFIER,
                      FolderBuildPropertyData.CENTRAL_STORAGE_PROPERTY)))) {
            centralStorages.add(resourceLocation);
          }
        } catch (CoreException e) {
          return false;
        }
        break;
      default:
    }
    return true;
  }