示例#1
0
 @Override
 protected IStatus run(IProgressMonitor monitor) {
   final XtextEditor editor = initialEditor;
   final boolean isMarkOccurrences = initialIsMarkOccurrences;
   final ITextSelection selection = initialSelection;
   final SubMonitor progress = SubMonitor.convert(monitor, 2);
   if (!progress.isCanceled()) {
     final Map<Annotation, Position> annotations =
         (isMarkOccurrences)
             ? occurrenceComputer.createAnnotationMap(editor, selection, progress.newChild(1))
             : Collections.<Annotation, Position>emptyMap();
     if (!progress.isCanceled()) {
       Display.getDefault()
           .asyncExec(
               new Runnable() {
                 public void run() {
                   if (!progress.isCanceled()) {
                     final IAnnotationModel annotationModel = getAnnotationModel(editor);
                     if (annotationModel instanceof IAnnotationModelExtension)
                       ((IAnnotationModelExtension) annotationModel)
                           .replaceAnnotations(
                               getExistingOccurrenceAnnotations(annotationModel), annotations);
                     else if (annotationModel != null)
                       throw new IllegalStateException(
                           "AnnotationModel does not implement IAnnotationModelExtension"); //$NON-NLS-1$
                   }
                 }
               });
     }
   }
   return progress.isCanceled() ? Status.CANCEL_STATUS : Status.OK_STATUS;
 }
  /**
   * Finds available WSO2 features in current profile and search for updates to them in WSO2 p2
   * repository for updates.
   *
   * @param monitor
   * @throws Exception
   */
  public void checkForAvailableUpdates(IProgressMonitor monitor) throws Exception {
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }
    SubMonitor progress = SubMonitor.convert(monitor, Messages.UpdateManager_18, 6);

    // get all available IUs in update repository
    IMetadataRepository metadataRepo =
        metadataRepoManager.loadRepository(getDevStudioUpdateSite(), progress.newChild(1));
    IQuery<IInstallableUnit> allIUQuery = QueryUtil.createIUAnyQuery();
    IQueryResult<IInstallableUnit> allIUQueryResult =
        metadataRepo.query(allIUQuery, progress.newChild(1));

    // read artifact repository for updates
    IArtifactRepository artifactRepo =
        artifactRepoManager.loadRepository(getDevStudioUpdateSite(), progress.newChild(1));

    // read meta-data of all available features
    Map<String, EnhancedFeature> allFeaturesInUpdateRepo =
        loadWSO2FeaturesInRepo(artifactRepo, allIUQueryResult, progress.newChild(1));

    // get all installed wso2 features
    Collection<IInstallableUnit> installedWSO2Features =
        getInstalledWSO2Features(progress.newChild(1));

    installedWSO2FeaturesMap = new HashMap<String, IInstallableUnit>();
    for (IInstallableUnit iInstallableUnit : installedWSO2Features) {
      installedWSO2FeaturesMap.put(iInstallableUnit.getId(), iInstallableUnit);
    }

    if (progress.isCanceled()) {
      throw new OperationCanceledException();
    }

    URI[] repos = new URI[] {getDevStudioUpdateSite()};
    updateOperation = new UpdateOperation(session, installedWSO2Features);
    updateOperation.getProvisioningContext().setArtifactRepositories(repos);
    updateOperation.getProvisioningContext().setMetadataRepositories(repos);

    // resolve update operation
    IStatus status = updateOperation.resolveModal(progress.newChild(1));
    // user cancelled the job while resolving
    if (status.getSeverity() == IStatus.CANCEL || progress.isCanceled()) {
      throw new OperationCanceledException();
    }
    // there is nothing to update
    if (status.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
      featuresWithPossibleUpdates = new HashMap<String, EnhancedFeature>();
      log.info(Messages.UpdateManager_19);
    } else if (status.getSeverity() == IStatus.ERROR) { // resolution errors
      // something wrong with the updates
      log.info(Messages.UpdateManager_20);
    } else {
      // good to proceed installing updates
      setPossibleUpdates(updateOperation.getPossibleUpdates(), allFeaturesInUpdateRepo);
    }
  }
示例#3
0
  @Override
  public void build(final IBuildContext context, IProgressMonitor monitor) throws CoreException {
    if (!isEnabled(context)) {
      return;
    }

    final List<IResourceDescription.Delta> deltas = getRelevantDeltas(context);
    if (deltas.isEmpty()) {
      return;
    }

    StoppedTask task =
        Stopwatches.forTask(
            "org.eclipse.xtext.builder.BuilderParticipant.build(IBuildContext, IProgressMonitor)");
    try {
      task.start();

      // monitor handling
      if (monitor.isCanceled()) throw new OperationCanceledException();
      SubMonitor subMonitor =
          SubMonitor.convert(monitor, context.getBuildType() == BuildType.RECOVERY ? 5 : 3);

      EclipseResourceFileSystemAccess2 access = fileSystemAccessProvider.get();
      IProject builtProject = context.getBuiltProject();
      access.setProject(builtProject);
      Map<String, OutputConfiguration> outputConfigurations = getOutputConfigurations(context);
      refreshOutputFolders(context, outputConfigurations, subMonitor.newChild(1));
      if (subMonitor.isCanceled()) {
        throw new OperationCanceledException();
      }
      access.setOutputConfigurations(outputConfigurations);
      if (context.getBuildType() == BuildType.CLEAN
          || context.getBuildType() == BuildType.RECOVERY) {
        SubMonitor cleanMonitor =
            SubMonitor.convert(subMonitor.newChild(2), outputConfigurations.size());
        for (OutputConfiguration config : outputConfigurations.values()) {
          cleanOutput(context, config, access, cleanMonitor.newChild(1));
        }
        if (context.getBuildType() == BuildType.CLEAN) return;
      }
      Map<OutputConfiguration, Iterable<IMarker>> generatorMarkers =
          getGeneratorMarkers(builtProject, outputConfigurations.values());
      if (subMonitor.isCanceled()) {
        throw new OperationCanceledException();
      }
      doBuild(
          deltas, outputConfigurations, generatorMarkers, context, access, subMonitor.newChild(2));

    } finally {
      task.stop();
    }
  }
