예제 #1
0
 private List<String> createChanges(final TextFileChange change, final SubMonitor progress)
     throws BadLocationException {
   final List<String> names = new ArrayList<String>();
   int remaining = fVariablesList.size() + 3;
   progress.setWorkRemaining(remaining);
   remaining -= 3;
   fSourceUnit.connect(progress.newChild(2));
   try {
     for (final Map<String, Variable> frameList : fVariablesList.values()) {
       progress.setWorkRemaining(remaining--);
       createMainChanges(frameList, change, names);
     }
     return names;
   } finally {
     fSourceUnit.disconnect(progress.newChild(1));
   }
 }
예제 #2
0
  void perform(
      MultiStatus status, EngineSession session, Operand[] operands, IProgressMonitor monitor) {
    SubMonitor subMonitor =
        SubMonitor.convert(monitor, prePerformWork + mainPerformWork + postPerformWork);
    session.recordPhaseEnter(this);
    prePerform(status, session, subMonitor.newChild(prePerformWork));
    if (status.matches(IStatus.ERROR | IStatus.CANCEL)) return;
    session.recordPhaseStart(this);

    subMonitor.setWorkRemaining(mainPerformWork + postPerformWork);
    mainPerform(status, session, operands, subMonitor.newChild(mainPerformWork));
    if (status.matches(IStatus.ERROR | IStatus.CANCEL)) return;

    session.recordPhaseEnd(this);
    subMonitor.setWorkRemaining(postPerformWork);
    postPerform(status, session, subMonitor.newChild(postPerformWork));
    phaseParameters.clear();
    if (status.matches(IStatus.ERROR | IStatus.CANCEL)) return;
    session.recordPhaseExit(this);
    subMonitor.done();
  }
예제 #3
0
  /**
   * Pre-loads all class binary data that belong to the given package by reading the archive once
   * and caching them internally.
   *
   * <p>This does not actually preload "classes", it just reads the unzipped bytes for a given
   * class. To obtain a class, one must call {@link #findClass(String)} later.
   *
   * <p>All classes which package name starts with "packageFilter" will be included and can be found
   * later.
   *
   * <p>May throw some exceptions if the framework JAR cannot be read.
   *
   * @param packageFilter The package that contains all the class data to preload, using a fully
   *     qualified binary name (.e.g "com.my.package."). The matching algorithm is simple
   *     "startsWith". Use an empty string to include everything.
   * @param taskLabel An optional task name for the sub monitor. Can be null.
   * @param monitor A progress monitor. Can be null. Caller is responsible for calling done.
   * @throws IOException
   * @throws InvalidAttributeValueException
   * @throws ClassFormatError
   */
  public void preLoadClasses(String packageFilter, String taskLabel, IProgressMonitor monitor)
      throws IOException, InvalidAttributeValueException, ClassFormatError {
    // Transform the package name into a zip entry path
    String pathFilter = packageFilter.replaceAll("\\.", "/"); // $NON-NLS-1$ //$NON-NLS-2$

    SubMonitor progress = SubMonitor.convert(monitor, taskLabel == null ? "" : taskLabel, 100);

    // create streams to read the intermediary archive
    FileInputStream fis = new FileInputStream(mOsFrameworkLocation);
    ZipInputStream zis = new ZipInputStream(fis);
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
      // get the name of the entry.
      String entryPath = entry.getName();

      if (!entryPath.endsWith(AdtConstants.DOT_CLASS)) {
        // only accept class files
        continue;
      }

      // check if it is part of the package to preload
      if (pathFilter.length() > 0 && !entryPath.startsWith(pathFilter)) {
        continue;
      }
      String className = entryPathToClassName(entryPath);

      if (!mEntryCache.containsKey(className)) {
        long entrySize = entry.getSize();
        if (entrySize > Integer.MAX_VALUE) {
          throw new InvalidAttributeValueException();
        }
        byte[] data = readZipData(zis, (int) entrySize);
        mEntryCache.put(className, data);
      }

      // advance 5% of whatever is allocated on the progress bar
      progress.setWorkRemaining(100);
      progress.worked(5);
      progress.subTask(String.format("Preload %1$s", className));
    }
  }
