Ejemplo n.º 1
0
  /**
   * @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;
  }
Ejemplo n.º 2
0
  /**
   * 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();
  }
 public UniversalUniqueIdentifier addBlob(IFileStore target, boolean moveContents)
     throws CoreException {
   UniversalUniqueIdentifier uuid = new UniversalUniqueIdentifier();
   folderFor(uuid).mkdir(EFS.NONE, null);
   IFileStore destination = fileFor(uuid);
   if (moveContents) target.move(destination, EFS.NONE, null);
   else target.copy(destination, EFS.NONE, null);
   return uuid;
 }
Ejemplo n.º 4
0
  // @formatter:on
  public void syncTest(boolean includeCloakedFiles, long sysTime)
      throws IOException, CoreException {
    String CLIENT_TEST = "client_test";
    String CLIENT_CONTROL = "client_control";
    String SERVER_LOCAL = "server_local";
    String SERVER_TEST = "server_test";
    int timeTolerance = 60000;

    IFileStore clientTestDirectory =
        clientDirectory.getFileStore(new Path("/" + CLIENT_TEST + sysTime));
    IFileStore clientControlDirectory =
        clientDirectory.getFileStore(new Path("/" + CLIENT_CONTROL + sysTime));
    IFileStore serverLocalDirectory =
        clientDirectory.getFileStore(new Path("/" + SERVER_LOCAL + sysTime));
    IFileStore serverTestDirectory =
        serverDirectory.getFileStore(new Path("/" + SERVER_TEST + sysTime));
    serverTestDirectory.mkdir(EFS.NONE, null);

    // clone version x of github-services to local directory (newer)
    System.out.println(
        "1) Writing github repo to " + EFSUtils.getAbsolutePath(clientTestDirectory));
    runGitClone(
        "git://github.com/DmitryBaranovskiy/raphael.git",
        clientDirectory,
        clientTestDirectory.getName());

    System.out.println(
        "2) Writing github repo to " + EFSUtils.getAbsolutePath(serverLocalDirectory));
    runGitClone(
        "git://github.com/DmitryBaranovskiy/raphael.git",
        clientDirectory,
        serverLocalDirectory.getName());

    // checkout specific tags
    System.out.println("Checking out tag v1.4.0 on client_test");
    runGitTag(clientTestDirectory, "v1.4.0");

    System.out.println("Checking out tag v1.3.0 on server_local");
    runGitTag(serverLocalDirectory, "v1.3.0");

    System.out.println(
        "3) Copying github repo to " + EFSUtils.getAbsolutePath(clientControlDirectory));
    clientTestDirectory.copy(clientControlDirectory, EFS.OVERWRITE, null);

    Synchronizer syncManager = new Synchronizer(true, timeTolerance, includeCloakedFiles);
    syncManager.setLogger(
        new ILogger() {

          public void logWarning(String message, Throwable th) {
            System.out.println(message);
          }

          public void logInfo(String message, Throwable th) {
            System.out.println(message);
          }

          public void logError(String message, Throwable th) {
            System.out.println(message);
          }
        });

    System.out.println("4) upload from server_local to server_test");
    VirtualFileSyncPair[] items =
        syncManager.getSyncItems(
            clientManager, serverManager, serverLocalDirectory, serverTestDirectory, null);
    syncManager.upload(items, null);

    System.out.println("5) ensure local version matches remote version");
    testDirectoriesEqual(
        serverLocalDirectory, serverTestDirectory, includeCloakedFiles, timeTolerance);

    System.out.println(
        "6) test to make sure client_test and client_control are identical, as nothing should have changed locally");
    testDirectoriesEqual(
        clientTestDirectory, clientControlDirectory, includeCloakedFiles, timeTolerance);

    // Now get sync items between local and remote directories
    System.out.println("7) sync between client_test and server_test, deleting on remote");
    VirtualFileSyncPair[] items2 =
        syncManager.getSyncItems(
            clientManager, serverManager, clientTestDirectory, serverTestDirectory, null);
    syncManager.uploadAndDelete(items2, null);

    System.out.println(
        "8) test to make sure client_test and client_control are identical, as nothing should have changed locally");
    testDirectoriesEqual(
        clientTestDirectory, clientControlDirectory, includeCloakedFiles, timeTolerance);

    System.out.println("9) test to make sure client_test and server_test are identical after sync");
    testDirectoriesEqual(
        clientTestDirectory, serverTestDirectory, includeCloakedFiles, timeTolerance);
  }
Ejemplo n.º 5
0
  public static void remoteFileDownload(
      ILaunchConfiguration config,
      ILaunch launch,
      String localExePath,
      String remoteExePath,
      IProgressMonitor monitor)
      throws CoreException {

    boolean skipDownload =
        config.getAttribute(
            IRemoteConnectionConfigurationConstants.ATTR_SKIP_DOWNLOAD_TO_TARGET, false);

    if (skipDownload)
      // Nothing to do. Download is skipped.
      return;
    monitor.beginTask(Messages.RemoteRunLaunchDelegate_2, 100);
    try {
      IRemoteConnection conn = getCurrentConnection(config);
      IRemoteFileService fs = conn.getService(IRemoteFileService.class);
      IFileStore remoteFile = fs.getResource(remoteExePath);

      IFileSystem localfs = EFS.getLocalFileSystem();
      IFileStore localFile = localfs.getStore(new Path(localExePath));

      if (!localFile.fetchInfo().exists()) {
        return;
      }
      localFile.copy(remoteFile, EFS.OVERWRITE, monitor);
      // Need to change the permissions to match the original file
      // permissions because of a bug in upload
      Process p =
          remoteShellExec(
              config,
              "",
              "chmod",
              "+x " + spaceEscapify(remoteExePath),
              new SubProgressMonitor(monitor, 5)); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

      // Wait if necessary for the permission change
      try {
        int timeOut = 10;
        boolean exited = p.waitFor(timeOut, TimeUnit.SECONDS);

        if (!exited) {
          Status status =
              new Status(
                  IStatus.ERROR,
                  Activator.PLUGIN_ID,
                  IStatus.ERROR,
                  "Failed to change file permissions in the remote system, path: "
                      + remoteExePath, //$NON-NLS-1$
                  null);
          throw new CoreException(status);
        }
      } catch (InterruptedException e) {
        Status status =
            new Status(
                IStatus.ERROR,
                Activator.PLUGIN_ID,
                IStatus.ERROR,
                "Interrupted while changing file permissions in the remote system, path: " //$NON-NLS-1$
                    + remoteExePath,
                e);
        throw new CoreException(status);
      }
    } catch (CoreException e) {
      abort(
          Messages.RemoteRunLaunchDelegate_6,
          e,
          ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
    } finally {
      monitor.done();
    }
  }
Ejemplo n.º 6
0
 /**
  * Perform a copy or move as specified by the request.
  *
  * @return <code>true</code> if the operation was successful, and <code>false</code> otherwise.
  */
 private boolean performCopyMove(
     HttpServletRequest request,
     HttpServletResponse response,
     JSONObject requestObject,
     IFileStore toCreate,
     boolean isCopy,
     int options)
     throws ServletException, CoreException {
   String locationString = requestObject.optString(ProtocolConstants.KEY_LOCATION, null);
   if (locationString == null) {
     statusHandler.handleRequest(
         request,
         response,
         new ServerStatus(
             IStatus.ERROR,
             HttpServletResponse.SC_BAD_REQUEST,
             "Copy or move request must specify source location",
             null));
     return false;
   }
   try {
     IFileStore source = resolveSourceLocation(request, locationString);
     if (source == null) {
       statusHandler.handleRequest(
           request,
           response,
           new ServerStatus(
               IStatus.ERROR,
               HttpServletResponse.SC_NOT_FOUND,
               NLS.bind("Source does not exist: ", locationString),
               null));
       return false;
     }
     boolean allowOverwrite = (options & CREATE_NO_OVERWRITE) == 0;
     int efsOptions = allowOverwrite ? EFS.OVERWRITE : EFS.NONE;
     try {
       if (isCopy) source.copy(toCreate, efsOptions, null);
       else source.move(toCreate, efsOptions, null);
     } catch (CoreException e) {
       if (!source.fetchInfo().exists()) {
         statusHandler.handleRequest(
             request,
             response,
             new ServerStatus(
                 IStatus.ERROR,
                 HttpServletResponse.SC_NOT_FOUND,
                 NLS.bind("Source does not exist: ", locationString),
                 e));
         return false;
       }
       if (e.getStatus().getCode() == EFS.ERROR_EXISTS) {
         statusHandler.handleRequest(
             request,
             response,
             new ServerStatus(
                 IStatus.ERROR,
                 HttpServletResponse.SC_PRECONDITION_FAILED,
                 "A file or folder with the same name already exists at this location",
                 null));
         return false;
       }
       // just rethrow if we can't do something more specific
       throw e;
     }
   } catch (URISyntaxException e) {
     statusHandler.handleRequest(
         request,
         response,
         new ServerStatus(
             IStatus.ERROR,
             HttpServletResponse.SC_BAD_REQUEST,
             NLS.bind("Bad source location in request: ", locationString),
             e));
     return false;
   }
   return true;
 }
  @Override
  public void launch(
      ILaunchConfiguration config, String mode, ILaunch launch, IProgressMonitor monitor)
      throws CoreException {
    try {
      ConfigUtils configUtils = new ConfigUtils(config);
      project = configUtils.getProject();
      // check if Perf exists in $PATH
      if (!PerfCore.checkPerfInPath(project)) {
        IStatus status =
            new Status(
                IStatus.ERROR,
                PerfPlugin.PLUGIN_ID,
                "Error: Perf was not found on PATH"); //$NON-NLS-1$
        throw new CoreException(status);
      }
      URI binURI = new URI(configUtils.getExecutablePath());
      binPath = Path.fromPortableString(binURI.toString());
      workingDirPath =
          Path.fromPortableString(
              Path.fromPortableString(binURI.toString()).removeLastSegments(2).toPortableString());
      PerfPlugin.getDefault().setWorkingDir(workingDirPath);
      if (config.getAttribute(PerfPlugin.ATTR_ShowStat, PerfPlugin.ATTR_ShowStat_default)) {
        showStat(config, launch);
      } else {
        URI exeURI = new URI(configUtils.getExecutablePath());
        String configWorkingDir = configUtils.getWorkingDirectory() + IPath.SEPARATOR;
        RemoteConnection exeRC = new RemoteConnection(exeURI);
        String perfPathString =
            RuntimeProcessFactory.getFactory().whichCommand(PerfPlugin.PERF_COMMAND, project);
        boolean copyExecutable = configUtils.getCopyExecutable();
        if (copyExecutable) {
          URI copyExeURI = new URI(configUtils.getCopyFromExecutablePath());
          RemoteConnection copyExeRC = new RemoteConnection(copyExeURI);
          IRemoteFileProxy copyExeRFP = copyExeRC.getRmtFileProxy();
          IFileStore copyExeFS = copyExeRFP.getResource(copyExeURI.getPath());
          IRemoteFileProxy exeRFP = exeRC.getRmtFileProxy();
          IFileStore exeFS = exeRFP.getResource(exeURI.getPath());
          IFileInfo exeFI = exeFS.fetchInfo();
          if (exeFI.isDirectory()) {
            // Assume the user wants to copy the file to the given directory, using
            // the same filename as the "copy from" executable.
            IPath copyExePath = Path.fromOSString(copyExeURI.getPath());
            IPath newExePath =
                Path.fromOSString(exeURI.getPath()).append(copyExePath.lastSegment());
            // update the exeURI with the new path.
            exeURI =
                new URI(
                    exeURI.getScheme(),
                    exeURI.getAuthority(),
                    newExePath.toString(),
                    exeURI.getQuery(),
                    exeURI.getFragment());
            exeFS = exeRFP.getResource(exeURI.getPath());
          }
          copyExeFS.copy(exeFS, EFS.OVERWRITE | EFS.SHALLOW, new SubProgressMonitor(monitor, 1));
          // Note: assume that we don't need to create a new exeRC since the
          // scheme and authority remain the same between the original exeURI and the new one.
        }
        IPath remoteBinFile = Path.fromOSString(exeURI.getPath());
        IFileStore workingDir;
        URI workingDirURI =
            new URI(RemoteProxyManager.getInstance().getRemoteProjectLocation(project));
        RemoteConnection workingDirRC = new RemoteConnection(workingDirURI);
        IRemoteFileProxy workingDirRFP = workingDirRC.getRmtFileProxy();
        workingDir = workingDirRFP.getResource(workingDirURI.getPath());
        // Build the commandline string to run perf recording the given project
        String arguments[] = getProgramArgumentsArray(config); // Program args from launch config.
        ArrayList<String> command = new ArrayList<>(4 + arguments.length);
        Version perfVersion = PerfCore.getPerfVersion(config);
        command.addAll(
            Arrays.asList(
                PerfCore.getRecordString(
                    config,
                    perfVersion))); // Get the base commandline string (with flags/options based on
                                    // config)
        command.add(remoteBinFile.toOSString()); // Add the path to the executable
        command.set(0, perfPathString);
        command.add(2, OUTPUT_STR + configWorkingDir + PerfPlugin.PERF_DEFAULT_DATA);
        // Compile string
        command.addAll(Arrays.asList(arguments));

        // Spawn the process
        String[] commandArray = command.toArray(new String[command.size()]);
        Process pProxy =
            RuntimeProcessFactory.getFactory()
                .exec(commandArray, getEnvironment(config), workingDir, project);
        MessageConsole console = new MessageConsole("Perf Console", null); // $NON-NLS-1$
        console.activate();
        ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] {console});
        MessageConsoleStream stream = console.newMessageStream();

        if (pProxy != null) {
          try (BufferedReader error =
              new BufferedReader(new InputStreamReader(pProxy.getErrorStream()))) {
            String err = error.readLine();
            while (err != null) {
              stream.println(err);
              err = error.readLine();
            }
          }
        }

        /* This commented part is the basic method to run perf record without integrating into eclipse.
        String binCall = exePath.toOSString();
        for(String arg : arguments) {
            binCall.concat(" " + arg);
        }
        PerfCore.Run(binCall);*/

        pProxy.destroy();
        PrintStream print = null;
        if (config.getAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true)) {
          // Get the console to output to.
          // This may not be the best way to accomplish this but it shall do for now.
          ConsolePlugin plugin = ConsolePlugin.getDefault();
          IConsoleManager conMan = plugin.getConsoleManager();
          IConsole[] existing = conMan.getConsoles();
          IOConsole binaryOutCons = null;

          // Find the console
          for (IConsole x : existing) {
            if (x.getName().contains(renderProcessLabel(commandArray[0]))) {
              binaryOutCons = (IOConsole) x;
            }
          }
          if ((binaryOutCons == null)
              && (existing.length
                  != 0)) { // if can't be found get the most recent opened, this should probably
                           // never happen.
            if (existing[existing.length - 1] instanceof IOConsole)
              binaryOutCons = (IOConsole) existing[existing.length - 1];
          }

          // Get the printstream via the outputstream.
          // Get ouput stream
          OutputStream outputTo;
          if (binaryOutCons != null) {
            outputTo = binaryOutCons.newOutputStream();
            // Get the printstream for that console
            print = new PrintStream(outputTo);
          }

          for (int i = 0; i < command.size(); i++) {
            print.print(command.get(i) + " "); // $NON-NLS-1$
          }

          // Print Message
          print.println();
          print.println("Analysing recorded perf.data, please wait..."); // $NON-NLS-1$
          // Possibly should pass this (the console reference) on to PerfCore.Report if theres
          // anything we ever want to spit out to user.
        }
        PerfCore.report(
            config,
            getEnvironment(config),
            Path.fromOSString(configWorkingDir),
            monitor,
            null,
            print);

        URI perfDataURI = null;
        IRemoteFileProxy proxy = null;
        perfDataURI =
            new URI(
                RemoteProxyManager.getInstance().getRemoteProjectLocation(project)
                    + PerfPlugin.PERF_DEFAULT_DATA);
        proxy = RemoteProxyManager.getInstance().getFileProxy(perfDataURI);
        IFileStore perfDataFileStore = proxy.getResource(perfDataURI.getPath());
        IFileInfo info = perfDataFileStore.fetchInfo();
        info.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true);
        perfDataFileStore.putInfo(info, EFS.SET_ATTRIBUTES, null);

        PerfCore.refreshView(renderProcessLabel(exeURI.getPath()));
        if (config.getAttribute(
            PerfPlugin.ATTR_ShowSourceDisassembly, PerfPlugin.ATTR_ShowSourceDisassembly_default)) {
          showSourceDisassembly(
              Path.fromPortableString(workingDirURI.toString() + IPath.SEPARATOR));
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
      abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
    } catch (RemoteConnectionException e) {
      e.printStackTrace();
      abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
    } catch (URISyntaxException e) {
      e.printStackTrace();
      abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
    }
  }