示例#4
0
  private void buildFile(
      BuildContext context, List<IBuildParticipant> participants, IProgressMonitor monitor)
      throws CoreException {
    if (CollectionsUtil.isEmpty(participants)) {
      return;
    }

    SubMonitor sub = SubMonitor.convert(monitor, 2 * participants.size());
    for (IBuildParticipant participant : participants) {
      long startTime = System.nanoTime();
      participant.buildFile(context, sub.newChild(1));
      if (traceParticipantsEnabled) {
        double endTime = ((double) System.nanoTime() - startTime) / 1000000;
        IdeLog.logTrace(
            BuildPathCorePlugin.getDefault(),
            MessageFormat.format(
                "Executed build participant ''{0}'' on ''{1}'' in {2} ms.",
                participant.getName(), context.getURI(), endTime),
            IDebugScopes.BUILDER_PARTICIPANTS); // $NON-NLS-1$
      }

      // stop building if it has been canceled
      if (sub.isCanceled()) {
        break;
      }
    }
    updateMarkers(context, sub.newChild(participants.size()));
    sub.done();
  }
 /* (non-Javadoc)
  * @see com.siteview.mde.internal.core.target.impl.AbstractBundleContainer#resolveBundles(com.siteview.mde.internal.core.target.provisional.ITargetDefinition, org.eclipse.core.runtime.IProgressMonitor)
  */
 protected IResolvedBundle[] resolveBundles(ITargetDefinition definition, IProgressMonitor monitor)
     throws CoreException {
   File dir = getDirectory();
   if (dir.isDirectory()) {
     File site = getSite(dir);
     File[] files = site.listFiles();
     SubMonitor localMonitor =
         SubMonitor.convert(monitor, Messages.DirectoryBundleContainer_0, files.length);
     List bundles = new ArrayList(files.length);
     for (int i = 0; i < files.length; i++) {
       if (localMonitor.isCanceled()) {
         return new IResolvedBundle[0];
       }
       try {
         IResolvedBundle rb = generateBundle(files[i]);
         if (rb != null) {
           bundles.add(rb);
         }
       } catch (CoreException e) {
         // ignore invalid bundles
       }
       localMonitor.worked(1);
     }
     localMonitor.done();
     return (IResolvedBundle[]) bundles.toArray(new IResolvedBundle[bundles.size()]);
   }
   throw new CoreException(
       new Status(
           IStatus.ERROR,
           MDECore.PLUGIN_ID,
           NLS.bind(Messages.DirectoryBundleContainer_1, dir.toString())));
 }
 private Collection<IInstallableUnit> filterInstallableUnits(
     String idPrefix,
     String idSuffix,
     IQueryResult<IInstallableUnit> queryResult,
     IProgressMonitor monitor)
     throws OperationCanceledException {
   if (monitor == null) {
     monitor = new NullProgressMonitor();
   }
   Collection<IInstallableUnit> wso2IUs = new ArrayList<IInstallableUnit>();
   Iterator<IInstallableUnit> iterator = queryResult.iterator();
   SubMonitor progress =
       SubMonitor.convert(monitor, Messages.UpdateManager_24, queryResult.toSet().size());
   ;
   while (iterator.hasNext()) {
     if (progress.isCanceled()) {
       throw new OperationCanceledException();
     }
     IInstallableUnit iu = iterator.next();
     String versionedID = iu.getId();
     progress.subTask(Messages.UpdateManager_25 + versionedID);
     if (versionedID != null
         && versionedID.startsWith(idPrefix)
         && versionedID.endsWith(idSuffix)) {
       wso2IUs.add(iu);
     }
     progress.worked(1);
   }
   return wso2IUs;
 }
  @Override
  public List<Object> computeContext(
      IInteractionContext context, IAdaptable input, IProgressMonitor monitor) {
    if (delegates == null || delegates.isEmpty()) {
      return Collections.emptyList();
    }
    List<Object> objects = new ArrayList<Object>();

    SubMonitor progress = SubMonitor.convert(monitor);
    int workPerDelegate = 1000;
    progress.beginTask(
        Messages.CompoundContextComputationStrategy_Computing_Context_Task_Label,
        delegates.size() * workPerDelegate);
    try {
      for (ContextComputationStrategy delegate : delegates) {
        if (progress.isCanceled()) {
          break;
        }
        objects.addAll(delegate.computeContext(context, input, progress.newChild(workPerDelegate)));
      }
    } finally {
      progress.done();
    }

    return objects;
  }
 protected void findIndexedReferences(
     Set<URI> targetURIs,
     IAcceptor<IReferenceDescription> acceptor,
     Predicate<IReferenceDescription> filter,
     IProgressMonitor monitor) {
   Set<URI> targetResourceURIs =
       newHashSet(
           transform(
               targetURIs,
               new Function<URI, URI>() {
                 public URI apply(URI from) {
                   return from.trimFragment();
                 }
               }));
   int numResources = Iterables.size(index.getAllResourceDescriptions());
   SubMonitor subMonitor =
       SubMonitor.convert(monitor, Messages.ReferenceQuery_monitor, numResources);
   for (IResourceDescription resourceDescription : index.getAllResourceDescriptions()) {
     if (subMonitor.isCanceled()) return;
     if (!targetResourceURIs.contains(resourceDescription.getURI())) {
       for (IReferenceDescription referenceDescription :
           resourceDescription.getReferenceDescriptions()) {
         if (targetURIs.contains(referenceDescription.getTargetEObjectUri())
             && (filter == null || filter.apply(referenceDescription))) {
           acceptor.accept(referenceDescription);
         }
       }
     }
     subMonitor.worked(1);
   }
 }