예제 #4
0
  /*
   * Read the database values for a build name and a list of scenarios.
   * The database is read only if the components does not already knows the
   * given build (i.e. if it has not been already read) or if the force arguments is set.
   */
  void updateBuild(
      String buildName,
      List scenarios,
      boolean force,
      File dataDir,
      SubMonitor subMonitor,
      PerformanceResults.RemainingTimeGuess timeGuess) {

    // Read all variations
    println("Component '" + this.name + "':"); // $NON-NLS-1$ //$NON-NLS-2$

    // manage monitor
    int size = scenarios.size();
    subMonitor.setWorkRemaining(size + 1);
    StringBuffer buffer = new StringBuffer("Component "); // $NON-NLS-1$
    buffer.append(this.name);
    buffer.append("..."); // $NON-NLS-1$
    String title = buffer.toString();
    subMonitor.subTask(title + timeGuess.display());
    timeGuess.count++;
    subMonitor.worked(1);
    if (subMonitor.isCanceled()) return;

    // Read new values for the local result
    boolean dirty = false;
    long readTime = System.currentTimeMillis();
    String log = " - read scenarios from DB:"; // $NON-NLS-1$
    if (size > 0) {
      for (int i = 0; i < size; i++) {

        // manage monitor
        subMonitor.subTask(title + timeGuess.display());
        timeGuess.count++;
        if (log != null) {
          println(log);
          log = null;
        }

        // read results
        ScenarioResults nextScenarioResults = (ScenarioResults) scenarios.get(i);
        ScenarioResults scenarioResults = (ScenarioResults) getResults(nextScenarioResults.id);
        if (scenarioResults == null) {
          // Scenario is not known yet, force an update
          scenarioResults = nextScenarioResults;
          scenarioResults.parent = this;
          scenarioResults.printStream = this.printStream;
          scenarioResults.updateBuild(buildName, true);
          dirty = true;
          addChild(scenarioResults, true);
        } else {
          if (scenarioResults.updateBuild(buildName, force)) {
            dirty = true;
          }
        }
        if (dataDir != null
            && dirty
            && (System.currentTimeMillis() - readTime) > 300000) { // save every 5mn
          writeData(buildName, dataDir, true, true);
          dirty = false;
          readTime = System.currentTimeMillis();
        }

        // manage monitor
        subMonitor.worked(1);
        if (subMonitor.isCanceled()) return;
      }
    }

    // Write local files
    if (dataDir != null) {
      writeData(buildName, dataDir, false, dirty);
    }

    // Print global time
    printGlobalTime(readTime);
  }
예제 #5
0
  /**
   * Finds the differences among three <code>IRangeComparator</code>s. The differences are returned
   * as a list of <code>RangeDifference</code>s. If no differences are detected an empty list is
   * returned. If the ancestor range comparator is <code>null</code>, a two-way comparison is
   * performed.
   *
   * @param pm if not <code>null</code> used to report progress
   * @param ancestor the ancestor range comparator or <code>null</code>
   * @param left the left range comparator
   * @param right the right range comparator
   * @return an array of range differences, or an empty array if no differences were found
   * @since 2.0
   */
  public static RangeDifference[] findDifferences(
      IProgressMonitor pm,
      LCSSettings settings,
      IRangeComparator ancestor,
      IRangeComparator left,
      IRangeComparator right) {
    try {
      if (ancestor == null) return findDifferences(pm, settings, left, right);
      SubMonitor monitor = SubMonitor.convert(pm, CompareMessages.RangeComparatorLCS_0, 100);
      RangeDifference[] leftAncestorScript = null;
      RangeDifference[] rightAncestorScript =
          findDifferences(monitor.newChild(50), settings, ancestor, right);
      if (rightAncestorScript != null) {
        monitor.setWorkRemaining(100);
        leftAncestorScript = findDifferences(monitor.newChild(50), settings, ancestor, left);
      }
      if (rightAncestorScript == null || leftAncestorScript == null) return null;

      DifferencesIterator myIter = new DifferencesIterator(rightAncestorScript);
      DifferencesIterator yourIter = new DifferencesIterator(leftAncestorScript);

      List diff3 = new ArrayList();
      diff3.add(new RangeDifference(RangeDifference.ERROR)); // add a
      // sentinel

      int changeRangeStart = 0;
      int changeRangeEnd = 0;
      //
      // Combine the two two-way edit scripts into one
      //
      monitor.setWorkRemaining(rightAncestorScript.length + leftAncestorScript.length);
      while (myIter.fDifference != null || yourIter.fDifference != null) {

        DifferencesIterator startThread;
        myIter.removeAll();
        yourIter.removeAll();
        //
        // take the next diff that is closer to the start
        //
        if (myIter.fDifference == null) startThread = yourIter;
        else if (yourIter.fDifference == null) startThread = myIter;
        else { // not at end of both scripts take the lowest range
          if (myIter.fDifference.fLeftStart <= yourIter.fDifference.fLeftStart) // 2
            // ->
            // common
            // (Ancestor)
            // change
            // range
            startThread = myIter;
          else startThread = yourIter;
        }
        changeRangeStart = startThread.fDifference.fLeftStart;
        changeRangeEnd = startThread.fDifference.leftEnd();

        startThread.next();
        monitor.worked(1);
        //
        // check for overlapping changes with other thread
        // merge overlapping changes with this range
        //
        DifferencesIterator other = startThread.other(myIter, yourIter);
        while (other.fDifference != null && other.fDifference.fLeftStart <= changeRangeEnd) {
          int newMax = other.fDifference.leftEnd();
          other.next();
          monitor.worked(1);
          if (newMax >= changeRangeEnd) {
            changeRangeEnd = newMax;
            other = other.other(myIter, yourIter);
          }
        }
        diff3.add(
            createRangeDifference3(
                myIter, yourIter, diff3, right, left, changeRangeStart, changeRangeEnd));
      }

      // remove sentinel
      diff3.remove(0);
      return (RangeDifference[]) diff3.toArray(EMPTY_RESULT);
    } finally {
      if (pm != null) pm.done();
    }
  }