示例#9
0
  @Override
  protected void clean(IProgressMonitor monitor) throws CoreException {
    super.clean(monitor);

    IProject project = getProjectHandle();

    IBuildParticipantManager manager = getBuildParticipantManager();
    if (manager == null) {
      return;
    }
    List<IBuildParticipant> participants = manager.getAllBuildParticipants();
    participants = filterToEnabled(participants, project);

    SubMonitor sub = SubMonitor.convert(monitor, participants.size() + 2);
    sub.worked(1);

    removeProblemsAndTasksFor(project);
    sub.worked(1);

    // FIXME Should we visit all files and call "deleteFile" sort of like what we do with fullBuild?
    for (IBuildParticipant participant : participants) {
      if (sub.isCanceled()) {
        return;
      }

      participant.clean(project, sub.newChild(1));
    }
    sub.done();
  }
示例#10
0
  private void doBuildFiles(
      List<IBuildParticipant> participants, Collection<IFile> files, IProgressMonitor monitor)
      throws CoreException {
    if (CollectionsUtil.isEmpty(files)) {
      return;
    }

    SubMonitor sub = SubMonitor.convert(monitor, 15 * files.size());
    for (IFile file : files) {
      BuildContext context = new BuildContext(file);
      sub.worked(1);

      IBuildParticipantManager manager = getBuildParticipantManager();
      if (manager == null) {
        return;
      }
      List<IBuildParticipant> filteredParticipants =
          manager.filterParticipants(participants, context.getContentType());
      sub.worked(2);

      buildFile(context, filteredParticipants, sub.newChild(12));

      // stop building if canceled
      if (sub.isCanceled()) {
        break;
      }
    }
    sub.done();
  }
  /**
   * Install selected features in to developer studio. Note: call {@link
   * #setSelectedFeaturesToInstall(List) setSelectedFeaturesToInstall} first.
   *
   * @param monitor
   */
  public void installSelectedFeatures(IProgressMonitor monitor) {
    SubMonitor progress = SubMonitor.convert(monitor, Messages.UpdateManager_32, 2);

    URI[] repos = new URI[] {getDevStudioReleaseSite()};
    session = new ProvisioningSession(p2Agent);
    installOperation = new InstallOperation(session, selectedFeatures);
    installOperation.getProvisioningContext().setArtifactRepositories(repos);
    installOperation.getProvisioningContext().setMetadataRepositories(repos);
    IStatus status = installOperation.resolveModal(progress.newChild(1));
    if (status.getSeverity() == IStatus.CANCEL || progress.isCanceled()) {
      throw new OperationCanceledException();
    } else if (status.getSeverity() == IStatus.ERROR) {
      String message = status.getChildren()[0].getMessage();
      log.error(Messages.UpdateManager_33 + message);
    } else {
      ProvisioningJob provisioningJob = installOperation.getProvisioningJob(progress.newChild(1));
      if (provisioningJob != null) {
        provisioningJob.addJobChangeListener(
            new JobChangeAdapter() {
              @Override
              public void done(IJobChangeEvent arg0) {
                Display.getDefault()
                    .syncExec(
                        new Runnable() {
                          @Override
                          public void run() {
                            boolean restart =
                                MessageDialog.openQuestion(
                                    Display.getDefault().getActiveShell(),
                                    Messages.UpdateManager_34,
                                    Messages.UpdateManager_35 + Messages.UpdateManager_36);
                            if (restart) {
                              PlatformUI.getWorkbench().restart();
                            }
                          }
                        });
              }
            });
        provisioningJob.schedule();
        Display.getDefault()
            .syncExec(
                new Runnable() {
                  @Override
                  public void run() {
                    try {
                      PlatformUI.getWorkbench()
                          .getActiveWorkbenchWindow()
                          .getActivePage()
                          .showView(IProgressConstants.PROGRESS_VIEW_ID);
                    } catch (PartInitException e) {
                      log.error(e);
                    }
                  }
                });
      } else {
        log.error(Messages.UpdateManager_37);
      }
    }
  }
示例#12
0
 public void findLocalReferences(
     Set<? extends EObject> targets,
     IAcceptor<IReferenceDescription> acceptor,
     Predicate<IReferenceDescription> filter,
     IProgressMonitor monitor) {
   if (monitor != null && monitor.isCanceled()) return;
   if (targets != null && !targets.isEmpty()) {
     Set<Resource> targetResources = new HashSet<Resource>();
     for (EObject target : targets) {
       targetResources.add(target.eResource());
     }
     Map<EObject, Collection<Setting>> targetResourceInternalCrossRefs =
         CrossReferencer.find(targetResources);
     Map<EObject, URI> exportedElementsMap = null;
     SubMonitor subMonitor =
         SubMonitor.convert(monitor, Messages.ReferenceQuery_monitor, targets.size());
     for (EObject target : targets) {
       Collection<Setting> crossRefSettings = targetResourceInternalCrossRefs.get(target);
       if (crossRefSettings != null) {
         SubMonitor subSubMonitor = subMonitor.newChild(crossRefSettings.size());
         for (Setting crossRefSetting : crossRefSettings) {
           if (subSubMonitor.isCanceled()) return;
           EObject source = crossRefSetting.getEObject();
           if (crossRefSetting.getEStructuralFeature() instanceof EReference) {
             EReference reference = (EReference) crossRefSetting.getEStructuralFeature();
             int index = 0;
             if (reference.isMany()) {
               List<?> values = (List<?>) source.eGet(reference);
               for (int i = 0; i < values.size(); ++i) {
                 if (target == values.get(i)) {
                   index = i;
                   break;
                 }
               }
             }
             if (exportedElementsMap == null)
               exportedElementsMap = createExportedElementsMap(target.eResource());
             IReferenceDescription localReferenceDescription =
                 new DefaultReferenceDescription(
                     source,
                     target,
                     reference,
                     index,
                     findClosestExportedContainerURI(source, exportedElementsMap));
             if (filter == null || filter.apply(localReferenceDescription))
               acceptor.accept(localReferenceDescription);
           }
           subSubMonitor.worked(1);
         }
       }
     }
   }
 }
示例#13
0
  /** @since 2.7 */
  protected void doBuild(
      List<IResourceDescription.Delta> deltas,
      Map<String, OutputConfiguration> outputConfigurations,
      Map<OutputConfiguration, Iterable<IMarker>> generatorMarkers,
      IBuildContext context,
      EclipseResourceFileSystemAccess2 access,
      IProgressMonitor progressMonitor)
      throws CoreException {
    final int numberOfDeltas = deltas.size();
    SubMonitor subMonitor =
        SubMonitor.convert(progressMonitor, numberOfDeltas / MONITOR_CHUNK_SIZE + 1);
    SubMonitor currentMonitor = null;
    int clusterIndex = 0;
    for (int i = 0; i < numberOfDeltas; i++) {
      IResourceDescription.Delta delta = deltas.get(i);

      if (subMonitor.isCanceled()) {
        throw new OperationCanceledException();
      }
      if (i % 10 == 0) {
        subMonitor.subTask(
            "Compiling chunk "
                + (i / MONITOR_CHUNK_SIZE + 1)
                + " of "
                + (numberOfDeltas / MONITOR_CHUNK_SIZE + 1));
        currentMonitor = subMonitor.newChild(1);
        access.setMonitor(currentMonitor);
      }
      if (logger.isDebugEnabled()) {
        logger.debug("Compiling " + delta.getUri() + " (" + i + " of " + numberOfDeltas + ")");
      }
      if (delta.getNew() != null
          && !clusteringPolicy.continueProcessing(
              context.getResourceSet(), delta.getUri(), clusterIndex)) {
        clearResourceSet(context.getResourceSet());
        clusterIndex = 0;
      }

      Set<IFile> derivedResources =
          getDerivedResources(delta, outputConfigurations, generatorMarkers);
      access.setPostProcessor(getPostProcessor(delta, context, derivedResources));

      if (doGenerate(delta, context, access)) {
        clusterIndex++;
        access.flushSourceTraces();
      }

      cleanDerivedResources(delta, derivedResources, context, access, currentMonitor);
    }
  }
示例#14
0
 @Override
 public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
     throws CoreException, OperationCanceledException {
   RefactoringStatus refactoringStatus = RefactoringStatus.create(Status.OK_STATUS);
   SubMonitor sm =
       SubMonitor.convert(
           pm,
           new StringBuffer("Checking initial conditions for ")
               .append(context.getLabel())
               .toString(),
           10);
   EObject element = context.getSourceElement();
   EObject container = EcoreUtil.getRootContainer(element);
   refactoringStatus =
       sm.isCanceled() ? RefactoringStatus.create(Status.CANCEL_STATUS) : validate(sm, container);
   sm.done();
   return refactoringStatus;
 }
示例#15
0
  public void compile(IProgressMonitor monitor) throws CoreException {
    SubMonitor sub = SubMonitor.convert(monitor, "Building " + project.getName() + "...", 100);
    notifyParticipants(sub.newChild(5));
    // traverse the delta
    BuildContext[] files = getBuildContexts();
    sub.worked(5);

    int workUnitsPerTask = 90 / (fParticipants.length + 1);

    if (monitor.isCanceled()) throw new OperationCanceledException();

    removeMarkers(markerManager, sub.newChild(workUnitsPerTask));

    if (sub.isCanceled()) throw new OperationCanceledException();

    compileFiles(files, sub.newChild(workUnitsPerTask * fParticipants.length));
    monitor.done();
  }
 private IStatus computeAllRemediations(IProgressMonitor monitor) {
   SubMonitor sub = SubMonitor.convert(monitor, remedyConfigs.length);
   sub.setTaskName(Messages.RemediationOperation_ProfileChangeRequestProgress);
   List<Remedy> tmpRemedies = new ArrayList<Remedy>(remedyConfigs.length);
   try {
     for (int i = 0; i < remedyConfigs.length; i++) {
       sub.subTask((i + 1) + " / " + remedyConfigs.length); // $NON-NLS-1$
       if (sub.isCanceled()) return Status.CANCEL_STATUS;
       Remedy remedy =
           computeRemedy(remedyConfigs[i], sub.newChild(1, SubMonitor.SUPPRESS_ALL_LABELS));
       if (remedy != null) {
         tmpRemedies.add(remedy);
       }
     }
   } finally {
     sub.done();
   }
   remedies = tmpRemedies;
   return getResolutionResult();
 }
  public ToBeBuilt updateProject(IProject project, IProgressMonitor monitor) throws CoreException {
    final SubMonitor progress =
        SubMonitor.convert(monitor, Messages.ToBeBuiltComputer_CollectingReosurces, 1);
    progress.subTask(Messages.ToBeBuiltComputer_CollectingReosurces);

    final ToBeBuilt toBeBuilt = removeProject(project, progress.newChild(1));
    if (!project.isAccessible()) return toBeBuilt;
    if (progress.isCanceled()) throw new OperationCanceledException();

    project.accept(
        new IResourceVisitor() {
          public boolean visit(IResource resource) throws CoreException {
            if (progress.isCanceled()) throw new OperationCanceledException();
            if (resource instanceof IStorage) {
              return updateStorage(null, toBeBuilt, (IStorage) resource);
            }
            return true;
          }
        });
    return toBeBuilt;
  }