예제 #6
0
  private void mainPerform(
      MultiStatus status, EngineSession session, Operand[] operands, SubMonitor subMonitor) {
    IProfile profile = session.getProfile();
    subMonitor.beginTask(null, operands.length);
    for (int i = 0; i < operands.length; i++) {
      subMonitor.setWorkRemaining(operands.length - i);
      if (subMonitor.isCanceled()) throw new OperationCanceledException();
      Operand operand = operands[i];
      if (!isApplicable(operand)) continue;

      session.recordOperandStart(operand);
      List<ProvisioningAction> actions = getActions(operand);
      operandParameters = new HashMap<String, Object>(phaseParameters);
      operandParameters.put(PARM_OPERAND, operand);
      mergeStatus(status, initializeOperand(profile, operand, operandParameters, subMonitor));
      if (status.matches(IStatus.ERROR | IStatus.CANCEL)) {
        operandParameters = null;
        return;
      }

      Touchpoint operandTouchpoint = (Touchpoint) operandParameters.get(PARM_TOUCHPOINT);
      if (operandTouchpoint != null) {
        mergeStatus(
            status,
            initializeTouchpointParameters(profile, operand, operandTouchpoint, subMonitor));
        if (status.matches(IStatus.ERROR | IStatus.CANCEL)) return;

        operandParameters = touchpointToTouchpointOperandParameters.get(operandTouchpoint);
      }

      operandParameters = Collections.unmodifiableMap(operandParameters);
      if (actions != null) {
        for (int j = 0; j < actions.size(); j++) {
          ProvisioningAction action = actions.get(j);
          Map<String, Object> parameters = operandParameters;
          Touchpoint touchpoint = action.getTouchpoint();
          if (touchpoint != null) {
            mergeStatus(
                status, initializeTouchpointParameters(profile, operand, touchpoint, subMonitor));
            if (status.matches(IStatus.ERROR | IStatus.CANCEL)) return;

            parameters = touchpointToTouchpointOperandParameters.get(touchpoint);
          }
          IStatus actionStatus = null;
          try {
            session.recordActionExecute(action, parameters);
            actionStatus = action.execute(parameters);
          } catch (RuntimeException e) {
            if (!forced) throw e;
            // "action.execute" calls user code and might throw an unchecked exception
            // we catch the error here to gather information on where the problem occurred.
            actionStatus =
                new Status(
                    IStatus.ERROR,
                    EngineActivator.ID,
                    NLS.bind(Messages.forced_action_execute_error, action.getClass().getName()),
                    e);
          } catch (LinkageError e) {
            if (!forced) throw e;
            // Catch linkage errors as these are generally recoverable but let other Errors
            // propagate (see bug 222001)
            actionStatus =
                new Status(
                    IStatus.ERROR,
                    EngineActivator.ID,
                    NLS.bind(Messages.forced_action_execute_error, action.getClass().getName()),
                    e);
          }
          if (forced && actionStatus != null && actionStatus.matches(IStatus.ERROR)) {
            MultiStatus result =
                new MultiStatus(EngineActivator.ID, IStatus.ERROR, getProblemMessage(), null);
            result.add(
                new Status(
                    IStatus.ERROR,
                    EngineActivator.ID,
                    session.getContextString(this, operand, action),
                    null));
            LogHelper.log(result);
            actionStatus = Status.OK_STATUS;
          }
          mergeStatus(status, actionStatus);
          if (status.matches(IStatus.ERROR | IStatus.CANCEL)) return;
        }
      }
      mergeStatus(
          status, touchpointCompleteOperand(profile, operand, operandParameters, subMonitor));
      mergeStatus(status, completeOperand(profile, operand, operandParameters, subMonitor));
      if (status.matches(IStatus.ERROR | IStatus.CANCEL)) return;
      operandParameters = null;
      session.recordOperandEnd(operand);
      subMonitor.worked(1);
    }
  }
예제 #7
0
  @Override
  protected IStatus run(IProgressMonitor mon) {
    SubMonitor monitor = SubMonitor.convert(mon, 100);
    final ITernServer server = project.getTernServer();
    do {
      if (mon.isCanceled()) {
        return Status.CANCEL_STATUS;
      }
      int i = 0;
      final TernDoc doc = new TernDoc();
      synchronized (files) {
        monitor.setWorkRemaining(files.size() + 1);
        Iterator<Entry<String, TernFile>> it = files.entrySet().iterator();
        while (i < MAX_FILES && it.hasNext()) {
          Entry<String, TernFile> entry = it.next();
          it.remove();
          doc.addFile(entry.getValue());
          i++;
        }
      }
      if (!doc.hasFiles()) {
        break;
      }
      if (server != null) {
        try {
          server.request(
              doc,
              new IResponseHandler() {

                @Override
                public void onSuccess(Object data, String dataAsJsonString) {}

                @Override
                public void onError(String error, Throwable t) {
                  project.handleException(new TernException(error, t));
                  // mark that files have not been uploaded correctly
                  project.getFileSynchronizer().uploadFailed(doc);
                  throw new UploadFailed();
                }

                @Override
                public boolean isDataAsJsonString() {
                  return false;
                }
              });
          monitor.worked(i);
        } catch (UploadFailed ex) {
          synchronized (files) {
            TernDoc doc2 = new TernDoc();
            for (TernFile tf : files.values()) {
              doc2.addFile(tf);
            }
            files.clear();
            project.getFileSynchronizer().uploadFailed(doc2);
            cancel();
          }
          return Status.CANCEL_STATUS;
        }
      }
    } while (!serverToBeDisposed);
    return Status.OK_STATUS;
  }
    @Override
    public void run(IProgressMonitor progress) throws InvocationTargetException {
      SubMonitor monitor = SubMonitor.convert(progress, 3);
      monitor.setTaskName("Loading Templates...");
      try {
        final Set<Template> templates = new LinkedHashSet<>();
        final List<String> errors = new LinkedList<>();

        // Load from workspace, if one exists
        Workspace ws = Central.getWorkspaceIfPresent();
        if (ws != null) {
          List<Repository> repos = ws.getPlugins(Repository.class);
          RepoPluginsBundleLocator locator = new RepoPluginsBundleLocator(ws.getRepositories());
          templates.addAll(
              new ReposTemplateLoader(repos, locator)
                  .findTemplates(
                      templateType, errors, monitor.newChild(1, SubMonitor.SUPPRESS_NONE)));
        }

        // Load from the preferences-configured template repository
        BndPreferences bndPrefs = new BndPreferences();
        if (bndPrefs.getEnableTemplateRepo()) {
          try {
            FixedIndexedRepo repo = loadRepo(bndPrefs.getTemplateRepoUriList());
            RepoPluginsBundleLocator locator =
                new RepoPluginsBundleLocator(Collections.<RepositoryPlugin>singletonList(repo));
            ReposTemplateLoader loader =
                new ReposTemplateLoader(Collections.<Repository>singletonList(repo), locator);
            templates.addAll(
                loader.findTemplates(
                    templateType, errors, monitor.newChild(1, SubMonitor.SUPPRESS_NONE)));
          } catch (Exception e) {
            throw new InvocationTargetException(e);
          }
        }

        // Log errors
        for (String error : errors) {
          Plugin.getDefault()
              .getLog()
              .log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, error, null));
        }

        // Add the build-in empty template if provided
        if (emptyTemplate != null) templates.add(emptyTemplate);

        // Load from extension registry
        if (templateExtPoint != null) {
          IConfigurationElement[] elements =
              Platform.getExtensionRegistry()
                  .getConfigurationElementsFor(Plugin.PLUGIN_ID, templateExtPoint);
          if (elements == null) elements = new IConfigurationElement[0];
          monitor.setWorkRemaining(elements.length);

          for (IConfigurationElement element : elements) {
            String elementName = element.getName();
            IContributor contributor = element.getContributor();
            try {
              Template extTemplate = (Template) element.createExecutableExtension("class");
              templates.add(extTemplate);
            } catch (CoreException e) {
              Plugin.getDefault()
                  .getLog()
                  .log(
                      new Status(
                          IStatus.ERROR,
                          Plugin.PLUGIN_ID,
                          0,
                          String.format(
                              "Error loading template '%s' from bundle %s",
                              elementName, contributor.getName()),
                          e));
            } finally {
              monitor.worked(1);
            }
          }
        }

        // Display results
        Control control = viewer.getControl();
        if (control != null && !control.isDisposed()) {
          control
              .getDisplay()
              .asyncExec(
                  new Runnable() {
                    @Override
                    public void run() {
                      setTemplates(templates);
                      IconLoaderJob iconLoaderJob =
                          new IconLoaderJob(templates, viewer, loadedImages, 5);
                      iconLoaderJob.setSystem(true);
                      iconLoaderJob.schedule(0);
                    }
                  });
        }

      } finally {
        monitor.done();
        // Restore the original message to the page
        if (!shell.isDisposed())
          shell
              .getDisplay()
              .asyncExec(
                  new Runnable() {
                    @Override
                    public void run() {
                      setMessage(originalMessage);
                    }
                  });
      }
    }
  private IStatus updateRServerList(final String combined, final IProgressMonitor monitor) {
    final List<RemoteR> infos = new ArrayList<>();

    final String[] addresses = ADDRESS_MULTI_PATTERN.split(combined, -1);
    if (addresses.length == 0) {
      return null;
    }
    final SubMonitor progress =
        SubMonitor.convert(
            monitor,
            Messages.RRemoteConsoleSelectionDialog_task_Gathering_message,
            addresses.length * 2 + 2);

    String failedHosts = null;
    final List<IStatus> failedStatus = new ArrayList<>();
    progress.worked(1);

    // Collect R engines for each address
    for (int i = 0; i < addresses.length; i++) {
      progress.setWorkRemaining((addresses.length - i) * 2 + 1);

      String address = addresses[i];
      final SpecialAddress special = fSpecialAddress.get(address);
      if (special == null) {
        if (address.startsWith("rmi:")) { // $NON-NLS-1$
          address = address.substring(4);
        }
        if (address.startsWith("//")) { // $NON-NLS-1$
          address = address.substring(2);
        }
      }
      if (address.isEmpty()) {
        return null;
      }
      if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
      }
      IStatus status;
      if (special == null) {
        final Matcher matcher = ADDRESS_WITH_PORT_PATTERN.matcher(address);
        if (matcher.matches()) {
          status =
              collectServerInfos(
                  matcher.group(1), Integer.parseInt(matcher.group(2)), null, infos, progress);
        } else {
          status = collectServerInfos(address, Registry.REGISTRY_PORT, null, infos, progress);
        }
      } else {
        address = special.fPublicHost;
        status = collectServerInfos(null, 0, special, infos, progress);
      }
      switch (status.getSeverity()) {
        case IStatus.CANCEL:
          return status;
        case IStatus.ERROR:
          StatusManager.getManager().handle(status, StatusManager.LOG);
          return status;
        case IStatus.WARNING:
          failedStatus.add(status);
          failedHosts =
              (failedHosts == null) ? address : (failedHosts + ", " + address); // $NON-NLS-1$
          continue;
        default:
          continue;
      }
    }

    if (!failedStatus.isEmpty()) {
      StatusManager.getManager()
          .handle(
              new MultiStatus(
                  RConsoleUIPlugin.PLUGIN_ID,
                  0,
                  failedStatus.toArray(new IStatus[failedStatus.size()]),
                  "Info about connection failures when browsing R engines:",
                  null), //$NON-NLS-1$
              StatusManager.LOG);
    }
    if (!infos.isEmpty() || failedStatus.isEmpty()) {
      fRServerList = infos;
    }

    if (failedHosts != null) {
      return new Status(
          IStatus.WARNING,
          RConsoleUIPlugin.PLUGIN_ID,
          Messages.RRemoteConsoleSelectionDialog_error_ConnectionFailed_message + failedHosts);
    }
    return Status.OK_STATUS;
  }