示例#18
0
  /**
   * @param monitor the progress monitor to use for reporting progress to the user. It is the
   *     caller's responsibility to call done() on the given monitor. Accepts null, indicating that
   *     no progress should be reported and that the operation cannot be cancelled.
   */
  protected void incrementalBuild(IResourceDelta delta, final IProgressMonitor monitor)
      throws CoreException {
    final SubMonitor progress =
        SubMonitor.convert(monitor, Messages.XtextBuilder_CollectingResources, 10);
    progress.subTask(Messages.XtextBuilder_CollectingResources);

    if (queuedBuildData.needRebuild(getProject())) {
      needRebuild();
    }

    final ToBeBuilt toBeBuilt = new ToBeBuilt();
    IResourceDeltaVisitor visitor =
        new IResourceDeltaVisitor() {
          @Override
          public boolean visit(IResourceDelta delta) throws CoreException {
            if (progress.isCanceled()) throw new OperationCanceledException();
            if (delta.getResource() instanceof IProject) {
              return delta.getResource() == getProject();
            }
            if (delta.getResource() instanceof IStorage) {
              if (delta.getKind() == IResourceDelta.REMOVED) {
                return toBeBuiltComputer.removeStorage(
                    null, toBeBuilt, (IStorage) delta.getResource());
              } else if (delta.getKind() == IResourceDelta.ADDED
                  || delta.getKind() == IResourceDelta.CHANGED) {
                return toBeBuiltComputer.updateStorage(
                    null, toBeBuilt, (IStorage) delta.getResource());
              }
            }
            return true;
          }
        };
    delta.accept(visitor);
    if (progress.isCanceled()) throw new OperationCanceledException();
    progress.worked(2);
    doBuild(toBeBuilt, progress.newChild(8), BuildType.INCREMENTAL);
  }
示例#19
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);
  }
示例#20
0
  /** Returns OK, WARN or ERROR. */
  public IS2ProjectValidationStatus validate(
      IS2Project s2Project, String securityRealmIdFilter, IProgressMonitor monitor) {
    log.debug("Validating SCM access for project {}", s2Project.getName());

    List<IS2Module> modules = s2Project.getModules();

    SubMonitor progress =
        SubMonitor.convert(monitor, "Validating source repository access", modules.size());

    ArrayList<IStatus> results = new ArrayList<IStatus>();

    for (final IS2Module module : modules) {
      if (progress.isCanceled()) {
        throw new OperationCanceledException();
      }

      progress.subTask(module.getName());

      IResourceLocation scmLocation = module.getScmLocation();
      if (scmLocation == null) {
        results.add(
            new Status(
                IStatus.ERROR,
                S2ProjectValidationPlugin.PLUGIN_ID,
                "SCM location is not specified"));
        monitor.worked(1);
        continue;
      }

      String scmUrl = scmLocation.getUrl();
      String realmIdForUrl = null;
      IAuthRealm realmForUrl = AuthFacade.getAuthRegistry().getRealmForURI(scmUrl);
      if (realmForUrl != null) {
        realmIdForUrl = realmForUrl.getId();
      }
      if (securityRealmIdFilter != null
          && !securityRealmIdFilter.equals(realmIdForUrl)
          && !urlsEquals(securityRealmIdFilter, scmUrl)) {
        // This location does not match the specified securityRealmId
        monitor.worked(1);
        continue;
      }
      log.debug("Validating SCM access for module {} at {}", module.getName(), scmUrl);

      IStatus status = validate(scmLocation, progress);
      results.add(status);
    }

    progress.subTask("");
    progress.done();

    if (results.isEmpty()) {
      return null;
    }

    return new S2ProjectValidationMultiStatus(
        this,
        -1,
        results.toArray(new IStatus[results.size()]),
        null /* message */,
        null /* exception */);
  }
示例#21
0
  /**
   * If the filePaths is empty, do batch operations!
   *
   * @param notify
   * @param filePaths
   * @param monitor
   * @return
   */
  IStatus refresh(boolean notify, Collection<IPath> filePaths, IProgressMonitor monitor) {
    SubMonitor sub = SubMonitor.convert(monitor, 100);
    if (sub.isCanceled()) {
      return Status.CANCEL_STATUS;
    }
    this.notify = notify;

    final Set<String> filePathStrings =
        new HashSet<String>(
            CollectionsUtil.map(
                filePaths,
                new IMap<IPath, String>() {
                  public String map(IPath location) {
                    return location.toPortableString();
                  }
                }));

    // If we don't run this, we end up showing files as unstaged when they're no longer modified!
    IStatus result;
    synchronized (this) {
      repository.forceWrite(); // Do we only want to try the lock if we're in UI thread?
      result =
          GitExecutable.instance()
              .runInBackground(
                  repository.workingDirectory(),
                  "update-index",
                  "-q", //$NON-NLS-1$ //$NON-NLS-2$
                  "--unmerged",
                  "--ignore-missing",
                  "--refresh"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      repository.exitWriteProcess();
    }
    if (result == null) // couldn't even execute!
    {
      return new Status(
          IStatus.ERROR,
          GitPlugin.getPluginId(),
          "Failed to execute git update-index"); //$NON-NLS-1$
    }
    if (!result.isOK()) {
      IdeLog.logError(
          GitPlugin.getDefault(),
          "Unable to run update-index: " + result.getMessage()); // $NON-NLS-1$
      return result;
    }

    Set<Callable<IStatus>> jobs = new HashSet<Callable<IStatus>>(3);
    jobs.add(new UntrackedFilesRefreshJob(this, filePathStrings));
    jobs.add(new UnstagedFilesRefreshJob(this, filePathStrings));
    jobs.add(new StagedFilesRefreshJob(this, filePathStrings));

    // Last chance to cancel...
    if (monitor != null && monitor.isCanceled()) {
      return Status.CANCEL_STATUS;
    }

    // Now create a new temporary list so we can build it up...
    this.files = Collections.synchronizedList(new ArrayList<ChangedFile>());

    // Schedule all the jobs
    MultiStatus errors =
        new MultiStatus(
            GitPlugin.PLUGIN_ID,
            1,
            "Errors occurred while grabbing changed file listings",
            null); //$NON-NLS-1$
    try {
      List<Future<IStatus>> futures = es.invokeAll(jobs);

      // Now wait for them to finish
      for (Future<IStatus> future : futures) {
        while (!future.isDone()) {
          if (monitor != null && monitor.isCanceled()) {
            future.cancel(true);
          }
          Thread.yield();
        }

        // When done, get their result
        try {
          IStatus futureResult = future.get();
          if (!futureResult.isOK()) {
            errors.merge(futureResult);
          }
        } catch (CancellationException ce) {
          // ignore
        } catch (ExecutionException e) {
          Throwable t = e.getCause();
          errors.merge(new Status(IStatus.ERROR, GitPlugin.PLUGIN_ID, t.getMessage(), t));
        }
      }
    } catch (InterruptedException e) {
      IdeLog.logError(GitPlugin.getDefault(), e);
    }

    // Copy the last full list of changed files we built up on refresh. Used to pass along the delta
    // FIXME I think the values here may have already changed! I saw a file that had staged changes
    // but no unstaged
    // prior to commit
    // but here it showed true for both (which should have only gotten modified by a pre-commit
    // hook)
    Collection<ChangedFile> preRefresh;
    synchronized (this.changedFilesLock) {
      if (this.changedFiles != null) {
        preRefresh = new ArrayList<ChangedFile>(this.changedFiles.size());
        for (ChangedFile file : this.changedFiles) {
          preRefresh.add(new ChangedFile(file));
        }
      } else {
        preRefresh = new ArrayList<ChangedFile>(0);
      }

      // Now wipe any existing ChangedFile entries for any of the filePaths and add the ones we
      // generated in
      // dictionary
      if (CollectionsUtil.isEmpty(filePathStrings)) {
        this.changedFiles = new ArrayList<ChangedFile>();
      } else {
        this.changedFiles =
            CollectionsUtil.filter(
                this.changedFiles,
                new IFilter<ChangedFile>() {
                  public boolean include(ChangedFile item) {
                    return !filePathStrings.contains(item.portablePath);
                  }
                });
      }
      if (!CollectionsUtil.isEmpty(this.files)) {
        this.changedFiles.addAll(this.files);
      }
    }

    // Don't hold onto temp list in memory!
    this.files = null;

    postIndexChange(preRefresh, this.changedFiles);
    sub.done();
    if (!errors.isOK()) {
      return errors;
    }
    return Status.OK_STATUS;
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ptp.rtsystem.IRuntimeSystem#startup(org.eclipse.core.runtime
   * .IProgressMonitor)
   */
  public void startup(IProgressMonitor monitor) throws CoreException {
    SubMonitor subMon = SubMonitor.convert(monitor, 100);

    synchronized (this) {
      startupMonitor = subMon;
    }

    initialize();

    subMon.subTask(Messages.AbstractToolRuntimeSystem_1);

    DebugUtil.trace(
        DebugUtil.RTS_TRACING,
        "RTS {0}: startup",
        getResourceManager().getConfiguration().getName()); // $NON-NLS-1$

    try {
      remoteServices =
          PTPRemoteCorePlugin.getDefault()
              .getRemoteServices(
                  getResourceManager().getControlConfiguration().getRemoteServicesId(),
                  subMon.newChild(10));
      if (remoteServices == null) {
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                RMCorePlugin.PLUGIN_ID,
                Messages.AbstractToolRuntimeSystem_Exception_NoRemoteServices));
      }

      IRemoteConnectionManager connectionManager = remoteServices.getConnectionManager();
      Assert.isNotNull(connectionManager);

      subMon.worked(10);
      subMon.subTask(Messages.AbstractToolRuntimeSystem_2);

      connection =
          connectionManager.getConnection(
              getResourceManager().getControlConfiguration().getConnectionName());
      if (connection == null) {
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                RMCorePlugin.PLUGIN_ID,
                Messages.AbstractToolRuntimeSystem_Exception_NoConnection));
      }

      if (!connection.isOpen()) {
        try {
          connection.open(subMon.newChild(50));
        } catch (RemoteConnectionException e) {
          throw new CoreException(
              new Status(IStatus.ERROR, RMCorePlugin.PLUGIN_ID, e.getMessage()));
        }
      }

      if (subMon.isCanceled()) {
        connection.close();
        return;
      }

      try {
        doStartup(subMon.newChild(40));
      } catch (CoreException e) {
        connection.close();
        throw e;
      }

      if (subMon.isCanceled()) {
        connection.close();
        return;
      }

      /*
       * Wait for discover job to complete so we can check it's status and
       * throw an exception if it fails.
       */
      Job discoverJob = createDiscoverJob();
      if (discoverJob != null) {
        /*
         * Disable error messages being displayed on job's progress
         * monitor. These are handled by the progress service starting
         * the RM.
         */
        discoverJob.setProperty(
            IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE);
        discoverJob.schedule();
        try {
          discoverJob.join();
        } catch (InterruptedException e) {
          // Just check result
        }
        IStatus status = discoverJob.getResult();
        if (!status.isOK()) {
          throw new CoreException(status);
        }
      }

      if (jobQueueThread == null) {
        jobQueueThread =
            new Thread(
                new JobRunner(), Messages.AbstractToolRuntimeSystem_JobQueueManagerThreadTitle);
        jobQueueThread.start();
      }

      /*
       * Register for connection events
       */
      connection.addConnectionChangeListener(fConnectionChangeHandler);

      fireRuntimeRunningStateEvent(eventFactory.newRuntimeRunningStateEvent());
    } finally {
      synchronized (this) {
        startupMonitor = null;
      }
      if (monitor != null) {
        monitor.done();
      }
    }
  }