예제 #10
0
  private void indexQueuedTasks(SubMonitor monitor)
      throws CorruptIndexException, LockObtainFailedException, IOException, CoreException {

    synchronized (reindexQueue) {
      if (reindexQueue.isEmpty()) {
        return;
      }

      monitor.beginTask(Messages.TaskListIndex_task_rebuilding_index, reindexQueue.size());
    }

    try {
      IndexWriter writer = null;
      try {
        Map<ITask, TaskData> workingQueue = new HashMap<ITask, TaskData>();

        // reindex tasks that are in the reindexQueue, making multiple passes so that we catch
        // anything
        // added/changed while we were reindexing
        for (; ; ) {
          workingQueue.clear();

          synchronized (reindexQueue) {
            if (reindexQueue.isEmpty()) {
              break;
            }
            // move items from the reindexQueue to the temporary working queue
            workingQueue.putAll(reindexQueue);
            reindexQueue.keySet().removeAll(workingQueue.keySet());
          }

          if (writer == null) {
            try {
              writer = createIndexWriter(false);
            } catch (CorruptIndexException e) {
              rebuildIndex = true;
              synchronized (reindexQueue) {
                reindexQueue.clear();
              }
              rebuildIndexCompletely(monitor);
              return;
            }
          }

          monitor.setWorkRemaining(workingQueue.size());

          for (Entry<ITask, TaskData> entry : workingQueue.entrySet()) {
            ITask task = entry.getKey();
            TaskData taskData = entry.getValue();

            writer.deleteDocuments(
                new Term(FIELD_IDENTIFIER.getIndexKey(), task.getHandleIdentifier()));

            add(writer, task, taskData);

            monitor.worked(1);
          }
        }
      } finally {
        if (writer != null) {
          writer.close();
        }
      }
    } finally {
      monitor.done();
    }
  }
  /**
   * @see
   *     org.eclipse.debug.core.model.ILaunchConfigurationDelegate#launch(org.eclipse.debug.core.ILaunchConfiguration,
   *     java.lang.String, org.eclipse.debug.core.ILaunch,
   *     org.eclipse.core.runtime.IProgressMonitor)
   */
  @Override
  public void launch(
      ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
      throws CoreException {
    SubMonitor submonitor = SubMonitor.convert(monitor, 13);
    try {
      // wait RSE is initialized
      // TODO not sure this is the good way to wait for init everywhere in the code
      RSEUtil.waitForRSEInitialization();

      // get configuration information
      String projectName =
          configuration.getAttribute(LuaRemoteDebugConstant.PROJECT_NAME, ""); // $NON-NLS-1$
      String scriptName =
          configuration.getAttribute(LuaRemoteDebugConstant.SCRIPT_NAME, ""); // $NON-NLS-1$
      IHost host = LuaRemoteLaunchConfigurationUtil.getHost(configuration);
      @SuppressWarnings("rawtypes")
      Map env =
          configuration.getAttribute(
              ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, Collections.EMPTY_MAP);

      // valid configuration information
      String errorMessage =
          LuaRemoteLaunchConfigurationUtil.validateRemoteLaunchConfiguration(
              projectName, scriptName, host);
      if (errorMessage != null)
        throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, errorMessage));
      submonitor.worked(1);

      // get Project
      IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);

      // get the first found remote file SubSystem
      IRemoteFileSubSystem remoteFileSubSystem = RSEUtil.getRemoteFileSubsystem(host);

      // get the first found Lua SubSystem
      LuaSubSystem luaSubSystem = LuaRSEUtil.getLuaSubSystem(host);

      // try to connect to the target
      try {
        if (submonitor.isCanceled()) return;
        remoteFileSubSystem.connect(submonitor.newChild(1), false);
        // CHECKSTYLE:OFF
      } catch (Exception e) {
        // CHECKSTYLE:ON
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                Activator.PLUGIN_ID,
                Messages.LuaRemoteLaunchConfigurationDelegate_error_connectionfailed,
                e));
      }

      // create script project
      IScriptProject scriptProject = DLTKCore.create(project);

      // compute the remote project workingdir
      if (submonitor.isCanceled()) return;
      String outputDirectory = luaSubSystem.getOutputDirectory();
      String defaultRemoteApplicationFolderPath =
          outputDirectory + remoteFileSubSystem.getSeparator() + configuration.getName();
      String remoteApplicationFolderPath =
          configuration.getAttribute(
              LuaRemoteDebugConstant.OUTPUT_DIRECTORY, defaultRemoteApplicationFolderPath);

      // compute script file source path relative path
      String scriptProjectRelativePath =
          configuration.getAttribute(
              LuaRemoteDebugConstant.SCRIPT_NAME, LuaConstants.DEFAULT_MAIN_FILE);
      IFile scriptFile = project.getFile(scriptProjectRelativePath);
      IModuleSource moduleSource =
          LuaUtils.getModuleSourceFromAbsoluteURI(scriptFile.getLocationURI(), scriptProject);
      if (moduleSource == null)
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                Activator.PLUGIN_ID,
                NLS.bind(
                    Messages
                        .LuaRemoteLaunchConfigurationDelegate_error_unabletofindsourcerelativepath,
                    scriptProjectRelativePath)));
      IPath scriptSourcePathRelativePath = LuaUtils.getSourcePathRelativePath(moduleSource);

      // kill Process if already running
      // could happen if connection is closed and last process launch is not terminate
      Session session = RSEUtil.getCurrentSshSession(host.getConnectorServices());
      SshProcess.killProcess(session, remoteApplicationFolderPath);

      // check an prepare remote folder
      try {
        if (submonitor.isCanceled()) return;
        IRemoteFile remoteApplicationPath =
            remoteFileSubSystem.getRemoteFileObject(outputDirectory, submonitor.newChild(1));
        if (remoteApplicationPath.exists()) {
          if (remoteApplicationPath.isFile()) {
            throw new CoreException(
                new Status(
                    IStatus.ERROR,
                    Activator.PLUGIN_ID,
                    NLS.bind(
                        Messages.LuaRemoteLaunchConfigurationDelegate_error_filealreadyexist,
                        outputDirectory)));
          }
        } else {
          remoteFileSubSystem.createFolder(remoteApplicationPath, submonitor.newChild(1));
        }
        submonitor.setWorkRemaining(9);

        // remoteFile is a folder
        // create(or delete and recreate) the working directory
        if (submonitor.isCanceled()) return;
        IRemoteFile remoteWorkingFolder =
            remoteFileSubSystem.getRemoteFileObject(
                remoteApplicationFolderPath, submonitor.newChild(1));
        if (remoteWorkingFolder.exists()) {
          if (remoteWorkingFolder.isFile()) {
            throw new CoreException(
                new Status(
                    IStatus.ERROR,
                    Activator.PLUGIN_ID,
                    MessageFormat.format(
                        Messages.LuaRemoteLaunchConfigurationDelegate_error_filealreadyexist,
                        remoteApplicationFolderPath)));
          } else {
            remoteFileSubSystem.delete(remoteWorkingFolder, submonitor.newChild(1));
          }
        }
        submonitor.setWorkRemaining(7);

        // create project application
        if (submonitor.isCanceled()) return;
        remoteFileSubSystem.createFolder(remoteWorkingFolder, submonitor.newChild(1));

        // upload sourcecode
        LuaRSEUtil.uploadFiles(
            remoteFileSubSystem,
            scriptProject,
            remoteApplicationFolderPath,
            submonitor.newChild(2));

        // upload Debug module
        if (mode.equals(ILaunchManager.DEBUG_MODE)) {
          SubMonitor debugmonitor = submonitor.newChild(1);
          debugmonitor.setWorkRemaining(DEBUG_FILES.length);

          String localEncoding = Charset.defaultCharset().name();
          String remoteEncoding = remoteFileSubSystem.getRemoteEncoding();

          for (String luaFile : DEBUG_FILES) {
            try {
              Bundle bundle =
                  Platform.getBundle(
                      org.eclipse.koneki.ldt.debug.core.internal.Activator.PLUGIN_ID);
              URL resource = bundle.getResource(luaFile);
              File result = new File(FileLocator.toFileURL(resource).getPath());
              String remotePath =
                  remoteApplicationFolderPath
                      + remoteFileSubSystem.getSeparator()
                      + result.getName();
              remoteFileSubSystem.upload(
                  result.getAbsolutePath(),
                  localEncoding,
                  remotePath,
                  remoteEncoding,
                  submonitor.newChild(1));
            } catch (IOException e) {
              throw new CoreException(
                  new Status(
                      IStatus.ERROR,
                      Activator.PLUGIN_ID,
                      Messages
                          .LuaRemoteLaunchConfigurationDelegate_error_unabletouploaddebuggerfiles,
                      e));
            }
          }
        }
      } catch (SystemMessageException e) {
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                Activator.PLUGIN_ID,
                NLS.bind(
                    Messages
                        .LuaRemoteLaunchConfigurationDelegate_error_unabletoaccestoremoteapplicationdir,
                    outputDirectory),
                e));
      }

      // set environment var
      Map<String, String> envVars = new HashMap<String, String>();
      String luaPath = luaSubSystem.getLuaPath();

      // if no luapath defined at subsystem level used the default one.
      if (luaPath == null || luaPath.isEmpty()) luaPath = "$LUA_PATH;"; // $NON-NLS-1$

      // add default lua envvar
      StringBuilder luaPathBuilder = new StringBuilder(luaPath);

      // check if lua path don't end with a ";"
      if (!luaPath.matches(".*;\\s*$")) // $NON-NLS-1$
      luaPathBuilder.append(";"); // $NON-NLS-1$

      // add working dir to lua path
      luaPathBuilder.append(remoteApplicationFolderPath);
      luaPathBuilder.append(remoteFileSubSystem.getSeparator());
      luaPathBuilder.append(LuaDebugConstants.LUA_PATTERN);
      // add init pattern for working dir to lua path
      luaPathBuilder.append(remoteApplicationFolderPath);
      luaPathBuilder.append(remoteFileSubSystem.getSeparator());
      luaPathBuilder.append(LuaDebugConstants.WILDCARD_PATTERN);
      luaPathBuilder.append(remoteFileSubSystem.getSeparator());
      luaPathBuilder.append(LuaDebugConstants.LUA_INIT_PATTERN);
      envVars.put(LuaDebugConstants.LUA_PATH, luaPathBuilder.toString());

      String luaCPath = luaSubSystem.getCLuaPath();
      if (luaCPath != null && !luaCPath.isEmpty())
        envVars.put(LuaDebugConstants.LUA_CPATH, luaCPath);

      String ldLibraryPath = luaSubSystem.getLDLibraryPath();
      if (ldLibraryPath != null && !ldLibraryPath.isEmpty())
        envVars.put(LuaDebugConstants.LUA_LDLIBRARYPATH, ldLibraryPath);

      // add launch configuration env vars
      for (Object oEntry : env.entrySet()) {
        @SuppressWarnings("rawtypes")
        Map.Entry entry = (Entry) oEntry;
        envVars.put(entry.getKey().toString(), entry.getValue().toString());
      }

      // add debug information
      String sessionID = null;
      if (mode.equals(ILaunchManager.DEBUG_MODE)) {
        sessionID = DbgpSessionIdGenerator.generate();

        // try to find host ide IP Address only if it's not define by user
        if (!envVars.containsKey(LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_HOST)) {
          String bindedAddress =
              NetworkUtil.findBindedAddress(host.getHostName(), submonitor.newChild(1));
          if (bindedAddress == null)
            throw new CoreException(
                new Status(
                    IStatus.ERROR,
                    Activator.PLUGIN_ID,
                    NLS.bind(
                        Messages.LuaRemoteLaunchConfigurationDelegate_error_unable_to_define_ideip,
                        LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_HOST)));

          envVars.put(LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_HOST, bindedAddress);
        }

        // dbgp env vars
        envVars.put(LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_KEY, sessionID);
        envVars.put(
            LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_PORT,
            String.valueOf(DLTKDebugPlugin.getDefault().getDbgpService().getPort()));
        envVars.put(LuaDebugConstants.ENV_VAR_KEY_DBGP_PLATFORM, "unix"); // $NON-NLS-1$
        envVars.put(LuaDebugConstants.ENV_VAR_KEY_DBGP_WORKINGDIR, remoteApplicationFolderPath);
        envVars.put(
            LuaDebugConstants.ENV_VAR_KEY_DBGP_TRANSPORT,
            "debugger.transport.luasocket_sched"); //$NON-NLS-1$
      }

      // create lua execution command
      StringBuilder cmd = new StringBuilder();

      // create command to run
      cmd.append(luaSubSystem.getLuaCommand());
      cmd.append(SshProcess.ARGUMENT_SEPARATOR);

      // insert interpreter args
      String interpreterArgs =
          configuration.getAttribute(LuaRemoteDebugConstant.INTERPRETER_ARGS, ""); // $NON-NLS-1$
      if (!interpreterArgs.isEmpty()) {
        cmd.append(interpreterArgs);
        cmd.append(SshProcess.ARGUMENT_SEPARATOR);
      }

      // FIXME is there a cleaner way to control buffering ?
      // see: http://lua-users.org/lists/lua-l/2011-05/msg00549.html
      String bootstrapCode = "io.stdout:setvbuf('line');"; // $NON-NLS-1$
      if (mode.equals(ILaunchManager.DEBUG_MODE)) {
        // load debugging libraries. The -l parameter cannot be used here because the debugger MUST
        // be the first module to be loaded
        bootstrapCode += " require('" + DEBGUGGER_MODULE + "')();"; // $NON-NLS-1$//$NON-NLS-2$
      }
      cmd.append("-e"); // $NON-NLS-1$
      cmd.append(SshProcess.ARGUMENT_SEPARATOR);
      cmd.append("\"" + bootstrapCode + "\""); // $NON-NLS-1$//$NON-NLS-2$
      cmd.append(SshProcess.ARGUMENT_SEPARATOR);
      cmd.append(SshProcess.escapeShell(scriptSourcePathRelativePath.toPortableString()));
      cmd.append(SshProcess.ARGUMENT_SEPARATOR);

      // insert script args
      String scriptArgs =
          configuration.getAttribute(LuaRemoteDebugConstant.SCRIPT_ARGS, ""); // $NON-NLS-1$
      if (!scriptArgs.isEmpty()) {
        cmd.append(scriptArgs);
        cmd.append(SshProcess.ARGUMENT_SEPARATOR);
      }

      submonitor.setWorkRemaining(1);

      // Create Process
      if (submonitor.isCanceled()) return;

      SshProcess process =
          new SshProcess(session, launch, remoteApplicationFolderPath, cmd.toString(), envVars);

      if (mode.equals(ILaunchManager.DEBUG_MODE)) {
        // Desactivate DBGP Stream redirection
        // TODO manage DBGP Stream redirection (so deactivate process redirection in debug mode)
        launch.setAttribute(
            DLTKDebugLaunchConstants.ATTR_DEBUG_CONSOLE, DLTKDebugLaunchConstants.FALSE);

        // manage break on first line
        if (configuration.getAttribute(LuaRemoteDebugConstant.BREAK_ON_FIRST_LINE, false)) {
          launch.setAttribute(
              DLTKDebugLaunchConstants.ATTR_BREAK_ON_FIRST_LINE, DLTKDebugLaunchConstants.TRUE);
        }

        // create runner
        LuaRemoteDebuggingEngineRunner debugingEngine =
            new LuaRemoteDebuggingEngineRunner(process, sessionID, remoteApplicationFolderPath);
        debugingEngine.run(new InterpreterConfig(), launch, submonitor.newChild(1));
        launch.addProcess(process);
      } else {
        process.start();
        launch.addProcess(process);
      }
    } finally {
      submonitor.done();
    }
  }