示例#23
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);
    }
  }
示例#24
0
  public void build(final IBuildContext context, IProgressMonitor monitor) throws CoreException {
    if (!isEnabled(context)) {
      return;
    }

    final List<IResourceDescription.Delta> deltas = getRelevantDeltas(context);
    if (deltas.isEmpty()) {
      return;
    }

    final int numberOfDeltas = deltas.size();

    // monitor handling
    if (monitor.isCanceled()) throw new OperationCanceledException();
    SubMonitor subMonitor = SubMonitor.convert(monitor, numberOfDeltas + 3);

    EclipseResourceFileSystemAccess2 access = fileSystemAccessProvider.get();
    final IProject builtProject = context.getBuiltProject();
    access.setProject(builtProject);
    final Map<String, OutputConfiguration> outputConfigurations = getOutputConfigurations(context);
    refreshOutputFolders(context, outputConfigurations, subMonitor.newChild(1));
    access.setOutputConfigurations(outputConfigurations);
    if (context.getBuildType() == BuildType.CLEAN || context.getBuildType() == BuildType.RECOVERY) {
      SubMonitor cleanMonitor =
          SubMonitor.convert(subMonitor.newChild(1), outputConfigurations.size());
      for (OutputConfiguration config : outputConfigurations.values()) {
        cleanOutput(context, config, cleanMonitor.newChild(1));
      }
      if (context.getBuildType() == BuildType.CLEAN) return;
    }

    Map<OutputConfiguration, Iterable<IMarker>> generatorMarkers = newHashMap();
    for (OutputConfiguration config : outputConfigurations.values()) {
      if (config.isCleanUpDerivedResources()) {
        final IFolder outputFolder = builtProject.getFolder(config.getOutputDirectory());
        final Iterable<IMarker> markers =
            derivedResourceMarkers.findDerivedResourceMarkers(
                outputFolder, generatorIdProvider.getGeneratorIdentifier());
        generatorMarkers.put(config, markers);
      }
    }

    for (int i = 0; i < numberOfDeltas; i++) {
      final IResourceDescription.Delta delta = deltas.get(i);

      // monitor handling
      if (subMonitor.isCanceled()) throw new OperationCanceledException();
      subMonitor.subTask(
          "Compiling " + delta.getUri().lastSegment() + " (" + i + " of " + numberOfDeltas + ")");
      access.setMonitor(subMonitor.newChild(1));

      final String uri = delta.getUri().toString();
      final Set<IFile> derivedResources = newLinkedHashSet();
      for (OutputConfiguration config : outputConfigurations.values()) {
        if (config.isCleanUpDerivedResources()) {
          Iterable<IMarker> markers = generatorMarkers.get(config);
          for (IMarker marker : markers) {
            String source = derivedResourceMarkers.getSource(marker);
            if (source != null && source.equals(uri))
              derivedResources.add((IFile) marker.getResource());
          }
        }
      }
      access.setPostProcessor(
          new EclipseResourceFileSystemAccess2.IFileCallback() {

            public boolean beforeFileDeletion(IFile file) {
              derivedResources.remove(file);
              context.needRebuild();
              return true;
            }

            public void afterFileUpdate(IFile file) {
              handleFileAccess(file);
            }

            public void afterFileCreation(IFile file) {
              handleFileAccess(file);
            }

            protected void handleFileAccess(IFile file) {
              try {
                derivedResources.remove(file);
                derivedResourceMarkers.installMarker(file, uri);
                context.needRebuild();
              } catch (CoreException e) {
                throw new RuntimeException(e);
              }
            }
          });
      if (delta.getNew() != null) {
        handleChangedContents(delta, context, access);
      }
      access.flushSourceTraces();
      SubMonitor deleteMonitor =
          SubMonitor.convert(subMonitor.newChild(1), derivedResources.size());
      for (IFile iFile : newLinkedHashSet(derivedResources)) {
        IMarker marker = derivedResourceMarkers.findDerivedResourceMarker(iFile, uri);
        if (marker != null) marker.delete();
        if (derivedResourceMarkers.findDerivedResourceMarkers(iFile).length == 0) {
          access.deleteFile(iFile, deleteMonitor);
          context.needRebuild();
        }
      }
    }
  }
  public IRepository<T> loadRepository(
      URI location, IProgressMonitor monitor, String type, int flags) throws ProvisionException {
    checkValidLocation(location);
    SubMonitor sub = SubMonitor.convert(monitor, 100);
    boolean added = false;
    IRepository<T> result = null;

    try {
      CachingTransport.startLoadingRepository(location);
      enterLoad(location, sub.newChild(5));

      result = basicGetRepository(location);
      if (result != null) {
        return result;
      }

      // Add the repository first so that it will be enabled, but don't send add event until after
      // the load.
      added = addRepository(location, true, false);

      LocationProperties indexFile = loadIndexFile(location, sub.newChild(15));
      String[] preferredOrder = getPreferredRepositorySearchOrder(indexFile);
      String[] allSuffixes = getAllSuffixes();
      String[] suffixes = sortSuffixes(allSuffixes, preferredOrder);

      sub =
          SubMonitor.convert(
              sub, NLS.bind("Adding repository {0}", location), suffixes.length * 100);
      ProvisionException failure = null;

      try {
        for (int i = 0; i < suffixes.length; i++) {
          if (sub.isCanceled()) {
            throw new OperationCanceledException();
          }

          try {
            result = loadRepository(location, suffixes[i], type, flags, sub.newChild(100));
          } catch (ProvisionException e) {
            failure = e;
            break;
          }

          if (result != null) {
            addRepository(result, false, suffixes[i]);
            cacheIndexFile(location, suffixes[i]);
            break;
          }
        }
      } finally {
        sub.done();
      }

      if (result == null) {
        // If we just added the repository, remove it because it cannot be loaded.
        if (added) {
          removeRepository(location, false);
        }

        // Eagerly cleanup missing system repositories.
        if (Boolean.valueOf(delegate.getRepositoryProperty(location, IRepository.PROP_SYSTEM))
            .booleanValue()) {
          delegate.removeRepository(location);
        }

        if (failure != null) {
          throw failure;
        }

        fail(location, ProvisionException.REPOSITORY_NOT_FOUND);
      }
    } finally {
      CachingTransport.stopLoadingRepository();
      exitLoad(location);
    }

    // Broadcast the add event after releasing lock.
    if (added) {
      broadcastChangeEvent(location, repositoryType, RepositoryEvent.ADDED, true);
    }

    return result;
  }
  /**
   * @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();
    }
  }
  private static IStatus collectServerInfos(
      String address,
      int port,
      final SpecialAddress special,
      final List<RemoteR> infos,
      final SubMonitor progress) {
    try {
      if (special != null) {
        address = special.fPublicHost;
        port = special.fPort;
      }
      progress.subTask(
          NLS.bind(Messages.RRemoteConsoleSelectionDialog_task_Resolving_message, address));
      final InetAddress inetAddress = InetAddress.getByName(address);
      final String hostname = inetAddress.getHostName();
      final String hostip = inetAddress.getHostAddress();
      progress.worked(1);
      if (progress.isCanceled()) {
        return Status.CANCEL_STATUS;
      }

      progress.subTask(
          NLS.bind(Messages.RRemoteConsoleSelectionDialog_task_Connecting_message, hostname));
      final Registry registry;
      if (special != null) {
        final RMIClientSocketFactory socketFactory = special.getSocketFactory(progress.newChild(5));
        RjsComConfig.setRMIClientSocketFactory(socketFactory);
        registry = LocateRegistry.getRegistry(special.fPrivateHost, port, socketFactory);
      } else {
        RjsComConfig.setRMIClientSocketFactory(null);
        registry = LocateRegistry.getRegistry(address, port);
      }
      final String rmiBase =
          (port == Registry.REGISTRY_PORT)
              ? "//" + address + '/'
              : //$NON-NLS-1$
              "//" + address + ':' + port + '/'; // $NON-NLS-1$
      final String[] names = registry.list();
      for (final String name : names) {
        try {
          final Remote remote = registry.lookup(name);
          if (remote instanceof Server) {
            final Server server = (Server) remote;
            final ServerInfo info = server.getInfo();
            final String rmiAddress = rmiBase + name;
            final RemoteR r = new RemoteR(hostname, hostip, rmiAddress, info);
            infos.add(r);
          }
        } catch (final Exception e) {
        }
      }
      return Status.OK_STATUS;
    } catch (final RemoteException e) {
      return new Status(IStatus.WARNING, RConsoleUIPlugin.PLUGIN_ID, address);
    } catch (final UnknownHostException e) {
      return new Status(
          IStatus.ERROR,
          RConsoleUIPlugin.PLUGIN_ID,
          "Unknown host: " + e.getLocalizedMessage()); // $NON-NLS-1$
    } catch (final CoreException e) {
      return e.getStatus();
    } finally {
      RjsComConfig.clearRMIClientSocketFactory();
    }
  }